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 @@ -9,6 +9,10 @@ All notable changes to `mcp/sdk` will be documented in this file.

* Fix const validation errors always reporting the expected value as null.

### Client

* Add `Client::callToolRound()` for the modern multi round-trip lifecycle: it returns the server's `InputRequiredResult` without resolving input, and a later call carrying the answers keyed by input request ID and the opaque `requestState` resumes it. `callTool()` keeps resolving input automatically, with its existing signature and return type.

0.10.0
------

Expand Down
56 changes: 51 additions & 5 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\Stateless\InputRequestResolver;
use Mcp\Client\Transport\TransportInterface;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Enum\ProtocolVersion;
Expand All @@ -42,10 +43,14 @@
use Mcp\Schema\ResourceReference;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\CompletionCompleteResult;
use Mcp\Schema\Result\CreateSamplingMessageResult;
use Mcp\Schema\Result\ElicitResult;
use Mcp\Schema\Result\GetPromptResult;
use Mcp\Schema\Result\InputRequiredResult;
use Mcp\Schema\Result\ListPromptsResult;
use Mcp\Schema\Result\ListResourcesResult;
use Mcp\Schema\Result\ListResourceTemplatesResult;
use Mcp\Schema\Result\ListRootsResult;
use Mcp\Schema\Result\ListToolsResult;
use Mcp\Schema\Result\ReadResourceResult;
use Mcp\Schema\ServerCapabilities;
Expand Down Expand Up @@ -235,6 +240,48 @@ public function listTools(?string $cursor = null): ListToolsResult
* @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException
*/
public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult
{
$response = $this->sendToolCall($name, $arguments, $onProgress, $cancellation, $timeoutSeconds);

return CallToolResult::fromArray($response->result);
}

