[Client] Feat: Implement MCP client component (#192)

* feat(client): add complete MCP client SDK with STDIO and HTTP transports

Add Client, Builder, ClientProtocol, ClientSession, and transport
implementations for communicating with MCP servers. Supports tools, resources, prompts, and real-time progress/logging notifications.

* refactor(examples): reorganize examples into server/ and client/ folders

* feat: add SamplingRequestHandler for handling server sampling requests

* feat: add setLoggingLevel method to control server logging verbosity

* refactor: make progress token dependent on request ID

* docs: Update server IP in usage instructions and add notes on sampling server requirements.

* feat: add complete() method for completion/complete requests

* refactor: properly parse and type initialize result

* refactor: standardize method names

* fix: revert changes to server related components

* fix: revert changes to server related components

* refactor: Restructure client transports and handlers into dedicated namespaces.

* fix: cs and php-stan errors fixes(partial)

* feat: Refactor request handlers to return `Response` or `Error` objects directly, adding a `SamplingException` and error logging for sampling requests.

* feat: Replace `ClientTransportInterface` with `TransportInterface` and move response result deserialization to client methods.

* refactor: remove redundant timeout check for intialize on transports

The processFiber that executes per tick while fiber is suspended already handles timeouts while waiting

* feat: broaden symfony/http-client dependency to support Symfony 5.4 to 8.0

* Update examples/client/README.md

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>

* Update examples/client/README.md

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>

* refactor: remove outgoing message queue from session and simplify transport send method to directly dispatch messages.

* refactor: Replace ClientSession with ClientState for clearer intent on runtime state management

* refactor: rename connectAndInitialize to connect for consistency

* chore: cs fix

* chore: use SamplingCallbackInterface instead of a closure for sampling request handler

---------

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
This commit is contained in:
Kyrian Obikwelu 2026-03-10 17:22:40 +01:00 • committed by GitHub
commit 3ef864c444
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 2731 additions and 9 deletions

170
src/Client/Builder.php Normal file
View file

@ -0,0 +1,170 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client;
use Mcp\Client;
use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
use Mcp\Client\Handler\Request\RequestHandlerInterface;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Implementation;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Fluent builder for creating Client instances.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
final class Builder
{
private string $name = 'mcp-php-client';
private string $version = '1.0.0';
private ?string $description = null;
private ?ProtocolVersion $protocolVersion = null;
private ?ClientCapabilities $capabilities = null;
private int $initTimeout = 30;
private int $requestTimeout = 120;
private int $maxRetries = 3;
private ?LoggerInterface $logger = null;
/** @var NotificationHandlerInterface[] */
private array $notificationHandlers = [];
/** @var RequestHandlerInterface<mixed>[] */
private array $requestHandlers = [];
/**
* Set the client name and version.
*/
public function setClientInfo(string $name, string $version, ?string $description = null): self
{
$this->name = $name;
$this->version = $version;
$this->description = $description;
return $this;
}
/**
* Set the protocol version to use.
*/
public function setProtocolVersion(ProtocolVersion $protocolVersion): self
{
$this->protocolVersion = $protocolVersion;
return $this;
}
/**
* Set client capabilities.
*/
public function setCapabilities(ClientCapabilities $capabilities): self
{
$this->capabilities = $capabilities;
return $this;
}
/**
* Set initialization timeout in seconds.
*/
public function setInitTimeout(int $seconds): self
{
$this->initTimeout = $seconds;
return $this;
}
/**
* Set request timeout in seconds.
*/
public function setRequestTimeout(int $seconds): self
{
$this->requestTimeout = $seconds;
return $this;
}
/**
* Set maximum retry attempts for failed connections.
*/
public function setMaxRetries(int $retries): self
{
$this->maxRetries = $retries;
return $this;
}
/**
* Set the logger.
*/
public function setLogger(LoggerInterface $logger): self
{
$this->logger = $logger;
return $this;
}
/**
* Add a notification handler for server notifications.
*/
public function addNotificationHandler(NotificationHandlerInterface $handler): self
{
$this->notificationHandlers[] = $handler;
return $this;
}
/**
* Add a request handler for server requests (e.g., sampling).
*
* @param RequestHandlerInterface<mixed> $handler
*/
public function addRequestHandler(RequestHandlerInterface $handler): self
{
$this->requestHandlers[] = $handler;
return $this;
}
/**
* Build the client instance.
*/
public function build(): Client
{
$logger = $this->logger ?? new NullLogger();
$clientInfo = new Implementation(
$this->name,
$this->version,
$this->description,
);
$config = new Configuration(
clientInfo: $clientInfo,
capabilities: $this->capabilities ?? new ClientCapabilities(),
protocolVersion: $this->protocolVersion ?? ProtocolVersion::V2025_06_18,
initTimeout: $this->initTimeout,
requestTimeout: $this->requestTimeout,
maxRetries: $this->maxRetries,
);
$protocol = new Protocol(
requestHandlers: $this->requestHandlers,
notificationHandlers: $this->notificationHandlers,
logger: $logger,
);
return new Client($protocol, $config, $logger);
}
}

View file

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Implementation;
/**
* Client configuration holder.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Configuration
{
public function __construct(
public readonly Implementation $clientInfo,
public readonly ClientCapabilities $capabilities,
public readonly ProtocolVersion $protocolVersion = ProtocolVersion::V2025_06_18,
public readonly int $initTimeout = 30,
public readonly int $requestTimeout = 120,
public readonly int $maxRetries = 3,
) {
}
}

View file

@ -0,0 +1,43 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Notification;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Schema\Notification\LoggingMessageNotification;
/**
* Handler for logging message notifications from the server.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class LoggingNotificationHandler implements NotificationHandlerInterface
{
/**
* @param callable(LoggingMessageNotification): void $callback
*/
public function __construct(
private readonly mixed $callback,
) {
}
public function supports(Notification $notification): bool
{
return $notification instanceof LoggingMessageNotification;
}
public function handle(Notification $notification): void
{
\assert($notification instanceof LoggingMessageNotification);
($this->callback)($notification);
}
}

