Protocol
Tags
Table of Contents
Constants
- SESSION_ACTIVE_REQUEST_META : mixed = '_mcp.active_request_meta'
- Session key for active request meta
- SESSION_LOGGING_LEVEL : mixed = '_mcp.logging_level'
- ABANDONED_REQUEST_GRACE : mixed = 60
- Seconds past its timeout after which a pending client request counts as abandoned by its stream.
- INTERNAL_ERROR_MESSAGE : mixed = 'Internal server error.'
- Deliberately generic: unexpected throwables carry internal details such as file paths, class names and argument types, which must not be handed to the peer. The full exception is logged.
- SESSION_BUSY_MESSAGE : mixed = 'Another request of this session is still being...
- Answer to a request that could not get its session's lock in time, see {@see SessionLockInterface}.
- SESSION_NOT_FOUND_MESSAGE : mixed = 'Session not found or has expired.'
- SESSION_OUTGOING_QUEUE : mixed = '_mcp.outgoing_queue'
- Session key for outgoing message queue
- SESSION_PENDING_REQUESTS : mixed = '_mcp.pending_requests'
- Session key for pending outgoing requests
- SESSION_PRINCIPAL : mixed = '_mcp.principal'
- Session key for the fingerprint of the principal that opened the session, null when it was opened without one
- SESSION_RESPONSES : mixed = '_mcp.responses'
- Session key for incoming client responses
- SESSION_SCOPED_REQUESTS : mixed = [\Mcp\Schema\Request\ResourceSubscribeRequest::...
- Requests whose effect has to outlast them, which a server without sessions cannot keep.
Properties
- $awaitedRequestIds : WeakMap<McpFiber, Uuid>
- The client request each suspended fiber waits on. Pending requests are stored in the session, which concurrent calls share, so a fiber must only be resumed with the answer to the one it sent.
- $droppedAwaitedRequestIds : array<string, true>
- Awaited requests another worker dropped as abandoned, e.g. while this one could not get the session lock to expire them: their fiber is still owed the timeout.
- $eventDispatcher : EventDispatcherInterface|null
- $fiberContext : FiberContextInterface|null
-
$fiberOutgoingMessages
: WeakMap<TransportInterface<string|int, mixed>, array<int, array{message: string, context: array
}>> - What each transport's fiber sends the client, kept out of the session for the same reason: a request or notification must go out on the stream of the call that produced it.
- $fiberScheduler : FiberSchedulerInterface|null
- $inputRequiredShim : InputRequiredShim|null
- $logger : LoggerInterface
- $messageFactory : MessageFactory
- $notificationHandlers : array<string|int, mixed>
- $requestHandlers : array<string|int, mixed>
- $requestStateCodec : RequestStateCodec|null
- $sessionless : bool
- $sessionLock : SessionLockInterface|null
- $sessionManager : SessionManagerInterface
Methods
- __construct() : mixed
- checkResponse() : Response<string|int, array<string, mixed>>|Error|null
- Check for a response to a specific request ID.
- connect() : void
- Connect this protocol to transport.
-
consumeOutgoingMessages()
: array<int, array{message: string, context: array
}> - Consume (get and clear) all outgoing messages for a session.
- destroySession() : bool
- Destroy a specific session.
- getPendingRequests() : array<string, mixed>
- Get pending requests for a session.
- handleFiberYield() : Uuid|null
- Handle values yielded by Fibers during transport-managed resumes.
- processInput() : void
- Handle an incoming message from the transport.
- sendNotification() : void
- Queues a notification for later delivery.
- sendRequest() : Uuid
- Sends a request to the client and returns the request ID.
- acquireSessionLock() : bool
- Returns false when another request holds the lock past the timeout, or right now when not waiting; true when it was acquired, or there is no lock.
- assertQueueable() : void
- createEphemeralSession() : EphemeralSession
- dispatchEvent() : T
- Dispatches an event through the event dispatcher if available.
- dispatchResult() : Response<string|int, mixed>|Error
- doProcessInput() : void
- dropAbandonedRequests() : void
- Drops the pending client requests, and their unconsumed answers, that no stream waits for anymore.
-
encodeOutgoing()
: array{message: string, context: array
}|null - endSession() : bool
- Ends a session at the request of a client, which must be the principal that opened it.
- errorForThrowable() : Error
- expireRequest() : Error|null
- Drops a timed out request from the pending ones and reports the timeout.
- findRequestId() : string|int|null
- The id of a request, so a refusal of the input can be correlated with it.
- findResponseId() : string|int|null
- Determines the id an unprocessable input has to be answered under.
- fingerprint() : string|null
- getAwaitedPendingRequests() : array<string, mixed>
- handleInvalidMessage() : void
- Handle an invalid message from the transport.
- handleMessage() : void
- handleNotification() : void
- handleRequest() : void
- Handle a request from the transport.
- handleResponse() : void
- hasTimedOut() : bool
- isSessionless() : bool
- Without sessions, every handshake-era request over Streamable HTTP is served on a session of its own.
- logRefusal() : void
- queueFiberOutgoing() : void
- Queues what a transport's fiber sends the client, for that transport alone.
- queueOutgoing() : void
- Helper to queue outgoing messages in session.
- refuseOtherPrincipal() : void
- refuseUnavailableStore() : void
- Not a 404: the session may well exist, so the client should retry instead of re-initializing.
- registerRequest() : Uuid
- Picks the id of a request to the client and stores the request as pending in the session.
- releaseSessionLock() : void
- resolveSession() : SessionInterface|null
- Resolves and validates the session based on the request context.
- saveResumedSession() : void
- The code after a resume runs without the lock, so the session's changes since it suspended are saved under it.
- sendResponse() : void
- Sends a response through the transport, on the exchange that carried its request.
- servesPrincipal() : bool
- Whether the session serves the principal: the one that opened it, or no principal for a session opened without one.
- settleAwaitedRequest() : void
- The fiber that awaited this request gets its answer now, so a later poll must not take it for one dropped elsewhere.
-
takeFiberOutgoingMessages()
: array<int, array{message: string, context: array
}> - trackAwaitedRequest() : void
- tryAcquireSessionLockForPoll() : bool
- A stream polls again on its next turn, so neither a busy lock nor a failing backend is waited on here.
Constants
SESSION_ACTIVE_REQUEST_META
Session key for active request meta
public
mixed
SESSION_ACTIVE_REQUEST_META
= '_mcp.active_request_meta'
SESSION_LOGGING_LEVEL
public
mixed
SESSION_LOGGING_LEVEL
= '_mcp.logging_level'
ABANDONED_REQUEST_GRACE
Seconds past its timeout after which a pending client request counts as abandoned by its stream.
private
mixed
ABANDONED_REQUEST_GRACE
= 60
Until then, the stream that sent it expires it itself and reports the timeout.
INTERNAL_ERROR_MESSAGE
Deliberately generic: unexpected throwables carry internal details such as file paths, class names and argument types, which must not be handed to the peer. The full exception is logged.
private
mixed
INTERNAL_ERROR_MESSAGE
= 'Internal server error.'
SESSION_BUSY_MESSAGE
Answer to a request that could not get its session's lock in time, see {@see SessionLockInterface}.
private
mixed
SESSION_BUSY_MESSAGE
= 'Another request of this session is still being processed.'
SESSION_NOT_FOUND_MESSAGE
private
mixed
SESSION_NOT_FOUND_MESSAGE
= 'Session not found or has expired.'
SESSION_OUTGOING_QUEUE
Session key for outgoing message queue
private
mixed
SESSION_OUTGOING_QUEUE
= '_mcp.outgoing_queue'
SESSION_PENDING_REQUESTS
Session key for pending outgoing requests
private
mixed
SESSION_PENDING_REQUESTS
= '_mcp.pending_requests'
SESSION_PRINCIPAL
Session key for the fingerprint of the principal that opened the session, null when it was opened without one
private
mixed
SESSION_PRINCIPAL
= '_mcp.principal'
SESSION_RESPONSES
Session key for incoming client responses
private
mixed
SESSION_RESPONSES
= '_mcp.responses'
SESSION_SCOPED_REQUESTS
Requests whose effect has to outlast them, which a server without sessions cannot keep.
private
mixed
SESSION_SCOPED_REQUESTS
= [\Mcp\Schema\Request\ResourceSubscribeRequest::class, \Mcp\Schema\Request\ResourceUnsubscribeRequest::class, \Mcp\Schema\Request\SetLogLevelRequest::class]
Properties
$awaitedRequestIds
The client request each suspended fiber waits on. Pending requests are stored in the session, which concurrent calls share, so a fiber must only be resumed with the answer to the one it sent.
private
WeakMap<McpFiber, Uuid>
$awaitedRequestIds
$droppedAwaitedRequestIds
Awaited requests another worker dropped as abandoned, e.g. while this one could not get the session lock to expire them: their fiber is still owed the timeout.
private
array<string, true>
$droppedAwaitedRequestIds
= []
$eventDispatcher read-only
private
EventDispatcherInterface|null
$eventDispatcher
= null
$fiberContext read-only
private
FiberContextInterface|null
$fiberContext
= null
$fiberOutgoingMessages
What each transport's fiber sends the client, kept out of the session for the same reason: a request or notification must go out on the stream of the call that produced it.
private
WeakMap<TransportInterface<string|int, mixed>, array<int, array{message: string, context: array}>>
$fiberOutgoingMessages
$fiberScheduler read-only
private
FiberSchedulerInterface|null
$fiberScheduler
= null
$inputRequiredShim read-only
private
InputRequiredShim|null
$inputRequiredShim
= null
$logger read-only
private
LoggerInterface
$logger
= new NullLogger()
$messageFactory read-only
private
MessageFactory
$messageFactory
$notificationHandlers read-only
private
array<string|int, mixed>
$notificationHandlers
$requestHandlers read-only
private
array<string|int, mixed>
$requestHandlers
$requestStateCodec read-only
private
RequestStateCodec|null
$requestStateCodec
= null
$sessionless read-only
private
bool
$sessionless
= false
$sessionLock read-only
private
SessionLockInterface|null
$sessionLock
$sessionManager read-only
private
SessionManagerInterface
$sessionManager
Methods
__construct()
public
__construct(array<int, RequestHandlerInterface<string|int, ResultInterface|array<string, mixed>>> $requestHandlers, array<int, NotificationHandlerInterface> $notificationHandlers, MessageFactory $messageFactory, SessionManagerInterface $sessionManager[, LoggerInterface $logger = new NullLogger() ][, EventDispatcherInterface|null $eventDispatcher = null ][, InputRequiredShim|null $inputRequiredShim = null ][, RequestStateCodec|null $requestStateCodec = null ][, SessionLockInterface|null $sessionLock = null ][, FiberSchedulerInterface|null $fiberScheduler = null ][, FiberContextInterface|null $fiberContext = null ][, bool $sessionless = false ]) : mixed
Parameters
- $requestHandlers : array<int, RequestHandlerInterface<string|int, ResultInterface|array<string, mixed>>>
- $notificationHandlers : array<int, NotificationHandlerInterface>
- $messageFactory : MessageFactory
- $sessionManager : SessionManagerInterface
- $logger : LoggerInterface = new NullLogger()
- $eventDispatcher : EventDispatcherInterface|null = null
- $inputRequiredShim : InputRequiredShim|null = null
- $requestStateCodec : RequestStateCodec|null = null
- $sessionLock : SessionLockInterface|null = null
- $fiberScheduler : FiberSchedulerInterface|null = null
- $fiberContext : FiberContextInterface|null = null
- $sessionless : bool = false
-
serve each handshake-era request over Streamable HTTP on a session of its own, without a
Mcp-Session-Id
checkResponse()
Check for a response to a specific request ID.
public
checkResponse(Uuid $requestId, Uuid $sessionId) : Response<string|int, array<string, mixed>>|Error|null
When a response is found, it is removed from the session, and the corresponding pending request is also cleared. A request that got no answer within its timeout is cleared the same way and reported as an internal error, so its pending entry does not outlive the wait.
Parameters
- $requestId : Uuid
- $sessionId : Uuid
Return values
Response<string|int, array<string, mixed>>|Error|nullconnect()
Connect this protocol to transport.
public
connect(TransportInterface<string|int, mixed> $transport) : void
The protocol takes ownership of the transport and sets up all callbacks.
Parameters
- $transport : TransportInterface<string|int, mixed>
consumeOutgoingMessages()
Consume (get and clear) all outgoing messages for a session.
public
consumeOutgoingMessages(Uuid $sessionId) : array<int, array{message: string, context: array}>
Parameters
- $sessionId : Uuid
Return values
array<int, array{message: string, context: arraydestroySession()
Destroy a specific session.
public
destroySession(Uuid $sessionId) : bool
Parameters
- $sessionId : Uuid
Return values
bool —false when the session does not exist
getPendingRequests()
Get pending requests for a session.
public
getPendingRequests(Uuid $sessionId) : array<string, mixed>
Parameters
- $sessionId : Uuid
Return values
array<string, mixed> —The pending requests
handleFiberYield()
Handle values yielded by Fibers during transport-managed resumes.
public
handleFiberYield(FiberSuspend|null $yieldedValue, Uuid|null $sessionId[, TransportInterface<string|int, mixed>|null $transport = null ]) : Uuid|null
With the transport the fiber runs on, what it sends goes out on that transport alone; without one, it is queued for whichever stream of the session asks first.
Parameters
- $yieldedValue : FiberSuspend|null
- $sessionId : Uuid|null
- $transport : TransportInterface<string|int, mixed>|null = null
Return values
Uuid|null —the ID of the request sent to the client, which the fiber now waits on
processInput()
Handle an incoming message from the transport.
public
processInput(TransportInterface<string|int, mixed> $transport, string $input, Uuid|null $sessionId[, AccessToken|null $accessToken = null ][, string|null $principal = null ]) : void
This is called by the transport whenever ANY message arrives.
Parameters
- $transport : TransportInterface<string|int, mixed>
- $input : string
- $sessionId : Uuid|null
- $accessToken : AccessToken|null = null
-
the token the input was authorized with, if the transport authorizes
- $principal : string|null = null
-
who the input was authenticated as, if the transport authenticates
sendNotification()
Queues a notification for later delivery.
public
sendNotification(Notification $notification, SessionInterface $session) : void
Parameters
- $notification : Notification
- $session : SessionInterface
sendRequest()
Sends a request to the client and returns the request ID.
public
sendRequest(Request $request, int $timeout, SessionInterface $session) : Uuid
Parameters
- $request : Request
- $timeout : int
- $session : SessionInterface
Return values
UuidacquireSessionLock()
Returns false when another request holds the lock past the timeout, or right now when not waiting; true when it was acquired, or there is no lock.
private
acquireSessionLock(Uuid $sessionId[, bool $wait = true ]) : bool
Parameters
- $sessionId : Uuid
- $wait : bool = true
-
false to only take a lock that is free right now
Tags
Return values
boolassertQueueable()
private
static assertQueueable(SessionInterface $session) : void
Parameters
- $session : SessionInterface
Tags
createEphemeralSession()
private
createEphemeralSession(StreamableHttpTransport $transport) : EphemeralSession
Parameters
- $transport : StreamableHttpTransport
Return values
EphemeralSessiondispatchEvent()
Dispatches an event through the event dispatcher if available.
private
dispatchEvent(T $event) : T
Parameters
- $event : T
Return values
TdispatchResult()
private
dispatchResult(Response<string|int, mixed>|Error $result, Request $request, SessionInterface $session) : Response<string|int, mixed>|Error
Parameters
- $result : Response<string|int, mixed>|Error
- $request : Request
- $session : SessionInterface
Return values
Response<string|int, mixed>|ErrordoProcessInput()
private
doProcessInput(TransportInterface<string|int, mixed> $transport, string $input, Uuid|null $sessionId, AccessToken|null $accessToken, string|null $principal) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $input : string
- $sessionId : Uuid|null
- $accessToken : AccessToken|null
- $principal : string|null
dropAbandonedRequests()
Drops the pending client requests, and their unconsumed answers, that no stream waits for anymore.
private
dropAbandonedRequests(SessionInterface $session) : void
Only the stream that sent a request clears it, so one whose stream is gone, through a client disconnect or a dead worker, would stay until the session expires.
Parameters
- $session : SessionInterface
encodeOutgoing()
private
encodeOutgoing(Request|Notification $message, array<string, mixed> $context) : array{message: string, context: array}|null
Parameters
- $message : Request|Notification
- $context : array<string, mixed>
Return values
array{message: string, context: arrayendSession()
Ends a session at the request of a client, which must be the principal that opened it.
private
endSession(Uuid $sessionId[, string|null $principal = null ]) : bool
Parameters
- $sessionId : Uuid
- $principal : string|null = null
Tags
Return values
bool —false when the session does not exist, or is another principal's
errorForThrowable()
private
errorForThrowable(Throwable $e, Request $request, SessionInterface $session) : Error
Parameters
- $e : Throwable
- $request : Request
- $session : SessionInterface
Return values
ErrorexpireRequest()
Drops a timed out request from the pending ones and reports the timeout.
private
expireRequest(Uuid $requestId, Uuid $sessionId) : Error|null
The session is loaded again as the caller's copy may be as old as the last poll, and saving it back would undo what other streams stored since.
Parameters
- $requestId : Uuid
- $sessionId : Uuid
Return values
Error|nullfindRequestId()
The id of a request, so a refusal of the input can be correlated with it.
private
static findRequestId(MessageInterface|InvalidInputMessageException $message) : string|int|null
Parameters
- $message : MessageInterface|InvalidInputMessageException
Return values
string|int|nullfindResponseId()
Determines the id an unprocessable input has to be answered under.
private
static findResponseId(string $input) : string|int|null
Returns null when the input carries no request at all, in which case it consists of notifications and client responses only, and JSON-RPC forbids answering it: an error under a response's id would read as the answer to the client's own request of that id.
Parameters
- $input : string
Return values
string|int|nullfingerprint()
private
static fingerprint(string|null $principal) : string|null
Parameters
- $principal : string|null
Return values
string|nullgetAwaitedPendingRequests()
private
getAwaitedPendingRequests(McpFiber $fiber, Uuid $sessionId) : array<string, mixed>
Parameters
- $fiber : McpFiber
- $sessionId : Uuid
Return values
array<string, mixed>handleInvalidMessage()
Handle an invalid message from the transport.
private
handleInvalidMessage(TransportInterface<string|int, mixed> $transport, InvalidInputMessageException $exception, SessionInterface|null $session[, array<string, mixed> $context = [] ]) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $exception : InvalidInputMessageException
- $session : SessionInterface|null
- $context : array<string, mixed> = []
handleMessage()
private
handleMessage(TransportInterface<string|int, mixed> $transport, Uuid|null $sessionId, MessageInterface|InvalidInputMessageException $message, AccessToken|null $accessToken, string|null $principal) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $sessionId : Uuid|null
- $message : MessageInterface|InvalidInputMessageException
- $accessToken : AccessToken|null
- $principal : string|null
handleNotification()
private
handleNotification(Notification $notification, SessionInterface $session) : void
Parameters
- $notification : Notification
- $session : SessionInterface
handleRequest()
Handle a request from the transport.
private
handleRequest(TransportInterface<string|int, mixed> $transport, Request $request, SessionInterface $session, AccessToken|null $accessToken) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $request : Request
- $session : SessionInterface
- $accessToken : AccessToken|null
handleResponse()
private
handleResponse(Response<string|int, array<string, mixed>>|Error $response, SessionInterface $session) : void
Parameters
- $response : Response<string|int, array<string, mixed>>|Error
- $session : SessionInterface
hasTimedOut()
private
hasTimedOut(array<string|int, mixed> $pending) : bool
Parameters
- $pending : array<string|int, mixed>
Return values
boolisSessionless()
Without sessions, every handshake-era request over Streamable HTTP is served on a session of its own.
private
isSessionless(TransportInterface<string|int, mixed>|null $transport) : bool
Parameters
- $transport : TransportInterface<string|int, mixed>|null
Tags
Return values
boollogRefusal()
private
logRefusal(string $what, SessionInterface $session) : void
Parameters
- $what : string
- $session : SessionInterface
queueFiberOutgoing()
Queues what a transport's fiber sends the client, for that transport alone.
private
queueFiberOutgoing(TransportInterface<string|int, mixed> $transport, Request|Notification $message) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $message : Request|Notification
queueOutgoing()
Helper to queue outgoing messages in session.
private
queueOutgoing(Request|Notification $message, array<string, mixed> $context, SessionInterface $session) : void
Parameters
- $message : Request|Notification
- $context : array<string, mixed>
- $session : SessionInterface
refuseOtherPrincipal()
private
refuseOtherPrincipal(TransportInterface<string|int, mixed> $transport, SessionInterface $session) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $session : SessionInterface
refuseUnavailableStore()
Not a 404: the session may well exist, so the client should retry instead of re-initializing.
private
refuseUnavailableStore(TransportInterface<string|int, mixed> $transport, Uuid $sessionId, string|int|null $requestId, SessionStoreException $exception) : void
Parameters
- $transport : TransportInterface<string|int, mixed>
- $sessionId : Uuid
- $requestId : string|int|null
- $exception : SessionStoreException
registerRequest()
Picks the id of a request to the client and stores the request as pending in the session.
private
registerRequest(Request $request, int $timeout, SessionInterface $session) : Uuid
The id is a UUID, not counted in the session: concurrent requests of a client load the session at the same time and would count up to the same id.
Parameters
- $request : Request
- $timeout : int
- $session : SessionInterface
Return values
UuidreleaseSessionLock()
private
releaseSessionLock(Uuid $sessionId) : void
Parameters
- $sessionId : Uuid
resolveSession()
Resolves and validates the session based on the request context.
private
resolveSession(TransportInterface<string|int, mixed> $transport, Uuid|null $sessionId, MessageInterface|InvalidInputMessageException $message, string|null $principal) : SessionInterface|null
Parameters
- $transport : TransportInterface<string|int, mixed>
- $sessionId : Uuid|null
-
The session ID from the transport
- $message : MessageInterface|InvalidInputMessageException
- $principal : string|null
-
Who the messages were authenticated as
Return values
SessionInterface|nullsaveResumedSession()
The code after a resume runs without the lock, so the session's changes since it suspended are saved under it.
private
saveResumedSession(SessionInterface $session) : void
Parameters
- $session : SessionInterface
sendResponse()
Sends a response through the transport, on the exchange that carried its request.
private
sendResponse(TransportInterface<string|int, mixed> $transport, Response<string|int, ResultInterface|array<string, mixed>>|Error $response, SessionInterface|null $session[, array<string, mixed> $context = [] ]) : void
Responses never go through the session's outgoing queue: the session is shared by the concurrent requests of a client and written back whole, so a queued response could be overwritten by another request, or taken by it.
Parameters
- $transport : TransportInterface<string|int, mixed>
- $response : Response<string|int, ResultInterface|array<string, mixed>>|Error
- $session : SessionInterface|null
- $context : array<string, mixed> = []
servesPrincipal()
Whether the session serves the principal: the one that opened it, or no principal for a session opened without one.
private
servesPrincipal(SessionInterface $session, string|null $principal) : bool
A session that does not record who opened it serves no one.
Parameters
- $session : SessionInterface
- $principal : string|null
Tags
Return values
boolsettleAwaitedRequest()
The fiber that awaited this request gets its answer now, so a later poll must not take it for one dropped elsewhere.
private
settleAwaitedRequest(string $id) : void
Parameters
- $id : string
takeFiberOutgoingMessages()
private
takeFiberOutgoingMessages(TransportInterface<string|int, mixed>|null $transport) : array<int, array{message: string, context: array}>
Parameters
- $transport : TransportInterface<string|int, mixed>|null
Return values
array<int, array{message: string, context: arraytrackAwaitedRequest()
private
trackAwaitedRequest(McpFiber $fiber, Uuid|null $requestId) : void
Parameters
- $fiber : McpFiber
- $requestId : Uuid|null
tryAcquireSessionLockForPoll()
A stream polls again on its next turn, so neither a busy lock nor a failing backend is waited on here.
private
tryAcquireSessionLockForPoll(Uuid $sessionId) : bool
Parameters
- $sessionId : Uuid