From 7d1d71af29fa16e142dbc3ea3aa7d4476187e4ed Mon Sep 17 00:00:00 2001 From: wangshun <96341168+xixi-box@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:03:35 +0000 Subject: [PATCH] Add opt-in task polling and input responses to the PHP client Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com> --- docs/protocol-versions.md | 4 +- docs/run/protocol-eras.md | 2 +- src/Client/Builder.php | 2 +- src/Client/Client.php | 49 ++++--- src/Client/Task/TaskClient.php | 102 ++++++++++++++ .../Extension/Tasks/CancelTaskRequest.php | 48 +++++++ .../Extension/Tasks/CreateTaskResult.php | 64 +++++++++ src/Schema/Extension/Tasks/GetTaskRequest.php | 48 +++++++ src/Schema/Extension/Tasks/Task.php | 125 ++++++++++++++++++ src/Schema/Extension/Tasks/TasksExtension.php | 40 ++++++ .../Extension/Tasks/UpdateTaskRequest.php | 87 ++++++++++++ tests/Integration/Fixture/tasks.php | 107 +++++++++++++++ tests/Integration/TasksTest.php | 125 ++++++++++++++++++ .../Client/Stateless/HeaderFactoryTest.php | 13 ++ .../Extension/Tasks/TasksExtensionTest.php | 73 ++++++++++ 15 files changed, 867 insertions(+), 22 deletions(-) create mode 100644 src/Client/Task/TaskClient.php create mode 100644 src/Schema/Extension/Tasks/CancelTaskRequest.php create mode 100644 src/Schema/Extension/Tasks/CreateTaskResult.php create mode 100644 src/Schema/Extension/Tasks/GetTaskRequest.php create mode 100644 src/Schema/Extension/Tasks/Task.php create mode 100644 src/Schema/Extension/Tasks/TasksExtension.php create mode 100644 src/Schema/Extension/Tasks/UpdateTaskRequest.php create mode 100644 tests/Integration/Fixture/tasks.php create mode 100644 tests/Integration/TasksTest.php create mode 100644 tests/Unit/Schema/Extension/Tasks/TasksExtensionTest.php diff --git a/docs/protocol-versions.md b/docs/protocol-versions.md index 5b29d1473..1d598670a 100644 --- a/docs/protocol-versions.md +++ b/docs/protocol-versions.md @@ -217,7 +217,9 @@ Also gone: `Mcp-Session-Id`, the HTTP `GET` stream, and SSE resumability (`Last- A broken response stream loses the request; the client re-issues it with a new id. This revision also removes `notifications/elicitation/complete` and the `elicitationId` field, and -moves tasks to the `io.modelcontextprotocol/tasks` extension. The SDK implements none of these. +moves tasks to the `io.modelcontextprotocol/tasks` extension. A client can enable it with +`Client::builder()->enableExtension(new TasksExtension())` and use `TaskClient` to poll handle +status, answer input requests and cancel tasks. Error code `-32002` (resource not found) is retired in favour of `-32602`, and must not be emitted by a server of this revision. The SDK picks the code from the revision serving the diff --git a/docs/run/protocol-eras.md b/docs/run/protocol-eras.md index 0cf66980f..c359186dc 100644 --- a/docs/run/protocol-eras.md +++ b/docs/run/protocol-eras.md @@ -49,7 +49,7 @@ Plus `Mcp-Method` on every request, and `Mcp-Name` on `tools/call`, `prompts/get with the body is refused with `-32020`; a missing required `_meta` member with `-32602`; an unsupported version with `-32022`, carrying the supported set for the client to retry from. -The SDK only checks the `Mcp-Name` header of the `tasks/*` methods. It doesn't implement these methods. +The SDK's `TaskClient` sends the `tasks/*` requests. The server validates their `Mcp-Name` headers. What a handler can read off all this is [Talking back to the client](../handlers/client-communication.md#request-metadata). diff --git a/src/Client/Builder.php b/src/Client/Builder.php index 745070085..3211ff4ad 100644 --- a/src/Client/Builder.php +++ b/src/Client/Builder.php @@ -97,7 +97,7 @@ public function setCapabilities(ClientCapabilities $capabilities): self /** * Enable one or more MCP protocol extensions, announced to the server under - * `capabilities.extensions` in the initialize request. + * `capabilities.extensions` in modern request metadata or in the initialize request. * * @throws InvalidArgumentException if the identifier is not a valid `_meta` prefix * @throws LogicException if the same extension is enabled more than once diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..e3dedff6b 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -236,23 +236,6 @@ public function listTools(?string $cursor = null): ListToolsResult */ public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult { - if ($cancellation?->isCancellationRequested()) { - throw new RequestCancelledException('The client cancelled the request.'); - } - - if (null !== $timeoutSeconds && (!is_finite($timeoutSeconds) || $timeoutSeconds <= 0)) { - throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.'); - } - - $catalog = $this->protocol->getToolCatalog(); - - // 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))); - } - $request = new CallToolRequest($name, $arguments); $response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds); @@ -403,16 +386,44 @@ public function sendRootsListChanged(): void } /** - * Send a request to the server and wait for response. + * Send a core or extension request and return the server response. * * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress * * @return Response * - * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException + * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException + * @throws RequestCancelledException|Exception\TimeoutException + */ + public function request(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response + { + return $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds); + } + + /** + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + * + * @return Response */ private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response { + if ($cancellation?->isCancellationRequested()) { + throw new RequestCancelledException('The client cancelled the request.'); + } + + if (null !== $timeoutSeconds && (!is_finite($timeoutSeconds) || $timeoutSeconds <= 0)) { + throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.'); + } + + if ($request instanceof CallToolRequest) { + $catalog = $this->protocol->getToolCatalog(); + + // A tool with invalid annotations cannot be sent with the headers it requires (SEP-2243). + if ($catalog->isRejected($request->name)) { + throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $request->name, $catalog->reasonFor($request->name))); + } + } + $transport = $this->transport; if (null === $transport || !$this->protocol->getState()->isInitialized()) { throw new ConnectionException('Client is not connected. Call connect() first.'); diff --git a/src/Client/Task/TaskClient.php b/src/Client/Task/TaskClient.php new file mode 100644 index 000000000..a90096e81 --- /dev/null +++ b/src/Client/Task/TaskClient.php @@ -0,0 +1,102 @@ + $arguments + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + */ + public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult|CreateTaskResult + { + $result = $this->client->request(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds)->result; + + return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null) + ? CreateTaskResult::fromArray($result) + : CallToolResult::fromArray($result); + } + + /** + * @param array $arguments + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + */ + public function getPrompt(string $name, array $arguments = [], ?callable $onProgress = null): GetPromptResult|CreateTaskResult + { + $result = $this->client->request(new GetPromptRequest($name, $arguments), $onProgress)->result; + + return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null) + ? CreateTaskResult::fromArray($result) + : GetPromptResult::fromArray($result); + } + + /** + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + */ + public function readResource(string $uri, ?callable $onProgress = null): ReadResourceResult|CreateTaskResult + { + if ('' === $uri) { + throw new InvalidArgumentException('Resource URI must not be empty.'); + } + + $result = $this->client->request(new ReadResourceRequest($uri), $onProgress)->result; + + return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null) + ? CreateTaskResult::fromArray($result) + : ReadResourceResult::fromArray($result); + } + + public function get(string $taskId): Task + { + return Task::fromArray($this->client->request(new GetTaskRequest($taskId))->result); + } + + /** + * @param array|ResultInterface> $inputResponses responses keyed by the server's input request IDs + */ + public function update(string $taskId, array $inputResponses): void + { + $this->client->request(new UpdateTaskRequest($taskId, $inputResponses)); + } + + public function cancel(string $taskId): void + { + $this->client->request(new CancelTaskRequest($taskId)); + } +} diff --git a/src/Schema/Extension/Tasks/CancelTaskRequest.php b/src/Schema/Extension/Tasks/CancelTaskRequest.php new file mode 100644 index 000000000..95e9c7fbb --- /dev/null +++ b/src/Schema/Extension/Tasks/CancelTaskRequest.php @@ -0,0 +1,48 @@ + $this->taskId]; + } +} diff --git a/src/Schema/Extension/Tasks/CreateTaskResult.php b/src/Schema/Extension/Tasks/CreateTaskResult.php new file mode 100644 index 000000000..83587c0ef --- /dev/null +++ b/src/Schema/Extension/Tasks/CreateTaskResult.php @@ -0,0 +1,64 @@ +|null $meta + */ + public function __construct( + public readonly Task $task, + public readonly ?array $meta = null, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + if (self::RESULT_TYPE !== ($data['resultType'] ?? null)) { + throw new InvalidArgumentException('Missing or invalid "resultType" in task creation result.'); + } + + if (isset($data['_meta']) && !\is_array($data['_meta']) && !$data['_meta'] instanceof \stdClass) { + throw new InvalidArgumentException('Invalid "_meta" in task creation result.'); + } + + return new self(Task::fromArray($data), isset($data['_meta']) ? (array) $data['_meta'] : null); + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + $data = ['resultType' => self::RESULT_TYPE, ...$this->task->jsonSerialize()]; + + if (null !== $this->meta) { + $data['_meta'] = (object) $this->meta; + } + + return $data; + } +} diff --git a/src/Schema/Extension/Tasks/GetTaskRequest.php b/src/Schema/Extension/Tasks/GetTaskRequest.php new file mode 100644 index 000000000..99e0537cf --- /dev/null +++ b/src/Schema/Extension/Tasks/GetTaskRequest.php @@ -0,0 +1,48 @@ + $this->taskId]; + } +} diff --git a/src/Schema/Extension/Tasks/Task.php b/src/Schema/Extension/Tasks/Task.php new file mode 100644 index 000000000..845db9827 --- /dev/null +++ b/src/Schema/Extension/Tasks/Task.php @@ -0,0 +1,125 @@ +|null $result the original method's result, available on completion + * @param array|null $error the JSON-RPC error, available on failure + * @param array|null $inputRequests server-assigned keys mapped to method/params pairs + */ + public function __construct( + public readonly string $taskId, + public readonly string $status, + public readonly string $createdAt, + public readonly string $lastUpdatedAt, + public readonly ?int $ttlMs, + public readonly ?string $statusMessage = null, + public readonly ?int $pollIntervalMs = null, + public readonly ?array $result = null, + public readonly ?array $error = null, + public readonly ?array $inputRequests = null, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + foreach (['taskId', 'status', 'createdAt', 'lastUpdatedAt'] as $member) { + if (!\is_string($data[$member] ?? null)) { + throw new InvalidArgumentException(\sprintf('Missing or invalid "%s" in task data.', $member)); + } + } + + if (!\array_key_exists('ttlMs', $data) || null !== $data['ttlMs'] && !\is_int($data['ttlMs'])) { + throw new InvalidArgumentException('Missing or invalid "ttlMs" in task data.'); + } + + if (isset($data['statusMessage']) && !\is_string($data['statusMessage'])) { + throw new InvalidArgumentException('Invalid "statusMessage" in task data.'); + } + + if (isset($data['pollIntervalMs']) && !\is_int($data['pollIntervalMs'])) { + throw new InvalidArgumentException('Invalid "pollIntervalMs" in task data.'); + } + + foreach (['result', 'error', 'inputRequests'] as $member) { + if (isset($data[$member]) && !\is_array($data[$member]) && !$data[$member] instanceof \stdClass) { + throw new InvalidArgumentException(\sprintf('Invalid "%s" in task data.', $member)); + } + } + + return new self( + $data['taskId'], + $data['status'], + $data['createdAt'], + $data['lastUpdatedAt'], + $data['ttlMs'], + $data['statusMessage'] ?? null, + $data['pollIntervalMs'] ?? null, + isset($data['result']) ? (array) $data['result'] : null, + isset($data['error']) ? (array) $data['error'] : null, + isset($data['inputRequests']) ? (array) $data['inputRequests'] : null, + ); + } + + /** + * @return array{ + * taskId: string, + * status: string, + * createdAt: string, + * lastUpdatedAt: string, + * ttlMs: int|null, + * statusMessage?: string, + * pollIntervalMs?: int, + * result?: \stdClass, + * error?: \stdClass, + * inputRequests?: \stdClass, + * } + */ + public function jsonSerialize(): array + { + $data = [ + 'taskId' => $this->taskId, + 'status' => $this->status, + 'createdAt' => $this->createdAt, + 'lastUpdatedAt' => $this->lastUpdatedAt, + 'ttlMs' => $this->ttlMs, + ]; + + if (null !== $this->statusMessage) { + $data['statusMessage'] = $this->statusMessage; + } + + if (null !== $this->pollIntervalMs) { + $data['pollIntervalMs'] = $this->pollIntervalMs; + } + + foreach (['result', 'error', 'inputRequests'] as $member) { + if (null !== $this->$member) { + $data[$member] = (object) $this->$member; + } + } + + return $data; + } +} diff --git a/src/Schema/Extension/Tasks/TasksExtension.php b/src/Schema/Extension/Tasks/TasksExtension.php new file mode 100644 index 000000000..13e23ec98 --- /dev/null +++ b/src/Schema/Extension/Tasks/TasksExtension.php @@ -0,0 +1,40 @@ +|\stdClass|ResultInterface> $inputResponses + */ + public function __construct( + public readonly string $taskId, + public readonly array $inputResponses, + ) { + } + + public static function getMethod(): string + { + return 'tasks/update'; + } + + public static function requiresJsonTypes(): bool + { + return true; + } + + protected static function paramsToArray(\stdClass $params): array + { + $data = parent::paramsToArray($params); + if (isset($params->inputResponses)) { + $data['inputResponses'] = $params->inputResponses; + } + + return $data; + } + + protected static function fromParams(?array $params): static + { + if (!\is_string($params['taskId'] ?? null)) { + throw new InvalidArgumentException('Missing or invalid "taskId" parameter for tasks/update.'); + } + + $inputResponses = $params['inputResponses'] ?? null; + if (!$inputResponses instanceof \stdClass) { + throw new InvalidArgumentException('Parameter "inputResponses" must be an object.'); + } + + $responses = []; + foreach ((array) $inputResponses as $key => $response) { + if (!$response instanceof \stdClass) { + throw new InvalidArgumentException('Each entry in "inputResponses" must be an object.'); + } + + $responses[$key] = $response; + } + + return new self($params['taskId'], $responses); + } + + /** + * @return array{taskId: string, inputResponses: \stdClass} + */ + protected function getParams(): array + { + $responses = array_map( + static fn (array|\stdClass|ResultInterface $response): object => \is_array($response) ? (object) $response : $response, + $this->inputResponses, + ); + + return ['taskId' => $this->taskId, 'inputResponses' => (object) $responses]; + } +} diff --git a/tests/Integration/Fixture/tasks.php b/tests/Integration/Fixture/tasks.php new file mode 100644 index 000000000..64021bb13 --- /dev/null +++ b/tests/Integration/Fixture/tasks.php @@ -0,0 +1,107 @@ + new stdClass()]; +$task = [ + 'taskId' => 'greeting', + 'status' => 'working', + 'statusMessage' => 'Starting greeting', + 'createdAt' => '2026-07-28T12:00:00Z', + 'lastUpdatedAt' => '2026-07-28T12:00:00Z', + 'ttlMs' => null, + 'pollIntervalMs' => 250, +]; + +$capabilities = ['tools' => new stdClass(), 'extensions' => $extensions]; +$serverInfo = ['name' => 'Tasks fixture', 'version' => '1.0.0']; +$inputRequests = (object) [[ + 'method' => 'elicitation/create', + 'params' => [ + 'mode' => 'form', + 'message' => 'What is your name?', + 'requestedSchema' => ['type' => 'object', 'properties' => ['name' => ['type' => 'string']]], + ], +]]; +$states = []; + +while (false !== $line = fgets(\STDIN)) { + $request = json_decode($line, flags: \JSON_THROW_ON_ERROR); + if (!$request instanceof stdClass || !isset($request->id)) { + continue; + } + + $params = $request->params; + $response = ['jsonrpc' => '2.0', 'id' => $request->id]; + $clientCapabilities = 'initialize' === $request->method + ? $params->capabilities + : $params->_meta->{RequestMeta::CLIENT_CAPABILITIES}; + + if (!($clientCapabilities->extensions->{$extension} ?? null) instanceof stdClass) { + $response['error'] = ['code' => -32021, 'message' => 'Expected the tasks capability as a JSON object']; + } elseif (str_starts_with($request->method, 'tasks/') && !isset($states[$params->taskId])) { + $response['error'] = ['code' => -32602, 'message' => 'Unknown task']; + } else { + $result = []; + switch ($request->method) { + case 'initialize': + $result = ['protocolVersion' => '2025-11-25', 'serverInfo' => $serverInfo, 'capabilities' => $capabilities]; + break; + case 'server/discover': + $result = ['supportedVersions' => ['2026-07-28'], 'serverInfo' => $serverInfo, 'capabilities' => $capabilities]; + break; + case 'tools/call': + case 'prompts/get': + case 'resources/read': + $result = match ($request->method) { + 'tools/call' => 'immediate' === $params->name ? ['content' => [['type' => 'text', 'text' => 'Immediate']]] : null, + 'prompts/get' => 'immediate' === $params->name ? ['description' => 'Immediate', 'messages' => []] : null, + default => 'test://immediate' === $params->uri ? ['contents' => [['uri' => $params->uri, 'text' => 'Immediate']]] : null, + }; + if (null === $result) { + $taskId = 'fail' === ($params->name ?? null) ? 'failure' : 'greeting'; + $states[$taskId] = 'failure' === $taskId + ? ['status' => 'failed', 'error' => ['code' => -32603, 'message' => 'Task failed']] + : ['status' => 'input_required', 'statusMessage' => 'Waiting for a name', 'pollIntervalMs' => 500, 'inputRequests' => $inputRequests]; + $result = ['resultType' => 'task', ...$task, 'taskId' => $taskId]; + } + break; + case 'tasks/get': + $result = [...$task, 'taskId' => $params->taskId, ...$states[$params->taskId]]; + break; + case 'tasks/update': + if (!$params->inputResponses instanceof stdClass || 'accept' !== ($params->inputResponses->{'0'}->action ?? null)) { + $response['error'] = ['code' => -32602, 'message' => 'Expected an answer keyed by the outstanding request ID']; + break; + } + $name = $params->inputResponses->{'0'}->content->name; + $states[$params->taskId] = [ + 'status' => 'completed', + 'result' => ['content' => [['type' => 'text', 'text' => 'Hello, '.$name.'!']]], + ]; + break; + case 'tasks/cancel': + $states[$params->taskId] = ['status' => 'cancelled']; + break; + default: + $response['error'] = ['code' => -32601, 'message' => 'Unknown method']; + } + if (!isset($response['error'])) { + $response['result'] = 'initialize' === $request->method ? $result : ['resultType' => 'complete', ...$result]; + } + } + + fwrite(\STDOUT, json_encode($response, \JSON_THROW_ON_ERROR)."\n"); +} diff --git a/tests/Integration/TasksTest.php b/tests/Integration/TasksTest.php new file mode 100644 index 000000000..7cc27ee5d --- /dev/null +++ b/tests/Integration/TasksTest.php @@ -0,0 +1,125 @@ +connectTasks(); + + $result = $client->callTool('greet'); + + $this->assertInstanceOf(CreateTaskResult::class, $result); + $this->assertSame('greeting', $result->task->taskId); + $this->assertSame('working', $result->task->status); + $this->assertSame(250, $result->task->pollIntervalMs); + } + + public function testPollsAndAnswersInputRequests(): void + { + $client = $this->connectTasks(); + $created = $client->callTool('greet'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + $taskId = $created->task->taskId; + + $pending = $client->get($taskId); + $this->assertSame('input_required', $pending->status); + $this->assertSame('Waiting for a name', $pending->statusMessage); + $this->assertSame(500, $pending->pollIntervalMs); + $this->assertNotNull($pending->inputRequests); + $this->assertArrayHasKey(0, $pending->inputRequests); + $this->assertSame('elicitation/create', $pending->inputRequests[0]['method']); + $this->assertSame('What is your name?', $pending->inputRequests[0]['params']['message']); + $this->assertSame($pending->inputRequests, $client->get($taskId)->inputRequests); + + $client->update($taskId, [0 => new ElicitResult(ElicitAction::Accept, ['name' => 'Ada'])]); + + $completed = $client->get($taskId); + $this->assertSame('completed', $completed->status); + $this->assertNull($completed->inputRequests); + $this->assertNotNull($completed->result); + $message = CallToolResult::fromArray($completed->result)->content[0]; + $this->assertInstanceOf(TextContent::class, $message); + $this->assertSame('Hello, Ada!', $message->text); + } + + public function testPollsFailedTaskAndCancelsAnotherTask(): void + { + $client = $this->connectTasks(); + $failed = $client->callTool('fail'); + $this->assertInstanceOf(CreateTaskResult::class, $failed); + $task = $client->get($failed->task->taskId); + $this->assertSame('failed', $task->status); + $this->assertSame(['code' => -32603, 'message' => 'Task failed'], $task->error); + + $working = $client->callTool('greet'); + $this->assertInstanceOf(CreateTaskResult::class, $working); + $client->cancel($working->task->taskId); + $this->assertSame('cancelled', $client->get($working->task->taskId)->status); + + $this->expectException(RequestException::class); + $this->expectExceptionMessage('Unknown task'); + $client->get('unknown'); + } + + public function testReturnsOrdinaryResultsAndDecodesTaskResultsForSiblingMethods(): void + { + $client = $this->connectTasks(); + + $tool = $client->callTool('immediate'); + $prompt = $client->getPrompt('immediate'); + $resource = $client->readResource('test://immediate'); + + $this->assertInstanceOf(CallToolResult::class, $tool); + $this->assertInstanceOf(TextContent::class, $tool->content[0]); + $this->assertSame('Immediate', $tool->content[0]->text); + $this->assertInstanceOf(GetPromptResult::class, $prompt); + $this->assertSame('Immediate', $prompt->description); + $this->assertInstanceOf(ReadResourceResult::class, $resource); + $this->assertSame('test://immediate', $resource->contents[0]->uri); + + $this->assertInstanceOf(CreateTaskResult::class, $client->getPrompt('deferred')); + $this->assertInstanceOf(CreateTaskResult::class, $client->readResource('test://deferred')); + } + + public function testAdvertisesExtensionDuringInitialize(): void + { + $client = $this->connect('tasks', $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2025_11_25) + ->enableExtension(new TasksExtension())); + + $this->assertSame(ProtocolVersion::V2025_11_25, $client->getProtocolVersion()); + } + + private function connectTasks(): TaskClient + { + return new TaskClient($this->connect('tasks', $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2026_07_28) + ->enableExtension(new TasksExtension()))); + } +} diff --git a/tests/Unit/Client/Stateless/HeaderFactoryTest.php b/tests/Unit/Client/Stateless/HeaderFactoryTest.php index 6ca35b68a..6c2284fd6 100644 --- a/tests/Unit/Client/Stateless/HeaderFactoryTest.php +++ b/tests/Unit/Client/Stateless/HeaderFactoryTest.php @@ -14,6 +14,9 @@ use Mcp\Client\Stateless\HeaderFactory; use Mcp\Client\Stateless\ToolCatalog; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Tasks\CancelTaskRequest; +use Mcp\Schema\Extension\Tasks\GetTaskRequest; +use Mcp\Schema\Extension\Tasks\UpdateTaskRequest; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -37,6 +40,16 @@ public function testNameHeader(): void $this->assertSame('search', $this->headersFor($payload)['Mcp-Name']); } + public function testTaskRequestsUseTheTaskIdForRouting(): void + { + foreach ([new GetTaskRequest('task-1'), new UpdateTaskRequest('task-1', []), new CancelTaskRequest('task-1')] as $request) { + $headers = $this->headersFor($request->withId(1)->jsonSerialize()); + + $this->assertSame('task-1', $headers['Mcp-Name']); + $this->assertSame($request::getMethod(), $headers['Mcp-Method']); + } + } + #[TestDox('wraps a subject that is not header-safe')] public function testUnsafeNameRoundTrips(): void { diff --git a/tests/Unit/Schema/Extension/Tasks/TasksExtensionTest.php b/tests/Unit/Schema/Extension/Tasks/TasksExtensionTest.php new file mode 100644 index 000000000..c12a13fcd --- /dev/null +++ b/tests/Unit/Schema/Extension/Tasks/TasksExtensionTest.php @@ -0,0 +1,73 @@ + 'task-1', + 'status' => 'completed', + 'createdAt' => '2026-07-28T12:00:00Z', + 'lastUpdatedAt' => '2026-07-28T12:00:01Z', + 'ttlMs' => null, + 'pollIntervalMs' => 0, + 'result' => [], + ]); + + $result = new CreateTaskResult($task, []); + $this->assertEquals($result, CreateTaskResult::fromArray($result->jsonSerialize())); + $this->assertJsonStringEqualsJsonString( + '{"resultType":"task","taskId":"task-1","status":"completed","createdAt":"2026-07-28T12:00:00Z","lastUpdatedAt":"2026-07-28T12:00:01Z","ttlMs":null,"pollIntervalMs":0,"result":{},"_meta":{}}', + json_encode($result, \JSON_THROW_ON_ERROR), + ); + } + + public function testTaskRequiresTtlEvenWhenItIsUnlimited(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Missing or invalid "ttlMs" in task data.'); + + Task::fromArray([ + 'taskId' => 'task-1', + 'status' => 'working', + 'createdAt' => '2026-07-28T12:00:00Z', + 'lastUpdatedAt' => '2026-07-28T12:00:00Z', + ]); + } + + public function testMessageFactoryRoundTripsAnUpdateWithNumericInputKeys(): void + { + $request = (new UpdateTaskRequest('task-1', [0 => [], 1 => ['action' => 'decline']]))->withId(1); + $encoded = json_encode($request, \JSON_THROW_ON_ERROR); + + $this->assertJsonStringEqualsJsonString( + '{"jsonrpc":"2.0","id":1,"method":"tasks/update","params":{"taskId":"task-1","inputResponses":{"0":{},"1":{"action":"decline"}}}}', + $encoded, + ); + $decoded = MessageFactory::make((new TasksExtension())->getMessages())->create($encoded); + $this->assertInstanceOf(UpdateTaskRequest::class, $decoded); + $this->assertSame($encoded, json_encode($decoded, \JSON_THROW_ON_ERROR)); + } +}