diff --git a/src/Client/Protocol.php b/src/Client/Protocol.php index 7476ef68..2daa92f1 100644 --- a/src/Client/Protocol.php +++ b/src/Client/Protocol.php @@ -40,7 +40,9 @@ use Mcp\Schema\Notification\ProgressNotification; use Mcp\Schema\Request\DiscoverRequest; use Mcp\Schema\Request\InitializeRequest; +use Mcp\Schema\Request\PingRequest; use Mcp\Schema\RequestMeta; +use Mcp\Schema\Result\EmptyResult; use Mcp\Schema\Result\InitializeResult; use Mcp\Schema\ServerCapabilities; use Psr\Log\LoggerInterface; @@ -931,6 +933,13 @@ private function handleRequest(Request $request): void } } + // Either side may ping, and the receiver MUST answer with an empty result. + if ($request instanceof PingRequest) { + $this->sendResponse(new Response($request->getId(), new EmptyResult())); + + return; + } + $error = Error::forMethodNotFound( \sprintf('Client does not handle "%s" requests.', $method), $request->getId() diff --git a/tests/Unit/Client/ProtocolTest.php b/tests/Unit/Client/ProtocolTest.php index 5ebc8dcd..d2c05cd4 100644 --- a/tests/Unit/Client/ProtocolTest.php +++ b/tests/Unit/Client/ProtocolTest.php @@ -700,6 +700,22 @@ public function handle(Request $request): Response $this->assertInstanceOf(\JsonException::class, $logger->warnings[0]['exception'] ?? null); } + #[TestDox('answers a ping from the server with an empty result')] + public function testAnswersServerPingWithEmptyResult(): void + { + $messages = []; + $transport = $this->createMock(TransportInterface::class); + $transport->method('send')->willReturnCallback(static function (string $data) use (&$messages): void { + $messages[] = json_decode($data, true, flags: \JSON_THROW_ON_ERROR); + }); + $protocol = new Protocol(); + $protocol->connect($transport, $this->createConfiguration(ProtocolVersion::V2025_11_25)); + + $protocol->processMessage('{"jsonrpc": "2.0", "id": "srv-1", "method": "ping"}'); + + $this->assertSame([['jsonrpc' => '2.0', 'id' => 'srv-1', 'result' => []]], $messages); + } + private function createConfiguration(ProtocolVersion $protocolVersion, ?ProtocolVersion $fallback = ProtocolVersion::V2025_11_25): Configuration { return new Configuration(