View file

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Notification;
use Mcp\Schema\JsonRpc\Notification;
/**
* Interface for handling notifications from the server.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
interface NotificationHandlerInterface
{
/**
* Check if this handler supports the given notification.
*/
public function supports(Notification $notification): bool;
/**
* Handle the notification.
*/
public function handle(Notification $notification): void;
}

View file

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Notification;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Schema\Notification\ProgressNotification;
/**
* Internal handler for progress notifications.
*
* Writes progress data to state for transport to consume and execute callbacks.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*
* @internal
*/
class ProgressNotificationHandler implements NotificationHandlerInterface
{
public function __construct(
private readonly ClientStateInterface $state,
) {
}
public function supports(Notification $notification): bool
{
return $notification instanceof ProgressNotification;
}
public function handle(Notification $notification): void
{
if (!$notification instanceof ProgressNotification) {
return;
}
$this->state->storeProgress(
(string) $notification->progressToken,
$notification->progress,
$notification->total,
$notification->message,
);
}
}

View file

@ -0,0 +1,38 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Request;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
/**
* Interface for handling requests from the server.
*
* @template TResult
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
interface RequestHandlerInterface
{
/**
* Check if this handler supports the given request.
*/
public function supports(Request $request): bool;
/**
* Handle the request and return a response or error.
*
* @return Response<TResult>|Error
*/
public function handle(Request $request): Response|Error;
}

View file

@ -0,0 +1,25 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Request;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
/**
* Contract for callbacks used by SamplingRequestHandler.
*
* Implementations perform the actual LLM sampling when requested by the server.
*/
interface SamplingCallbackInterface
{
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult;
}

View file

