MCP PHP SDK

StdioTransport extends BaseTransport implements StatelessAwareTransportInterface

Serves one client over the standard streams, in whichever protocol era it opens with.

The client's first request decides, once, for the life of the process: a request carrying the 2026-07-28 per-request _meta envelope opens a modern connection, anything else — the initialize handshake above all — a handshake-era one. A later request from the other era is refused rather than served, so a client that probed with server/discover, timed out and fell back to the handshake learns the connection is already modern.

Tags
see
https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions
phpstan-import-type

McpFiber from TransportInterface

author

Kyrian Obikwelu koshnawaza@gmail.com

Table of Contents

Interfaces

StatelessAwareTransportInterface
A transport that can carry the modern (SEP-2575) lifecycle as well as the handshake one.

Constants

DEFAULT_MAX_LINE_BYTES  : mixed = 4 * 1024 * 1024
Default cap on the bytes read for a single input line.
CANCELLED_NOTIFICATION  : mixed = 'notifications/cancelled'

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
$discardingLine  : bool
Whether the current over-length line is still being drained and discarded.
$fibers  : array<int, McpFiber>
Handshake-era handlers suspended on the client, by object id: the client pipelines its requests, so several can be in flight at once.
$handlingNotification  : bool
$handshakeVersions  : array<int, ProtocolVersion>|null
$input  : mixed
$maxLineBytes  : positive-int
$modern  : bool|null
Null until the client's first request settles the era.
$output  : mixed
$partialLine  : string
Start of a line whose newline has not arrived yet, as a large message takes several reads.
$runnerControl  : RunnerControlInterface
$stateless  : StatelessProtocol|null
$streams  : array<string, Generator<string|int, mixed>>
Modern-era answers still being written, by the id of the request they answer: a `subscriptions/listen` for as long as it lasts, and a request whose handler streams notifications until its result is in.

Methods

__construct()  : mixed
attachFiberToSession()  : void
close()  : void
Closes the transport and cleans up any resources.
connectStateless()  : void
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
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>>
handleFiberYield()  : void
Hands what the session's fiber yielded to the yield handler.
handleMessage()  : void
handleSessionEnd()  : bool
processInput()  : void
resumeHandlerFiber()  : Error|null
Resumes the session's fiber and handles what it yields next.
flushOutgoingMessages()  : void
handleFiberTermination()  : void
isNotification()  : bool
processFibers()  : void
Resumes every suspended handler that can go on: one that sent a notification right away, one that sent a request once its answer is in or it timed out.
processStreams()  : void
Writes what each open stream has ready: every frame up to its next idle poll, so a listen stream polls once per tick and a handler's notifications go out as it emits them.
resumeFiber()  : Error|null
route()  : void
Hands one message to the era it belongs to, settling the connection's era on the first request.
routeLine()  : void
routeModern()  : void
streamKey()  : string
waitForInput()  : bool
Idles until input arrives, for at most 50ms, so the run loop still gets to suspended fibers, open streams and queued messages in between.
writeError()  : void
writeLine()  : void

Constants

DEFAULT_MAX_LINE_BYTES

Default cap on the bytes read for a single input line.

public mixed DEFAULT_MAX_LINE_BYTES = 4 * 1024 * 1024

CANCELLED_NOTIFICATION

private mixed CANCELLED_NOTIFICATION = 'notifications/cancelled'

Properties

$outgoingMessagesProvider

protected callable(Uuid): array<int, array{message: string, context: array}> $outgoingMessagesProvider

$pendingRequestsProvider

protected callable(Uuid, McpFiber): array<string, array<string, mixed>> $pendingRequestsProvider

$discardingLine

Whether the current over-length line is still being drained and discarded.

private bool $discardingLine = false

$fibers

Handshake-era handlers suspended on the client, by object id: the client pipelines its requests, so several can be in flight at once.

private array<int, McpFiber> $fibers = []

$handlingNotification

private bool $handlingNotification = false

$modern

Null until the client's first request settles the era.

private bool|null $modern = null

$partialLine

Start of a line whose newline has not arrived yet, as a large message takes several reads.

private string $partialLine = ''

$streams

Modern-era answers still being written, by the id of the request they answer: a `subscriptions/listen` for as long as it lasts, and a request whose handler streams notifications until its result is in.

private array<string, Generator<string|int, mixed>> $streams = []

Keyed by self::streamKey(), since PHP would fold the ids "5" and 5 into one key, and JSON-RPC tells them apart.

Methods

__construct()

public __construct([resource $input = STDIN ][, resource $output = STDOUT ][, LoggerInterface|null $logger = null ][, RunnerControlInterface $runnerControl = new RunnerControl() ][, int $maxLineBytes = self::DEFAULT_MAX_LINE_BYTES ]) : mixed
Parameters
$input : resource = STDIN
$output : resource = STDOUT
$logger : LoggerInterface|null = null
$runnerControl : RunnerControlInterface = new RunnerControl()
$maxLineBytes : int = self::DEFAULT_MAX_LINE_BYTES

Maximum bytes of a single input line, including its newline. fgets() with no length reads until a newline or EOF, so a peer that never sends a newline would buffer the whole stream into one allocation and exhaust memory; a line exceeding this cap is discarded instead.

attachFiberToSession()

public attachFiberToSession(Fiber $fiber, Uuid $sessionId) : void
Parameters
$fiber : Fiber
$sessionId : Uuid

close()

Closes the transport and cleans up any resources.

public close() : void

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

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
phpstan-return

FiberResume

Return values
Response|Error|null

endSessionOnShutdown()

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: array}>

getPendingRequests()

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>>

handleFiberYield()

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

handleSessionEnd()

protected handleSessionEnd(Uuid|null $sessionId[, string|null $principal = null ]) : bool
Parameters
$sessionId : Uuid|null
$principal : string|null = null
Tags
throws
SessionStoreException

when the listener cannot tell who opened the session

Return values
bool —

false when the listener reported that the session does not exist

resumeHandlerFiber()

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|null

handleFiberTermination()

private handleFiberTermination(McpFiber $fiber) : void
Parameters
$fiber : McpFiber

isNotification()

private static isNotification(mixed $decoded) : bool
Parameters
$decoded : mixed
Return values
bool

processFibers()

Resumes every suspended handler that can go on: one that sent a notification right away, one that sent a request once its answer is in or it timed out.

private processFibers() : void

processStreams()

Writes what each open stream has ready: every frame up to its next idle poll, so a listen stream polls once per tick and a handler's notifications go out as it emits them.

private processStreams() : void

resumeFiber()

private resumeFiber(McpFiber $fiber) : Error|null
Parameters
$fiber : McpFiber
Return values
Error|null

route()

Hands one message to the era it belongs to, settling the connection's era on the first request.

private route(string $message) : void
Parameters
$message : string

routeLine()

private routeLine(string $line) : void
Parameters
$line : string

routeModern()

private routeModern(string $message, mixed $decoded, array<string, mixed>|null $request) : void
Parameters
$message : string
$decoded : mixed

the message, decoded

$request : array<string, mixed>|null

the message when it is a request

streamKey()

private static streamKey(string|int $id) : string
Parameters
$id : string|int
Return values
string

waitForInput()

Idles until input arrives, for at most 50ms, so the run loop still gets to suspended fibers, open streams and queued messages in between.

private waitForInput() : bool
Return values
bool

writeLine()

private writeLine(string $payload) : void
Parameters
$payload : string
On this page

Search results