From 18dfc32b6cb168eb3211b385134d0d10849d1403 Mon Sep 17 00:00:00 2001 From: Diego D'amico Date: Mon, 23 Nov 2026 13:29:46 -0300 Subject: [PATCH 1/2] [Client] Retry a tool call refused for its parameter headers after listing the tools The client only mirrors x-mcp-header arguments for tools it has listed, so a tool called without listing it first was refused with -32020. The spec asks the client to list the tools and retry in that case. --- CHANGELOG.md | 4 ++ docs/protocol-versions.md | 3 +- src/Client/Client.php | 40 +++++++++--- tests/Integration/Fixture/tool_headers.php | 33 ++++++++++ tests/Integration/ToolHeaderRetryTest.php | 76 ++++++++++++++++++++++ 5 files changed, 146 insertions(+), 10 deletions(-) create mode 100644 tests/Integration/Fixture/tool_headers.php create mode 100644 tests/Integration/ToolHeaderRetryTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..a58970530 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. + ### 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..df8f95cb4 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -244,18 +244,21 @@ 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))); - } + try { + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds); + } catch (RequestException $e) { + if (Error::HEADER_MISMATCH !== $e->getCode()) { + throw $e; + } - $request = new CallToolRequest($name, $arguments); + // The tool was never listed or its schema changed: list again and retry once (SEP-2243). + $this->recordTools(); + $this->refuseRejectedTool($name); - $response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds); + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds); + } return CallToolResult::fromArray($response->result); } @@ -402,6 +405,25 @@ 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(): void + { + $cursor = null; + + do { + $cursor = $this->listTools($cursor)->nextCursor; + } while (null !== $cursor); + } + /** * 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..8a663ec9b --- /dev/null +++ b/tests/Integration/Fixture/tool_headers.php @@ -0,0 +1,33 @@ +setServerInfo('tool-headers', '1.0.0') + ->addTool(static fn (string $owner, string $repo): string => $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'], + ]) + ->buildStateless(); + +(new SapiEmitter())->emit((new StatelessHttpTransport($server))->handle((new Psr17Factory())->createServerRequestFromGlobals())); diff --git a/tests/Integration/ToolHeaderRetryTest.php b/tests/Integration/ToolHeaderRetryTest.php new file mode 100644 index 000000000..34bfff662 --- /dev/null +++ b/tests/Integration/ToolHeaderRetryTest.php @@ -0,0 +1,76 @@ +port = ServerProcess::findFreePort(); + + $this->server = new Process([\PHP_BINARY, '-S', \sprintf('127.0.0.1:%d', $this->port), __DIR__.'/Fixture/tool_headers.php']); + $this->server->start(); + + $deadline = microtime(true) + 5; + + while (microtime(true) < $deadline) { + if (@fsockopen('127.0.0.1', $this->port, $errno, $error, 0.1)) { + return; + } + + usleep(50_000); + } + + $this->fail(\sprintf('The fixture server did not start: %s', $this->server->getErrorOutput())); + } + + protected function tearDown(): void + { + ServerProcess::stop($this->server); + } + + public function testACallRejectedForMissingHeadersIsRetriedAfterListingTheTools(): void + { + $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))); + + $result = $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex']); + + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('odiseoteam/reflex', $result->content[0]->text); + + $client->disconnect(); + } +} From e0107d4ae86c01135e229c1dcdbe8b1a23b99ad1 Mon Sep 17 00:00:00 2001 From: Diego D'amico Date: Thu, 26 Nov 2026 14:45:57 -0300 Subject: [PATCH 2/2] [Client] Share the call's deadline and cancellation with the retry listing The listing and the retry after a -32020 only get what is left of the call's timeout, so the call no longer blocks past it, and the listing observes the cancellation without changing listTools(). --- CHANGELOG.md | 2 +- src/Client/Client.php | 39 +++++++-- tests/Integration/Fixture/tool_headers.php | 22 ++++- tests/Integration/ToolHeaderRetryTest.php | 98 ++++++++++++++++++---- 4 files changed, 132 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a58970530..b3f847017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to `mcp/sdk` will be documented in this file. ### 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. +* 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 diff --git a/src/Client/Client.php b/src/Client/Client.php index df8f95cb4..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 @@ -246,18 +252,21 @@ public function callTool(string $name, array $arguments = [], ?callable $onProgr $this->refuseRejectedTool($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); + try { - $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds); + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, self::remaining($deadline)); } catch (RequestException $e) { if (Error::HEADER_MISMATCH !== $e->getCode()) { throw $e; } // The tool was never listed or its schema changed: list again and retry once (SEP-2243). - $this->recordTools(); + $this->recordTools($cancellation, $deadline); $this->refuseRejectedTool($name); - $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds); + $response = $this->sendRequest(new CallToolRequest($name, $arguments), $onProgress, $cancellation, self::remaining($deadline)); } return CallToolResult::fromArray($response->result); @@ -415,15 +424,29 @@ private function refuseRejectedTool(string $name): void } } - private function recordTools(): void + private function recordTools(?CancellationTokenInterface $cancellation, float $deadline): void { $cursor = null; do { - $cursor = $this->listTools($cursor)->nextCursor; + $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 index 8a663ec9b..1648144a3 100644 --- a/tests/Integration/Fixture/tool_headers.php +++ b/tests/Integration/Fixture/tool_headers.php @@ -10,6 +10,8 @@ */ // Server for ToolHeaderRetryTest under `php -S`: a tool that mirrors its arguments into Mcp-Param-* headers. +// MCP_FIXTURE_LIST_DELAY and MCP_FIXTURE_TOOL_DELAY slow down each tools/list page and the tool, in seconds; +// MCP_FIXTURE_LOG gets a line per tools/list request. use Http\Discovery\Psr17Factory; use Laminas\HttpHandlerRunner\Emitter\SapiEmitter; @@ -18,9 +20,24 @@ require_once dirname(__DIR__, 3).'/vendor/autoload.php'; +$request = (new Psr17Factory())->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') - ->addTool(static fn (string $owner, string $repo): string => $owner.'/'.$repo, name: 'list_issues', inputSchema: [ + // 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'], @@ -28,6 +45,7 @@ ], 'required' => ['owner', 'repo'], ]) + ->addTool(static fn (): string => 'pong', name: 'ping') ->buildStateless(); -(new SapiEmitter())->emit((new StatelessHttpTransport($server))->handle((new Psr17Factory())->createServerRequestFromGlobals())); +(new SapiEmitter())->emit((new StatelessHttpTransport($server))->handle($request)); diff --git a/tests/Integration/ToolHeaderRetryTest.php b/tests/Integration/ToolHeaderRetryTest.php index 34bfff662..05bea002e 100644 --- a/tests/Integration/ToolHeaderRetryTest.php +++ b/tests/Integration/ToolHeaderRetryTest.php @@ -11,7 +11,10 @@ namespace Mcp\Tests\Integration; +use Mcp\Client\CancellationTokenInterface; use Mcp\Client\Client; +use Mcp\Client\Exception\RequestCancelledException; +use Mcp\Client\Exception\TimeoutException; use Mcp\Client\Transport\HttpTransport; use Mcp\Schema\Content\TextContent; use Mcp\Schema\Enum\ProtocolVersion; @@ -30,34 +33,93 @@ final class ToolHeaderRetryTest extends TestCase private ?Process $server = null; private int $port; + private string $log; protected function setUp(): void { - $this->port = ServerProcess::findFreePort(); + $this->log = (string) tempnam(sys_get_temp_dir(), 'mcp-tool-headers-'); + } - $this->server = new Process([\PHP_BINARY, '-S', \sprintf('127.0.0.1:%d', $this->port), __DIR__.'/Fixture/tool_headers.php']); - $this->server->start(); + protected function tearDown(): void + { + ServerProcess::stop($this->server); + @unlink($this->log); + } - $deadline = microtime(true) + 5; + public function testACallRejectedForMissingHeadersIsRetriedAfterListingTheTools(): void + { + $client = $this->connect(); - while (microtime(true) < $deadline) { - if (@fsockopen('127.0.0.1', $this->port, $errno, $error, 0.1)) { - return; - } + $result = $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex']); - usleep(50_000); + $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->fail(\sprintf('The fixture server did not start: %s', $this->server->getErrorOutput())); + $this->assertLessThan(2.0, microtime(true) - $started); } - protected function tearDown(): void + public function testACancellationDuringTheListingStopsIt(): void { - ServerProcess::stop($this->server); + $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.'); } - public function testACallRejectedForMissingHeadersIsRetriedAfterListingTheTools(): void + /** + * @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) @@ -66,11 +128,11 @@ public function testACallRejectedForMissingHeadersIsRetriedAfterListingTheTools( ->build(); $client->connect(new HttpTransport(\sprintf('http://127.0.0.1:%d/', $this->port))); - $result = $client->callTool('list_issues', ['owner' => 'odiseoteam', 'repo' => 'reflex']); - - $this->assertInstanceOf(TextContent::class, $result->content[0]); - $this->assertSame('odiseoteam/reflex', $result->content[0]->text); + return $client; + } - $client->disconnect(); + private function listings(): int + { + return \count(file($this->log, \FILE_SKIP_EMPTY_LINES) ?: []); } }