@ -0,0 +1,67 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Handler\Request;
use Mcp\Exception\SamplingException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Handler for sampling requests from the server.
*
* The MCP server may request the client to sample an LLM during tool execution.
* This handler wraps a user-provided callback that performs the actual LLM call.
*
* @implements RequestHandlerInterface<CreateSamplingMessageResult>
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class SamplingRequestHandler implements RequestHandlerInterface
{
public function __construct(
private readonly SamplingCallbackInterface $callback,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
public function supports(Request $request): bool
{
return $request instanceof CreateSamplingMessageRequest;
}
/**
* @return Response<CreateSamplingMessageResult>|Error
*/
public function handle(Request $request): Response|Error
{
\assert($request instanceof CreateSamplingMessageRequest);
try {
$result = $this->callback->__invoke($request);
return new Response($request->getId(), $result);
} catch (SamplingException $e) {
$this->logger->error('Sampling failed: '.$e->getMessage());
return Error::forInternalError($e->getMessage(), $request->getId());
} catch (\Throwable $e) {
$this->logger->error('Unexpected error during sampling', ['exception' => $e]);
return Error::forInternalError('Error while sampling LLM', $request->getId());
}
}
}

318
src/Client/Protocol.php Normal file
View file

@ -0,0 +1,318 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client;
use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
use Mcp\Client\Handler\Notification\ProgressNotificationHandler;
use Mcp\Client\Handler\Request\RequestHandlerInterface;
use Mcp\Client\State\ClientState;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Client\Transport\TransportInterface;
use Mcp\JsonRpc\MessageFactory;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Notification\InitializedNotification;
use Mcp\Schema\Request\InitializeRequest;
use Mcp\Schema\Result\InitializeResult;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Client protocol handler for MCP communication.
*
* Handles message routing, request/response correlation, and the initialization handshake.
* All blocking operations are delegated to the transport.
*
* @phpstan-import-type FiberSuspend from TransportInterface
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Protocol
{
private ?TransportInterface $transport = null;
private ClientStateInterface $state;
private MessageFactory $messageFactory;
private LoggerInterface $logger;
/** @var NotificationHandlerInterface[] */
private array $notificationHandlers;
/**
* @param RequestHandlerInterface<mixed>[] $requestHandlers
* @param NotificationHandlerInterface[] $notificationHandlers
*/
public function __construct(
private readonly array $requestHandlers = [],
array $notificationHandlers = [],
?MessageFactory $messageFactory = null,
?LoggerInterface $logger = null,
) {
$this->state = new ClientState();
$this->messageFactory = $messageFactory ?? MessageFactory::make();
$this->logger = $logger ?? new NullLogger();
$this->notificationHandlers = [
new ProgressNotificationHandler($this->state),
...$notificationHandlers,
];
}
/**
* Connect this protocol to a transport.
*
* Sets up message handling callbacks.
*
* @param TransportInterface $transport The transport to connect
* @param Configuration $config The client configuration for initialization
*/
public function connect(TransportInterface $transport, Configuration $config): void
{
$this->transport = $transport;
$transport->setState($this->state);
$transport->onInitialize(fn () => $this->initialize($config));
$transport->onMessage($this->processMessage(...));
$transport->onError(fn (\Throwable $e) => $this->logger->error('Transport error', ['exception' => $e]));
$this->logger->info('Protocol connected to transport', ['transport' => $transport::class]);
}
/**
* Perform the MCP initialization handshake.
*
* Sends InitializeRequest and waits for response, then sends InitializedNotification.
*
* @param Configuration $config The client configuration
*
* @return Response<array<string, mixed>>|Error
*/
public function initialize(Configuration $config): Response|Error
{
$request = new InitializeRequest(
$config->protocolVersion->value,
$config->capabilities,
$config->clientInfo,
);
$response = $this->request($request, $config->initTimeout);
if ($response instanceof Response) {
$initResult = InitializeResult::fromArray($response->result);
$this->state->setServerInfo($initResult->serverInfo);
$this->state->setInstructions($initResult->instructions);
$this->state->setInitialized(true);
$this->sendNotification(new InitializedNotification());
$this->logger->info('Initialization complete', [
'server' => $initResult->serverInfo->name,
]);
}
return $response;
}
/**
* Send a request to the server and wait for response.
*
* If a response is immediately available (sync HTTP), returns it.
* Otherwise, suspends the Fiber and waits for the transport to resume it.
*
* @param Request $request The request to send
* @param int $timeout The timeout in seconds
* @param bool $withProgress Whether to attach a progress token to the request
*
* @return Response<array<string, mixed>>|Error
*/
public function request(Request $request, int $timeout, bool $withProgress = false): Response|Error
{
$requestId = $this->state->nextRequestId();
$request = $request->withId($requestId);
if ($withProgress) {
$progressToken = "prog-{$requestId}";
$request = $request->withMeta(['progressToken' => $progressToken]);
}
$this->state->addPendingRequest($requestId, $timeout);
$this->sendRequest($request);
$immediate = $this->state->consumeResponse($requestId);
if (null !== $immediate) {
$this->logger->debug('Received immediate response', ['id' => $requestId]);
return $immediate;
}
$this->logger->debug('Suspending fiber for response', ['id' => $requestId]);
return \Fiber::suspend([
'type' => 'await_response',
'request_id' => $requestId,
'timeout' => $timeout,
]);
}
/**
* Send a request to the server.
*/
private function sendRequest(Request $request): void
{
$this->logger->debug('Sending request', [
'id' => $request->getId(),
'method' => $request::getMethod(),
]);
$encoded = json_encode($request, \JSON_THROW_ON_ERROR);
$this->transport?->send($encoded);
}
/**
* Send a notification to the server (fire and forget).
*/
public function sendNotification(Notification $notification): void
{
$this->logger->debug('Sending notification', ['method' => $notification::getMethod()]);
$encoded = json_encode($notification, \JSON_THROW_ON_ERROR);
$this->transport?->send($encoded);
}
/**
* Send a response back to the server (for server-initiated requests).
*
* @param Response<mixed>|Error $response
*/
private function sendResponse(Response|Error $response): void
{
$this->logger->debug('Sending response', ['id' => $response->getId()]);
$encoded = json_encode($response, \JSON_THROW_ON_ERROR);
$this->transport?->send($encoded);
}
/**
* Process an incoming message from the server.
*
* Routes to appropriate handler based on message type.
*/
public function processMessage(string $input): void
{
$this->logger->debug('Received message', ['input' => $input]);
try {
$messages = $this->messageFactory->create($input);
} catch (\JsonException $e) {
$this->logger->warning('Failed to parse message', ['exception' => $e]);
return;
}
foreach ($messages as $message) {
if ($message instanceof Response || $message instanceof Error) {
$this->handleResponse($message);
} elseif ($message instanceof Request) {
$this->handleRequest($message);
} elseif ($message instanceof Notification) {
$this->handleNotification($message);
}
}
}
/**
* Handle a response from the server.
*
* This stores it in session. The transport will pick it up and resume the Fiber.
*
* @param Response<mixed>|Error $response
*/
private function handleResponse(Response|Error $response): void
{
$requestId = $response->getId();
$this->logger->debug('Handling response', ['id' => $requestId]);
$this->state->storeResponse($requestId, $response->jsonSerialize());
}
/**
* Handle a request from the server (e.g., sampling request).
*/
private function handleRequest(Request $request): void
{
$method = $request::getMethod();
$this->logger->debug('Received server request', [
'method' => $method,
'id' => $request->getId(),
]);
foreach ($this->requestHandlers as $handler) {
if ($handler->supports($request)) {
try {
$response = $handler->handle($request);
} catch (\Throwable $e) {
$this->logger->error('Unexpected error while handling request', [
'method' => $method,
'exception' => $e,
]);
$response = Error::forInternalError(
\sprintf('Unexpected error while handling "%s" request', $method),
$request->getId()
);
}
$this->sendResponse($response);
return;
}
}
$error = Error::forMethodNotFound(
\sprintf('Client does not handle "%s" requests.', $method),
$request->getId()
);
$this->sendResponse($error);
}
/**
* Handle a notification from the server.
*/
private function handleNotification(Notification $notification): void
{
$method = $notification::getMethod();
$this->logger->debug('Received server notification', [
'method' => $method,
]);
foreach ($this->notificationHandlers as $handler) {
if ($handler->supports($notification)) {
try {
$handler->handle($notification);
} catch (\Throwable $e) {
$this->logger->warning('Notification handler failed', ['exception' => $e]);
}
return;
}
}
}
public function getState(): ClientStateInterface
{
return $this->state;
}
}

View file

@ -0,0 +1,136 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\State;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
/**
* In-memory client state implementation.
*
* Stores ephemeral runtime state for the client's connection to a server.
* This includes pending requests, responses, progress updates, and
* negotiated parameters from initialization.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ClientState implements ClientStateInterface
{
private int $requestIdCounter = 1;
private bool $initialized = false;
private ?Implementation $serverInfo = null;
private ?string $instructions = null;
/** @var array<int|string, array{request_id: int|string, timestamp: int, timeout: int}> */
private array $pendingRequests = [];
/** @var array<int|string, array<string, mixed>> */
private array $responses = [];
/** @var array<int, array{token: string, progress: float, total: ?float, message: ?string}> */
private array $progressUpdates = [];
public function nextRequestId(): int
{
return $this->requestIdCounter++;
}
public function addPendingRequest(int|string $requestId, int $timeout): void
{
$this->pendingRequests[$requestId] = [
'request_id' => $requestId,
'timestamp' => time(),
'timeout' => $timeout,
];
}
public function removePendingRequest(int|string $requestId): void
{
unset($this->pendingRequests[$requestId]);
}
public function getPendingRequests(): array
{
return $this->pendingRequests;
}
public function storeResponse(int|string $requestId, array $responseData): void
{
$this->responses[$requestId] = $responseData;
}
public function consumeResponse(int|string $requestId): Response|Error|null
{
if (!isset($this->responses[$requestId])) {
return null;
}
$data = $this->responses[$requestId];
unset($this->responses[$requestId]);
$this->removePendingRequest($requestId);
if (isset($data['error'])) {
return Error::fromArray($data);
}
return Response::fromArray($data);
}
public function setInitialized(bool $initialized): void
{
$this->initialized = $initialized;
}
public function isInitialized(): bool
{
return $this->initialized;
}
public function setServerInfo(Implementation $serverInfo): void
{
$this->serverInfo = $serverInfo;
}
public function getServerInfo(): ?Implementation
{
return $this->serverInfo;
}
public function setInstructions(?string $instructions): void
{
$this->instructions = $instructions;
}
public function getInstructions(): ?string
{
return $this->instructions;
}
public function storeProgress(string $token, float $progress, ?float $total, ?string $message): void
{
$this->progressUpdates[] = [
'token' => $token,
'progress' => $progress,
'total' => $total,
'message' => $message,
];
}
public function consumeProgressUpdates(): array
{
$updates = $this->progressUpdates;
$this->progressUpdates = [];
return $updates;
}
}

