StreamableHttpTransport extends BaseTransport implements StatelessAwareTransportInterface uses ReadsBoundedBody
Carries MCP over HTTP, in either protocol era.
Every request is classified once, before anything else looks at it, and
routed to the lifecycle it belongs to: a per-request envelope claiming a
modern revision goes to StatelessProtocol, everything else — the
initialize handshake, its session's later requests, its DELETE teardown —
goes to the session machinery below. One endpoint, both eras, nothing for the
client to pick.
A server run without a modern-era dispatcher (see Builder::withoutModernEra()) serves the handshake era alone and refuses modern claims, naming the revisions it does serve.
Tags
Table of Contents
Interfaces
- StatelessAwareTransportInterface
- A transport that can carry the modern (SEP-2575) lifecycle as well as the handshake one.
Constants
- DEFAULT_MAX_BODY_BYTES : mixed = 4 * 1024 * 1024
- Upper bound on the request body read for a POST, guarding against memory exhaustion from an oversized (or unbounded chunked) payload.
- PRINCIPAL_ATTRIBUTE : mixed = 'mcp.principal'
- PSR-7 request attribute holding a non-empty string that identifies the authenticated principal.
- PROTOCOL_VERSION_HEADER : mixed = 'Mcp-Protocol-Version'
- SESSION_HEADER : mixed = 'Mcp-Session-Id'
Properties
- $fiberYieldHandler : callable(Array, Array, McpFiber): void
- $logger : LoggerInterface
- $messageListener : callable(TransportInterface<string|int, mixed>, string, Array, Array, Array): void
-
$outgoingMessagesProvider
: callable(Uuid): array<int, array{message: string, context: array
}> - $pendingRequestsProvider : callable(Uuid, McpFiber): array<string, array<string, mixed>>
- $responseFinder : callable(Uuid, Uuid): Array|null
- $sessionEndListener : callable(Uuid, Array): bool
- $sessionFiber : McpFiber|null
- $sessionId : Uuid|null
- $classifier : InboundClassifier
- $handshakeVersions : array<int, ProtocolVersion>|null
- $headerProtocolVersion : ProtocolVersion
- $immediateResponse : string|null
- $immediateStatusCode : int|null
- $jsonRpcResponse : string|null
- $maxBodyBytes : int
- $middleware : array<int, MiddlewareInterface>|null
- $request : ServerRequestInterface
- $responder : StatelessResponder
- $responseFactory : ResponseFactoryInterface
- $sessionless : bool
- $stateless : StatelessProtocol|null
- $streamFactory : StreamFactoryInterface
Methods
- __construct() : mixed
- A non-null `$middleware` list replaces {@see self::defaultMiddleware()}.
- attachFiberToSession() : void
- close() : void
- Closes the transport and cleans up any resources.
- connectStateless() : void
- defaultMiddleware() : array<int, MiddlewareInterface>
- Secure default middleware stack applied when no `$middleware` is provided to the constructor.
- handshakeMiddleware() : array<int, MiddlewareInterface>
- Middleware applied only to requests classified as handshake-era traffic.
- initialize() : void
- Initializes the transport.
- listen() : TResult
- Starts the transport's execution process.
- onMessage() : void
- onSessionEnd() : void
- send() : void
- Send a message to the client immediately (bypassing session queue).
- setFiberYieldHandler() : void
- setHandshakeVersions() : void
- Revisions the handshake dispatcher negotiates, named when a modern-era request reaches a server without the modern era.
- setOutgoingMessagesProvider() : void
- setPendingRequestsProvider() : void
- setResponseFinder() : void
- setSessionId() : void
- Set the session ID for the current transport context.
- checkForResponse() : Response|Error|null
- createErrorResponse() : ResponseInterface
- createJsonResponse() : ResponseInterface
- createStreamedResponse() : ResponseInterface
- endSessionOnShutdown() : void
- Ends the session of a transport shutting down, which has no client to report a store failure to.
-
getOutgoingMessages()
: array<int, array{message: string, context: array
}> - getPendingRequests() : array<string, array<string, mixed>>
- handleDeleteRequest() : ResponseInterface
- handleFiberYield() : void
- Hands what the session's fiber yielded to the yield handler.
- handleMessage() : void
- handleOptionsRequest() : ResponseInterface
- handlePostRequest() : ResponseInterface
- handleSessionEnd() : bool
- isConnectionAborted() : bool
- resumeHandlerFiber() : Error|null
- Resumes the session's fiber and handles what it yields next.
- accessToken() : AccessToken|null
- The token an authorization middleware validated, see {@see Http\Middleware\AuthorizationMiddleware}.
- finalFrame() : Generator<int, string>
- handleHandshakeRequest() : ResponseInterface
- handleModernRequest() : ResponseInterface
- Answers a request that claimed the modern era's per-request envelope.
- handleRequest() : ResponseInterface
- headers() : array<string, string>
- normalizeMiddleware() : array<int, MiddlewareInterface>
- outgoingFrames() : Generator<int, string>
- readBody() : string|null
- Reads the request body, bounded by {@see self::$maxBodyBytes}.
- readBoundedBody() : string|null
- Returns the body contents, or `null` when the payload exceeds $maxBytes.
Constants
DEFAULT_MAX_BODY_BYTES
Upper bound on the request body read for a POST, guarding against memory exhaustion from an oversized (or unbounded chunked) payload.
public
mixed
DEFAULT_MAX_BODY_BYTES
= 4 * 1024 * 1024
PRINCIPAL_ATTRIBUTE
PSR-7 request attribute holding a non-empty string that identifies the authenticated principal.
public
mixed
PRINCIPAL_ATTRIBUTE
= 'mcp.principal'
A session only serves the principal that opened it. Without this attribute, the principal is the one of the request's AccessToken; set it to identify users another way.
PROTOCOL_VERSION_HEADER
public
mixed
PROTOCOL_VERSION_HEADER
= 'Mcp-Protocol-Version'
SESSION_HEADER
public
mixed
SESSION_HEADER
= 'Mcp-Session-Id'
Properties
$fiberYieldHandler
protected
callable(Array, Array, McpFiber): void
$fiberYieldHandler
$logger
protected
LoggerInterface
$logger
$messageListener
protected
callable(TransportInterface<string|int, mixed>, string, Array, Array, Array): void
$messageListener
$outgoingMessagesProvider
protected
callable(Uuid): array<int, array{message: string, context: array}>
$outgoingMessagesProvider
$pendingRequestsProvider
protected
callable(Uuid, McpFiber): array<string, array<string, mixed>>
$pendingRequestsProvider
$responseFinder
protected
callable(Uuid, Uuid): Array|null
$responseFinder
$sessionEndListener
protected
callable(Uuid, Array): bool
$sessionEndListener
$sessionFiber
protected
McpFiber|null
$sessionFiber
= null
$sessionId
protected
Uuid|null
$sessionId
= null
$classifier
private
InboundClassifier
$classifier
$handshakeVersions
private
array<int, ProtocolVersion>|null
$handshakeVersions
= null
null names every handshake revision
$headerProtocolVersion
private
ProtocolVersion
$headerProtocolVersion
= \Mcp\Schema\Enum\ProtocolVersion::DEFAULT_HEADER_VERSION
$immediateResponse
private
string|null
$immediateResponse
= null
$immediateStatusCode
private
int|null
$immediateStatusCode
= null
$jsonRpcResponse
private
string|null
$jsonRpcResponse
= null
$maxBodyBytes read-only
private
int
$maxBodyBytes
= self::DEFAULT_MAX_BODY_BYTES
$middleware
private
array<int, MiddlewareInterface>|null
$middleware
null until self::listen() resolves the defaults
$request read-only
private
ServerRequestInterface
$request
$responder
private
StatelessResponder
$responder
$responseFactory
private
ResponseFactoryInterface
$responseFactory
$sessionless
private
bool
$sessionless
= false
$stateless
private
StatelessProtocol|null
$stateless
= null
$streamFactory
private
StreamFactoryInterface
$streamFactory
Methods
__construct()
A non-null `$middleware` list replaces {@see self::defaultMiddleware()}.
public
__construct(ServerRequestInterface $request[, ResponseFactoryInterface|null $responseFactory = null ][, StreamFactoryInterface|null $streamFactory = null ][, LoggerInterface|null $logger = null ][, iterable<string|int, MiddlewareInterface>|null $middleware = null ][, int $maxBodyBytes = self::DEFAULT_MAX_BODY_BYTES ]) : mixed
An empty list is treated as a likely mistake and logs a warning on every
request. When the host application already handles CORS and host
validation, opt out explicitly with [new PassthroughMiddleware()].
Parameters
- $request : ServerRequestInterface
- $responseFactory : ResponseFactoryInterface|null = null
- $streamFactory : StreamFactoryInterface|null = null
- $logger : LoggerInterface|null = null
- $middleware : iterable<string|int, MiddlewareInterface>|null = null
-
nullinstalls self::defaultMiddleware();[]disables them and logs a warning - $maxBodyBytes : int = self::DEFAULT_MAX_BODY_BYTES
attachFiberToSession()
public
attachFiberToSession(McpFiber $fiber, Uuid $sessionId) : void
Parameters
- $fiber : McpFiber
- $sessionId : Uuid
close()
Closes the transport and cleans up any resources.
public
close() : void
connectStateless()
public
connectStateless(StatelessProtocol $protocol) : void
Parameters
- $protocol : StatelessProtocol
defaultMiddleware()
Secure default middleware stack applied when no `$middleware` is provided to the constructor.
public
static defaultMiddleware() : array<int, MiddlewareInterface>
These run at the edge, before the request's era is known, because what
they enforce — origin policy, DNS rebinding — is true of both eras. The
MCP-Protocol-Version header rule is not: it belongs to the handshake
era, so self::handshakeMiddleware() carries it instead and the
modern leg answers for its own revisions.
Return values
array<int, MiddlewareInterface>handshakeMiddleware()
Middleware applied only to requests classified as handshake-era traffic.
public
static handshakeMiddleware() : array<int, MiddlewareInterface>
Return values
array<int, MiddlewareInterface>initialize()
Initializes the transport.
public
initialize() : void
listen()
Starts the transport's execution process.
public
listen() : TResult
- For a blocking transport like STDIO, this method will run a continuous loop.
- For a single-request transport like HTTP, this will process the request and return a result (e.g., a PSR-7 Response) to be sent to the client.
Return values
TResult —the result of the transport's execution, if any
onMessage()
public
onMessage(callable $listener) : void
Parameters
- $listener : callable
onSessionEnd()
public
onSessionEnd(callable $listener) : void
Parameters
- $listener : callable
send()
Send a message to the client immediately (bypassing session queue).
public
send(string $data, array<string|int, mixed> $context) : void
Used for the response of a handler that returns without suspending, on the
exchange that carried its request. A handler that suspends returns its
result from the fiber the transport resumes instead. An error with a
status_code was raised before a session was resolved and rejects the
whole exchange. The transport decides HOW to send based on context.
Parameters
- $data : string
- $context : array<string|int, mixed>
-
Context about this message:
- 'session_id': Uuid|null
- 'type': 'response'|'request'|'notification'
- 'status_code': int (HTTP status code for errors)
setFiberYieldHandler()
public
setFiberYieldHandler(callable(Array, Array, McpFiber): void $handler) : void
Parameters
- $handler : callable(Array, Array, McpFiber): void
setHandshakeVersions()
Revisions the handshake dispatcher negotiates, named when a modern-era request reaches a server without the modern era.
public
setHandshakeVersions(array<string|int, mixed> $versions) : void
Parameters
- $versions : array<string|int, mixed>
setOutgoingMessagesProvider()
public
setOutgoingMessagesProvider(callable $provider) : void
Parameters
- $provider : callable
setPendingRequestsProvider()
public
setPendingRequestsProvider(callable $provider) : void
Parameters
- $provider : callable
setResponseFinder()
public
setResponseFinder(callable(Uuid, Uuid): Array $finder) : void
Parameters
- $finder : callable(Uuid, Uuid): Array
setSessionId()
Set the session ID for the current transport context.
public
setSessionId(Uuid|null $sessionId) : void
Parameters
- $sessionId : Uuid|null
-
The session ID, or null to clear
checkForResponse()
protected
checkForResponse(Uuid $requestId, Uuid|null $sessionId) : Response|Error|null
Parameters
- $requestId : Uuid
- $sessionId : Uuid|null
Tags
Return values
Response|Error|nullcreateErrorResponse()
protected
createErrorResponse(Error $jsonRpcError, int $statusCode) : ResponseInterface
Parameters
- $jsonRpcError : Error
- $statusCode : int
Return values
ResponseInterfacecreateJsonResponse()
protected
createJsonResponse() : ResponseInterface
Return values
ResponseInterfacecreateStreamedResponse()
protected
createStreamedResponse() : ResponseInterface
Return values
ResponseInterfaceendSessionOnShutdown()
Ends the session of a transport shutting down, which has no client to report a store failure to.
protected
endSessionOnShutdown(Uuid|null $sessionId) : void
Parameters
- $sessionId : Uuid|null
getOutgoingMessages()
protected
getOutgoingMessages(Uuid|null $sessionId) : array<int, array{message: string, context: array}>
Parameters
- $sessionId : Uuid|null
Return values
array<int, array{message: string, context: arraygetPendingRequests()
protected
getPendingRequests(Uuid|null $sessionId, McpFiber $fiber) : array<string, array<string, mixed>>
Parameters
- $sessionId : Uuid|null
- $fiber : McpFiber
Return values
array<string, array<string, mixed>>handleDeleteRequest()
protected
handleDeleteRequest([string|null $principal = null ]) : ResponseInterface
Parameters
- $principal : string|null = null
-
the principal the request was authenticated as, see self::PRINCIPAL_ATTRIBUTE
Return values
ResponseInterfacehandleFiberYield()
Hands what the session's fiber yielded to the yield handler.
protected
handleFiberYield(FiberSuspend|null $yielded, Uuid|null $sessionId, McpFiber $fiber) : void
When the handler fails, the message the fiber suspended on never reaches the client, so the fiber is resumed with an error instead of being left waiting on nothing; whatever it yields next is handled the same way.
Parameters
- $yielded : FiberSuspend|null
- $sessionId : Uuid|null
- $fiber : McpFiber
-
the fiber that yielded
handleMessage()
protected
handleMessage(string $payload, Uuid|null $sessionId[, AccessToken|null $accessToken = null ][, string|null $principal = null ]) : void
Parameters
- $payload : string
- $sessionId : Uuid|null
- $accessToken : AccessToken|null = null
- $principal : string|null = null
handleOptionsRequest()
protected
handleOptionsRequest() : ResponseInterface
Return values
ResponseInterfacehandlePostRequest()
protected
handlePostRequest(string $body[, AccessToken|null $accessToken = null ][, string|null $principal = null ]) : ResponseInterface
Parameters
- $body : string
-
the request body, already read and bounded by self::handleRequest()
- $accessToken : AccessToken|null = null
-
the token the request was authorized with, see self::accessToken()
- $principal : string|null = null
-
the principal the request was authenticated as, see self::PRINCIPAL_ATTRIBUTE
Return values
ResponseInterfacehandleSessionEnd()
protected
handleSessionEnd(Uuid|null $sessionId[, string|null $principal = null ]) : bool
Parameters
- $sessionId : Uuid|null
- $principal : string|null = null
Tags
Return values
bool —false when the listener reported that the session does not exist
isConnectionAborted()
protected
isConnectionAborted() : bool
Return values
boolresumeHandlerFiber()
Resumes the session's fiber and handles what it yields next.
protected
resumeHandlerFiber(McpFiber $fiber, Uuid|null $sessionId[, FiberResume $value = null ]) : Error|null
Returns the error answering its request when it cannot be driven further, an event loop still holding it for instance: the fiber is left to its runtime, and the transport drops it.
Parameters
- $fiber : McpFiber
- $sessionId : Uuid|null
- $value : FiberResume = null
Return values
Error|nullaccessToken()
The token an authorization middleware validated, see {@see Http\Middleware\AuthorizationMiddleware}.
private
static accessToken(ServerRequestInterface $request) : AccessToken|null
Parameters
- $request : ServerRequestInterface
Return values
AccessToken|nullfinalFrame()
private
finalFrame(mixed $finalResult) : Generator<int, string>
Parameters
- $finalResult : mixed
Return values
Generator<int, string>handleHandshakeRequest()
private
handleHandshakeRequest(ServerRequestInterface $request, string|null $body) : ResponseInterface
Parameters
- $request : ServerRequestInterface
- $body : string|null
Return values
ResponseInterfacehandleModernRequest()
Answers a request that claimed the modern era's per-request envelope.
private
handleModernRequest(ServerRequestInterface $request, string $body, string $claimedVersion) : ResponseInterface
Parameters
- $request : ServerRequestInterface
- $body : string
- $claimedVersion : string
Return values
ResponseInterfacehandleRequest()
private
handleRequest(ServerRequestInterface $request) : ResponseInterface
Parameters
- $request : ServerRequestInterface
Return values
ResponseInterfaceheaders()
private
static headers(ServerRequestInterface $request) : array<string, string>
Parameters
- $request : ServerRequestInterface
Return values
array<string, string>normalizeMiddleware()
private
static normalizeMiddleware(iterable<string|int, MiddlewareInterface> $middleware) : array<int, MiddlewareInterface>
Parameters
- $middleware : iterable<string|int, MiddlewareInterface>
Return values
array<int, MiddlewareInterface>outgoingFrames()
private
outgoingFrames() : Generator<int, string>
Return values
Generator<int, string>readBody()
Reads the request body, bounded by {@see self::$maxBodyBytes}.
private
readBody(StreamInterface $body) : string|null
Parameters
- $body : StreamInterface
Return values
string|nullreadBoundedBody()
Returns the body contents, or `null` when the payload exceeds $maxBytes.
private
readBoundedBody(StreamInterface $body, int $maxBytes) : string|null
A stream advertising its size is rejected up front; otherwise the read is incremental and stops at the cap, so an unbounded stream cannot exhaust memory.
Parameters
- $body : StreamInterface
- $maxBytes : int