diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..2ea5972da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ------ diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..8f2c9b28d 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\Stateless\InputRequestResolver; use Mcp\Client\Transport\TransportInterface; use Mcp\Schema\Enum\LoggingLevel; use Mcp\Schema\Enum\ProtocolVersion; @@ -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; @@ -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 $arguments + * @param array>|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 $arguments + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + * @param array{inputResponses?: \stdClass, requestState?: string}|null $round + * + * @return Response + */ + 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.'); @@ -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); } /** @@ -406,12 +451,13 @@ 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 * * @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()) { @@ -419,7 +465,7 @@ private function sendRequest(Request $request, ?callable $onProgress = null, ?Ca } $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 { diff --git a/src/Client/Protocol.php b/src/Client/Protocol.php index 7476ef68f..ce0218e56 100644 --- a/src/Client/Protocol.php +++ b/src/Client/Protocol.php @@ -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>|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) { @@ -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) { diff --git a/src/Client/Stateless/InputRequestResolver.php b/src/Client/Stateless/InputRequestResolver.php index d8e547beb..44611e9f2 100644 --- a/src/Client/Stateless/InputRequestResolver.php +++ b/src/Client/Stateless/InputRequestResolver.php @@ -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; @@ -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> + * @var array|class-string|class-string> */ private const RESOLVABLE = [ 'elicitation/create' => ElicitRequest::class, @@ -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 $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); + } + /** * Resolves every ask into the `inputResponses` map the retry carries. * @@ -107,6 +134,25 @@ public function resolve(array $inputRequests): array * @return array */ 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)); @@ -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; } /** diff --git a/tests/Integration/StatelessClientTest.php b/tests/Integration/StatelessClientTest.php index 75112ce16..87ee541c9 100644 --- a/tests/Integration/StatelessClientTest.php +++ b/tests/Integration/StatelessClientTest.php @@ -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; @@ -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; /** @@ -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 { @@ -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') @@ -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; }