View file

@ -0,0 +1,115 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\State;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
/**
* Interface for client state management.
*
* Tracks pending requests, stores responses, and manages runtime state
* for the client's connection to a server. This is ephemeral state that
* exists only for the lifetime of the connection.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
interface ClientStateInterface
{
/**
* Get the next request ID for outgoing requests.
*/
public function nextRequestId(): int;
/**
* Add a pending request to track.
*
* @param int|string $requestId The request ID
* @param int $timeout Timeout in seconds
*/
public function addPendingRequest(int|string $requestId, int $timeout): void;
/**
* Remove a pending request.
*/
public function removePendingRequest(int|string $requestId): void;
/**
* Get all pending requests.
*
* @return array<int|string, array{request_id: int|string, timestamp: int, timeout: int}>
*/
public function getPendingRequests(): array;
/**
* Store a received response.
*
* @param int|string $requestId The request ID
* @param array<string, mixed> $responseData The raw response data
*/
public function storeResponse(int|string $requestId, array $responseData): void;
/**
* Check and consume a response for a request ID.
*
* @return Response<array<string, mixed>>|Error|null
*/
public function consumeResponse(int|string $requestId): Response|Error|null;
/**
* Set initialization state.
*/
public function setInitialized(bool $initialized): void;
/**
* Check if connection is initialized.
*/
public function isInitialized(): bool;
/**
* Store the server info from initialization.
*/
public function setServerInfo(Implementation $serverInfo): void;
/**
* Get the server info from initialization.
*/
public function getServerInfo(): ?Implementation;
/**
* Store the server instructions from initialization.
*/
public function setInstructions(?string $instructions): void;
/**
* Get the server instructions from initialization.
*/
public function getInstructions(): ?string;
/**
* Store progress data received from a notification.
*
* @param string $token The progress token
* @param float $progress Current progress value
* @param float|null $total Total progress value (if known)
* @param string|null $message Progress message
*/
public function storeProgress(string $token, float $progress, ?float $total, ?string $message): void;
/**
* Consume all pending progress updates.
*
* @return array<int, array{token: string, progress: float, total: ?float, message: ?string}>
*/
public function consumeProgressUpdates(): array;
}

