Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/protocol-versions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 57 additions & 12 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -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
Expand All @@ -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);
}
Expand Down Expand Up @@ -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.
*
Expand Down
51 changes: 51 additions & 0 deletions tests/Integration/Fixture/tool_headers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?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.
*/

// 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;
use Mcp\Server\Server;
use Mcp\Server\Transport\StatelessHttpTransport;

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')
// 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));
138 changes: 138 additions & 0 deletions tests/Integration/ToolHeaderRetryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?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\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;
use Mcp\Tests\Support\ServerProcess;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;

/**
* A tool whose arguments go into Mcp-Param-* headers, called without listing the tools first.
*
* @author Diego D'amico
*/
final class ToolHeaderRetryTest extends TestCase
{
private const TIMEOUT = 5;

private ?Process $server = null;
private int $port;
private string $log;

protected function setUp(): void
{
$this->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<string, string> $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) ?: []);
}
}