/**
* Call a tool using the modern lifecycle and return its next result without resolving input automatically.
*
* To resume, call this method again with the original name and arguments,
* the answers keyed by input request ID, and the opaque state from the last result.
*
* @param array<string, mixed> $arguments
* @param array<array-key, ElicitResult|CreateSamplingMessageResult|ListRootsResult|array<string, mixed>>|null $inputResponses
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*
* @throws RequestCancelledException|Exception\TimeoutException
* @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException
*/
public function callToolRound(string $name, array $arguments = [], ?array $inputResponses = null, ?string $requestState = null, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult|InputRequiredResult
{
$round = [];
if (null !== $inputResponses) {
$round['inputResponses'] = (object) $inputResponses;
}
if (null !== $requestState) {
$round['requestState'] = $requestState;
}

$response = $this->sendToolCall($name, $arguments, $onProgress, $cancellation, $timeoutSeconds, $round);

return InputRequestResolver::parseResult($response->result) ?? CallToolResult::fromArray($response->result);
}

/**
* @param array<string, mixed> $arguments
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* @param array{inputResponses?: \stdClass, requestState?: string}|null $round
*
* @return Response<mixed>
*/
private function sendToolCall(string $name, array $arguments, ?callable $onProgress, ?CancellationTokenInterface $cancellation, ?float $timeoutSeconds, ?array $round = null): Response
{
if ($cancellation?->isCancellationRequested()) {
throw new RequestCancelledException('The client cancelled the request.');
Expand All @@ -255,9 +302,7 @@ public function callTool(string $name, array $arguments = [], ?callable $onProgr

$request = new CallToolRequest($name, $arguments);

$response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds);

return CallToolResult::fromArray($response->result);
return $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds, $round);
}

/**
Expand Down Expand Up @@ -406,20 +451,21 @@ public function sendRootsListChanged(): void
* Send a request to the server and wait for response.
*
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* @param array{inputResponses?: \stdClass, requestState?: string}|null $round
*
* @return Response<mixed>
*
* @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException
*/
private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response
private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null, ?array $round = null): Response
{
$transport = $this->transport;
if (null === $transport || !$this->protocol->getState()->isInitialized()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
}

$withProgress = null !== $onProgress;
$fiber = new \Fiber(fn () => $this->protocol->request($request, $this->config->requestTimeout, $withProgress, $cancellation, $timeoutSeconds ?? $this->config->requestTimeout));
$fiber = new \Fiber(fn () => $this->protocol->request($request, $this->config->requestTimeout, $withProgress, $cancellation, $timeoutSeconds ?? $this->config->requestTimeout, $round));
$this->protocol->setProgressCallback($onProgress);

try {
Expand Down
21 changes: 17 additions & 4 deletions src/Client/Protocol.php
Original file line number Diff line number Diff line change
Expand Up @@ -551,18 +551,27 @@ private static function describe(Response|Error $probe): string
* revision the server accepts (SEP-2575). Both re-send the same call, so
* they belong together and above the single exchange.
*
* @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
* @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
* @param array{inputResponses?: \stdClass, requestState?: string}|null $round Resume data for a multi round-trip call
*
* @return Response<array<string, mixed>>|Error
*/
public function request(Request $request, int $timeout, bool $withProgress = false, ?CancellationTokenInterface $cancellation = null, ?float $callTimeout = null): Response|Error
public function request(Request $request, int $timeout, bool $withProgress = false, ?CancellationTokenInterface $cancellation = null, ?float $callTimeout = null, ?array $round = null): Response|Error
{
if (null !== $round && null === $this->envelope) {
throw new InvalidArgumentException('Calling a tool one round at a time requires protocol revision 2026-07-28 or later.');
}

$deadline = null !== $callTimeout ? microtime(true) + $callTimeout : null;
$payload = $request->withId(0)->jsonSerialize();
unset($payload['id']);

if (null !== $round) {
$payload['params'] = [...(array) ($payload['params'] ?? []), ...$round];
}

$this->progressToken = $withProgress ? 'prog-'.++$this->progressTokens : null;

if (null !== $this->progressToken) {
Expand All @@ -587,6 +596,10 @@ public function request(Request $request, int $timeout, bool $withProgress = fal
continue;
}

if (null !== $round) {
return $response;
}

$asked = InputRequestResolver::asked($response->result);

if (null === $asked) {
Expand Down
68 changes: 50 additions & 18 deletions src/Client/Stateless/InputRequestResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Request\ElicitRequest;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\InputRequiredResult;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

Expand All @@ -42,7 +43,7 @@ final class InputRequestResolver
* The only requests a server may park in `inputRequests`. Anything else is
* a server fault, and answering it would be inventing protocol.
*
* @var array<string, class-string<Request>>
* @var array<string, class-string<ElicitRequest>|class-string<CreateSamplingMessageRequest>|class-string<ListRootsRequest>>
*/
private const RESOLVABLE = [
'elicitation/create' => ElicitRequest::class,
Expand Down Expand Up @@ -72,13 +73,39 @@ public function __construct(
*/
public static function asked(array $result): ?array
{
if (($result['resultType'] ?? null) !== 'input_required') {
if (($result['resultType'] ?? null) !== InputRequiredResult::RESULT_TYPE) {
return null;
}

return \is_array($result['inputRequests'] ?? null) ? $result['inputRequests'] : [];
}

/**
* @param array<string, mixed> $result
*
* @throws RuntimeException when the server sent an ask that cannot be parsed, or an "input_required" result without input requests or state
*/
public static function parseResult(array $result): ?InputRequiredResult
{
$asked = self::asked($result);
if (null === $asked) {
return null;
}

$requests = [];
foreach ($asked as $key => $ask) {
$requests[$key] = self::parseRequest((string) $key, $ask);
}

$state = $result['requestState'] ?? null;

if ([] === $requests && !\is_string($state)) {
throw new RuntimeException(\sprintf('Server answered "%s" without input requests or a state to resume.', InputRequiredResult::RESULT_TYPE));
}

return new InputRequiredResult($requests, \is_string($state) ? $state : null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the server answers input_required with no requests and no state, this throws a Schema InvalidArgumentException, while the auto path throws a client RuntimeException on server faults. Maybe check it here and throw the same one?

}

/**
* Resolves every ask into the `inputResponses` map the retry carries.
*
Expand Down Expand Up @@ -107,6 +134,25 @@ public function resolve(array $inputRequests): array
* @return array<string, mixed>
*/
private function answer(string $key, mixed $ask): array
{
$request = self::parseRequest($key, $ask);
$method = $request::getMethod();

$this->logger->debug('Resolving multi round-trip input request', [
'key' => $key,
'method' => $method,
]);

$result = $this->dispatch($request);

if ($result instanceof Error) {
throw new RuntimeException(\sprintf('Cannot answer the server\'s "%s" input request under "%s": %s', $method, $key, $result->message));
}

return $result;
}

private static function parseRequest(string $key, mixed $ask): ElicitRequest|CreateSamplingMessageRequest|ListRootsRequest
{
if (!\is_array($ask) || !\is_string($ask['method'] ?? null)) {
throw new RuntimeException(\sprintf('Server asked for input under "%s" without a method to answer.', $key));
Expand All @@ -125,27 +171,13 @@ private function answer(string $key, mixed $ask): array
}

// The ask is a bare method/params pair, but the handlers speak in
// messages. The id never reaches the wire — the answer is keyed by
// $key — so any id will do.
$request = $class::fromArray([
// messages, so use the map key as the local message id.
return $class::fromArray([
'jsonrpc' => '2.0',
'id' => $key,
'method' => $method,
'params' => \is_array($params) ? $params : null,
]);

$this->logger->debug('Resolving multi round-trip input request', [
'key' => $key,
'method' => $method,
]);

$result = $this->dispatch($request);

if ($result instanceof Error) {
throw new RuntimeException(\sprintf('Cannot answer the server\'s "%s" input request under "%s": %s', $method, $key, $result->message));
}

return $result;
}

/**
Expand Down
52 changes: 50 additions & 2 deletions tests/Integration/StatelessClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Mcp\Tests\Integration;

use Http\Discovery\Psr18ClientDiscovery;
use Mcp\Client\Client;
use Mcp\Client\Handler\Request\RequestHandlerInterface;
use Mcp\Client\Transport\HttpTransport;
Expand All @@ -23,9 +24,13 @@
use Mcp\Schema\Request\ElicitRequest;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\ElicitResult;
use Mcp\Schema\Result\InputRequiredResult;
use Mcp\Tests\Support\ServerProcess;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Process\Process;

/**
Expand Down Expand Up @@ -113,6 +118,49 @@ public function testMultiRoundTripIsTransparentToTheCaller(): void
$client->disconnect();
}

#[TestDox('defers and resumes tool input')]
public function testDefersAndResumesToolInput(): void
{
$calls = [];
$httpClient = $this->createMock(ClientInterface::class);
$delegate = Psr18ClientDiscovery::find();
$httpClient->method('sendRequest')->willReturnCallback(static function (RequestInterface $request) use (&$calls, $delegate): ResponseInterface {
$body = json_decode((string) $request->getBody(), flags: \JSON_THROW_ON_ERROR);
if ('tools/call' === ($body->method ?? null)) {
$calls[] = $body;
}

return $delegate->sendRequest($request);
});

$client = $this->connect(elicitation: true, httpClient: $httpClient);

$pending = $client->callToolRound('greet');

$this->assertInstanceOf(InputRequiredResult::class, $pending, 'Received '.get_debug_type($pending).' instead of being able to defer the tool call.');
$this->assertInstanceOf(ElicitRequest::class, $pending->inputRequests['who']);
$this->assertSame('What name should the greeting use?', $pending->inputRequests['who']->message);
$this->assertNotNull($pending->requestState);
$this->assertCount(1, $calls);
$this->assertObjectNotHasProperty('inputResponses', $calls[0]->params);
$this->assertObjectNotHasProperty('requestState', $calls[0]->params);

$result = $client->callToolRound(
'greet',
inputResponses: ['who' => new ElicitResult(ElicitAction::Accept, ['name' => 'Grace'])],
requestState: $pending->requestState,
);

$this->assertInstanceOf(CallToolResult::class, $result);
$this->assertSame('Hello, Grace!', self::text($result));
$this->assertCount(2, $calls);
$this->assertNotSame($calls[0]->id, $calls[1]->id);
$this->assertSame($pending->requestState, $calls[1]->params->requestState);
$this->assertSame('Grace', $calls[1]->params->inputResponses->who->content->name);

$client->disconnect();
}

#[TestDox('a capability the client never declared is refused up front, and costs only that call')]
public function testUndeclaredCapabilityIsRefused(): void
{
Expand Down Expand Up @@ -143,7 +191,7 @@ private static function text(CallToolResult $result): string
return $first->text;
}

private function connect(bool $elicitation = false): Client
private function connect(bool $elicitation = false, ?ClientInterface $httpClient = null): Client
{
$builder = Client::builder()
->setClientInfo('stateless-integration-client', '1.0.0')
Expand All @@ -166,7 +214,7 @@ public function handle(Request $request): Response
}

$client = $builder->build();
$client->connect(new HttpTransport(\sprintf('http://127.0.0.1:%d/', $this->port)));
$client->connect(new HttpTransport(\sprintf('http://127.0.0.1:%d/', $this->port), httpClient: $httpClient));

return $client;
}
Expand Down