View file

@ -0,0 +1,126 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Transport;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Exception\RuntimeException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Base implementation for client transports.
*
* Provides callback management and common utilities.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
abstract class BaseTransport implements TransportInterface
{
/** @var callable(): mixed|null */
protected $initializeCallback;
/** @var callable(string): void|null */
protected $messageCallback;
/** @var callable(\Throwable): void|null */
protected $errorCallback;
/** @var callable(string): void|null */
protected $closeCallback;
protected ?ClientStateInterface $state = null;
protected LoggerInterface $logger;
public function __construct(?LoggerInterface $logger = null)
{
$this->logger = $logger ?? new NullLogger();
}
public function onInitialize(callable $listener): void
{
$this->initializeCallback = $listener;
}
public function onMessage(callable $listener): void
{
$this->messageCallback = $listener;
}
public function onError(callable $listener): void
{
$this->errorCallback = $listener;
}
public function onClose(callable $listener): void
{
$this->closeCallback = $listener;
}
public function setState(ClientStateInterface $state): void
{
$this->state = $state;
}
/**
* Perform initialization via the registered callback.
*
* @return mixed The result from the initialization callback
*
* @throws RuntimeException If no initialize listener is registered
*/
protected function handleInitialize(): mixed
{
if (!\is_callable($this->initializeCallback)) {
throw new RuntimeException('No initialize listener registered');
}
return ($this->initializeCallback)();
}
/**
* Handle an incoming message from the server.
*/
protected function handleMessage(string $message): void
{
if (\is_callable($this->messageCallback)) {
try {
($this->messageCallback)($message);
} catch (\Throwable $e) {
$this->handleError($e);
}
}
}
/**
* Handle a transport error.
*/
protected function handleError(\Throwable $error): void
{
$this->logger->error('Transport error', ['exception' => $error]);
if (\is_callable($this->errorCallback)) {
($this->errorCallback)($error);
}
}
/**
* Handle connection close.
*/
protected function handleClose(string $reason): void
{
$this->logger->info('Transport closed', ['reason' => $reason]);
if (\is_callable($this->closeCallback)) {
($this->closeCallback)($reason);
}
}
}

View file

