HttpTransport extends BaseTransport implements HeaderAwareTransportInterface
HTTP-based client transport using PSR-18 HTTP client.
PSR-18 HTTP clients are auto-discovered if not provided.
Tags
Table of Contents
Interfaces
- HeaderAwareTransportInterface
- A transport whose messages carry headers the protocol gets to fill in.
Constants
- DEFAULT_MAX_RESPONSE_BODY_BYTES : mixed = 8 * 1024 * 1024
- Default cap on the bytes read from a response body that is not an SSE stream.
- DEFAULT_MAX_SSE_BUFFER_BYTES : mixed = 8 * 1024 * 1024
- Default cap on the bytes buffered while waiting for a complete SSE event.
- MAX_LISTEN_BYTES_PER_TICK : mixed = 64 * 1024
- MAX_LOGGED_BODY_BYTES : mixed = 4096
Properties
- $closeCallback : callable(string): void|null
- $errorCallback : callable(Throwable): void|null
- $initializeCallback : callable(): mixed|null
- $logger : LoggerInterface
- $messageCallback : callable(string): void|null
- $state : ClientStateInterface|null
- $activeFiber : McpFiber|null
- $activeStream : StreamInterface|null
- $activeSuspend : FiberSuspend|SendSuspend|null
- $clock : ClockInterface
- $endpoint : string
- $headerCallback : callable(string): array<string, string>|null
- $headers : array<string|int, mixed>
- $httpClient : ClientInterface
- $lastEventId : string|null
- Last event ID received on the current logical SSE stream.
- $listen : bool
- $listenParser : SseParser
- $listenStream : StreamInterface|null
- $maxResponseBodyBytes : int
- $nextReconnectAtMs : float|null
- Clock timestamp, in milliseconds, when the next resumption may start.
- $reconnectAttempts : int
- Number of GET resumption attempts made for the current logical stream.
- $reconnectPolicy : ReconnectPolicy
- $requestFactory : RequestFactoryInterface
- $serverRetryMs : int|null
- Reconnection delay requested by the server, in milliseconds.
- $sessionId : string|null
- $sseParser : SseParser
- $sseRequestCompleted : bool
- Whether the current SSE stream delivered that request's final response.
- $sseRequestId : int|string|null
- The request whose POST response opened the current SSE stream.
- $streamFactory : StreamFactoryInterface
Methods
- __construct() : mixed
- close() : void
- Close the transport and clean up resources.
- connect() : void
- Connect to the MCP server and perform initialization handshake.
- getSessionId() : string|null
- The session ID minted by the server for this connection, if any.
- onClose() : void
- Register callback for when connection closes.
- onError() : void
- Register callback for transport errors.
- onHeaders() : void
- Register the source of per-message headers.
- onInitialize() : void
- Register callback for initialization handshake.
- onMessage() : void
- Register callback for incoming messages from server.
- runRequest() : Response<string|int, array<string, mixed>>|Error
- Run a request fiber to completion.
- send() : void
- Send a message to the server immediately.
- setState() : void
- Set the client state for runtime state management.
- handleClose() : void
- Handle connection close.
- handleError() : void
- Handle a transport error.
- handleInitialize() : mixed
- Perform initialization via the registered callback.
- handleMessage() : void
- Handle an incoming message from the server.
- abortSseStream() : void
- Tear down the active SSE stream and fail any in-flight request.
- answers() : bool
- authorizationFailure() : AuthorizationException
- bodyExcerpt() : string
- checkInterruption() : void
- closeListenStream() : void
- describeRedirect() : string|null
- What to report for a 3xx answer, null for any other.
- dispatchSseData() : void
- expireSession() : void
- Forget a session the server no longer knows, so the next connect starts a new one.
- failRedirected() : void
- Fails a redirected request at once, or reports a redirected message nobody waits on.
- failRequest() : void
- failSseResumption() : void
- Fails the waiting request with the exception itself, as a JSON-RPC error would lose its type.
- failSseStream() : void
- Give up on the current response stream and fail the request it belongs to.
- failUnanswered() : void
- Fails a request whose response ended without its answer at once, rather than at its timeout.
- handleErrorStatus() : void
- Fails a request refused at the HTTP level at once, rather than at its timeout.
- isInitialize() : bool
- isNotification() : bool
- Whether the outgoing message is a notification: a `method` and no `id`, so it asks the server for nothing and no answer of its own can exist.
- isResponseForCurrentSseRequest() : bool
- isSseStreamExpected() : bool
- isWellFormedAnswer() : bool
- nonBlocking() : StreamInterface
- The same body, made to return what it has instead of waiting for more.
- nowMs() : float
- openListenStream() : void
- Open the standalone GET stream, if the server offers one.
- processFiber() : void
- processListenStream() : void
- Read what arrived on the listening stream, if one is open.
- processSends() : void
- Send what the request fiber stepped out for, from {main}.
- processSSEEvent() : void
- Handle an event of the response stream, tracking what a resumption needs.
- processSseReconnect() : void
- Resume an interrupted response stream once its delay has elapsed.
- processSSEStream() : void
- Read SSE data incrementally from active stream.
- protocolHeaders() : array<string, string>
- pumpSse() : bool
- Read a chunk of an SSE stream and dispatch every event it completes.
- readResponseBody() : string
- The body cut at its limit, closing the stream when there is more to it.
- requestIdOf() : int|string|null
- The ID of an outgoing request, or null for a notification or a response.
- resetSseState() : void
- responseStream() : StreamInterface
- The body of a response stream, readable alongside the listening stream.
- scheduleSseReconnect() : void
- Arrange the next GET resumption without blocking request timeout handling.
- sendUnchallenged() : ResponseInterface
- sessionHeaders() : array<string, string>
- Headers a handshake-era connection carries on every request after `initialize`.
- startSseStream() : void
- tick() : void
Constants
DEFAULT_MAX_RESPONSE_BODY_BYTES
Default cap on the bytes read from a response body that is not an SSE stream.
public
mixed
DEFAULT_MAX_RESPONSE_BODY_BYTES
= 8 * 1024 * 1024
DEFAULT_MAX_SSE_BUFFER_BYTES
Default cap on the bytes buffered while waiting for a complete SSE event.
public
mixed
DEFAULT_MAX_SSE_BUFFER_BYTES
= 8 * 1024 * 1024
MAX_LISTEN_BYTES_PER_TICK
private
mixed
MAX_LISTEN_BYTES_PER_TICK
= 64 * 1024
MAX_LOGGED_BODY_BYTES
private
mixed
MAX_LOGGED_BODY_BYTES
= 4096
Properties
$closeCallback
protected
callable(string): void|null
$closeCallback
$errorCallback
protected
callable(Throwable): void|null
$errorCallback
$initializeCallback
protected
callable(): mixed|null
$initializeCallback
$logger
protected
LoggerInterface
$logger
$messageCallback
protected
callable(string): void|null
$messageCallback
$state
protected
ClientStateInterface|null
$state
= null
$activeFiber
private
McpFiber|null
$activeFiber
= null
$activeStream
private
StreamInterface|null
$activeStream
= null
Active SSE stream being read
$activeSuspend
private
FiberSuspend|SendSuspend|null
$activeSuspend
= null
$clock read-only
private
ClockInterface
$clock
$endpoint read-only
private
string
$endpoint
$headerCallback
private
callable(string): array<string, string>|null
$headerCallback
$headers read-only
private
array<string|int, mixed>
$headers
= []
$httpClient
private
ClientInterface
$httpClient
$lastEventId
Last event ID received on the current logical SSE stream.
private
string|null
$lastEventId
= null
$listen read-only
private
bool
$listen
= false
$listenParser read-only
private
SseParser
$listenParser
$listenStream
private
StreamInterface|null
$listenStream
= null
The standalone GET stream the server may send on unprompted
$maxResponseBodyBytes read-only
private
int
$maxResponseBodyBytes
= self::DEFAULT_MAX_RESPONSE_BODY_BYTES
$nextReconnectAtMs
Clock timestamp, in milliseconds, when the next resumption may start.
private
float|null
$nextReconnectAtMs
= null
$reconnectAttempts
Number of GET resumption attempts made for the current logical stream.
private
int
$reconnectAttempts
= 0
$reconnectPolicy read-only
private
ReconnectPolicy
$reconnectPolicy
$requestFactory
private
RequestFactoryInterface
$requestFactory
$serverRetryMs
Reconnection delay requested by the server, in milliseconds.
private
int|null
$serverRetryMs
= null
$sessionId
private
string|null
$sessionId
= null
$sseParser read-only
private
SseParser
$sseParser
$sseRequestCompleted
Whether the current SSE stream delivered that request's final response.
private
bool
$sseRequestCompleted
= false
$sseRequestId
The request whose POST response opened the current SSE stream.
private
int|string|null
$sseRequestId
= null
$streamFactory
private
StreamFactoryInterface
$streamFactory
Methods
__construct()
public
__construct(string $endpoint[, array<string, string> $headers = [] ][, ClientInterface|null $httpClient = null ][, RequestFactoryInterface|null $requestFactory = null ][, StreamFactoryInterface|null $streamFactory = null ][, LoggerInterface|null $logger = null ][, int $maxSseBufferBytes = self::DEFAULT_MAX_SSE_BUFFER_BYTES ][, bool $listen = false ][, ReconnectPolicy|null $reconnectPolicy = null ][, ClockInterface|null $clock = null ][, int $maxResponseBodyBytes = self::DEFAULT_MAX_RESPONSE_BODY_BYTES ][, AuthenticatorInterface|null $auth = null ]) : mixed
Parameters
- $endpoint : string
-
The MCP server endpoint URL
- $headers : array<string, string> = []
-
Additional headers to send
- $httpClient : ClientInterface|null = null
-
PSR-18 HTTP client (auto-discovered if null)
- $requestFactory : RequestFactoryInterface|null = null
-
PSR-17 request factory (auto-discovered if null)
- $streamFactory : StreamFactoryInterface|null = null
-
PSR-17 stream factory (auto-discovered if null)
- $logger : LoggerInterface|null = null
- $maxSseBufferBytes : int = self::DEFAULT_MAX_SSE_BUFFER_BYTES
-
Maximum bytes buffered while waiting for a complete SSE event. A server that never sends the "\n\n" event delimiter would otherwise grow the buffer without bound and exhaust client memory; reaching the cap aborts the stream instead. Raise it for servers that legitimately emit single events larger than the default.
- $listen : bool = false
-
Open the standalone GET stream after the handshake (2025 revisions only). Needs a PSR-18 client that streams response bodies; see docs/client/transports.md.
- $reconnectPolicy : ReconnectPolicy|null = null
-
How an SSE stream that closed before its response arrived is resumed (default: 5 attempts, 1-10 s backoff)
- $clock : ClockInterface|null = null
-
Clock for scheduling reconnects (default: a monotonic clock)
- $maxResponseBodyBytes : int = self::DEFAULT_MAX_RESPONSE_BODY_BYTES
-
Maximum bytes read from a response body that is not an SSE stream
- $auth : AuthenticatorInterface|null = null
-
Credentials for a server that requires authorization. Pass OAuth to negotiate them on demand, or BearerToken when the token is already at hand. Every request the transport makes is authenticated, and one the server challenges is retried once credentials are obtained.
close()
Close the transport and clean up resources.
public
close() : void
connect()
Connect to the MCP server and perform initialization handshake.
public
connect() : void
This method blocks until:
- Initialization completes successfully
- Connection fails (throws ConnectionException)
getSessionId()
The session ID minted by the server for this connection, if any.
public
getSessionId() : string|null
Captured from the Mcp-Session-Id header of the initialize response;
always null on 2026-07-28, which removed protocol-level sessions
(SEP-2567). Useful for logging: every connect() starts a new session
and close() ends it, so it cannot be reused on a later transport.
Return values
string|null —null until the server mints a session, and again after close() or a 404 session expiry
onClose()
Register callback for when connection closes.
public
onClose(callable $listener) : void
Parameters
- $listener : callable
onError()
Register callback for transport errors.
public
onError(callable $listener) : void
Parameters
- $listener : callable
onHeaders()
Register the source of per-message headers.
public
onHeaders(callable $callback) : void
Parameters
- $callback : callable
-
receives the encoded message
onInitialize()
Register callback for initialization handshake.
public
onInitialize(callable $listener) : void
The callback should return a Fiber that performs the initialization.
Parameters
- $listener : callable
onMessage()
Register callback for incoming messages from server.
public
onMessage(callable $listener) : void
Parameters
- $listener : callable
runRequest()
Run a request fiber to completion.
public
runRequest(McpFiber $fiber[, callable(float $progress, Array $total, Array $message): void|null $onProgress = null ]) : Response<string|int, array<string, mixed>>|Error
Parameters
- $fiber : McpFiber
- $onProgress : callable(float $progress, Array $total, Array $message): void|null = null
Return values
Response<string|int, array<string, mixed>>|Error —The response or error
send()
Send a message to the server immediately.
public
send(string $data) : void
Parameters
- $data : string
-
JSON-encoded message
setState()
Set the client state for runtime state management.
public
setState(ClientStateInterface $state) : void
Parameters
- $state : ClientStateInterface
handleClose()
Handle connection close.
protected
handleClose(string $reason) : void
Parameters
- $reason : string
handleError()
Handle a transport error.
protected
handleError(Throwable $error) : void
Parameters
- $error : Throwable
handleInitialize()
Perform initialization via the registered callback.
protected
handleInitialize() : mixed
Tags
Return values
mixed —The result from the initialization callback
handleMessage()
Handle an incoming message from the server.
protected
handleMessage(string $message) : void
Parameters
- $message : string
abortSseStream()
Tear down the active SSE stream and fail any in-flight request.
private
abortSseStream(string $reason) : void
The waiting fiber is resolved with an error immediately so the caller fails fast, rather than spinning until the request timeout elapses.
Parameters
- $reason : string
answers()
private
static answers(string $data, int|string $requestId) : bool
Parameters
- $data : string
- $requestId : int|string
Return values
boolauthorizationFailure()
private
authorizationFailure(ResponseInterface $response) : AuthorizationException
Parameters
- $response : ResponseInterface
Return values
AuthorizationExceptionbodyExcerpt()
private
static bodyExcerpt(string $body, bool $truncated) : string
Parameters
- $body : string
- $truncated : bool
Return values
stringcheckInterruption()
private
checkInterruption() : void
closeListenStream()
private
closeListenStream() : void
describeRedirect()
What to report for a 3xx answer, null for any other.
private
static describeRedirect(ResponseInterface $response) : string|null
Parameters
- $response : ResponseInterface
Return values
string|nulldispatchSseData()
private
dispatchSseData(SseEvent $event) : void
Parameters
- $event : SseEvent
expireSession()
Forget a session the server no longer knows, so the next connect starts a new one.
private
expireSession() : void
failRedirected()
Fails a redirected request at once, or reports a redirected message nobody waits on.
private
failRedirected(string $sent, string $reason) : void
Parameters
- $sent : string
- $reason : string
failRequest()
private
failRequest(string $sent, string $message[, array<string, bool>|null $data = null ]) : void
Parameters
- $sent : string
- $message : string
- $data : array<string, bool>|null = null
failSseResumption()
Fails the waiting request with the exception itself, as a JSON-RPC error would lose its type.
private
failSseResumption(AuthorizationException $failure) : void
Parameters
- $failure : AuthorizationException
failSseStream()
Give up on the current response stream and fail the request it belongs to.
private
failSseStream(string $reason[, array<string, bool>|null $data = null ]) : void
Parameters
- $reason : string
- $data : array<string, bool>|null = null
failUnanswered()
Fails a request whose response ended without its answer at once, rather than at its timeout.
private
failUnanswered(string $sent, string $reason) : void
Parameters
- $sent : string
- $reason : string
handleErrorStatus()
Fails a request refused at the HTTP level at once, rather than at its timeout.
private
handleErrorStatus(string $sent, int $status, string $reason, string $body, bool $truncated) : void
Parameters
- $sent : string
- $status : int
- $reason : string
- $body : string
- $truncated : bool
isInitialize()
private
static isInitialize(string $data) : bool
Parameters
- $data : string
Return values
boolisNotification()
Whether the outgoing message is a notification: a `method` and no `id`, so it asks the server for nothing and no answer of its own can exist.
private
static isNotification(string $data) : bool
Parameters
- $data : string
Return values
boolisResponseForCurrentSseRequest()
private
isResponseForCurrentSseRequest(string $data) : bool
Parameters
- $data : string
Return values
boolisSseStreamExpected()
private
isSseStreamExpected() : bool
Return values
boolisWellFormedAnswer()
private
static isWellFormedAnswer(array<string|int, mixed> $answer) : bool
Parameters
- $answer : array<string|int, mixed>
Return values
boolnonBlocking()
The same body, made to return what it has instead of waiting for more.
private
nonBlocking(StreamInterface $body[, bool|null &$switched = null ]) : StreamInterface
Always returns a stream to read the body with: the given one when it has no PHP stream behind it to switch, as detaching it would leave nothing to read with.
Parameters
- $body : StreamInterface
- $switched : bool|null = null
Tags
Return values
StreamInterfacenowMs()
private
nowMs() : float
Return values
floatopenListenStream()
Open the standalone GET stream, if the server offers one.
private
openListenStream() : void
Failing to does not end the connection: the stream is optional on both sides, and everything that belongs to a request still arrives on its response.
processFiber()
private
processFiber() : void
processListenStream()
Read what arrived on the listening stream, if one is open.
private
processListenStream() : void
Its end is no error: the server may close it at any time, and every response still arrives on its own request.
processSends()
Send what the request fiber stepped out for, from {main}.
private
processSends() : void
A failure is thrown back into the fiber, so it surfaces from send() as it would have had the message been sent in place.
processSSEEvent()
Handle an event of the response stream, tracking what a resumption needs.
private
processSSEEvent(SseEvent $event) : void
Parameters
- $event : SseEvent
processSseReconnect()
Resume an interrupted response stream once its delay has elapsed.
private
processSseReconnect() : void
Tags
processSSEStream()
Read SSE data incrementally from active stream.
private
processSSEStream() : void
protocolHeaders()
private
protocolHeaders(string $payload) : array<string, string>
Parameters
- $payload : string
Return values
array<string, string>pumpSse()
Read a chunk of an SSE stream and dispatch every event it completes.
private
pumpSse(StreamInterface $stream, SseParser $parser, callable(SseEvent): void $onEvent, callable(string $reason): void $onOverflow[, int|null &$read = null ][, int $length = 4096 ]) : bool
Parameters
- $stream : StreamInterface
- $parser : SseParser
- $onEvent : callable(SseEvent): void
- $onOverflow : callable(string $reason): void
-
called when the buffer would exceed its cap
- $read : int|null = null
- $length : int = 4096
Tags
Return values
bool —whether the stream is done: ended, or given up for its size
readResponseBody()
The body cut at its limit, closing the stream when there is more to it.
private
readResponseBody(StreamInterface $stream, bool|null &$truncated) : string
Parameters
- $stream : StreamInterface
- $truncated : bool|null
Tags
Return values
stringrequestIdOf()
The ID of an outgoing request, or null for a notification or a response.
private
static requestIdOf(string $data) : int|string|null
Parameters
- $data : string
Return values
int|string|nullresetSseState()
private
resetSseState() : void
responseStream()
The body of a response stream, readable alongside the listening stream.
private
responseStream(StreamInterface $body) : StreamInterface
While listening, a request on the GET stream can be what this response waits for, so neither stream may block the other.
Parameters
- $body : StreamInterface
Return values
StreamInterfacescheduleSseReconnect()
Arrange the next GET resumption without blocking request timeout handling.
private
scheduleSseReconnect() : void
sendUnchallenged()
private
sendUnchallenged(RequestInterface $request) : ResponseInterface
Parameters
- $request : RequestInterface
Return values
ResponseInterfacesessionHeaders()
Headers a handshake-era connection carries on every request after `initialize`.
private
sessionHeaders() : array<string, string>
2026-07-28 derives its version header from each message instead, see protocolHeaders().
Tags
Return values
array<string, string>startSseStream()
private
startSseStream(StreamInterface $stream, int|string|null $requestId) : void
Parameters
- $stream : StreamInterface
- $requestId : int|string|null
tick()
private
tick() : void