diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..b3f847017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to `mcp/sdk` will be documented in this file. 0.11.0 ------ +### Client + +* Retry a tool call refused with `-32020` once, after listing the tools again, so a tool called without being listed gets its `Mcp-Param-*` headers; the listing and the retry share the call's timeout and cancellation. + ### Server * Fix const validation errors always reporting the expected value as null. diff --git a/docs/protocol-versions.md b/docs/protocol-versions.md index 5b29d1473..f36d8a6b3 100644 --- a/docs/protocol-versions.md +++ b/docs/protocol-versions.md @@ -178,7 +178,8 @@ What being modern changes underneath: - **Headers on every POST** — `MCP-Protocol-Version`, `Mcp-Method`, and `Mcp-Name` where the method addresses a subject. Arguments annotated with `x-mcp-header` are mirrored into `Mcp-Param-*`, which requires the client to have listed the tool first; `tools/list` is what - populates that knowledge. A tool whose annotations are malformed is dropped from the listing + populates that knowledge. A call the server refuses with `-32020` is retried once after + listing the tools again. A tool whose annotations are malformed is dropped from the listing and refused if called, since the client cannot produce the headers it demands. - **[Multi round-trip calls](handlers/input-required.md) are answered by the client.** A result of `resultType: "input_required"` is resolved through the same diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..2da643790 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -18,6 +18,7 @@ use Mcp\Client\Exception\RequestCancelledException; use Mcp\Client\Exception\RequestException; use Mcp\Client\Exception\RuntimeException; +use Mcp\Client\Exception\TimeoutException; use Mcp\Client\Transport\TransportInterface; use Mcp\Schema\Enum\LoggingLevel; use Mcp\Schema\Enum\ProtocolVersion; @@ -199,10 +200,15 @@ public function ping(): void * List available tools from the server. */ public function listTools(?string $cursor = null): ListToolsResult + { + return $this->listToolsPage($cursor); + } + + private function listToolsPage(?string $cursor, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): ListToolsResult { $request = new ListToolsRequest($cursor); - $response = $this->sendRequest($request); + $response = $this->sendRequest($request, null, $cancellation, $timeoutSeconds); $result = $response->result; @@ -228,10 +234,10 @@ public function listTools(?string $cursor = null): ListToolsResult * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress * Optional callback for progress updates * @param CancellationTokenInterface|null $cancellation Non-blocking cancellation signal - * @param float|null $timeoutSeconds Finite positive timeout replacing the default for this call + * @param float|null $timeoutSeconds Finite positive timeout replacing the default for this call, retry included * * @throws RequestCancelledException When cancellation is observed - * @throws Exception\TimeoutException When the request timeout is observed to have expired + * @throws TimeoutException When the request timeout is observed to have expired * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException */ public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult @@ -244,18 +250,24 @@ public function callTool(string $name, array $arguments = [], ?callable $onProgr throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.'); } - $catalog = $this->protocol->getToolCatalog(); + $this->refuseRejectedTool($name); - // A tool the listing showed to be malformed is refused here rather than - // sent: the client cannot produce the headers its annotations demand, - // so the call could only go out misdescribed (SEP-2243). - if ($catalog->isRejected($name)) { - throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $name, $catalog->reasonFor($name))); - } + // One deadline for the whole call: the listing and the retry only get what is left of it. + $deadline = microtime(true) + ($timeoutSeconds ?? $this->config->requestTimeout); - $request = new CallToolRequest($name, $arguments); + try { + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, self::remaining($deadline)); + } catch (RequestException $e) { + if (Error::HEADER_MISMATCH !== $e->getCode()) { + throw $e; + } - $response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds); + // The tool was never listed or its schema changed: list again and retry once (SEP-2243). + $this->recordTools($cancellation, $deadline); + $this->refuseRejectedTool($name); + + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, self::remaining($deadline)); + } return CallToolResult::fromArray($response->result); } @@ -402,6 +414,39 @@ public function sendRootsListChanged(): void $this->protocol->sendNotification(new RootsListChangedNotification()); } + // A malformed tool can't get the headers its annotations demand, so it is never sent (SEP-2243). + private function refuseRejectedTool(string $name): void + { + $catalog = $this->protocol->getToolCatalog(); + + if ($catalog->isRejected($name)) { + throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $name, $catalog->reasonFor($name))); + } + } + + private function recordTools(?CancellationTokenInterface $cancellation, float $deadline): void + { + $cursor = null; + + do { + $cursor = $this->listToolsPage($cursor, $cancellation, self::remaining($deadline))->nextCursor; + } while (null !== $cursor); + } + + /** + * @throws TimeoutException when nothing is left + */ + private static function remaining(float $deadline): float + { + $left = $deadline - microtime(true); + + if ($left <= 0) { + throw new TimeoutException('The request deadline expired.'); + } + + return $left; + } + /** * Send a request to the server and wait for response. * diff --git a/tests/Integration/Fixture/tool_headers.php b/tests/Integration/Fixture/tool_headers.php new file mode 100644 index 000000000..1648144a3 --- /dev/null +++ b/tests/Integration/Fixture/tool_headers.php @@ -0,0 +1,51 @@ +createServerRequestFromGlobals(); + +if ('tools/list' === (json_decode((string) file_get_contents('php://input'), true)['method'] ?? null)) { + if ('' !== $log = (string) getenv('MCP_FIXTURE_LOG')) { + file_put_contents($log, "tools/list\n", \FILE_APPEND); + } + usleep((int) ((float) getenv('MCP_FIXTURE_LIST_DELAY') * 1_000_000)); +} + +$server = Server::builder() + ->setServerInfo('tool-headers', '1.0.0') + // One tool per page, so listing takes more than one request. + ->setPaginationLimit(1) + ->addTool(static function (string $owner, string $repo): string { + usleep((int) ((float) getenv('MCP_FIXTURE_TOOL_DELAY') * 1_000_000)); + + return $owner.'/'.$repo; + }, name: 'list_issues', inputSchema: [ + 'type' => 'object', + 'properties' => [ + 'owner' => ['type' => 'string', 'x-mcp-header' => 'Owner'], + 'repo' => ['type' => 'string', 'x-mcp-header' => 'Repo'], + ], + 'required' => ['owner', 'repo'], + ]) + ->addTool(static fn (): string => 'pong', name: 'ping') + ->buildStateless(); + +(new SapiEmitter())->emit((new StatelessHttpTransport($server))->handle($request)); diff --git a/tests/Integration/ToolHeaderRetryTest.php b/tests/Integration/ToolHeaderRetryTest.php new file mode 100644 index 000000000..05bea002e --- /dev/null +++ b/tests/Integration/ToolHeaderRetryTest.php @@ -0,0 +1,138 @@ +log = (string) tempnam(sys_get_temp_dir(), 'mcp-tool-headers-'); + } + + protected function tearDown(): void + { + ServerProcess::stop($this->server); + @unlink($this->log); + } + + public function testACallRejectedForMissingHeadersIsRetriedAfterListingTheTools(): void + { + $client = $this->connect(); + + $result = $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex']); + + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('odiseoteam/reflex', $result->content[0]->text); + $this->assertSame(2, $this->listings(), 'Both pages of tools are listed before the retry.'); + + $client->disconnect(); + } + + public function testTheListingAndTheRetryShareTheCallsTimeout(): void + { + // Each page takes 0.5 s and the tool 0.8 s: listing leaves less than the tool needs. + $client = $this->connect(['MCP_FIXTURE_LIST_DELAY' => '0.5', 'MCP_FIXTURE_TOOL_DELAY' => '0.8']); + + $started = microtime(true); + try { + $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex'], timeoutSeconds: 1.5); + $this->fail('The retry should run out of the time the listing left.'); + } catch (TimeoutException) { + } + + $this->assertLessThan(2.0, microtime(true) - $started); + } + + public function testACancellationDuringTheListingStopsIt(): void + { + $client = $this->connect(['MCP_FIXTURE_LIST_DELAY' => '0.5']); + $cancellation = new class(microtime(true) + 0.2) implements CancellationTokenInterface { + public function __construct(private readonly float $at) + { + } + + public function isCancellationRequested(): bool + { + return microtime(true) >= $this->at; + } + }; + + try { + $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex'], cancellation: $cancellation); + $this->fail('The cancellation should stop the call.'); + } catch (RequestCancelledException) { + } + + $this->assertSame(1, $this->listings(), 'The second page is not requested once cancelled.'); + } + + /** + * @param array $env + */ + private function connect(array $env = []): Client + { + $this->port = ServerProcess::findFreePort(); + + $this->server = new Process( + [\PHP_BINARY, '-S', \sprintf('127.0.0.1:%d', $this->port), __DIR__.'/Fixture/tool_headers.php'], + env: ['MCP_FIXTURE_LOG' => $this->log, ...$env], + ); + $this->server->start(); + + $deadline = microtime(true) + 5; + + while (!@fsockopen('127.0.0.1', $this->port, $errno, $error, 0.1)) { + if (microtime(true) >= $deadline) { + $this->fail(\sprintf('The fixture server did not start: %s', $this->server->getErrorOutput())); + } + + usleep(50_000); + } + + $client = Client::builder() + ->setClientInfo('integration-client', '1.0.0') + ->setProtocolVersion(ProtocolVersion::V2026_07_28) + ->setInitTimeout(self::TIMEOUT) + ->setRequestTimeout(self::TIMEOUT) + ->build(); + $client->connect(new HttpTransport(\sprintf('http://127.0.0.1:%d/', $this->port))); + + return $client; + } + + private function listings(): int + { + return \count(file($this->log, \FILE_SKIP_EMPTY_LINES) ?: []); + } +}