@ -0,0 +1,298 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Transport;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Mcp\Exception\ConnectionException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;
/**
* HTTP-based client transport using PSR-18 HTTP client.
*
* PSR-18 HTTP clients are auto-discovered if not provided.
*
* @phpstan-import-type McpFiber from TransportInterface
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class HttpTransport extends BaseTransport
{
private ClientInterface $httpClient;
private RequestFactoryInterface $requestFactory;
private StreamFactoryInterface $streamFactory;
private ?string $sessionId = null;
/** @var McpFiber|null */
private ?\Fiber $activeFiber = null;
/** @var (callable(float, ?float, ?string): void)|null */
private $activeProgressCallback;
/** @var StreamInterface|null Active SSE stream being read */
private ?StreamInterface $activeStream = null;
/** @var string Buffer for incomplete SSE data */
private string $sseBuffer = '';
/**
* @param string $endpoint The MCP server endpoint URL
* @param array<string, string> $headers Additional headers to send
* @param ClientInterface|null $httpClient PSR-18 HTTP client (auto-discovered if null)
* @param RequestFactoryInterface|null $requestFactory PSR-17 request factory (auto-discovered if null)
* @param StreamFactoryInterface|null $streamFactory PSR-17 stream factory (auto-discovered if null)
*/
public function __construct(
private readonly string $endpoint,
private readonly array $headers = [],
?ClientInterface $httpClient = null,
?RequestFactoryInterface $requestFactory = null,
?StreamFactoryInterface $streamFactory = null,
?LoggerInterface $logger = null,
) {
parent::__construct($logger);
$this->httpClient = $httpClient ?? Psr18ClientDiscovery::find();
$this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory();
$this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();
}
public function connect(): void
{
$this->activeFiber = new \Fiber(fn () => $this->handleInitialize());
$this->activeFiber->start();
while (!$this->activeFiber->isTerminated()) {
$this->tick();
}
$result = $this->activeFiber->getReturn();
$this->activeFiber = null;
if ($result instanceof Error) {
throw new ConnectionException('Initialization failed: '.$result->message);
}
$this->logger->info('HTTP client connected and initialized', ['endpoint' => $this->endpoint]);
}
public function send(string $data): void
{
$request = $this->requestFactory->createRequest('POST', $this->endpoint)
->withHeader('Content-Type', 'application/json')
->withHeader('Accept', 'application/json, text/event-stream')
->withBody($this->streamFactory->createStream($data));
if (null !== $this->sessionId) {
$request = $request->withHeader('Mcp-Session-Id', $this->sessionId);
}
foreach ($this->headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
$this->logger->debug('Sending HTTP request', ['data' => $data]);
try {
$response = $this->httpClient->sendRequest($request);
} catch (\Throwable $e) {
$this->handleError($e);
throw new ConnectionException('HTTP request failed: '.$e->getMessage(), 0, $e);
}
if ($response->hasHeader('Mcp-Session-Id')) {
$this->sessionId = $response->getHeaderLine('Mcp-Session-Id');
$this->logger->debug('Received session ID', ['session_id' => $this->sessionId]);
}
$contentType = $response->getHeaderLine('Content-Type');
if (str_contains($contentType, 'text/event-stream')) {
$this->activeStream = $response->getBody();
$this->sseBuffer = '';
} elseif (str_contains($contentType, 'application/json')) {
$body = $response->getBody()->getContents();
if (!empty($body)) {
$this->handleMessage($body);
}
}
}
/**
* @param McpFiber $fiber
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*/
public function runRequest(\Fiber $fiber, ?callable $onProgress = null): Response|Error
{
$this->activeFiber = $fiber;
$this->activeProgressCallback = $onProgress;
$fiber->start();
while (!$fiber->isTerminated()) {
$this->tick();
}
$this->activeFiber = null;
$this->activeProgressCallback = null;
$this->activeStream = null;
return $fiber->getReturn();
}
public function close(): void
{
if (null !== $this->sessionId) {
try {
$request = $this->requestFactory->createRequest('DELETE', $this->endpoint)
->withHeader('Mcp-Session-Id', $this->sessionId);
foreach ($this->headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
$this->httpClient->sendRequest($request);
$this->logger->info('Session closed', ['session_id' => $this->sessionId]);
} catch (\Throwable $e) {
$this->logger->warning('Failed to close session', ['error' => $e->getMessage()]);
}
}
$this->sessionId = null;
$this->activeStream = null;
$this->handleClose('Transport closed');
}
private function tick(): void
{
$this->processSSEStream();
$this->processProgress();
$this->processFiber();
usleep(1000); // 1ms
}
/**
* Read SSE data incrementally from active stream.
*/
private function processSSEStream(): void
{
if (null === $this->activeStream) {
return;
}
if (!$this->activeStream->eof()) {
$chunk = $this->activeStream->read(4096);
if ('' !== $chunk) {
$this->sseBuffer .= $chunk;
}
}
while (false !== ($pos = strpos($this->sseBuffer, "\n\n"))) {
$event = substr($this->sseBuffer, 0, $pos);
$this->sseBuffer = substr($this->sseBuffer, $pos + 2);
if (!empty(trim($event))) {
$this->processSSEEvent($event);
}
}
if ($this->activeStream->eof() && empty($this->sseBuffer)) {
$this->activeStream = null;
}
}
/**
* Parse a single SSE event and handle the message.
*/
private function processSSEEvent(string $event): void
{
$data = '';
foreach (explode("\n", $event) as $line) {
if (str_starts_with($line, 'data:')) {
$data .= trim(substr($line, 5));
}
}
if (!empty($data)) {
$this->handleMessage($data);
}
}
/**
* Process pending progress updates from session and execute callback.
*/
private function processProgress(): void
{
if (null === $this->activeProgressCallback || null === $this->state) {
return;
}
$updates = $this->state->consumeProgressUpdates();
foreach ($updates as $update) {
try {
($this->activeProgressCallback)(
$update['progress'],
$update['total'],
$update['message'],
);
} catch (\Throwable $e) {
$this->logger->warning('Progress callback failed', ['exception' => $e]);
}
}
}
private function processFiber(): void
{
if (null === $this->activeFiber || !$this->activeFiber->isSuspended()) {
return;
}
if (null === $this->state) {
return;
}
$pendingRequests = $this->state->getPendingRequests();
foreach ($pendingRequests as $pending) {
$requestId = $pending['request_id'];
$timestamp = $pending['timestamp'];
$timeout = $pending['timeout'];
$response = $this->state->consumeResponse($requestId);
if (null !== $response) {
$this->logger->debug('Resuming fiber with response', ['request_id' => $requestId]);
$this->activeFiber->resume($response);
return;
}
if (time() - $timestamp >= $timeout) {
$this->logger->warning('Request timed out', ['request_id' => $requestId]);
$error = Error::forInternalError('Request timed out', $requestId);
$this->activeFiber->resume($error);
return;
}
}
}
}

View file

@ -0,0 +1,289 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Transport;
use Mcp\Exception\ConnectionException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Psr\Log\LoggerInterface;
/**
* Client transport that spawns a child process and communicates via stdio.
*
* This transport handles all blocking operations:
* - Spawning the server process
* - Reading from stdout in a polling loop
* - Writing to stdin
* - Managing Fibers waiting for responses
*
* @phpstan-import-type McpFiber from TransportInterface
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class StdioTransport extends BaseTransport
{
/** @var resource|null */
private $process;
/** @var resource|null */
private $stdin;
/** @var resource|null */
private $stdout;
/** @var resource|null */
private $stderr;
private string $inputBuffer = '';
/** @var McpFiber|null */
private ?\Fiber $activeFiber = null;
/** @var (callable(float, ?float, ?string): void)|null */
private $activeProgressCallback;
/**
* @param string $command The command to run
* @param array<int, string> $args Command arguments
* @param string|null $cwd Working directory
* @param array<string, string>|null $env Environment variables
*/
public function __construct(
private readonly string $command,
private readonly array $args = [],
private readonly ?string $cwd = null,
private readonly ?array $env = null,
?LoggerInterface $logger = null,
) {
parent::__construct($logger);
}
public function connect(): void
{
$this->spawnProcess();
$this->activeFiber = new \Fiber(fn () => $this->handleInitialize());
$this->activeFiber->start();
while (!$this->activeFiber->isTerminated()) {
$this->tick();
}
$result = $this->activeFiber->getReturn();
$this->activeFiber = null;
if ($result instanceof Error) {
$this->close();
throw new ConnectionException('Initialization failed: '.$result->message);
}
$this->logger->info('Client connected and initialized');
}
public function send(string $data): void
{
if (null === $this->stdin || !\is_resource($this->stdin)) {
throw new ConnectionException('Process stdin not available');
}
fwrite($this->stdin, $data."\n");
fflush($this->stdin);
$this->logger->debug('Sent message to server', ['data' => $data]);
}
/**
* @param McpFiber $fiber
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*/
public function runRequest(\Fiber $fiber, ?callable $onProgress = null): Response|Error
{
$this->activeFiber = $fiber;
$this->activeProgressCallback = $onProgress;
$fiber->start();
while (!$fiber->isTerminated()) {
$this->tick();
}
$this->activeFiber = null;
$this->activeProgressCallback = null;
return $fiber->getReturn();
}
public function close(): void
{
if (\is_resource($this->stdin)) {
fclose($this->stdin);
$this->stdin = null;
}
if (\is_resource($this->stdout)) {
fclose($this->stdout);
$this->stdout = null;
}
if (\is_resource($this->stderr)) {
fclose($this->stderr);
$this->stderr = null;
}
if (\is_resource($this->process)) {
proc_terminate($this->process, 15); // SIGTERM
proc_close($this->process);
$this->process = null;
}
$this->handleClose('Transport closed');
}
private function spawnProcess(): void
{
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
];
$cmd = escapeshellcmd($this->command);
foreach ($this->args as $arg) {
$cmd .= ' '.escapeshellarg($arg);
}
$this->process = proc_open(
$cmd,
$descriptors,
$pipes,
$this->cwd,
$this->env
);
if (!\is_resource($this->process)) {
throw new ConnectionException('Failed to start process: '.$cmd);
}
$this->stdin = $pipes[0];
$this->stdout = $pipes[1];
$this->stderr = $pipes[2];
// Set non-blocking mode for reading
stream_set_blocking($this->stdout, false);
stream_set_blocking($this->stderr, false);
$this->logger->info('Started MCP server process', ['command' => $cmd]);
}
private function tick(): void
{
$this->processInput();
$this->processProgress();
$this->processFiber();
$this->processStderr();
usleep(1000); // 1ms
}
/**
* Process pending progress updates from session and execute callback.
*/
private function processProgress(): void
{
if (null === $this->activeProgressCallback || null === $this->state) {
return;
}
$updates = $this->state->consumeProgressUpdates();
foreach ($updates as $update) {
try {
($this->activeProgressCallback)(
$update['progress'],
$update['total'],
$update['message'],
);
} catch (\Throwable $e) {
$this->logger->warning('Progress callback failed', ['exception' => $e]);
}
}
}
private function processInput(): void
{
if (null === $this->stdout || !\is_resource($this->stdout)) {
return;
}
$data = fread($this->stdout, 8192);
if (false !== $data && '' !== $data) {
$this->inputBuffer .= $data;
}
while (false !== ($pos = strpos($this->inputBuffer, "\n"))) {
$line = substr($this->inputBuffer, 0, $pos);
$this->inputBuffer = substr($this->inputBuffer, $pos + 1);
$trimmed = trim($line);
if (!empty($trimmed)) {
$this->handleMessage($trimmed);
}
}
}
private function processFiber(): void
{
if (null === $this->activeFiber || !$this->activeFiber->isSuspended()) {
return;
}
if (null === $this->state) {
return;
}
$pendingRequests = $this->state->getPendingRequests();
foreach ($pendingRequests as $pending) {
$requestId = $pending['request_id'];
$timestamp = $pending['timestamp'];
$timeout = $pending['timeout'];
// Check if response arrived
$response = $this->state->consumeResponse($requestId);
if (null !== $response) {
$this->logger->debug('Resuming fiber with response', ['request_id' => $requestId]);
$this->activeFiber->resume($response);
return;
}
// Check timeout
if (time() - $timestamp >= $timeout) {
$this->logger->warning('Request timed out', ['request_id' => $requestId]);
$error = Error::forInternalError('Request timed out', $requestId);
$this->activeFiber->resume($error);
return;
}
}
}
private function processStderr(): void
{
if (null === $this->stderr || !\is_resource($this->stderr)) {
return;
}
$stderr = fread($this->stderr, 8192);
if (false !== $stderr && '' !== $stderr) {
$this->logger->debug('Server stderr', ['output' => trim($stderr)]);
}
}
}

