Protocol
Client protocol handler for MCP communication.
Handles message routing, request/response correlation, and the initialization handshake. All blocking operations are delegated to the transport.
Tags
Table of Contents
Constants
- MAX_ROUND_TRIPS : mixed = 10
- How many times a request may be re-sent before the client gives up.
Properties
- $envelope : RequestEnvelope|null
- Set only when the configured revision has no handshake.
- $headers : HeaderFactory|null
- $inputRequests : InputRequestResolver
- $logger : LoggerInterface
- $logLevel : LoggingLevel|null
- $messageFactory : MessageFactory
- $notificationHandlers : array<string|int, NotificationHandlerInterface>
- $onProgress : callable(float, Array, Array): void|null
- $progressToken : string|null
- The token of the request in flight, the only one whose progress reaches the callback.
- $progressTokens : int
- Progress tokens are only required to be unique within a connection, and a retry keeps the caller's one — the work being reported on is the same.
- $requestHandlers : array<string|int, mixed>
- $state : ClientStateInterface
- $tools : ToolCatalog
- $transport : TransportInterface|null
Methods
- __construct() : mixed
- connect() : void
- Connect this protocol to a transport.
- getState() : ClientStateInterface
- getToolCatalog() : ToolCatalog
- What the client knows about the server's tools, from `tools/list`.
- initialize() : Response<string|int, array<string, mixed>>|Error
- Ready the connection for use, settling which protocol era it speaks.
- isModern() : bool
- processMessage() : void
- Process an incoming message from the server.
- request() : Response<string|int, array<string, mixed>>|Error
- Send a request to the server and wait for response.
- sendNotification() : void
- Send a notification to the server (fire and forget).
- setLogLevel() : void
- The modern era's stand-in for `logging/setLevel`.
- setProgressCallback() : void
- Set the callback for progress on the request in flight, null to clear it.
- adopt() : Response<string|int, array<string, mixed>>|Error|null
- The modern connection, an error ending the attempt, or null to fall back.
- deliverProgress() : void
- describe() : string
- enterModernEra() : void
- exchange() : Response<string|int, array<string, mixed>>|Error
- One request on the wire: assign an id, send, and wait for its answer.
- forgetServer() : void
- handleNotification() : void
- Handle a notification from the server.
- handleRequest() : void
- Handle a request from the server (e.g., sampling request).
- handleResponse() : void
- Handle a response from the server.
- handshake() : Response<string|int, array<string, mixed>>|Error
- headersFor() : array<string, string>
- The headers belonging to an encoded message, for a transport that has any.
- interruption() : RequestCancelledException|TimeoutException|null
- The interruption an in-flight request is subject to, if any. Checked on both sides of a send and after the transport resumes a suspended request.
- mutualModern() : ProtocolVersion|null
- The newest modern revision a refusal names that this client speaks.
- namedVersions() : array<int, string>
- negotiate() : Response<string|int, array<string, mixed>>|Error
- Probe for the modern era, falling back to the handshake unless the server proves to speak it.
- notifyCancellation() : void
- Tell the server an abandoned request's result will go unused. Only stdio and handshake-era HTTP need it: a modern connection signals by closing the response stream. Best effort — a send failure is logged, not raised.
- readDiscovery() : void
- Read defensively: nothing beyond the revisions is load-bearing.
- send() : void
- Encode and hand a message to the transport, stamping the per-request envelope on the way out when the revision calls for one.
- sendResponse() : void
- Send a response back to the server (for server-initiated requests).
- settleModern() : Response<string|int, array<string, mixed>>
- supportedVersions() : array<int, ProtocolVersion>
- withAcceptedVersion() : ProtocolVersion|null
- Switches the offered revision when the server refuses the current one, or null when there is nothing to retry with.
- withMeta() : array<string, mixed>
Constants
MAX_ROUND_TRIPS
How many times a request may be re-sent before the client gives up.
private
mixed
MAX_ROUND_TRIPS
= 10
Both loops that re-send are bounded by it: a server that keeps asking for input, and one that keeps rejecting the offered revision. Neither is expected to run more than a round or two, so the cap is only there to stop a broken or hostile server from spinning the client forever.
Properties
$envelope
Set only when the configured revision has no handshake.
private
RequestEnvelope|null
$envelope
= null
$headers
private
HeaderFactory|null
$headers
= null
$inputRequests read-only
private
InputRequestResolver
$inputRequests
$logger
private
LoggerInterface
$logger
$logLevel
private
LoggingLevel|null
$logLevel
= null
$messageFactory
private
MessageFactory
$messageFactory
$notificationHandlers
private
array<string|int, NotificationHandlerInterface>
$notificationHandlers
$onProgress
private
callable(float, Array, Array): void|null
$onProgress
$progressToken
The token of the request in flight, the only one whose progress reaches the callback.
private
string|null
$progressToken
= null
$progressTokens
Progress tokens are only required to be unique within a connection, and a retry keeps the caller's one — the work being reported on is the same.
private
int
$progressTokens
= 0
$requestHandlers read-only
private
array<string|int, mixed>
$requestHandlers
= []
$state
private
ClientStateInterface
$state
$tools
private
ToolCatalog
$tools
$transport
private
TransportInterface|null
$transport
= null
Methods
__construct()
public
__construct([array<string|int, RequestHandlerInterface<string|int, mixed>> $requestHandlers = [] ][, array<string|int, NotificationHandlerInterface> $notificationHandlers = [] ][, MessageFactory|null $messageFactory = null ][, LoggerInterface|null $logger = null ]) : mixed
Parameters
- $requestHandlers : array<string|int, RequestHandlerInterface<string|int, mixed>> = []
- $notificationHandlers : array<string|int, NotificationHandlerInterface> = []
- $messageFactory : MessageFactory|null = null
- $logger : LoggerInterface|null = null
connect()
Connect this protocol to a transport.
public
connect(TransportInterface $transport, Configuration $config) : void
Sets up message handling callbacks.
Parameters
- $transport : TransportInterface
-
The transport to connect
- $config : Configuration
-
The client configuration for initialization
getState()
public
getState() : ClientStateInterface
Return values
ClientStateInterfacegetToolCatalog()
What the client knows about the server's tools, from `tools/list`.
public
getToolCatalog() : ToolCatalog
Kept on the protocol rather than the facade because it is what makes the SEP-2243 headers derivable at send time.
Return values
ToolCataloginitialize()
Ready the connection for use, settling which protocol era it speaks.
public
initialize(Configuration $config) : Response<string|int, array<string, mixed>>|Error
Parameters
- $config : Configuration
-
The client configuration
Return values
Response<string|int, array<string, mixed>>|ErrorisModern()
public
isModern() : bool
Return values
boolprocessMessage()
Process an incoming message from the server.
public
processMessage(string $input) : void
Routes to appropriate handler based on message type.
Parameters
- $input : string
request()
Send a request to the server and wait for response.
public
request(Request $request, int $timeout[, bool $withProgress = false ][, CancellationTokenInterface|null $cancellation = null ][, float|null $callTimeout = null ]) : Response<string|int, array<string, mixed>>|Error
If a response is immediately available (sync HTTP), returns it. Otherwise, suspends the Fiber and waits for the transport to resume it.
In the modern era this is also where the two loops that re-send live: answering a server's request for input (SEP-2322), and retrying under a revision the server accepts (SEP-2575). Both re-send the same call, so they belong together and above the single exchange.
Parameters
- $request : Request
-
The request to send
- $timeout : int
-
The timeout in seconds
- $withProgress : bool = false
-
Whether to attach a progress token to the request
- $cancellation : CancellationTokenInterface|null = null
- $callTimeout : float|null = null
Return values
Response<string|int, array<string, mixed>>|ErrorsendNotification()
Send a notification to the server (fire and forget).
public
sendNotification(Notification $notification) : void
Parameters
- $notification : Notification
setLogLevel()
The modern era's stand-in for `logging/setLevel`.
public
setLogLevel(LoggingLevel $level) : void
Parameters
- $level : LoggingLevel
setProgressCallback()
Set the callback for progress on the request in flight, null to clear it.
public
setProgressCallback(callable(float $progress, Array $total, Array $message): void|null $onProgress) : void
Parameters
- $onProgress : callable(float $progress, Array $total, Array $message): void|null
adopt()
The modern connection, an error ending the attempt, or null to fall back.
private
adopt(Response<string|int, array<string, mixed>>|Error $probe) : Response<string|int, array<string, mixed>>|Error|null
Parameters
Return values
Response<string|int, array<string, mixed>>|Error|nulldeliverProgress()
private
deliverProgress(ProgressNotification $notification) : void
Parameters
- $notification : ProgressNotification
describe()
private
static describe(Response<string|int, array<string, mixed>>|Error $probe) : string
Parameters
Return values
stringenterModernEra()
private
enterModernEra(ProtocolVersion $version, Configuration $config) : void
Parameters
- $version : ProtocolVersion
- $config : Configuration
exchange()
One request on the wire: assign an id, send, and wait for its answer.
private
exchange(array<string, mixed> $payload, int $timeout[, CancellationTokenInterface|null $cancellation = null ][, float|null $deadline = null ]) : Response<string|int, array<string, mixed>>|Error
A retry gets a new id, because the previous one is spent — the server has already answered it, and reusing it would make the two indistinguishable.
Parameters
- $payload : array<string, mixed>
- $timeout : int
- $cancellation : CancellationTokenInterface|null = null
- $deadline : float|null = null
Return values
Response<string|int, array<string, mixed>>|ErrorforgetServer()
private
forgetServer() : void
handleNotification()
Handle a notification from the server.
private
handleNotification(Notification $notification) : void
Parameters
- $notification : Notification
handleRequest()
Handle a request from the server (e.g., sampling request).
private
handleRequest(Request $request) : void
Parameters
- $request : Request
handleResponse()
Handle a response from the server.
private
handleResponse(Response<string|int, mixed>|Error $response) : void
This stores it in session. The transport will pick it up and resume the Fiber.
Parameters
handshake()
private
handshake(ProtocolVersion $offered, Configuration $config) : Response<string|int, array<string, mixed>>|Error
Parameters
- $offered : ProtocolVersion
- $config : Configuration
Return values
Response<string|int, array<string, mixed>>|ErrorheadersFor()
The headers belonging to an encoded message, for a transport that has any.
private
headersFor(string $payload) : array<string, string>
Parameters
- $payload : string
Return values
array<string, string>interruption()
The interruption an in-flight request is subject to, if any. Checked on both sides of a send and after the transport resumes a suspended request.
private
static interruption(CancellationTokenInterface|null $cancellation, float|null $deadline) : RequestCancelledException|TimeoutException|null
Parameters
- $cancellation : CancellationTokenInterface|null
- $deadline : float|null
Tags
Return values
RequestCancelledException|TimeoutException|nullmutualModern()
The newest modern revision a refusal names that this client speaks.
private
static mutualModern(Error $error) : ProtocolVersion|null
Parameters
- $error : Error
Return values
ProtocolVersion|nullnamedVersions()
private
static namedVersions(Error $error) : array<int, string>
Parameters
- $error : Error
Return values
array<int, string>negotiate()
Probe for the modern era, falling back to the handshake unless the server proves to speak it.
private
negotiate(Configuration $config[, ProtocolVersion|null $version = null ][, bool $reprobed = false ]) : Response<string|int, array<string, mixed>>|Error
Parameters
- $config : Configuration
- $version : ProtocolVersion|null = null
- $reprobed : bool = false
Tags
Return values
Response<string|int, array<string, mixed>>|ErrornotifyCancellation()
Tell the server an abandoned request's result will go unused. Only stdio and handshake-era HTTP need it: a modern connection signals by closing the response stream. Best effort — a send failure is logged, not raised.
private
notifyCancellation(int $requestId, string $reason) : void
Parameters
- $requestId : int
- $reason : string
readDiscovery()
Read defensively: nothing beyond the revisions is load-bearing.
private
readDiscovery(array<string, mixed> $result) : void
Parameters
- $result : array<string, mixed>
send()
Encode and hand a message to the transport, stamping the per-request envelope on the way out when the revision calls for one.
private
send(array<string, mixed> $payload, string $kind) : void
Parameters
- $payload : array<string, mixed>
- $kind : string
Tags
sendResponse()
Send a response back to the server (for server-initiated requests).
private
sendResponse(Response<string|int, mixed>|Error $response) : void
Parameters
settleModern()
private
settleModern(Response<string|int, array<string, mixed>> $probe) : Response<string|int, array<string, mixed>>
Parameters
- $probe : Response<string|int, array<string, mixed>>
Return values
Response<string|int, array<string, mixed>>supportedVersions()
private
static supportedVersions(Error $error) : array<int, ProtocolVersion>
Parameters
- $error : Error
Return values
array<int, ProtocolVersion>withAcceptedVersion()
Switches the offered revision when the server refuses the current one, or null when there is nothing to retry with.
private
withAcceptedVersion(Error $error) : ProtocolVersion|null
Parameters
- $error : Error
-
the server's refusal
Return values
ProtocolVersion|nullwithMeta()
private
static withMeta(array<string, mixed> $payload, array<string, mixed> $meta) : array<string, mixed>
Parameters
- $payload : array<string, mixed>
- $meta : array<string, mixed>