View file

@ -0,0 +1,107 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client\Transport;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
/**
* Interface for client transports that communicate with MCP servers.
*
* The transport owns its execution loop and manages all blocking operations.
* The client delegates completely to the transport for I/O.
*
* @phpstan-type FiberReturn (Response<mixed>|Error)
* @phpstan-type FiberResume (Response<mixed>|Error)
* @phpstan-type FiberSuspend array{type: 'await_response', request_id: int, timeout: int}
* @phpstan-type McpFiber \Fiber<null, FiberResume, FiberReturn, FiberSuspend>
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
interface TransportInterface
{
/**
* Connect to the MCP server and perform initialization handshake.
*
* This method blocks until:
* - Initialization completes successfully
* - Connection fails (throws ConnectionException)
*
* @throws \Mcp\Exception\ConnectionException
*/
public function connect(): void;
/**
* Send a message to the server immediately.
*
* @param string $data JSON-encoded message
*/
public function send(string $data): void;
/**
* Run a request fiber to completion.
*
* The transport starts the fiber, runs its internal loop, and resumes
* the fiber when a response arrives or timeout occurs.
*
* During the loop, the transport checks session for progress data and
* executes the callback if provided.
*
* @param McpFiber $fiber The fiber to execute
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* Optional callback for progress updates
*
* @return Response<array<string, mixed>>|Error The response or error
*/
public function runRequest(\Fiber $fiber, ?callable $onProgress = null): Response|Error;
/**
* Close the transport and clean up resources.
*/
public function close(): void;
/**
* Register callback for initialization handshake.
*
* The callback should return a Fiber that performs the initialization.
*
* @param callable(): mixed $callback
*/
public function onInitialize(callable $callback): void;
/**
* Register callback for incoming messages from server.
*
* @param callable(string $message): void $callback
*/
public function onMessage(callable $callback): void;
/**
* Register callback for transport errors.
*
* @param callable(\Throwable $error): void $callback
*/
public function onError(callable $callback): void;
/**
* Register callback for when connection closes.
*
* @param callable(string $reason): void $callback
*/
public function onClose(callable $callback): void;
/**
* Set the client state for runtime state management.
*/
public function setState(ClientStateInterface $state): void;
}