From 07a9cbdfc61716cd0de0d80869d3edfee48c542a Mon Sep 17 00:00:00 2001 From: Christopher Hertel Date: Tue, 18 Aug 2026 01:44:45 +0200 Subject: [PATCH 1/2] [Schema][Client][Server] Add the Tasks extension (SEP-2663) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `io.modelcontextprotocol/tasks`: `Task` and `TaskStatus`, `ResultType::Task`, the `CreateTaskResult` / `TaskResult` wire shapes, the `tasks/get` / `tasks/update` / `tasks/cancel` handlers behind `TasksExtension`, `TaskStoreInterface` with in-memory and PSR-16 stores, and a `TaskContext` handed to handlers for creating tasks — refused with -32021 for a client that did not declare the extension. The core stays extension-agnostic: `MethodProvidingExtensionInterface` and `ArgumentProvidingExtensionInterface` let an extension register its messages, handlers and injectable handler arguments; the core handlers pass any `ResultInterface` through; a `MissingRequiredClientCapabilityException` from handler code becomes -32021; `Client::request()` sends any request. On the client, `TaskClient` speaks the extension. Covered end to end by an integration test against a stdio fixture server. Extension settings serialize as `{}` rather than `[]` when empty. --- CHANGELOG.md | 2 + docs/advanced/extensions.md | 115 +++++++ src/Client/Client.php | 16 + src/Client/Task/TaskClient.php | 122 ++++++++ src/Schema/Enum/ResultType.php | 3 + src/Schema/Enum/TaskStatus.php | 52 ++++ .../ArgumentProvidingExtensionInterface.php | 35 +++ src/Schema/Request/TasksCancelRequest.php | 48 +++ src/Schema/Request/TasksGetRequest.php | 48 +++ src/Schema/Request/TasksUpdateRequest.php | 63 ++++ src/Schema/Result/CreateTaskResult.php | 73 +++++ src/Schema/Result/TaskResult.php | 49 +++ src/Schema/Task.php | 271 +++++++++++++++++ src/Server/Builder.php | 31 +- .../Capability/Discovery/SchemaGenerator.php | 16 +- .../Capability/Registry/ReferenceHandler.php | 16 + .../Handler/Request/CallToolHandler.php | 16 +- .../Handler/Request/GetPromptHandler.php | 11 +- .../Handler/Request/ReadResourceHandler.php | 14 +- src/Server/Protocol.php | 5 +- .../Task/Handler/TasksCancelHandler.php | 72 +++++ src/Server/Task/Handler/TasksGetHandler.php | 65 ++++ .../Task/Handler/TasksUpdateHandler.php | 80 +++++ src/Server/Task/InMemoryTaskStore.php | 84 +++++ src/Server/Task/Psr16TaskStore.php | 119 ++++++++ src/Server/Task/TaskCapabilityGuard.php | 61 ++++ src/Server/Task/TaskContext.php | 116 +++++++ src/Server/Task/TaskInputHandlerInterface.php | 35 +++ src/Server/Task/TaskStoreInterface.php | 46 +++ src/Server/Task/TasksExtension.php | 116 +++++++ tests/Integration/Fixture/tasks.php | 152 ++++++++++ tests/Integration/TasksTest.php | 207 +++++++++++++ tests/Unit/Server/BuilderTest.php | 26 ++ .../Registry/ReferenceHandlerTest.php | 18 ++ .../Handler/Request/CallToolHandlerTest.php | 39 +++ tests/Unit/Server/Task/TaskStoreTest.php | 239 +++++++++++++++ tests/Unit/Server/Task/TaskTest.php | 173 +++++++++++ tests/Unit/Server/Task/TasksExtensionTest.php | 286 ++++++++++++++++++ 38 files changed, 2913 insertions(+), 27 deletions(-) create mode 100644 src/Client/Task/TaskClient.php create mode 100644 src/Schema/Enum/TaskStatus.php create mode 100644 src/Schema/Extension/ArgumentProvidingExtensionInterface.php create mode 100644 src/Schema/Request/TasksCancelRequest.php create mode 100644 src/Schema/Request/TasksGetRequest.php create mode 100644 src/Schema/Request/TasksUpdateRequest.php create mode 100644 src/Schema/Result/CreateTaskResult.php create mode 100644 src/Schema/Result/TaskResult.php create mode 100644 src/Schema/Task.php create mode 100644 src/Server/Task/Handler/TasksCancelHandler.php create mode 100644 src/Server/Task/Handler/TasksGetHandler.php create mode 100644 src/Server/Task/Handler/TasksUpdateHandler.php create mode 100644 src/Server/Task/InMemoryTaskStore.php create mode 100644 src/Server/Task/Psr16TaskStore.php create mode 100644 src/Server/Task/TaskCapabilityGuard.php create mode 100644 src/Server/Task/TaskContext.php create mode 100644 src/Server/Task/TaskInputHandlerInterface.php create mode 100644 src/Server/Task/TaskStoreInterface.php create mode 100644 src/Server/Task/TasksExtension.php create mode 100644 tests/Integration/Fixture/tasks.php create mode 100644 tests/Integration/TasksTest.php create mode 100644 tests/Unit/Server/Task/TaskStoreTest.php create mode 100644 tests/Unit/Server/Task/TaskTest.php create mode 100644 tests/Unit/Server/Task/TasksExtensionTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..89c1c06c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Server * Fix const validation errors always reporting the expected value as null. +* Add the Tasks extension (SEP-2663, `io.modelcontextprotocol/tasks`): a server hands back a durable handle instead of holding a connection open — `Mcp\Schema\Task` and `TaskStatus`, `ResultType::Task`, the flat `CreateTaskResult` / `TaskResult` wire shapes, the `tasks/get` / `tasks/update` / `tasks/cancel` surface, and `TaskStoreInterface` with `InMemoryTaskStore` and `Psr16TaskStore` (what PHP-FPM needs). Enable with `Builder::enableExtension(new TasksExtension($store))`; a handler declares a `TaskContext` parameter and creates a task through `TaskContext::create()` after `isSupported()` — a task for a client that did not declare the extension is refused with `-32021`. Advancing a task is the application's job. On the client, `enableExtension(new TasksExtension())` declares it and `Client\Task\TaskClient` speaks it. +* Let an extension reach handler code without the core knowing it: `ArgumentProvidingExtensionInterface` hands handlers objects of the extension's own, injected like a `RequestContext` and left out of the generated schemas; the tool, prompt and resource handlers pass any `ResultInterface` a handler returns through untouched; a `MissingRequiredClientCapabilityException` thrown from handler code is answered as `-32021`; `Client::request()` sends any request. 0.10.0 ------ diff --git a/docs/advanced/extensions.md b/docs/advanced/extensions.md index 989926d76..6bbfe6c55 100644 --- a/docs/advanced/extensions.md +++ b/docs/advanced/extensions.md @@ -91,6 +91,120 @@ the same method, `enableExtension()` throws a `LogicException`. Extensions bring notification handlers: add those with `Builder::addNotificationHandler()`. They [don't run on revision `2026-07-28`](custom-handlers.md#protocol-2026-07-28). +An extension that hands handlers an object of its own implements +`ArgumentProvidingExtensionInterface` on top: a handler declaring a parameter +of a provided type receives it for the request being served, the way it +receives a `RequestContext` — and it stays out of the generated input schemas. + +## Tasks (`io.modelcontextprotocol/tasks`) + +The [Tasks extension][ext-tasks] (SEP-2663) lets a server hand back a durable +handle instead of holding a connection open for a long-running request. The +client polls `tasks/get` until the task settles, answers anything it asks for +through `tasks/update`, and may `tasks/cancel` it. + +```php +use Mcp\Server; +use Mcp\Server\Task\InMemoryTaskStore; +use Mcp\Server\Task\Psr16TaskStore; +use Mcp\Server\Task\TasksExtension; + +$server = Server::builder() + ->enableExtension(new TasksExtension(new InMemoryTaskStore())) + ->build(); +``` + +`InMemoryTaskStore` is right for stdio and any single-process runtime and drops +its oldest task past a configurable limit (1000 by default). Under PHP-FPM the +worker that creates a task is not the one polled for it, so use +`Psr16TaskStore` over a shared cache there — a filesystem adapter is enough. + +Creating a task is the *server's* decision, made per request by returning a +`CreateTaskResult` from any tool, prompt or resource handler. The extension +hands handlers a `TaskContext` — declare the parameter and it arrives, like a +`RequestContext` does: + +```php +use Mcp\Schema\Result\CreateTaskResult; +use Mcp\Server\Task\TaskContext; + +static function (TaskContext $tasks) use ($queue): CreateTaskResult|string { + if (!$tasks->isSupported()) { + return runSynchronously(); // the client cannot poll, so answer now + } + + $created = $tasks->create(ttlMs: 600_000, pollIntervalMs: 1000); + $queue->push($created->task->taskId); // a worker calls $store->save() as it progresses + + return $created; +} +``` + +`create()` stores the task *before* returning it, so the first `tasks/get` +cannot arrive before the task exists. A client that did not declare the +extension during `initialize` cannot redeem a handle, so `create()` refuses +with `-32021` (missing required client capability) instead of handing one out — +the right answer for a handler whose task support is *required*, and what +`isSupported()` lets an optional one avoid. + +The SDK owns storage and the `tasks/get` / `tasks/update` / `tasks/cancel` +surface; **advancing** a task is the application's job. A worker (or a +handler, through `TaskContext::getStore()`) saves the task with a new status +as it goes: + +```php +use Mcp\Schema\Enum\TaskStatus; + +$store->save($task->with(TaskStatus::Completed, result: ['content' => [/* ... */]])); +``` + +A task that needs the client's input parks itself as `input_required` with +`inputRequests` (elicitation, sampling or roots requests keyed by name); the +client answers through `tasks/update`, and a `TaskInputHandlerInterface` passed +to `TasksExtension` decides what those answers mean for the task. + +Status semantics worth getting right: a tool that ran and reported a problem is +`completed` with `isError` on its result — `failed` is reserved for +protocol-level errors, and carries the error inlined instead of a result. +`Task` refuses to be constructed the other way round. + +### On the client + +A client declares the extension the same way, and then handles whichever +result shape arrives. `TaskClient` wraps a connected `Client`: its `callTool()`, +`getPrompt()` and `readResource()` return a `CreateTaskResult` when the server +chose to answer with a task, and `get()` / `update()` / `cancel()` drive it: + +```php +use Mcp\Client; +use Mcp\Client\Task\TaskClient; +use Mcp\Schema\Result\CallToolResult; +use Mcp\Schema\Result\CreateTaskResult; +use Mcp\Server\Task\TasksExtension; + +$client = Client::builder() + ->enableExtension(new TasksExtension()) + ->build(); +$client->connect($transport); + +$tasks = new TaskClient($client); +$result = $tasks->callTool('long_job'); + +if ($result instanceof CreateTaskResult) { + do { + usleep(1000 * ($result->task->pollIntervalMs ?? 1000)); + $task = $tasks->get($result->task->taskId); + } while (!$task->status->isTerminal()); + + $result = CallToolResult::fromArray($task->result); // once completed +} +``` + +A task waiting as `input_required` lists its `inputRequests`; answer them with +`update($taskId, ['' => $answer])`, keyed as the requests were, and +`cancel($taskId)` asks the server to stop. The core `Client` itself stays +task-agnostic; `Client::request()` sends any request for code like this. + ## MCP Apps (`io.modelcontextprotocol/ui`) The [MCP Apps extension][ext-apps] lets servers expose interactive HTML UIs as @@ -206,3 +320,4 @@ working minimal view is included in [`examples/server/mcp-apps/weather-app.html`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/server/mcp-apps/weather-app.html). [ext-apps]: https://github.com/modelcontextprotocol/ext-apps +[ext-tasks]: https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2663 diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..b331ea3f9 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -435,6 +435,22 @@ private function sendRequest(Request $request, ?callable $onProgress = null, ?Ca return $response; } + /** + * Sends any request and returns the raw response — the way to speak a + * method the typed API does not cover, such as an extension's. + * + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + * Optional callback for progress updates + * + * @return Response + * + * @throws RequestException|ConnectionException + */ + public function request(Request $request, ?callable $onProgress = null): Response + { + return $this->sendRequest($request, $onProgress); + } + /** * Disconnect from the server. */ diff --git a/src/Client/Task/TaskClient.php b/src/Client/Task/TaskClient.php new file mode 100644 index 000000000..301d9ffeb --- /dev/null +++ b/src/Client/Task/TaskClient.php @@ -0,0 +1,122 @@ +enableExtension(new TasksExtension())->build(); + * $client->connect($transport); + * + * $tasks = new TaskClient($client); + * $result = $tasks->callTool('long_job'); + * + * if ($result instanceof CreateTaskResult) { + * do { + * usleep(1000 * ($result->task->pollIntervalMs ?? 1000)); + * $task = $tasks->get($result->task->taskId); + * } while (!$task->status->isTerminal()); + * } + * ``` + * + * The core client's `callTool()`, `getPrompt()` and `readResource()` expect + * the answer itself; these variants accept a task handle in its place, which a + * server may send once the extension is declared. + * + * @author Christopher Hertel + */ +final class TaskClient +{ + public function __construct( + private readonly Client $client, + ) { + } + + /** + * @param array $arguments + * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress + */ + public function callTool(string $name, array $arguments = [], ?callable $onProgress = null): CallToolResult|CreateTaskResult + { + $result = $this->client->request(new CallToolRequest($name, $arguments), $onProgress)->result; + + return CreateTaskResult::describes($result) ? 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::describes($result) ? 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 + { + $result = $this->client->request(new ReadResourceRequest($uri), $onProgress)->result; + + return CreateTaskResult::describes($result) ? CreateTaskResult::fromArray($result) : ReadResourceResult::fromArray($result); + } + + /** + * The current state of a task (`tasks/get`). + * + * Poll it at the task's `pollIntervalMs` until {@see \Mcp\Schema\Enum\TaskStatus::isTerminal()}; + * a completed task carries the original request's result, an + * `input_required` one what it is waiting for, to answer with {@see self::update()}. + */ + public function get(string $taskId): Task + { + return TaskResult::fromArray($this->client->request(new TasksGetRequest($taskId))->result)->task; + } + + /** + * Answers what a task asked for (`tasks/update`). + * + * @param array $inputResponses keyed as the task's `inputRequests` were + */ + public function update(string $taskId, array $inputResponses): void + { + $this->client->request(new TasksUpdateRequest($taskId, $inputResponses)); + } + + /** + * Asks the server to cancel a task (`tasks/cancel`). Cooperative: the task + * may still finish. + */ + public function cancel(string $taskId): void + { + $this->client->request(new TasksCancelRequest($taskId)); + } +} diff --git a/src/Schema/Enum/ResultType.php b/src/Schema/Enum/ResultType.php index 8319bc496..0a2e37140 100644 --- a/src/Schema/Enum/ResultType.php +++ b/src/Schema/Enum/ResultType.php @@ -27,4 +27,7 @@ enum ResultType: string /** The request needs more input before it can finish (MRTR). */ case InputRequired = 'input_required'; + + /** The request became a task; the result is the handle to poll (Tasks extension). */ + case Task = 'task'; } diff --git a/src/Schema/Enum/TaskStatus.php b/src/Schema/Enum/TaskStatus.php new file mode 100644 index 000000000..a2382b65e --- /dev/null +++ b/src/Schema/Enum/TaskStatus.php @@ -0,0 +1,52 @@ + + */ +enum TaskStatus: string +{ + /** The work is in progress. */ + case Working = 'working'; + + /** The server needs client input before it can continue. */ + case InputRequired = 'input_required'; + + /** The work finished; the result is what the original request would have returned. */ + case Completed = 'completed'; + + /** A protocol-level error stopped the work; the error is inlined. */ + case Failed = 'failed'; + + /** The work was cancelled. Cooperative: reaching it is never guaranteed. */ + case Cancelled = 'cancelled'; + + /** + * Whether the task can still change. Terminal states never do. + */ + public function isTerminal(): bool + { + return match ($this) { + self::Completed, self::Failed, self::Cancelled => true, + self::Working, self::InputRequired => false, + }; + } +} diff --git a/src/Schema/Extension/ArgumentProvidingExtensionInterface.php b/src/Schema/Extension/ArgumentProvidingExtensionInterface.php new file mode 100644 index 000000000..d3c9b5958 --- /dev/null +++ b/src/Schema/Extension/ArgumentProvidingExtensionInterface.php @@ -0,0 +1,35 @@ + + */ +interface ArgumentProvidingExtensionInterface extends ExtensionInterface +{ + /** + * Builders for the types this extension injects, keyed by the type. + * + * @return array + */ + public function getArgumentProviders(): array; +} diff --git a/src/Schema/Request/TasksCancelRequest.php b/src/Schema/Request/TasksCancelRequest.php new file mode 100644 index 000000000..d98c00f1c --- /dev/null +++ b/src/Schema/Request/TasksCancelRequest.php @@ -0,0 +1,48 @@ + + */ +final class TasksCancelRequest extends Request +{ + public function __construct( + public readonly string $taskId, + ) { + } + + public static function getMethod(): string + { + return 'tasks/cancel'; + } + + protected static function fromParams(?array $params): static + { + if (!isset($params['taskId']) || !\is_string($params['taskId']) || '' === $params['taskId']) { + throw new InvalidArgumentException('Missing or invalid "taskId" parameter for tasks/cancel.'); + } + + return new self($params['taskId']); + } + + /** + * @return array{taskId: string} + */ + protected function getParams(): array + { + return ['taskId' => $this->taskId]; + } +} diff --git a/src/Schema/Request/TasksGetRequest.php b/src/Schema/Request/TasksGetRequest.php new file mode 100644 index 000000000..659543a38 --- /dev/null +++ b/src/Schema/Request/TasksGetRequest.php @@ -0,0 +1,48 @@ + + */ +final class TasksGetRequest extends Request +{ + public function __construct( + public readonly string $taskId, + ) { + } + + public static function getMethod(): string + { + return 'tasks/get'; + } + + protected static function fromParams(?array $params): static + { + if (!isset($params['taskId']) || !\is_string($params['taskId']) || '' === $params['taskId']) { + throw new InvalidArgumentException('Missing or invalid "taskId" parameter for tasks/get.'); + } + + return new self($params['taskId']); + } + + /** + * @return array{taskId: string} + */ + protected function getParams(): array + { + return ['taskId' => $this->taskId]; + } +} diff --git a/src/Schema/Request/TasksUpdateRequest.php b/src/Schema/Request/TasksUpdateRequest.php new file mode 100644 index 000000000..4d3b6dc57 --- /dev/null +++ b/src/Schema/Request/TasksUpdateRequest.php @@ -0,0 +1,63 @@ + + */ +final class TasksUpdateRequest extends Request +{ + /** + * @param array $inputResponses client answers, keyed as the task's inputRequests were + */ + public function __construct( + public readonly string $taskId, + public readonly array $inputResponses = [], + ) { + } + + public static function getMethod(): string + { + return 'tasks/update'; + } + + protected static function fromParams(?array $params): static + { + if (!isset($params['taskId']) || !\is_string($params['taskId']) || '' === $params['taskId']) { + throw new InvalidArgumentException('Missing or invalid "taskId" parameter for tasks/update.'); + } + + $responses = $params['inputResponses'] ?? []; + + if (!\is_array($responses)) { + throw new InvalidArgumentException('Invalid "inputResponses" parameter for tasks/update.'); + } + + return new self($params['taskId'], $responses); + } + + /** + * @return array{taskId: string, inputResponses: array} + */ + protected function getParams(): array + { + return ['taskId' => $this->taskId, 'inputResponses' => $this->inputResponses]; + } +} diff --git a/src/Schema/Result/CreateTaskResult.php b/src/Schema/Result/CreateTaskResult.php new file mode 100644 index 000000000..c1800e3ba --- /dev/null +++ b/src/Schema/Result/CreateTaskResult.php @@ -0,0 +1,73 @@ + + */ +class CreateTaskResult implements ResultInterface +{ + public function __construct( + public readonly Task $task, + ) { + } + + /** + * @param array $data + * + * @throws InvalidArgumentException when the data is not a task handle + */ + public static function fromArray(array $data): self + { + if (ResultType::Task->value !== ($data['resultType'] ?? null)) { + throw new InvalidArgumentException('Missing or invalid "resultType" in CreateTaskResult data.'); + } + + return new self(Task::fromArray($data)); + } + + /** + * Whether a result is a task handle rather than the answer itself. + * + * @param array $data + */ + public static function describes(array $data): bool + { + return ResultType::Task->value === ($data['resultType'] ?? null); + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + // The envelope only: a task that was just created has no result, no + // error and nothing it is waiting for. + return ['resultType' => ResultType::Task->value, ...$this->task->toEnvelope()]; + } +} diff --git a/src/Schema/Result/TaskResult.php b/src/Schema/Result/TaskResult.php new file mode 100644 index 000000000..254680916 --- /dev/null +++ b/src/Schema/Result/TaskResult.php @@ -0,0 +1,49 @@ + + */ +class TaskResult implements ResultInterface +{ + public function __construct( + public readonly Task $task, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self(Task::fromArray($data)); + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + return $this->task->jsonSerialize(); + } +} diff --git a/src/Schema/Task.php b/src/Schema/Task.php new file mode 100644 index 000000000..5eec72965 --- /dev/null +++ b/src/Schema/Task.php @@ -0,0 +1,271 @@ + + */ +class Task implements \JsonSerializable +{ + /** + * @param string $taskId server-assigned, unique and durable + * @param ?string $statusMessage human-readable progress, e.g. "42 of 100 rows" + * @param ?int $ttlMs how long the task stays readable through `tasks/get`; null means no limit + * @param ?int $pollIntervalMs how long a client should wait between polls + * @param mixed $result what the original request would have returned, once completed + * @param ?Error $error a protocol-level failure, inlined when the status is `failed` + * @param array $inputRequests what the task is waiting for, when the status is `input_required` + */ + public function __construct( + public readonly string $taskId, + public readonly TaskStatus $status = TaskStatus::Working, + public readonly ?\DateTimeImmutable $createdAt = null, + public readonly ?\DateTimeImmutable $lastUpdatedAt = null, + public readonly ?int $ttlMs = null, + public readonly ?int $pollIntervalMs = null, + public readonly ?string $statusMessage = null, + public readonly mixed $result = null, + public readonly ?Error $error = null, + public readonly array $inputRequests = [], + ) { + if ('' === $this->taskId) { + throw new InvalidArgumentException('A task must have a non-empty "taskId".'); + } + + // Both are milliseconds, and both are guidance a client acts on — a + // fractional or negative one is not guidance, it is a bug on the wire. + if (null !== $this->ttlMs && $this->ttlMs <= 0) { + throw new InvalidArgumentException(\sprintf('A task "ttlMs" must be a positive number of milliseconds or null, got %d.', $this->ttlMs)); + } + + if (null !== $this->pollIntervalMs && $this->pollIntervalMs <= 0) { + throw new InvalidArgumentException(\sprintf('A task "pollIntervalMs" must be a positive number of milliseconds, got %d.', $this->pollIntervalMs)); + } + + if (TaskStatus::Failed === $this->status && null === $this->error) { + throw new InvalidArgumentException('A failed task must carry the error that stopped it.'); + } + + if (null !== $this->error && TaskStatus::Failed !== $this->status) { + throw new InvalidArgumentException('Only a failed task carries an "error"; a tool that ran and reported a problem is completed with "isError" on its result.'); + } + } + + /** + * Reads a task back from its wire shape — what {@see self::jsonSerialize()} + * produces, or a superset of it. + * + * @param array $data + * + * @throws InvalidArgumentException when the data does not describe a task + */ + public static function fromArray(array $data): self + { + if (!\is_string($data['taskId'] ?? null) || '' === $data['taskId']) { + throw new InvalidArgumentException('Missing or invalid "taskId" in Task data.'); + } + + $status = TaskStatus::tryFrom(\is_string($data['status'] ?? null) ? $data['status'] : ''); + if (null === $status) { + throw new InvalidArgumentException(\sprintf('Missing or invalid "status" in Task data for task "%s".', $data['taskId'])); + } + + $error = \is_array($data['error'] ?? null) && isset($data['error']['code'], $data['error']['message']) + ? new Error(null, (int) $data['error']['code'], (string) $data['error']['message'], $data['error']['data'] ?? null) + : null; + + return new self( + $data['taskId'], + $status, + \is_string($data['createdAt'] ?? null) ? new \DateTimeImmutable($data['createdAt']) : null, + \is_string($data['lastUpdatedAt'] ?? null) ? new \DateTimeImmutable($data['lastUpdatedAt']) : null, + \is_int($data['ttlMs'] ?? null) ? $data['ttlMs'] : null, + \is_int($data['pollIntervalMs'] ?? null) ? $data['pollIntervalMs'] : null, + \is_string($data['statusMessage'] ?? null) ? $data['statusMessage'] : null, + $data['result'] ?? null, + $error, + self::inputRequestsFrom($data['inputRequests'] ?? []), + ); + } + + /** + * The `inputRequests` map, from bare method/params pairs or full envelopes. + * + * @return array + */ + private static function inputRequestsFrom(mixed $raw): array + { + if (!\is_array($raw)) { + return []; + } + + $requests = []; + + foreach ($raw as $key => $envelope) { + if (!\is_array($envelope) || !\is_string($envelope['method'] ?? null)) { + continue; + } + + $class = match ($envelope['method']) { + ElicitRequest::getMethod() => ElicitRequest::class, + CreateSamplingMessageRequest::getMethod() => CreateSamplingMessageRequest::class, + ListRootsRequest::getMethod() => ListRootsRequest::class, + default => null, + }; + + if (null === $class) { + continue; + } + + // On the wire the pair has no id — the map key is what answers are + // keyed by — so one is supplied to satisfy the message parser. + $requests[(string) $key] = $class::fromArray($envelope + ['jsonrpc' => MessageInterface::JSONRPC_VERSION, 'id' => 0]); + } + + return $requests; + } + + /** + * A copy with a new status and whatever that status carries. + * + * @param array $inputRequests + */ + public function with( + TaskStatus $status, + mixed $result = null, + ?Error $error = null, + array $inputRequests = [], + ?string $statusMessage = null, + ?\DateTimeImmutable $now = null, + ): self { + return new self( + $this->taskId, + $status, + $this->createdAt, + $now ?? new \DateTimeImmutable(), + $this->ttlMs, + $this->pollIntervalMs, + $statusMessage ?? $this->statusMessage, + $result ?? $this->result, + $error ?? $this->error, + [] !== $inputRequests ? $inputRequests : $this->inputRequests, + ); + } + + /** + * Whether the task is still readable, given its TTL. + */ + public function isReadable(?\DateTimeImmutable $now = null): bool + { + if (null === $this->ttlMs || null === $this->createdAt) { + return true; + } + + $expiresAt = $this->createdAt->modify(\sprintf('+%d milliseconds', $this->ttlMs)); + + return ($now ?? new \DateTimeImmutable()) < $expiresAt; + } + + /** + * The task's own fields, without anything only a detailed view carries. + * + * @return array + */ + public function toEnvelope(): array + { + $data = [ + 'taskId' => $this->taskId, + 'status' => $this->status->value, + ]; + + if (null !== $this->createdAt) { + $data['createdAt'] = $this->createdAt->format(\DATE_ATOM); + } + + if (null !== $this->lastUpdatedAt) { + $data['lastUpdatedAt'] = $this->lastUpdatedAt->format(\DATE_ATOM); + } + + // Emitted even as null: absent would mean "the server said nothing + // about how long this lives", and null means "as long as you like". + $data['ttlMs'] = $this->ttlMs; + + if (null !== $this->pollIntervalMs) { + $data['pollIntervalMs'] = $this->pollIntervalMs; + } + + if (null !== $this->statusMessage) { + $data['statusMessage'] = $this->statusMessage; + } + + return $data; + } + + /** + * The envelope plus whatever the current status carries. + * + * @return array + */ + public function jsonSerialize(): array + { + $data = $this->toEnvelope(); + + if (TaskStatus::Completed === $this->status) { + $data['result'] = $this->result; + } + + if (null !== $this->error) { + $error = ['code' => $this->error->code, 'message' => $this->error->message]; + + if (null !== $this->error->data) { + $error['data'] = $this->error->data; + } + + $data['error'] = $error; + } + + if ([] !== $this->inputRequests) { + $requests = []; + foreach ($this->inputRequests as $key => $request) { + // Values are bare method/params pairs, not messages: the client + // keys answers by the map key. getParams() is protected, so the + // envelope is built with a throwaway id and then discarded. + $params = $request->withId(0)->jsonSerialize()['params'] ?? null; + + $requests[$key] = [ + 'method' => $request::getMethod(), + // An empty PHP array would encode as `[]`, not `{}`. + 'params' => [] === $params || null === $params ? new \stdClass() : $params, + ]; + } + $data['inputRequests'] = $requests; + } + + return $data; + } +} diff --git a/src/Server/Builder.php b/src/Server/Builder.php index aa8a850da..35cdbd46c 100644 --- a/src/Server/Builder.php +++ b/src/Server/Builder.php @@ -14,6 +14,7 @@ use Mcp\Schema\Annotations; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\Extension\AbstractExtension; +use Mcp\Schema\Extension\ArgumentProvidingExtensionInterface; use Mcp\Schema\Extension\ExtensionInterface; use Mcp\Schema\Icon; use Mcp\Schema\Implementation; @@ -29,6 +30,8 @@ use Mcp\Server\Capability\Discovery\CachedDiscoverer; use Mcp\Server\Capability\Discovery\Discoverer; use Mcp\Server\Capability\Discovery\DiscovererInterface; +use Mcp\Server\Capability\Discovery\DocBlockParser; +use Mcp\Server\Capability\Discovery\SchemaGenerator; use Mcp\Server\Capability\Discovery\SchemaGeneratorInterface; use Mcp\Server\Capability\Discovery\SchemaValidator; use Mcp\Server\Capability\Registry; @@ -57,6 +60,7 @@ use Mcp\Server\Resource\SessionSubscriptionManager; use Mcp\Server\Resource\SubscriptionManagerInterface; use Mcp\Server\Session\InMemorySessionStore; +use Mcp\Server\Session\SessionInterface; use Mcp\Server\Session\SessionLockInterface; use Mcp\Server\Session\SessionManager; use Mcp\Server\Session\SessionManagerInterface; @@ -151,6 +155,9 @@ final class Builder /** @var list|class-string<\Mcp\Schema\JsonRpc\Notification>> */ private array $extensionMessages = []; + /** @var array */ + private array $extensionArgumentProviders = []; + /** @var string|list|null */ private string|array|null $requestStateKey = null; @@ -505,6 +512,10 @@ public function enableExtension(ExtensionInterface ...$extensions): self $this->extensions[$id] = $extension->getCapabilities(); + if ($extension instanceof ArgumentProvidingExtensionInterface) { + $this->extensionArgumentProviders += $extension->getArgumentProviders(); + } + // Without this the method cannot be decoded at all, so nothing // downstream ever sees it. foreach ($extension->getMessages() as $message) { @@ -1150,7 +1161,7 @@ private function resolve(): array $this->explicitResourceTemplates, $this->explicitPrompts, ), - new ReflectedElementLoader($this->tools, $this->resources, $this->resourceTemplates, $this->prompts, $logger, $this->schemaGenerator), + new ReflectedElementLoader($this->tools, $this->resources, $this->resourceTemplates, $this->prompts, $logger, $this->schemaGenerator($logger)), ]; if (null !== $this->discoveryBasePath) { @@ -1199,7 +1210,7 @@ private function resolve(): array $serverInfo = $this->serverInfo ?? new Implementation(); $configuration = new Configuration($serverInfo, $capabilities, $this->paginationLimit, $this->instructions, $this->protocolVersion); - $referenceHandler = $this->referenceHandler ?? new ReferenceHandler($container); + $referenceHandler = $this->referenceHandler ?? new ReferenceHandler($container, $this->extensionArgumentProviders); $requestHandlers = array_merge($this->requestHandlers, [ new Handler\Request\CallToolHandler($registry, $referenceHandler, $logger, $this->schemaValidator), @@ -1278,9 +1289,23 @@ private function detectCapabilities(RegistryInterface $registry, bool $eagerlyLo ); } + /** + * The configured generator, or one that leaves the parameter types + * extensions inject out of the schemas — null when nothing needs that, + * so the loaders keep their own defaults. + */ + private function schemaGenerator(LoggerInterface $logger): ?SchemaGeneratorInterface + { + if (null !== $this->schemaGenerator || [] === $this->extensionArgumentProviders) { + return $this->schemaGenerator; + } + + return new SchemaGenerator(new DocBlockParser(logger: $logger), array_keys($this->extensionArgumentProviders)); + } + private function createDiscoverer(LoggerInterface $logger): DiscovererInterface { - $discoverer = new Discoverer($logger, null, $this->schemaGenerator); + $discoverer = new Discoverer($logger, null, $this->schemaGenerator($logger)); if (null !== $this->discoveryCache) { return new CachedDiscoverer($discoverer, $this->discoveryCache, $logger); diff --git a/src/Server/Capability/Discovery/SchemaGenerator.php b/src/Server/Capability/Discovery/SchemaGenerator.php index 4b26e7a1d..4cbaf132f 100644 --- a/src/Server/Capability/Discovery/SchemaGenerator.php +++ b/src/Server/Capability/Discovery/SchemaGenerator.php @@ -54,8 +54,14 @@ */ final class SchemaGenerator implements SchemaGeneratorInterface { + /** + * @param list $injectedTypes parameter types the runtime injects rather than the caller supplies, + * on top of {@see InjectableParameters} — an extension's, say — and + * which therefore do not belong in a schema + */ public function __construct( private readonly DocBlockParser $docBlockParser, + private readonly array $injectedTypes = [], ) { } @@ -539,10 +545,12 @@ private function parseParametersInfo(\ReflectionMethod|\ReflectionFunction $refl foreach ($reflection->getParameters() as $rp) { $reflectionType = $rp->getType(); - if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin() - && InjectableParameters::supports($reflectionType->getName()) - ) { - continue; + if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin()) { + $typeName = $reflectionType->getName(); + + if (InjectableParameters::supports($typeName) || \in_array($typeName, $this->injectedTypes, true)) { + continue; + } } $paramName = $rp->getName(); diff --git a/src/Server/Capability/Registry/ReferenceHandler.php b/src/Server/Capability/Registry/ReferenceHandler.php index a3121bf8b..0c371de1b 100644 --- a/src/Server/Capability/Registry/ReferenceHandler.php +++ b/src/Server/Capability/Registry/ReferenceHandler.php @@ -12,6 +12,7 @@ namespace Mcp\Server\Capability\Registry; use Mcp\Schema\Json; +use Mcp\Schema\JsonRpc\Request; use Mcp\Server\Exception\InvalidArgumentException; use Mcp\Server\Exception\RegistryException; use Mcp\Server\Session\SessionInterface; @@ -22,8 +23,14 @@ */ final class ReferenceHandler implements ReferenceHandlerInterface { + /** + * @param array $argumentProviders builders for further + * injectable parameter types, + * e.g. an extension's + */ public function __construct( private readonly ?ContainerInterface $container = null, + private readonly array $argumentProviders = [], ) { } @@ -153,6 +160,15 @@ private function prepareArguments(\ReflectionFunctionAbstract $reflection, array $finalArgs[$paramPosition] = $injected; continue; } + + // An extension may contribute further injectable types; the + // core stays unaware of what they are. + $typeName = $type->getName(); + + if (isset($this->argumentProviders[$typeName], $arguments['_session'], $arguments['_request'])) { + $finalArgs[$paramPosition] = ($this->argumentProviders[$typeName])($arguments['_session'], $arguments['_request']); + continue; + } } if (isset($arguments[$paramName]) || (\array_key_exists($paramName, $arguments) && $parameter->allowsNull())) { diff --git a/src/Server/Handler/Request/CallToolHandler.php b/src/Server/Handler/Request/CallToolHandler.php index e4d4ad5aa..db61adb31 100644 --- a/src/Server/Handler/Request/CallToolHandler.php +++ b/src/Server/Handler/Request/CallToolHandler.php @@ -16,9 +16,9 @@ use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; +use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\Request\CallToolRequest; use Mcp\Schema\Result\CallToolResult; -use Mcp\Schema\Result\InputRequiredResult; use Mcp\Schema\Tool; use Mcp\Server\Capability\Discovery\SchemaValidator; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; @@ -34,10 +34,11 @@ use Psr\Log\NullLogger; /** - * A tools/call answers with the tool's output or, under MRTR, with a request - * for the input it still needs. + * A tools/call answers with the tool's output, under MRTR with a request for + * the input it still needs, or — under an extension — with a result of its + * own kind. * - * @implements RequestHandlerInterface + * @implements RequestHandlerInterface * * @author Christopher Hertel * @author Tobias Nyholm @@ -61,7 +62,7 @@ public function supports(Request $request): bool } /** - * @return Response|Error + * @return Response|Error */ public function handle(Request $request, SessionInterface $session): Response|Error { @@ -100,8 +101,9 @@ public function handle(Request $request, SessionInterface $session): Response|Er try { $result = $this->referenceHandler->handle($reference, $arguments); - // An ask is a result in its own right, not tool output. - if ($result instanceof InputRequiredResult) { + // A handler that built a whole result of another kind — an + // extension's, say — keeps what it decided; it is not tool output. + if ($result instanceof ResultInterface && !$result instanceof CallToolResult) { return new Response($request->getId(), $result); } diff --git a/src/Server/Handler/Request/GetPromptHandler.php b/src/Server/Handler/Request/GetPromptHandler.php index c1cc10aa6..5b4fae920 100644 --- a/src/Server/Handler/Request/GetPromptHandler.php +++ b/src/Server/Handler/Request/GetPromptHandler.php @@ -14,9 +14,9 @@ use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; +use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\Request\GetPromptRequest; use Mcp\Schema\Result\GetPromptResult; -use Mcp\Schema\Result\InputRequiredResult; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\RegistryInterface; use Mcp\Server\Exception\MissingRequiredClientCapabilityException; @@ -29,7 +29,7 @@ use Psr\Log\NullLogger; /** - * @implements RequestHandlerInterface + * @implements RequestHandlerInterface * * @author Tobias Nyholm */ @@ -48,7 +48,7 @@ public function supports(Request $request): bool } /** - * @return Response|Error + * @return Response|Error */ public function handle(Request $request, SessionInterface $session): Response|Error { @@ -65,8 +65,9 @@ public function handle(Request $request, SessionInterface $session): Response|Er $result = $this->referenceHandler->handle($reference, $arguments); - // An ask is a result in its own right, not prompt content. - if ($result instanceof InputRequiredResult) { + // A handler that built a whole result of another kind — an + // extension's, say — keeps what it decided; it is not prompt messages. + if ($result instanceof ResultInterface) { return new Response($request->getId(), $result); } diff --git a/src/Server/Handler/Request/ReadResourceHandler.php b/src/Server/Handler/Request/ReadResourceHandler.php index def85079f..94169175d 100644 --- a/src/Server/Handler/Request/ReadResourceHandler.php +++ b/src/Server/Handler/Request/ReadResourceHandler.php @@ -14,8 +14,8 @@ use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; +use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\Request\ReadResourceRequest; -use Mcp\Schema\Result\InputRequiredResult; use Mcp\Schema\Result\ReadResourceResult; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\Registry\ResourceTemplateReference; @@ -31,7 +31,7 @@ use Psr\Log\NullLogger; /** - * @implements RequestHandlerInterface + * @implements RequestHandlerInterface * * @author Tobias Nyholm */ @@ -50,7 +50,7 @@ public function supports(Request $request): bool } /** - * @return Response|Error + * @return Response|Error */ public function handle(Request $request, SessionInterface $session): Response|Error { @@ -76,9 +76,9 @@ public function handle(Request $request, SessionInterface $session): Response|Er $result = $this->referenceHandler->handle($reference, $arguments); // An ask is a result in its own right, not resource contents; - // and a handler that built the whole result keeps what it - // decided, caching hints included on the modern era. - if ($result instanceof InputRequiredResult) { + // and a handler that built the whole result — an + // extension's kind — keeps what it decided. + if ($result instanceof ResultInterface && !$result instanceof ReadResourceResult) { return new Response($request->getId(), $result); } @@ -90,7 +90,7 @@ public function handle(Request $request, SessionInterface $session): Response|Er } else { $result = $this->referenceHandler->handle($reference, $arguments); - if ($result instanceof InputRequiredResult) { + if ($result instanceof ResultInterface && !$result instanceof ReadResourceResult) { return new Response($request->getId(), $result); } diff --git a/src/Server/Protocol.php b/src/Server/Protocol.php index 90c40e81a..0619c9dbe 100644 --- a/src/Server/Protocol.php +++ b/src/Server/Protocol.php @@ -31,6 +31,7 @@ use Mcp\Server\Event\ResponseEvent; use Mcp\Server\Event\ServerRequestEvent; use Mcp\Server\Exception\ConfigurationException; +use Mcp\Server\Exception\MissingRequiredClientCapabilityException; use Mcp\Server\Exception\RuntimeException; use Mcp\Server\Exception\SessionLockException; use Mcp\Server\Exception\SessionLockTimeoutException; @@ -1181,7 +1182,9 @@ private function saveResumedSession(SessionInterface $session): void private function errorForThrowable(\Throwable $e, Request $request, SessionInterface $session): Error { - if ($e instanceof \InvalidArgumentException && !$e instanceof ConfigurationException) { + if ($e instanceof MissingRequiredClientCapabilityException) { + $error = Error::forMissingRequiredClientCapability($e->getMessage(), $e->requiredCapabilities, $request->getId()); + } elseif ($e instanceof \InvalidArgumentException && !$e instanceof ConfigurationException) { $this->logger->warning(\sprintf('Invalid argument: %s', $e->getMessage()), ['exception' => $e]); $error = Error::forInvalidParams($e->getMessage(), $request->getId()); } elseif ($e instanceof SessionRequiredException) { diff --git a/src/Server/Task/Handler/TasksCancelHandler.php b/src/Server/Task/Handler/TasksCancelHandler.php new file mode 100644 index 000000000..9607116b8 --- /dev/null +++ b/src/Server/Task/Handler/TasksCancelHandler.php @@ -0,0 +1,72 @@ + + * + * @author Christopher Hertel + */ +final class TasksCancelHandler implements RequestHandlerInterface +{ + public function __construct( + private readonly TaskStoreInterface $store, + ) { + } + + public function supports(Request $request): bool + { + return $request instanceof TasksCancelRequest; + } + + public function handle(Request $request, SessionInterface $session): Response|Error + { + \assert($request instanceof TasksCancelRequest); + + // The task surface is gated on negotiation: to a client that never + // declared the extension these methods do not exist as *its* methods, + // and -32021 says which declaration is missing. + if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { + return $refusal; + } + + $task = $this->store->get($request->taskId); + + if (null === $task) { + return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); + } + + if (!$task->status->isTerminal()) { + $this->store->save($task->with(TaskStatus::Cancelled)); + } + + return new Response($request->getId(), new EmptyResult()); + } +} diff --git a/src/Server/Task/Handler/TasksGetHandler.php b/src/Server/Task/Handler/TasksGetHandler.php new file mode 100644 index 000000000..6a6701133 --- /dev/null +++ b/src/Server/Task/Handler/TasksGetHandler.php @@ -0,0 +1,65 @@ + + * + * @author Christopher Hertel + */ +final class TasksGetHandler implements RequestHandlerInterface +{ + public function __construct( + private readonly TaskStoreInterface $store, + ) { + } + + public function supports(Request $request): bool + { + return $request instanceof TasksGetRequest; + } + + public function handle(Request $request, SessionInterface $session): Response|Error + { + \assert($request instanceof TasksGetRequest); + + // The task surface is gated on negotiation: to a client that never + // declared the extension these methods do not exist as *its* methods, + // and -32021 says which declaration is missing. + if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { + return $refusal; + } + + $task = $this->store->get($request->taskId); + + if (null === $task) { + // An unknown id and a lapsed one are the same answer: the spec + // reserves -32602 for exactly this, and a client cannot act on the + // difference. + return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); + } + + return new Response($request->getId(), new TaskResult($task)); + } +} diff --git a/src/Server/Task/Handler/TasksUpdateHandler.php b/src/Server/Task/Handler/TasksUpdateHandler.php new file mode 100644 index 000000000..3b053f521 --- /dev/null +++ b/src/Server/Task/Handler/TasksUpdateHandler.php @@ -0,0 +1,80 @@ + + * + * @author Christopher Hertel + */ +final class TasksUpdateHandler implements RequestHandlerInterface +{ + public function __construct( + private readonly TaskStoreInterface $store, + private readonly ?TaskInputHandlerInterface $inputHandler = null, + ) { + } + + public function supports(Request $request): bool + { + return $request instanceof TasksUpdateRequest; + } + + public function handle(Request $request, SessionInterface $session): Response|Error + { + \assert($request instanceof TasksUpdateRequest); + + // The task surface is gated on negotiation: to a client that never + // declared the extension these methods do not exist as *its* methods, + // and -32021 says which declaration is missing. + if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { + return $refusal; + } + + $task = $this->store->get($request->taskId); + + if (null === $task) { + return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); + } + + // Answers to something already finished, or never asked for, are + // ignored rather than refused: the spec says to drop responses for + // unknown or already-satisfied keys, and a terminal task is the same + // case one step further along. + if (TaskStatus::InputRequired === $task->status) { + $updated = $this->inputHandler?->receive($task, $request->inputResponses) + ?? $task->with(TaskStatus::Working, statusMessage: 'Input received.'); + + $this->store->save($updated); + } + + return new Response($request->getId(), new EmptyResult()); + } +} diff --git a/src/Server/Task/InMemoryTaskStore.php b/src/Server/Task/InMemoryTaskStore.php new file mode 100644 index 000000000..7ac56bb2c --- /dev/null +++ b/src/Server/Task/InMemoryTaskStore.php @@ -0,0 +1,84 @@ + + */ +final class InMemoryTaskStore implements TaskStoreInterface +{ + /** @var array */ + private array $tasks = []; + + private readonly ClockInterface $clock; + + /** + * @param int $limit how many tasks to keep before dropping the oldest, so an unbounded + * run of task creation cannot exhaust memory + */ + public function __construct( + private readonly int $limit = 1000, + ?ClockInterface $clock = null, + ) { + if ($this->limit < 1) { + throw new InvalidArgumentException(\sprintf('A task store must hold at least one task, got %d.', $this->limit)); + } + + $this->clock = $clock ?? new NativeClock(); + } + + public function save(Task $task): void + { + // Re-inserted rather than updated in place, so the eviction order below + // reflects last use and a task being polled is not the one dropped. + unset($this->tasks[$task->taskId]); + $this->tasks[$task->taskId] = $task; + + while (\count($this->tasks) > $this->limit) { + array_shift($this->tasks); + } + } + + public function get(string $taskId): ?Task + { + $task = $this->tasks[$taskId] ?? null; + + if (null === $task) { + return null; + } + + if (!$task->isReadable($this->clock->now())) { + unset($this->tasks[$taskId]); + + return null; + } + + return $task; + } + + public function delete(string $taskId): void + { + unset($this->tasks[$taskId]); + } +} diff --git a/src/Server/Task/Psr16TaskStore.php b/src/Server/Task/Psr16TaskStore.php new file mode 100644 index 000000000..3b0bedf4d --- /dev/null +++ b/src/Server/Task/Psr16TaskStore.php @@ -0,0 +1,119 @@ + + */ +final class Psr16TaskStore implements TaskStoreInterface +{ + private readonly ClockInterface $clock; + + /** + * @param string $prefix namespace for this store's keys, so one cache can carry several + * @param int $defaultTtl seconds a task with no `ttlMs` of its own is kept + */ + public function __construct( + private readonly CacheInterface $cache, + private readonly string $prefix = 'mcp.tasks.', + private readonly int $defaultTtl = 3600, + private readonly LoggerInterface $logger = new NullLogger(), + ?ClockInterface $clock = null, + ) { + $this->clock = $clock ?? new NativeClock(); + } + + public function save(Task $task): void + { + $ttl = null !== $task->ttlMs + ? max(1, (int) ceil($task->ttlMs / 1000)) + : $this->defaultTtl; + + $this->cache->set($this->prefix.$task->taskId, json_encode(self::toArray($task), \JSON_THROW_ON_ERROR), $ttl); + } + + public function get(string $taskId): ?Task + { + $raw = $this->cache->get($this->prefix.$taskId); + + if (!\is_string($raw)) { + return null; + } + + try { + /** @var array $data */ + $data = json_decode($raw, true, flags: \JSON_THROW_ON_ERROR); + $task = Task::fromArray($data); + } catch (\Throwable $e) { + // Written by an older shape, or corrupted. Unreadable and expired + // look the same to a client, and neither is worth failing on. + $this->logger->warning('Dropped an unreadable task from the store.', ['taskId' => $taskId, 'exception' => $e]); + + return null; + } + + // The cache TTL is coarser than the task's own — it is whole seconds — + // so the task still has the last word on whether it is readable. + return $task->isReadable($this->clock->now()) ? $task : null; + } + + public function delete(string $taskId): void + { + $this->cache->delete($this->prefix.$taskId); + } + + /** + * @return array + */ + private static function toArray(Task $task): array + { + return [ + 'taskId' => $task->taskId, + 'status' => $task->status->value, + 'createdAt' => $task->createdAt?->format(\DATE_ATOM), + 'lastUpdatedAt' => $task->lastUpdatedAt?->format(\DATE_ATOM), + 'ttlMs' => $task->ttlMs, + 'pollIntervalMs' => $task->pollIntervalMs, + 'statusMessage' => $task->statusMessage, + 'result' => $task->result, + 'error' => null !== $task->error + ? ['code' => $task->error->code, 'message' => $task->error->message, 'data' => $task->error->data] + : null, + // Kept as the envelopes they go out as, so a parked task still + // knows what it is waiting for after a round trip through storage. + 'inputRequests' => array_map( + static fn (Request $request): array => $request->withId(0)->jsonSerialize(), + $task->inputRequests, + ), + ]; + } +} diff --git a/src/Server/Task/TaskCapabilityGuard.php b/src/Server/Task/TaskCapabilityGuard.php new file mode 100644 index 000000000..6f258557f --- /dev/null +++ b/src/Server/Task/TaskCapabilityGuard.php @@ -0,0 +1,61 @@ + + */ +final class TaskCapabilityGuard +{ + /** + * The refusal to return, or null when the client declared the extension. + */ + public static function refuse(Request $request, SessionInterface $session): ?Error + { + if (self::declared($session)) { + return null; + } + + return Error::forMissingRequiredClientCapability( + \sprintf('The "%s" methods need the extension the client did not declare.', TasksExtension::ID), + self::required(), + $request->getId(), + ); + } + + /** + * Whether the client declared the extension during `initialize`. + */ + public static function declared(SessionInterface $session): bool + { + $capabilities = (array) $session->get('client_capabilities', []); + $extensions = $capabilities['extensions'] ?? null; + + return TasksExtension::declaredBy(null === $extensions ? null : (array) $extensions); + } + + private static function required(): ClientCapabilities + { + return new ClientCapabilities(roots: false, extensions: [TasksExtension::ID => new \stdClass()]); + } +} diff --git a/src/Server/Task/TaskContext.php b/src/Server/Task/TaskContext.php new file mode 100644 index 000000000..ed18a6628 --- /dev/null +++ b/src/Server/Task/TaskContext.php @@ -0,0 +1,116 @@ +isSupported()) { + * return runSynchronously(); + * } + * + * $created = $tasks->create(pollIntervalMs: 1000); + * $queue->push($created->task->taskId); + * + * return $created; + * } + * ``` + * + * @author Christopher Hertel + */ +final class TaskContext +{ + public function __construct( + private readonly SessionInterface $session, + private readonly TaskStoreInterface $store, + ) { + } + + /** + * Whether this client declared the extension during `initialize`. + * + * A handler that can work either way must ask before creating a task: a + * client that did not declare it has no polling loop, and the specification + * says such a request falls through to running synchronously rather than + * failing. + */ + public function isSupported(): bool + { + return TaskCapabilityGuard::declared($this->session); + } + + /** + * Creates a task and stores it, returning the result to hand back. + * + * The handler's own work is not started here — that is the application's, + * and in PHP it usually means enqueueing something a worker picks up. What + * this guarantees is the part the specification cares about: the task is + * durably stored *before* its id reaches the client, so the first + * `tasks/get` cannot arrive before the task exists. + * + * @param ?int $ttlMs how long the task stays readable; null for no limit + * @param ?int $pollIntervalMs how long the client should wait between polls + * + * @throws MissingRequiredClientCapabilityException when the client did not declare the extension — it has no + * `tasks/get` loop, and a handle it will never poll is worse + * than a slow answer; the server answers `-32021` instead + */ + public function create( + ?string $taskId = null, + ?int $ttlMs = 3_600_000, + ?int $pollIntervalMs = 1000, + ?string $statusMessage = null, + ): CreateTaskResult { + if (!$this->isSupported()) { + throw new MissingRequiredClientCapabilityException(new ClientCapabilities(roots: false, extensions: [TasksExtension::ID => new \stdClass()]), \sprintf('This request is served as a task, which needs the "%s" extension the client did not declare.', TasksExtension::ID)); + } + + $now = new \DateTimeImmutable(); + + $task = new Task( + $taskId ?? Uuid::v4()->toRfc4122(), + TaskStatus::Working, + $now, + $now, + $ttlMs, + $pollIntervalMs, + $statusMessage, + ); + + $this->store->save($task); + + return new CreateTaskResult($task); + } + + /** + * The store this request is served with, for a handler that needs to + * advance a task it did not create here. + */ + public function getStore(): TaskStoreInterface + { + return $this->store; + } +} diff --git a/src/Server/Task/TaskInputHandlerInterface.php b/src/Server/Task/TaskInputHandlerInterface.php new file mode 100644 index 000000000..0171f4e0e --- /dev/null +++ b/src/Server/Task/TaskInputHandlerInterface.php @@ -0,0 +1,35 @@ + + */ +interface TaskInputHandlerInterface +{ + /** + * Applies $inputResponses to $task and returns its new state. + * + * Keys match the task's `inputRequests`. Anything unrecognized should be + * ignored rather than refused. + * + * @param array $inputResponses + */ + public function receive(Task $task, array $inputResponses): Task; +} diff --git a/src/Server/Task/TaskStoreInterface.php b/src/Server/Task/TaskStoreInterface.php new file mode 100644 index 000000000..b4b9adcd0 --- /dev/null +++ b/src/Server/Task/TaskStoreInterface.php @@ -0,0 +1,46 @@ + + */ +interface TaskStoreInterface +{ + /** + * Stores a task, overwriting any earlier state under the same id. + */ + public function save(Task $task): void; + + /** + * The task, or null when there is no such id — or when its TTL has lapsed, + * which a client cannot tell apart and does not need to. + */ + public function get(string $taskId): ?Task; + + /** + * Drops a task before its TTL, if the store supports it. + */ + public function delete(string $taskId): void; +} diff --git a/src/Server/Task/TasksExtension.php b/src/Server/Task/TasksExtension.php new file mode 100644 index 000000000..35c73315a --- /dev/null +++ b/src/Server/Task/TasksExtension.php @@ -0,0 +1,116 @@ +enableExtension(new TasksExtension(new InMemoryTaskStore())); + * Client::builder()->enableExtension(new TasksExtension()); + * ``` + * + * Creating a task is the *server's* decision, made per request — a client opts + * in once by declaring the extension and then handles whichever result shape + * arrives. A handler creates one through the {@see TaskContext} it can declare + * as a parameter, and returns the {@see \Mcp\Schema\Result\CreateTaskResult}. + * + * @author Christopher Hertel + */ +final class TasksExtension implements ServerExtensionInterface, ArgumentProvidingExtensionInterface +{ + public const ID = 'io.modelcontextprotocol/tasks'; + + /** + * @param ?TaskStoreInterface $store where a server keeps its tasks; a client declaring the extension needs none + */ + public function __construct( + private readonly ?TaskStoreInterface $store = null, + private readonly ?TaskInputHandlerInterface $inputHandler = null, + ) { + } + + public function getId(): ExtensionIdentifier + { + return new ExtensionIdentifier(self::ID); + } + + public function getCapabilities(): array + { + return []; + } + + public function getMessages(): array + { + return [ + TasksGetRequest::class, + TasksUpdateRequest::class, + TasksCancelRequest::class, + ]; + } + + public function getRequestHandlers(): iterable + { + $store = $this->getStore(); + + yield new TasksGetHandler($store); + yield new TasksUpdateHandler($store, $this->inputHandler); + yield new TasksCancelHandler($store); + } + + public function getArgumentProviders(): array + { + $store = $this->getStore(); + + return [ + TaskContext::class => static fn (SessionInterface $session, Request $request): TaskContext => new TaskContext($session, $store), + ]; + } + + /** + * @throws LogicException when enabled on a server without a store + */ + public function getStore(): TaskStoreInterface + { + return $this->store ?? throw new LogicException(\sprintf('The Tasks extension needs a store to serve tasks/*; enable it with new %s(new InMemoryTaskStore()) or another %s.', self::class, TaskStoreInterface::class)); + } + + /** + * Whether a client's declared capabilities include this extension. + * + * The gate on task creation: a client that never declared it has no + * `tasks/get` loop and would be left holding a handle it does not know how + * to redeem. + * + * @param ?array $extensions the `extensions` member of the request's clientCapabilities + */ + public static function declaredBy(?array $extensions): bool + { + return \array_key_exists(self::ID, $extensions ?? []); + } +} diff --git a/tests/Integration/Fixture/tasks.php b/tests/Integration/Fixture/tasks.php new file mode 100644 index 000000000..02194d4a5 --- /dev/null +++ b/tests/Integration/Fixture/tasks.php @@ -0,0 +1,152 @@ +> what each task becomes on its next polls */ + private array $plans = []; + + public function __construct(private readonly TaskStoreInterface $inner) + { + } + + /** + * @param list $states + */ + public function plan(string $taskId, array $states): void + { + $this->plans[$taskId] = $states; + } + + public function save(Task $task): void + { + $this->inner->save($task); + } + + public function get(string $taskId): ?Task + { + $task = $this->inner->get($taskId); + + if (null === $task || $task->status->isTerminal() || [] === ($this->plans[$taskId] ?? [])) { + return $task; + } + + $next = array_shift($this->plans[$taskId]); + $this->inner->save($next); + + return $next; + } + + public function delete(string $taskId): void + { + $this->inner->delete($taskId); + } + + public function receive(Task $task, array $inputResponses): Task + { + $name = $inputResponses['name']['content']['name'] ?? 'nobody'; + + return $task->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('Hello, '.$name)])); + } +}; + +Server::builder() + ->setServerInfo('integration-server', '1.0.0') + ->enableExtension(new TasksExtension($store, $store)) + ->addTool( + static function (TaskContext $tasks) use ($store): CreateTaskResult|string { + if (!$tasks->isSupported()) { + return 'sync'; + } + + $created = $tasks->create(pollIntervalMs: 10, statusMessage: 'queued'); + $store->plan($created->task->taskId, [ + $created->task->with(TaskStatus::Working, statusMessage: 'halfway'), + $created->task->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('done')])), + ]); + + return $created; + }, + name: 'long_job', + description: 'Runs as a task when the client can poll, synchronously otherwise.', + ) + ->addTool( + static fn (TaskContext $tasks): CreateTaskResult => $tasks->create(pollIntervalMs: 10), + name: 'task_only', + description: 'Always creates a task, even for a client that cannot poll.', + ) + ->addTool( + static function (TaskContext $tasks) use ($store): CreateTaskResult { + $created = $tasks->create(pollIntervalMs: 10); + $store->plan($created->task->taskId, [ + $created->task->with(TaskStatus::InputRequired, inputRequests: [ + 'name' => new ElicitRequest('What is your name?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])), + ]), + ]); + + return $created; + }, + name: 'ask_job', + description: 'Parks for the client\'s name, then greets.', + ) + ->addTool( + static function (TaskContext $tasks) use ($store): CreateTaskResult { + $created = $tasks->create(pollIntervalMs: 10); + $store->plan($created->task->taskId, [$created->task->with(TaskStatus::Failed, error: Error::forInternalError('the worker died'))]); + + return $created; + }, + name: 'failing_job', + description: 'Fails at the protocol level.', + ) + ->addPrompt( + static function (TaskContext $tasks) use ($store): CreateTaskResult { + $created = $tasks->create(pollIntervalMs: 10); + $store->plan($created->task->taskId, [ + $created->task->with(TaskStatus::Completed, result: new GetPromptResult([new PromptMessage(Role::User, new TextContent('prompt done'))])), + ]); + + return $created; + }, + name: 'slow_prompt', + description: 'A prompt served as a task.', + ) + ->build() + ->run(new StdioTransport()); diff --git a/tests/Integration/TasksTest.php b/tests/Integration/TasksTest.php new file mode 100644 index 000000000..a0b81859c --- /dev/null +++ b/tests/Integration/TasksTest.php @@ -0,0 +1,207 @@ +connectDeclaring(); + + $result = $client->callTool('long_job'); + + $this->assertInstanceOf(CreateTaskResult::class, $result); + $this->assertSame(TaskStatus::Working, $result->task->status); + $this->assertSame('queued', $result->task->statusMessage); + $this->assertSame(10, $result->task->pollIntervalMs); + $this->assertNotNull($result->task->createdAt); + } + + #[TestDox('a task is polled to completion and carries the tool result')] + public function testTaskIsPolledToCompletion(): void + { + $client = $this->connectDeclaring(); + $created = $client->callTool('long_job'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + + $polled = $client->get($created->task->taskId); + $this->assertSame(TaskStatus::Working, $polled->status); + $this->assertSame('halfway', $polled->statusMessage); + + $done = $this->settle($client, $created->task->taskId); + $this->assertSame(TaskStatus::Completed, $done->status); + $this->assertNull($done->error); + + $result = CallToolResult::fromArray($done->result); + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('done', $result->content[0]->text); + } + + #[TestDox('a client that did not declare the extension gets the synchronous answer')] + public function testUndeclaredClientIsServedSynchronously(): void + { + $client = $this->connect('tasks'); + + $result = $client->callTool('long_job'); + + $this->assertInstanceOf(CallToolResult::class, $result); + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('sync', $result->content[0]->text); + } + + #[TestDox('a task-only tool refuses a client that cannot poll with -32021')] + public function testUndeclaredClientIsRefusedARequiredTask(): void + { + $client = $this->connect('tasks'); + + try { + $client->callTool('task_only'); + $this->fail('Expected the task to be refused.'); + } catch (RequestException $e) { + $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $e->getError()?->code); + $this->assertArrayHasKey(TasksExtension::ID, $e->getError()->data['requiredCapabilities']['extensions']); + } + } + + #[TestDox('the tasks/* methods themselves are refused to a client that did not declare the extension')] + public function testUndeclaredClientCannotPoll(): void + { + $client = new TaskClient($this->connect('tasks')); + + try { + $client->get('anything'); + $this->fail('Expected tasks/get to be refused.'); + } catch (RequestException $e) { + $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $e->getError()?->code); + } + } + + #[TestDox('a parked task exposes what it asks for, and an answer through tasks/update completes it')] + public function testInputRequiredRoundTrip(): void + { + $client = $this->connectDeclaring(); + $created = $client->callTool('ask_job'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + + $parked = $client->get($created->task->taskId); + $this->assertSame(TaskStatus::InputRequired, $parked->status); + $this->assertArrayHasKey('name', $parked->inputRequests); + $this->assertInstanceOf(ElicitRequest::class, $parked->inputRequests['name']); + $this->assertSame('What is your name?', $parked->inputRequests['name']->message); + + $client->update($created->task->taskId, ['name' => ['action' => 'accept', 'content' => ['name' => 'Ada']]]); + + $done = $client->get($created->task->taskId); + $this->assertSame(TaskStatus::Completed, $done->status); + $this->assertSame('Hello, Ada', CallToolResult::fromArray($done->result)->content[0]->text ?? null); + } + + #[TestDox('a failed task carries the error inline and no result')] + public function testFailedTask(): void + { + $client = $this->connectDeclaring(); + $created = $client->callTool('failing_job'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + + $failed = $this->settle($client, $created->task->taskId); + + $this->assertSame(TaskStatus::Failed, $failed->status); + $this->assertNull($failed->result); + $this->assertSame(Error::INTERNAL_ERROR, $failed->error?->code); + $this->assertSame('the worker died', $failed->error->message); + } + + #[TestDox('cancelling is cooperative and idempotent')] + public function testCancel(): void + { + $client = $this->connectDeclaring(); + $created = $client->callTool('task_only'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + + $client->cancel($created->task->taskId); + $this->assertSame(TaskStatus::Cancelled, $client->get($created->task->taskId)->status); + + $client->cancel($created->task->taskId); + $this->assertSame(TaskStatus::Cancelled, $client->get($created->task->taskId)->status); + } + + #[TestDox('an unknown task is invalid params, not a missing method')] + public function testUnknownTask(): void + { + $client = $this->connectDeclaring(); + + try { + $client->get('no-such-task'); + $this->fail('Expected tasks/get to fail.'); + } catch (RequestException $e) { + $this->assertSame(Error::INVALID_PARAMS, $e->getError()?->code); + } + } + + #[TestDox('a prompt can be served as a task too')] + public function testPromptAsTask(): void + { + $client = $this->connectDeclaring(); + $created = $client->getPrompt('slow_prompt'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + + $done = $this->settle($client, $created->task->taskId); + + $this->assertSame(TaskStatus::Completed, $done->status); + $prompt = GetPromptResult::fromArray($done->result); + $this->assertSame('prompt done', $prompt->messages[0]->content->text ?? null); + } + + private function connectDeclaring(): TaskClient + { + return new TaskClient($this->connect('tasks', $this->clientBuilder()->enableExtension(new TasksExtension()))); + } + + /** + * Polls until the task reaches a terminal status, honouring `pollIntervalMs`. + */ + private function settle(TaskClient $client, string $taskId): Task + { + for ($i = 0; $i < 20; ++$i) { + $task = $client->get($taskId); + + if ($task->status->isTerminal()) { + return $task; + } + + usleep(1000 * ($task->pollIntervalMs ?? 10)); + } + + $this->fail(\sprintf('Task "%s" did not settle.', $taskId)); + } +} diff --git a/tests/Unit/Server/BuilderTest.php b/tests/Unit/Server/BuilderTest.php index 32acdf3a1..df468075a 100644 --- a/tests/Unit/Server/BuilderTest.php +++ b/tests/Unit/Server/BuilderTest.php @@ -39,6 +39,9 @@ use Mcp\Server\Stateless\StatelessProtocol; use Mcp\Server\Subscription\InMemoryNotificationBus; use Mcp\Server\Subscription\PublishingEventDispatcher; +use Mcp\Server\Task\InMemoryTaskStore; +use Mcp\Server\Task\TaskContext; +use Mcp\Server\Task\TasksExtension; use Mcp\Server\Transport\InMemoryTransport; use Mcp\Tests\Unit\Server\Extension\ThingExtension; use Mcp\Tests\Unit\Server\Extension\ThingListHandler; @@ -190,6 +193,29 @@ public function testEnableExtensionRejectsDuplicate(): void Server::builder()->enableExtension(new McpApps(), new McpApps()); } + #[TestDox('enableExtension() lets an extension hand its own object to handlers, and keeps it out of the schema')] + public function testEnableExtensionProvidesHandlerArguments(): void + { + $server = Server::builder() + ->setServerInfo('test', '1.0.0') + ->enableExtension(new TasksExtension(new InMemoryTaskStore())) + ->addTool(static fn (TaskContext $tasks): string => $tasks->isSupported() ? 'tasks' : 'no tasks', name: 'probe') + ->build(); + + $this->assertArrayHasKey(TasksExtension::ID, $this->extractServerCapabilities($server)->extensions ?? []); + $this->assertSame('no tasks', $this->callTool($server, 'probe')); + + $protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server); + foreach ((new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol) as $handler) { + if ($handler instanceof CallToolHandler) { + $registry = (new \ReflectionClass($handler))->getProperty('registry')->getValue($handler); + $schema = $registry->getTool('probe')->tool->inputSchema; + $this->assertArrayNotHasKey('required', $schema); + $this->assertSame([], (array) ($schema['properties'] ?? [])); + } + } + } + #[TestDox('enableExtension() extensions are merged into capabilities set via setCapabilities()')] public function testEnableExtensionMergesIntoCustomCapabilities(): void { diff --git a/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php b/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php index b1ad60b7e..09848a2ed 100644 --- a/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php +++ b/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php @@ -12,6 +12,7 @@ namespace Mcp\Tests\Unit\Server\Capability\Registry; use Mcp\Schema\JsonRpc\Error; +use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\Request\PingRequest; use Mcp\Server\Capability\Registry\Container; use Mcp\Server\Capability\Registry\ElementReference; @@ -259,6 +260,23 @@ public function testHandleStillReflectsOrdinaryClosuresAndDoesNotInjectArgumentB $this->assertSame('value', $captured); } + public function testHandleInjectsWhatAnArgumentProviderBuildsForTheRequest(): void + { + $session = $this->createMock(SessionInterface::class); + $request = PingRequest::fromArray(['jsonrpc' => '2.0', 'id' => 7, 'method' => 'ping']); + + $closure = static fn (\ArrayObject $provided, string $kept): string => $provided['request'].':'.$kept; + $reference = new ElementReference($closure); + + $handler = new ReferenceHandler(argumentProviders: [ + \ArrayObject::class => static fn (SessionInterface $s, Request $r): \ArrayObject => new \ArrayObject(['request' => $r::getMethod().'#'.$r->getId()]), + ]); + + $result = $handler->handle($reference, ['_session' => $session, '_request' => $request, 'kept' => 'value']); + + $this->assertSame('ping#7:value', $result); + } + public function testHandleThrowsForStringHandlerThatIsNeitherFunctionNorClass(): void { $session = $this->createMock(SessionInterface::class); diff --git a/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php index e19ac9339..6c3cf62f1 100644 --- a/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php +++ b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php @@ -11,16 +11,19 @@ namespace Mcp\Tests\Unit\Server\Handler\Request; +use Mcp\Schema\ClientCapabilities; use Mcp\Schema\Content\TextContent; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Response; use Mcp\Schema\Request\CallToolRequest; use Mcp\Schema\Result\CallToolResult; +use Mcp\Schema\Result\EmptyResult; use Mcp\Schema\Tool; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\Registry\ToolReference; use Mcp\Server\Capability\RegistryInterface; +use Mcp\Server\Exception\MissingRequiredClientCapabilityException; use Mcp\Server\Exception\RegistryException; use Mcp\Server\Exception\ToolCallException; use Mcp\Server\Exception\ToolNotFoundException; @@ -104,6 +107,42 @@ public function testHandleSuccessfulToolCall(): void $this->assertEquals($expectedResult, $response->result); } + public function testAResultOfAnotherKindIsPassedThroughUntouched(): void + { + // What an extension's handler returns — a task handle, say — is a + // result in its own right, not tool output to be formatted. + $request = $this->createCallToolRequest('slow_tool', []); + $toolReference = $this->createToolReference('slow_tool', static fn () => null); + $foreign = new EmptyResult(); + + $this->registry->method('getTool')->willReturn($toolReference); + $this->referenceHandler->method('handle')->willReturn($foreign); + $toolReference->expects($this->never())->method('formatResult'); + + $response = $this->handler->handle($request, $this->session); + + $this->assertInstanceOf(Response::class, $response); + $this->assertSame($foreign, $response->result); + } + + public function testAMissingClientCapabilityIsLeftToTheProtocol(): void + { + // Not a tool failure: the request was unservable, and the protocol + // renders it as -32021. The handler must let it through rather than + // turn it into tool output. + $request = $this->createCallToolRequest('slow_tool', []); + $toolReference = $this->createToolReference('slow_tool', static fn () => null); + $required = new ClientCapabilities(extensions: ['io.example/thing' => new \stdClass()]); + + $this->registry->method('getTool')->willReturn($toolReference); + $this->referenceHandler->method('handle')->willThrowException(new MissingRequiredClientCapabilityException($required, 'Needs the thing.')); + + $this->expectException(MissingRequiredClientCapabilityException::class); + $this->expectExceptionMessage('Needs the thing.'); + + $this->handler->handle($request, $this->session); + } + public function testHandleToolCallWithEmptyArguments(): void { $request = $this->createCallToolRequest('simple_tool', []); diff --git a/tests/Unit/Server/Task/TaskStoreTest.php b/tests/Unit/Server/Task/TaskStoreTest.php new file mode 100644 index 000000000..d0f99ea8b --- /dev/null +++ b/tests/Unit/Server/Task/TaskStoreTest.php @@ -0,0 +1,239 @@ + + */ + public static function stores(): iterable + { + yield 'in memory' => [new InMemoryTaskStore()]; + yield 'psr-16' => [new Psr16TaskStore(self::arrayCache())]; + } + + #[DataProvider('stores')] + #[TestDox('a task round-trips through the store')] + public function testRoundTrip(TaskStoreInterface $store): void + { + $store->save(new Task('t-1', TaskStatus::Working, new \DateTimeImmutable(), new \DateTimeImmutable(), 600_000, 250, 'halfway')); + + $task = $store->get('t-1'); + + $this->assertNotNull($task); + $this->assertSame('t-1', $task->taskId); + $this->assertSame(TaskStatus::Working, $task->status); + $this->assertSame(600_000, $task->ttlMs); + $this->assertSame(250, $task->pollIntervalMs); + $this->assertSame('halfway', $task->statusMessage); + } + + #[DataProvider('stores')] + #[TestDox('an unknown id reads as absent')] + public function testUnknownIdIsNull(TaskStoreInterface $store): void + { + $this->assertNull($store->get('nope')); + } + + #[DataProvider('stores')] + #[TestDox('a saved task overwrites the earlier state under the same id')] + public function testSaveOverwrites(TaskStoreInterface $store): void + { + $task = new Task('t-2', TaskStatus::Working, new \DateTimeImmutable(), new \DateTimeImmutable(), 600_000); + $store->save($task); + $store->save($task->with(TaskStatus::Cancelled)); + + $this->assertSame(TaskStatus::Cancelled, $store->get('t-2')?->status); + } + + #[DataProvider('stores')] + #[TestDox('a failed task keeps its error across the store')] + public function testErrorSurvives(TaskStoreInterface $store): void + { + $task = (new Task('t-3', TaskStatus::Working, new \DateTimeImmutable(), null, 600_000)) + ->with(TaskStatus::Failed, error: Error::forInternalError('boom')); + + $store->save($task); + + $read = $store->get('t-3'); + $this->assertNotNull($read); + $this->assertNotNull($read->error); + $this->assertSame(Error::INTERNAL_ERROR, $read->error->code); + $this->assertSame('boom', $read->error->message); + } + + #[DataProvider('stores')] + #[TestDox('a parked task still knows what it is waiting for after a round trip')] + public function testInputRequestsSurvive(TaskStoreInterface $store): void + { + $task = (new Task('t-4', TaskStatus::Working, new \DateTimeImmutable(), null, 600_000)) + ->with(TaskStatus::InputRequired, inputRequests: [ + 'who' => new ElicitRequest('Who?', new ElicitationSchema(['n' => new StringSchemaDefinition('N')], ['n'])), + ]); + + $store->save($task); + + $read = $store->get('t-4'); + $this->assertNotNull($read); + $this->assertArrayHasKey('who', $read->inputRequests); + $this->assertInstanceOf(ElicitRequest::class, $read->inputRequests['who']); + $this->assertSame('Who?', $read->inputRequests['who']->message); + } + + #[DataProvider('stores')] + #[TestDox('a deleted task is gone')] + public function testDelete(TaskStoreInterface $store): void + { + $store->save(new Task('t-5')); + $store->delete('t-5'); + + $this->assertNull($store->get('t-5')); + } + + #[TestDox('a task past its TTL reads as absent')] + public function testTtlExpiry(): void + { + $created = new \DateTimeImmutable('2026-08-15T10:00:00+00:00'); + $clock = new class($created) implements ClockInterface { + public function __construct(public \DateTimeImmutable $now) + { + } + + public function now(): \DateTimeImmutable + { + return $this->now; + } + }; + + $store = new InMemoryTaskStore(clock: $clock); + $store->save(new Task('t-6', TaskStatus::Working, $created, $created, 1000)); + + $this->assertNotNull($store->get('t-6')); + + $clock->now = $created->modify('+2 seconds'); + $this->assertNull($store->get('t-6')); + } + + #[TestDox('the in-memory store drops the least recently used task past its limit')] + public function testInMemoryEviction(): void + { + $store = new InMemoryTaskStore(limit: 2); + + $store->save(new Task('a')); + $store->save(new Task('b')); + // Touching `a` makes `b` the least recently used. + $store->save(new Task('a', TaskStatus::Working)); + $store->save(new Task('c')); + + $this->assertNotNull($store->get('a')); + $this->assertNull($store->get('b')); + $this->assertNotNull($store->get('c')); + } + + #[TestDox('a store that can hold nothing is refused')] + public function testZeroLimitIsRefused(): void + { + $this->expectException(InvalidArgumentException::class); + + new InMemoryTaskStore(limit: 0); + } + + #[TestDox('an unreadable stored payload reads as absent rather than throwing')] + public function testCorruptPayloadIsDropped(): void + { + $cache = self::arrayCache(); + $cache->set('mcp.tasks.t-7', 'not json at all'); + + $this->assertNull((new Psr16TaskStore($cache))->get('t-7')); + } + + private static function arrayCache(): CacheInterface + { + return new class implements CacheInterface { + /** @var array */ + private array $values = []; + + public function get(string $key, mixed $default = null): mixed + { + return $this->values[$key] ?? $default; + } + + public function set(string $key, mixed $value, int|\DateInterval|null $ttl = null): bool + { + $this->values[$key] = $value; + + return true; + } + + public function delete(string $key): bool + { + unset($this->values[$key]); + + return true; + } + + public function clear(): bool + { + $this->values = []; + + return true; + } + + public function getMultiple(iterable $keys, mixed $default = null): iterable + { + foreach ($keys as $key) { + yield $key => $this->get($key, $default); + } + } + + public function setMultiple(iterable $values, int|\DateInterval|null $ttl = null): bool + { + foreach ($values as $key => $value) { + $this->set((string) $key, $value, $ttl); + } + + return true; + } + + public function deleteMultiple(iterable $keys): bool + { + foreach ($keys as $key) { + $this->delete($key); + } + + return true; + } + + public function has(string $key): bool + { + return \array_key_exists($key, $this->values); + } + }; + } +} diff --git a/tests/Unit/Server/Task/TaskTest.php b/tests/Unit/Server/Task/TaskTest.php new file mode 100644 index 000000000..52ce5040f --- /dev/null +++ b/tests/Unit/Server/Task/TaskTest.php @@ -0,0 +1,173 @@ +jsonSerialize(); + + $this->assertSame('task', $data['resultType']); + $this->assertSame('task-1', $data['taskId']); + $this->assertSame('working', $data['status']); + $this->assertSame(600_000, $data['ttlMs']); + $this->assertSame(250, $data['pollIntervalMs']); + $this->assertArrayNotHasKey('task', $data); + + // A task that was just created has nothing to report yet. + $this->assertArrayNotHasKey('result', $data); + $this->assertArrayNotHasKey('error', $data); + $this->assertArrayNotHasKey('inputRequests', $data); + } + + #[TestDox('the wire fields carry their unit in the name')] + public function testLegacyWireNamesAreGone(): void + { + $data = (new CreateTaskResult(self::task()))->jsonSerialize(); + + $this->assertArrayNotHasKey('ttl', $data); + $this->assertArrayNotHasKey('pollInterval', $data); + } + + #[TestDox('timestamps are ISO-8601')] + public function testTimestampsAreIso8601(): void + { + $data = (new CreateTaskResult(self::task()))->jsonSerialize(); + + $this->assertSame('2026-08-15T10:00:00+00:00', $data['createdAt']); + $this->assertSame('2026-08-15T10:00:00+00:00', $data['lastUpdatedAt']); + } + + #[TestDox('an unlimited TTL is emitted as null, not omitted')] + public function testNullTtlIsEmitted(): void + { + $data = (new CreateTaskResult(new Task('task-1', ttlMs: null)))->jsonSerialize(); + + $this->assertArrayHasKey('ttlMs', $data); + $this->assertNull($data['ttlMs']); + } + + #[TestDox('a completed task inlines the result the request would have returned')] + public function testCompletedTaskInlinesItsResult(): void + { + $task = self::task()->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('done')])); + + $data = (new TaskResult($task))->jsonSerialize(); + + $this->assertSame('completed', $data['status']); + $this->assertSame('done', $data['result']->content[0]->text); + } + + #[TestDox('a failed task inlines the error and carries no result')] + public function testFailedTaskInlinesItsError(): void + { + $task = self::task()->with(TaskStatus::Failed, error: Error::forInternalError('boom')); + + $data = (new TaskResult($task))->jsonSerialize(); + + $this->assertSame('failed', $data['status']); + $this->assertSame(Error::INTERNAL_ERROR, $data['error']['code']); + $this->assertSame('boom', $data['error']['message']); + $this->assertArrayNotHasKey('result', $data); + } + + #[TestDox('a tool that ran and reported a problem is completed, never failed')] + public function testToolErrorCannotBeSpelledAsFailed(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageMatches('/isError/'); + + new Task('task-1', TaskStatus::Completed, error: Error::forInternalError('boom')); + } + + #[TestDox('a failed task without an error is refused')] + public function testFailedTaskNeedsAnError(): void + { + $this->expectException(InvalidArgumentException::class); + + new Task('task-1', TaskStatus::Failed); + } + + #[TestDox('a waiting task surfaces what it is waiting for')] + public function testInputRequiredTaskCarriesItsRequests(): void + { + $task = self::task()->with(TaskStatus::InputRequired, inputRequests: [ + 'who' => new ElicitRequest('Who?', new ElicitationSchema(['n' => new StringSchemaDefinition('N')], ['n'])), + ]); + + $data = (new TaskResult($task))->jsonSerialize(); + + $this->assertSame('input_required', $data['status']); + $this->assertSame('elicitation/create', $data['inputRequests']['who']['method']); + } + + #[TestDox('terminal states are the ones that never change again')] + public function testTerminalStates(): void + { + $this->assertTrue(TaskStatus::Completed->isTerminal()); + $this->assertTrue(TaskStatus::Failed->isTerminal()); + $this->assertTrue(TaskStatus::Cancelled->isTerminal()); + $this->assertFalse(TaskStatus::Working->isTerminal()); + $this->assertFalse(TaskStatus::InputRequired->isTerminal()); + } + + #[TestDox('a task stays readable for its whole TTL, and not past it')] + public function testTtlBoundsReadability(): void + { + $task = self::task(); + + $this->assertTrue($task->isReadable(new \DateTimeImmutable('2026-08-15T10:09:59+00:00'))); + $this->assertFalse($task->isReadable(new \DateTimeImmutable('2026-08-15T10:10:01+00:00'))); + } + + #[TestDox('a task with no TTL is always readable')] + public function testNoTtlIsAlwaysReadable(): void + { + $this->assertTrue((new Task('task-1'))->isReadable(new \DateTimeImmutable('2099-01-01T00:00:00+00:00'))); + } + + #[TestDox('a fractional or negative duration is refused: it is not guidance a client can act on')] + public function testDurationsMustBePositive(): void + { + $this->expectException(InvalidArgumentException::class); + + new Task('task-1', ttlMs: -1); + } +} diff --git a/tests/Unit/Server/Task/TasksExtensionTest.php b/tests/Unit/Server/Task/TasksExtensionTest.php new file mode 100644 index 000000000..a28f870ae --- /dev/null +++ b/tests/Unit/Server/Task/TasksExtensionTest.php @@ -0,0 +1,286 @@ +store = new InMemoryTaskStore(); + } + + public function testDeclaresItselfWithoutSettings(): void + { + $extension = new TasksExtension($this->store); + + $this->assertSame('io.modelcontextprotocol/tasks', (string) $extension->getId()); + $this->assertSame([], $extension->getCapabilities()); + $this->assertSame([TasksGetRequest::class, TasksUpdateRequest::class, TasksCancelRequest::class], $extension->getMessages()); + $this->assertSame($this->store, $extension->getStore()); + } + + public function testWithoutAStoreItOnlyDeclares(): void + { + $extension = new TasksExtension(); + + $this->assertSame([], $extension->getCapabilities()); + $this->expectException(LogicException::class); + $extension->getStore(); + } + + public function testProvidesATaskContextToHandlers(): void + { + $providers = (new TasksExtension($this->store))->getArgumentProviders(); + + $this->assertSame([TaskContext::class], array_keys($providers)); + $context = $providers[TaskContext::class]($this->session(), PingRequest::fromArray(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'ping'])); + $this->assertInstanceOf(TaskContext::class, $context); + $this->assertSame($this->store, $context->getStore()); + } + + public function testTaskContextStoresTheTaskBeforeHandingOutTheHandle(): void + { + $context = new TaskContext($this->session(), $this->store); + $this->assertTrue($context->isSupported()); + + $created = $context->create(ttlMs: 60_000, pollIntervalMs: 500, statusMessage: 'Queued.'); + + $this->assertSame(TaskStatus::Working, $created->task->status); + $this->assertSame(60_000, $created->task->ttlMs); + $this->assertSame(500, $created->task->pollIntervalMs); + $this->assertSame('Queued.', $created->task->statusMessage); + $this->assertSame($created->task, $this->store->get($created->task->taskId)); + } + + public function testTaskContextRefusesAHandleToAClientThatCannotRedeemIt(): void + { + $context = new TaskContext($this->session(declared: false), $this->store); + $this->assertFalse($context->isSupported()); + + try { + $context->create(); + $this->fail('Expected the task to be refused.'); + } catch (MissingRequiredClientCapabilityException $e) { + $this->assertArrayHasKey(TasksExtension::ID, $e->requiredCapabilities->extensions); + $this->assertSame( + Error::MISSING_REQUIRED_CLIENT_CAPABILITY, + Error::forMissingRequiredClientCapability($e->getMessage(), $e->requiredCapabilities, 1)->code, + ); + } + } + + public function testEachMethodHasAHandler(): void + { + $handlers = [...(new TasksExtension($this->store))->getRequestHandlers()]; + + $this->assertCount(3, $handlers); + foreach ([$this->get('t'), $this->update('t'), $this->cancel('t')] as $request) { + $this->assertCount(1, array_filter($handlers, static fn (RequestHandlerInterface $h): bool => $h->supports($request))); + } + } + + public function testDeclaredBy(): void + { + $this->assertTrue(TasksExtension::declaredBy(['io.modelcontextprotocol/tasks' => []])); + $this->assertTrue(TasksExtension::declaredBy(['io.modelcontextprotocol/tasks' => new \stdClass()])); + $this->assertFalse(TasksExtension::declaredBy(['io.modelcontextprotocol/ui' => []])); + $this->assertFalse(TasksExtension::declaredBy(null)); + } + + public function testGetReturnsTheTaskInDetail(): void + { + $this->store->save((new Task('t-1', createdAt: new \DateTimeImmutable('2026-01-01T00:00:00Z'))) + ->with(TaskStatus::Completed, result: ['content' => []], now: new \DateTimeImmutable('2026-01-01T00:00:01Z'))); + + $response = $this->handle($this->get('t-1'), $this->session()); + + $this->assertInstanceOf(Response::class, $response); + $this->assertInstanceOf(TaskResult::class, $response->result); + $this->assertSame([ + 'taskId' => 't-1', + 'status' => 'completed', + 'createdAt' => '2026-01-01T00:00:00+00:00', + 'lastUpdatedAt' => '2026-01-01T00:00:01+00:00', + 'ttlMs' => null, + 'result' => ['content' => []], + ], $response->result->jsonSerialize()); + } + + public function testUnknownTaskIsInvalidParams(): void + { + foreach ([$this->get('nope'), $this->update('nope'), $this->cancel('nope')] as $request) { + $response = $this->handle($request, $this->session()); + + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::INVALID_PARAMS, $response->code); + $this->assertSame(['taskId' => 'nope'], $response->data); + } + } + + public function testUndeclaredClientIsRefusedWithMissingCapability(): void + { + $this->store->save(new Task('t-1')); + + foreach ([$this->get('t-1'), $this->update('t-1'), $this->cancel('t-1')] as $request) { + $response = $this->handle($request, $this->session(declared: false)); + + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $response->code); + $this->assertInstanceOf(ClientCapabilities::class, $response->data['requiredCapabilities']); + $this->assertArrayHasKey(TasksExtension::ID, $response->data['requiredCapabilities']->extensions); + } + + $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + } + + public function testCancelIsCooperativeAndIdempotent(): void + { + $this->store->save(new Task('t-1')); + + $response = $this->handle($this->cancel('t-1'), $this->session()); + $this->assertInstanceOf(Response::class, $response); + $this->assertInstanceOf(EmptyResult::class, $response->result); + $this->assertSame(TaskStatus::Cancelled, $this->store->get('t-1')?->status); + + // A second cancel, and a cancel of something finished, change nothing. + $this->handle($this->cancel('t-1'), $this->session()); + $this->assertSame(TaskStatus::Cancelled, $this->store->get('t-1')->status); + + $this->store->save((new Task('t-2'))->with(TaskStatus::Completed, result: 'done')); + $this->handle($this->cancel('t-2'), $this->session()); + $this->assertSame(TaskStatus::Completed, $this->store->get('t-2')?->status); + } + + public function testUpdateHandsTheAnswersToTheInputHandler(): void + { + $ask = new ElicitRequest('Who?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])); + $this->store->save((new Task('t-1'))->with(TaskStatus::InputRequired, inputRequests: ['who' => $ask])); + + $inputHandler = new class implements TaskInputHandlerInterface { + /** @var array */ + public array $received = []; + + public function receive(Task $task, array $inputResponses): Task + { + $this->received = $inputResponses; + + return $task->with(TaskStatus::Completed, result: 'Hello, '.$inputResponses['who']['content']['name']); + } + }; + + $answers = ['who' => ['action' => 'accept', 'content' => ['name' => 'Ada']]]; + $response = $this->handle($this->update('t-1', $answers), $this->session(), $inputHandler); + + $this->assertInstanceOf(Response::class, $response); + $this->assertInstanceOf(EmptyResult::class, $response->result); + $this->assertSame($answers, $inputHandler->received); + $this->assertSame(TaskStatus::Completed, $this->store->get('t-1')?->status); + $this->assertSame('Hello, Ada', $this->store->get('t-1')->result); + } + + public function testUpdateWithoutAnInputHandlerResumesTheTask(): void + { + $ask = new ElicitRequest('Who?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])); + $this->store->save((new Task('t-1'))->with(TaskStatus::InputRequired, inputRequests: ['who' => $ask])); + + $this->handle($this->update('t-1', ['who' => ['action' => 'decline']]), $this->session()); + + $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + } + + public function testUpdateOfATaskNotWaitingIsIgnored(): void + { + $this->store->save(new Task('t-1')); + + $response = $this->handle($this->update('t-1', ['stale' => []]), $this->session()); + + $this->assertInstanceOf(Response::class, $response); + $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + } + + /** + * @return Response<\Mcp\Schema\JsonRpc\ResultInterface>|Error + */ + private function handle(Request $request, SessionInterface $session, ?TaskInputHandlerInterface $inputHandler = null): Response|Error + { + foreach ((new TasksExtension($this->store, $inputHandler))->getRequestHandlers() as $handler) { + if ($handler->supports($request)) { + return $handler->handle($request, $session); + } + } + + $this->fail(\sprintf('No handler for "%s".', $request::getMethod())); + } + + /** + * A session as `initialize` leaves it, with or without the extension declared. + */ + private function session(bool $declared = true): SessionInterface + { + $session = new Session(new InMemorySessionStore()); + $capabilities = new ClientCapabilities(extensions: $declared ? [TasksExtension::ID => new \stdClass()] : null); + $session->set('client_capabilities', $capabilities->jsonSerialize()); + + return $session; + } + + private function get(string $taskId): TasksGetRequest + { + return TasksGetRequest::fromArray(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tasks/get', 'params' => ['taskId' => $taskId]]); + } + + /** + * @param array $inputResponses + */ + private function update(string $taskId, array $inputResponses = []): TasksUpdateRequest + { + return TasksUpdateRequest::fromArray(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tasks/update', 'params' => ['taskId' => $taskId, 'inputResponses' => $inputResponses]]); + } + + private function cancel(string $taskId): TasksCancelRequest + { + return TasksCancelRequest::fromArray(['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tasks/cancel', 'params' => ['taskId' => $taskId]]); + } +} From b8b7322a27b2f570f2d0b43cd5875fa4ced9048d Mon Sep 17 00:00:00 2001 From: soyuka Date: Thu, 26 Nov 2026 15:29:44 +0100 Subject: [PATCH 2/2] [Server] Rework the Tasks extension Scope it to what survives SEP-3570 and fix the SEP-2663 deviations: - TaskManager held by the application replaces the argument provider seam - tools/call only, no tasks/update nor input_required until MRTR lands - served on 2026-07-28 only, tasks bound to the OAuth client and subject - terminal states are final, PSR-16 writes are checked - Client::callTool() refuses a task result, use TaskClient - marked experimental --- CHANGELOG.md | 4 +- docs/advanced/extensions.md | 107 ++++--- src/Client/Client.php | 44 ++- src/Client/Task/TaskClient.php | 82 +----- .../ArgumentProvidingExtensionInterface.php | 35 --- .../Tasks}/CreateTaskResult.php | 19 +- src/Schema/Extension/Tasks/Task.php | 212 ++++++++++++++ .../{Enum => Extension/Tasks}/TaskStatus.php | 7 +- .../Tasks}/TasksCancelRequest.php | 2 +- .../Tasks}/TasksGetRequest.php | 2 +- src/Schema/Request/TasksUpdateRequest.php | 63 ---- src/Schema/Result/TaskResult.php | 49 ---- src/Schema/Task.php | 271 ------------------ src/Server/Builder.php | 31 +- .../Capability/Discovery/SchemaGenerator.php | 16 +- .../Capability/Registry/ReferenceHandler.php | 16 -- .../Handler/Request/GetPromptHandler.php | 11 +- .../Handler/Request/ReadResourceHandler.php | 14 +- .../Task/Handler/TasksCancelHandler.php | 72 ----- src/Server/Task/Handler/TasksGetHandler.php | 65 ----- src/Server/Task/Handler/TasksHandler.php | 75 +++++ .../Task/Handler/TasksUpdateHandler.php | 80 ------ src/Server/Task/InMemoryTaskStore.php | 29 +- src/Server/Task/Psr16TaskStore.php | 82 ++---- src/Server/Task/TaskCapabilityGuard.php | 61 ---- src/Server/Task/TaskContext.php | 116 -------- src/Server/Task/TaskInputHandlerInterface.php | 35 --- src/Server/Task/TaskManager.php | 158 ++++++++++ src/Server/Task/TaskStoreInterface.php | 22 +- src/Server/Task/TasksExtension.php | 73 +---- tests/Integration/Fixture/tasks.php | 90 ++---- tests/Integration/TasksTest.php | 139 ++++----- .../Unit/Schema/Extension/Tasks/TaskTest.php | 149 ++++++++++ tests/Unit/Server/BuilderTest.php | 26 -- .../Registry/ReferenceHandlerTest.php | 18 -- .../Handler/Request/CallToolHandlerTest.php | 20 -- tests/Unit/Server/ProtocolTest.php | 28 ++ tests/Unit/Server/Task/TaskManagerTest.php | 153 ++++++++++ tests/Unit/Server/Task/TaskStoreTest.php | 223 +++++--------- tests/Unit/Server/Task/TaskTest.php | 173 ----------- tests/Unit/Server/Task/TasksExtensionTest.php | 264 ++++++----------- 41 files changed, 1166 insertions(+), 1970 deletions(-) delete mode 100644 src/Schema/Extension/ArgumentProvidingExtensionInterface.php rename src/Schema/{Result => Extension/Tasks}/CreateTaskResult.php (65%) create mode 100644 src/Schema/Extension/Tasks/Task.php rename src/Schema/{Enum => Extension/Tasks}/TaskStatus.php (88%) rename src/Schema/{Request => Extension/Tasks}/TasksCancelRequest.php (96%) rename src/Schema/{Request => Extension/Tasks}/TasksGetRequest.php (96%) delete mode 100644 src/Schema/Request/TasksUpdateRequest.php delete mode 100644 src/Schema/Result/TaskResult.php delete mode 100644 src/Schema/Task.php delete mode 100644 src/Server/Task/Handler/TasksCancelHandler.php delete mode 100644 src/Server/Task/Handler/TasksGetHandler.php create mode 100644 src/Server/Task/Handler/TasksHandler.php delete mode 100644 src/Server/Task/Handler/TasksUpdateHandler.php delete mode 100644 src/Server/Task/TaskCapabilityGuard.php delete mode 100644 src/Server/Task/TaskContext.php delete mode 100644 src/Server/Task/TaskInputHandlerInterface.php create mode 100644 src/Server/Task/TaskManager.php create mode 100644 tests/Unit/Schema/Extension/Tasks/TaskTest.php create mode 100644 tests/Unit/Server/Task/TaskManagerTest.php delete mode 100644 tests/Unit/Server/Task/TaskTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 89c1c06c7..d33f73609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,8 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Server * Fix const validation errors always reporting the expected value as null. -* Add the Tasks extension (SEP-2663, `io.modelcontextprotocol/tasks`): a server hands back a durable handle instead of holding a connection open — `Mcp\Schema\Task` and `TaskStatus`, `ResultType::Task`, the flat `CreateTaskResult` / `TaskResult` wire shapes, the `tasks/get` / `tasks/update` / `tasks/cancel` surface, and `TaskStoreInterface` with `InMemoryTaskStore` and `Psr16TaskStore` (what PHP-FPM needs). Enable with `Builder::enableExtension(new TasksExtension($store))`; a handler declares a `TaskContext` parameter and creates a task through `TaskContext::create()` after `isSupported()` — a task for a client that did not declare the extension is refused with `-32021`. Advancing a task is the application's job. On the client, `enableExtension(new TasksExtension())` declares it and `Client\Task\TaskClient` speaks it. -* Let an extension reach handler code without the core knowing it: `ArgumentProvidingExtensionInterface` hands handlers objects of the extension's own, injected like a `RequestContext` and left out of the generated schemas; the tool, prompt and resource handlers pass any `ResultInterface` a handler returns through untouched; a `MissingRequiredClientCapabilityException` thrown from handler code is answered as `-32021`; `Client::request()` sends any request. +* Add the Tasks extension (SEP-2663, `io.modelcontextprotocol/tasks`), experimental, API may change with SEP-3570: a `tools/call` can be answered with a durable task the client polls through `tasks/get` and cancels through `tasks/cancel`, from protocol revision `2026-07-28` on. A tool creates one with `TaskManager::create($requestContext)` (refused with `-32021` to a client that did not declare the extension); the task is bound to the OAuth client id and subject of the request, and the application advances it with `TaskManager::transition()`. Stores: `InMemoryTaskStore`, `Psr16TaskStore`. On the client, `Client\Task\TaskClient::callTool()` returns `CallToolResult|CreateTaskResult`, while `Client::callTool()` throws on a task. +* `CallToolHandler` passes any `ResultInterface` a tool returns through untouched, so an extension's result (e.g. `CreateTaskResult`) reaches the client; a `MissingRequiredClientCapabilityException` thrown from a handler is answered as `-32021` on the handshake era too; `Client::sendRequest()` is public, to send requests the typed API does not cover. 0.10.0 ------ diff --git a/docs/advanced/extensions.md b/docs/advanced/extensions.md index 6bbfe6c55..a301c137a 100644 --- a/docs/advanced/extensions.md +++ b/docs/advanced/extensions.md @@ -91,95 +91,90 @@ the same method, `enableExtension()` throws a `LogicException`. Extensions bring notification handlers: add those with `Builder::addNotificationHandler()`. They [don't run on revision `2026-07-28`](custom-handlers.md#protocol-2026-07-28). -An extension that hands handlers an object of its own implements -`ArgumentProvidingExtensionInterface` on top: a handler declaring a parameter -of a provided type receives it for the request being served, the way it -receives a `RequestContext` — and it stays out of the generated input schemas. - ## Tasks (`io.modelcontextprotocol/tasks`) -The [Tasks extension][ext-tasks] (SEP-2663) lets a server hand back a durable -handle instead of holding a connection open for a long-running request. The -client polls `tasks/get` until the task settles, answers anything it asks for -through `tasks/update`, and may `tasks/cancel` it. +!!! warning "Experimental" + The Tasks support is experimental: its API may change with SEP-3570. + +The [Tasks extension][ext-tasks] (SEP-2663) lets a server answer a `tools/call` with a durable +handle instead of holding the connection open. The client polls `tasks/get` until the task +settles, and may `tasks/cancel` it. Only `tools/call` can become a task, and only on protocol +revision `2026-07-28` and later: on older revisions `tasks/*` answer `-32601` and no task is +created. + +Tools create tasks through a `TaskManager`, which you build with a store and pass to the +extension: ```php -use Mcp\Server; +use Mcp\Server\Server; use Mcp\Server\Task\InMemoryTaskStore; -use Mcp\Server\Task\Psr16TaskStore; +use Mcp\Server\Task\TaskManager; use Mcp\Server\Task\TasksExtension; +$tasks = new TaskManager(new InMemoryTaskStore()); + $server = Server::builder() - ->enableExtension(new TasksExtension(new InMemoryTaskStore())) + ->enableExtension(new TasksExtension($tasks)) ->build(); ``` -`InMemoryTaskStore` is right for stdio and any single-process runtime and drops -its oldest task past a configurable limit (1000 by default). Under PHP-FPM the -worker that creates a task is not the one polled for it, so use -`Psr16TaskStore` over a shared cache there — a filesystem adapter is enough. +`InMemoryTaskStore` suits stdio and any single-process runtime, and drops the least recently +saved task past a limit (1000 by default). Under PHP-FPM the worker that creates a task is not +the one polled for it, so use `Psr16TaskStore` over a shared cache. It throws when the cache does +not keep a task, so no handle is handed out for a task `tasks/get` would not find. -Creating a task is the *server's* decision, made per request by returning a -`CreateTaskResult` from any tool, prompt or resource handler. The extension -hands handlers a `TaskContext` — declare the parameter and it arrives, like a -`RequestContext` does: +Creating a task is the server's decision, made per call. A tool takes the `RequestContext` and +asks the manager: ```php -use Mcp\Schema\Result\CreateTaskResult; -use Mcp\Server\Task\TaskContext; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Server\RequestContext; -static function (TaskContext $tasks) use ($queue): CreateTaskResult|string { - if (!$tasks->isSupported()) { +static function (RequestContext $context) use ($tasks, $queue): CreateTaskResult|string { + if (!$tasks->isSupported($context)) { return runSynchronously(); // the client cannot poll, so answer now } - $created = $tasks->create(ttlMs: 600_000, pollIntervalMs: 1000); - $queue->push($created->task->taskId); // a worker calls $store->save() as it progresses + $created = $tasks->create($context, ttlMs: 600_000, pollIntervalMs: 1000); + $queue->push($created->task->taskId); return $created; } ``` -`create()` stores the task *before* returning it, so the first `tasks/get` -cannot arrive before the task exists. A client that did not declare the -extension during `initialize` cannot redeem a handle, so `create()` refuses -with `-32021` (missing required client capability) instead of handing one out — -the right answer for a handler whose task support is *required*, and what -`isSupported()` lets an optional one avoid. +`create()` stores the task before returning it, under a random UUIDv4 id. For a client that did +not declare the extension it throws a `MissingRequiredClientCapabilityException`, answered as +`-32021`: what a tool that can only run as a task should let through. -The SDK owns storage and the `tasks/get` / `tasks/update` / `tasks/cancel` -surface; **advancing** a task is the application's job. A worker (or a -handler, through `TaskContext::getStore()`) saves the task with a new status -as it goes: +When the request was authorized (see [Authorization](../run/authorization.md)), the task is bound +to the OAuth client id and subject of the access token. `tasks/get` and `tasks/cancel` from +another client or subject answer `-32602` "Unknown task", like an id that does not exist. Without +authorization the task id is the only credential. + +The SDK serves `tasks/get` and `tasks/cancel`; running the task is the application's job. A +worker moves it on through the manager: ```php -use Mcp\Schema\Enum\TaskStatus; +use Mcp\Schema\Extension\Tasks\TaskStatus; -$store->save($task->with(TaskStatus::Completed, result: ['content' => [/* ... */]])); +$tasks->transition($taskId, TaskStatus::Completed, result: $callToolResult->jsonSerialize()); ``` -A task that needs the client's input parks itself as `input_required` with -`inputRequests` (elicitation, sampling or roots requests keyed by name); the -client answers through `tasks/update`, and a `TaskInputHandlerInterface` passed -to `TasksExtension` decides what those answers mean for the task. - -Status semantics worth getting right: a tool that ran and reported a problem is -`completed` with `isError` on its result — `failed` is reserved for -protocol-level errors, and carries the error inlined instead of a result. -`Task` refuses to be constructed the other way round. +A task in a terminal status (`completed`, `failed`, `cancelled`) never changes again: +`transition()` throws, so a worker cannot overwrite a cancellation. A tool that ran and reported +a problem is `completed` with `isError` on its result; `failed` is reserved for protocol-level +errors and carries the error instead of a result. ### On the client -A client declares the extension the same way, and then handles whichever -result shape arrives. `TaskClient` wraps a connected `Client`: its `callTool()`, -`getPrompt()` and `readResource()` return a `CreateTaskResult` when the server -chose to answer with a task, and `get()` / `update()` / `cancel()` drive it: +A client declares the extension, then handles either result shape through `TaskClient`. The +plain `Client::callTool()` throws when the server answers with a task. ```php -use Mcp\Client; +use Mcp\Client\Client; use Mcp\Client\Task\TaskClient; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; use Mcp\Schema\Result\CallToolResult; -use Mcp\Schema\Result\CreateTaskResult; use Mcp\Server\Task\TasksExtension; $client = Client::builder() @@ -200,10 +195,8 @@ if ($result instanceof CreateTaskResult) { } ``` -A task waiting as `input_required` lists its `inputRequests`; answer them with -`update($taskId, ['' => $answer])`, keyed as the requests were, and -`cancel($taskId)` asks the server to stop. The core `Client` itself stays -task-agnostic; `Client::request()` sends any request for code like this. +`cancel($taskId)` asks the server to stop; cancellation is cooperative and the task may still +finish. ## MCP Apps (`io.modelcontextprotocol/ui`) diff --git a/src/Client/Client.php b/src/Client/Client.php index b331ea3f9..0b3529e43 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -18,9 +18,11 @@ use Mcp\Client\Exception\RequestCancelledException; use Mcp\Client\Exception\RequestException; use Mcp\Client\Exception\RuntimeException; +use Mcp\Client\Task\TaskClient; use Mcp\Client\Transport\TransportInterface; use Mcp\Schema\Enum\LoggingLevel; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Enum\ResultType; use Mcp\Schema\Exception\ExceptionInterface; use Mcp\Schema\Implementation; use Mcp\Schema\JsonRpc\Error; @@ -244,19 +246,14 @@ 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(); - - // 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); + if (ResultType::Task->value === ($response->result['resultType'] ?? null)) { + throw new RuntimeException(\sprintf('The server answered tool "%s" with a task; call it through %s::callTool() to handle task results.', $name, TaskClient::class)); + } + return CallToolResult::fromArray($response->result); } @@ -409,15 +406,24 @@ public function sendRootsListChanged(): void * * @return Response * - * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException + * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException */ - private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response + public function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response { $transport = $this->transport; if (null === $transport || !$this->protocol->getState()->isInitialized()) { throw new ConnectionException('Client is not connected. Call connect() first.'); } + $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 ($request instanceof CallToolRequest && $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))); + } + $withProgress = null !== $onProgress; $fiber = new \Fiber(fn () => $this->protocol->request($request, $this->config->requestTimeout, $withProgress, $cancellation, $timeoutSeconds ?? $this->config->requestTimeout)); $this->protocol->setProgressCallback($onProgress); @@ -435,22 +441,6 @@ private function sendRequest(Request $request, ?callable $onProgress = null, ?Ca return $response; } - /** - * Sends any request and returns the raw response — the way to speak a - * method the typed API does not cover, such as an extension's. - * - * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress - * Optional callback for progress updates - * - * @return Response - * - * @throws RequestException|ConnectionException - */ - public function request(Request $request, ?callable $onProgress = null): Response - { - return $this->sendRequest($request, $onProgress); - } - /** * Disconnect from the server. */ diff --git a/src/Client/Task/TaskClient.php b/src/Client/Task/TaskClient.php index 301d9ffeb..808192163 100644 --- a/src/Client/Task/TaskClient.php +++ b/src/Client/Task/TaskClient.php @@ -12,41 +12,18 @@ namespace Mcp\Client\Task; use Mcp\Client\Client; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Schema\Extension\Tasks\TasksCancelRequest; +use Mcp\Schema\Extension\Tasks\TasksGetRequest; use Mcp\Schema\Request\CallToolRequest; -use Mcp\Schema\Request\GetPromptRequest; -use Mcp\Schema\Request\ReadResourceRequest; -use Mcp\Schema\Request\TasksCancelRequest; -use Mcp\Schema\Request\TasksGetRequest; -use Mcp\Schema\Request\TasksUpdateRequest; use Mcp\Schema\Result\CallToolResult; -use Mcp\Schema\Result\CreateTaskResult; -use Mcp\Schema\Result\GetPromptResult; -use Mcp\Schema\Result\ReadResourceResult; -use Mcp\Schema\Result\TaskResult; -use Mcp\Schema\Task; /** * The client side of the Tasks extension (SEP-2663), on top of a connected * {@see Client} that declared it. * - * ```php - * $client = Client::builder()->enableExtension(new TasksExtension())->build(); - * $client->connect($transport); - * - * $tasks = new TaskClient($client); - * $result = $tasks->callTool('long_job'); - * - * if ($result instanceof CreateTaskResult) { - * do { - * usleep(1000 * ($result->task->pollIntervalMs ?? 1000)); - * $task = $tasks->get($result->task->taskId); - * } while (!$task->status->isTerminal()); - * } - * ``` - * - * The core client's `callTool()`, `getPrompt()` and `readResource()` expect - * the answer itself; these variants accept a task handle in its place, which a - * server may send once the extension is declared. + * @experimental * * @author Christopher Hertel */ @@ -58,65 +35,32 @@ public function __construct( } /** + * Calls a tool, which the server may answer with a task to poll instead of its result. + * * @param array $arguments * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress */ public function callTool(string $name, array $arguments = [], ?callable $onProgress = null): CallToolResult|CreateTaskResult { - $result = $this->client->request(new CallToolRequest($name, $arguments), $onProgress)->result; + $result = $this->client->sendRequest(new CallToolRequest($name, $arguments), $onProgress)->result; return CreateTaskResult::describes($result) ? 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::describes($result) ? 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 - { - $result = $this->client->request(new ReadResourceRequest($uri), $onProgress)->result; - - return CreateTaskResult::describes($result) ? CreateTaskResult::fromArray($result) : ReadResourceResult::fromArray($result); - } - - /** - * The current state of a task (`tasks/get`). - * - * Poll it at the task's `pollIntervalMs` until {@see \Mcp\Schema\Enum\TaskStatus::isTerminal()}; - * a completed task carries the original request's result, an - * `input_required` one what it is waiting for, to answer with {@see self::update()}. + * The current state of a task (`tasks/get`). Poll it at its `pollIntervalMs` + * until its status is terminal; a completed task carries the tool result. */ public function get(string $taskId): Task { - return TaskResult::fromArray($this->client->request(new TasksGetRequest($taskId))->result)->task; - } - - /** - * Answers what a task asked for (`tasks/update`). - * - * @param array $inputResponses keyed as the task's `inputRequests` were - */ - public function update(string $taskId, array $inputResponses): void - { - $this->client->request(new TasksUpdateRequest($taskId, $inputResponses)); + return Task::fromArray($this->client->sendRequest(new TasksGetRequest($taskId))->result); } /** - * Asks the server to cancel a task (`tasks/cancel`). Cooperative: the task - * may still finish. + * Asks the server to cancel a task (`tasks/cancel`). Cooperative: the task may still finish. */ public function cancel(string $taskId): void { - $this->client->request(new TasksCancelRequest($taskId)); + $this->client->sendRequest(new TasksCancelRequest($taskId)); } } diff --git a/src/Schema/Extension/ArgumentProvidingExtensionInterface.php b/src/Schema/Extension/ArgumentProvidingExtensionInterface.php deleted file mode 100644 index d3c9b5958..000000000 --- a/src/Schema/Extension/ArgumentProvidingExtensionInterface.php +++ /dev/null @@ -1,35 +0,0 @@ - - */ -interface ArgumentProvidingExtensionInterface extends ExtensionInterface -{ - /** - * Builders for the types this extension injects, keyed by the type. - * - * @return array - */ - public function getArgumentProviders(): array; -} diff --git a/src/Schema/Result/CreateTaskResult.php b/src/Schema/Extension/Tasks/CreateTaskResult.php similarity index 65% rename from src/Schema/Result/CreateTaskResult.php rename to src/Schema/Extension/Tasks/CreateTaskResult.php index c1800e3ba..2cc9d8cd3 100644 --- a/src/Schema/Result/CreateTaskResult.php +++ b/src/Schema/Extension/Tasks/CreateTaskResult.php @@ -9,28 +9,21 @@ * file that was distributed with this source code. */ -namespace Mcp\Schema\Result; +namespace Mcp\Schema\Extension\Tasks; use Mcp\Schema\Enum\ResultType; use Mcp\Schema\Exception\InvalidArgumentException; use Mcp\Schema\JsonRpc\ResultInterface; -use Mcp\Schema\Task; /** - * The answer to a request the server decided to run as a task (SEP-2663). + * The answer to a `tools/call` the server decided to run as a task (SEP-2663). * * The result *is* the task: `resultType: "task"` alongside the task's own - * fields, at the root. A nested wrapper would make a client unpack one shape - * here and another from `tasks/get`, for no gain. - * - * Whether to create a task is the server's decision, not something the client - * asks for per request — but the server must not make it for a client that did - * not declare the extension, which {@see \Mcp\Server\Task\TasksExtension} is - * what checks. + * fields, at the root. * * @author Christopher Hertel */ -class CreateTaskResult implements ResultInterface +final class CreateTaskResult implements ResultInterface { public function __construct( public readonly Task $task, @@ -44,7 +37,7 @@ public function __construct( */ public static function fromArray(array $data): self { - if (ResultType::Task->value !== ($data['resultType'] ?? null)) { + if (!self::describes($data)) { throw new InvalidArgumentException('Missing or invalid "resultType" in CreateTaskResult data.'); } @@ -66,8 +59,6 @@ public static function describes(array $data): bool */ public function jsonSerialize(): array { - // The envelope only: a task that was just created has no result, no - // error and nothing it is waiting for. return ['resultType' => ResultType::Task->value, ...$this->task->toEnvelope()]; } } diff --git a/src/Schema/Extension/Tasks/Task.php b/src/Schema/Extension/Tasks/Task.php new file mode 100644 index 000000000..ae64a1db8 --- /dev/null +++ b/src/Schema/Extension/Tasks/Task.php @@ -0,0 +1,212 @@ + + */ +final class Task implements ResultInterface +{ + /** + * @param string $taskId server-assigned, unique and durable + * @param ?int $ttlMs how long the task stays readable through `tasks/get`; null means no limit + * @param ?int $pollIntervalMs how long a client should wait between polls + * @param ?string $statusMessage human-readable progress, e.g. "42 of 100 rows" + * @param ?array $result what the original request would have returned, once completed + * @param ?Error $error a protocol-level failure, inlined when the status is `failed` + * @param ?string $owner who created the task, checked on every access; never sent on the wire + */ + public function __construct( + public readonly string $taskId, + public readonly TaskStatus $status, + public readonly \DateTimeImmutable $createdAt, + public readonly \DateTimeImmutable $lastUpdatedAt, + public readonly ?int $ttlMs = null, + public readonly ?int $pollIntervalMs = null, + public readonly ?string $statusMessage = null, + public readonly ?array $result = null, + public readonly ?Error $error = null, + public readonly ?string $owner = null, + ) { + if ('' === $this->taskId) { + throw new InvalidArgumentException('A task must have a non-empty "taskId".'); + } + + if (null !== $this->ttlMs && $this->ttlMs <= 0) { + throw new InvalidArgumentException(\sprintf('A task "ttlMs" must be a positive number of milliseconds or null, got %d.', $this->ttlMs)); + } + + if (null !== $this->pollIntervalMs && $this->pollIntervalMs <= 0) { + throw new InvalidArgumentException(\sprintf('A task "pollIntervalMs" must be a positive number of milliseconds, got %d.', $this->pollIntervalMs)); + } + + if (TaskStatus::Failed === $this->status && null === $this->error) { + throw new InvalidArgumentException('A failed task must carry the error that stopped it.'); + } + + if (null !== $this->error && TaskStatus::Failed !== $this->status) { + throw new InvalidArgumentException('Only a failed task carries an "error"; a tool that ran and reported a problem is completed with "isError" on its result.'); + } + + if (TaskStatus::Completed === $this->status && null === $this->result) { + throw new InvalidArgumentException('A completed task must carry the "result" the request would have returned.'); + } + } + + /** + * Reads a task back from its wire shape, or from the superset a store keeps. + * + * @param array $data + * + * @throws InvalidArgumentException when the data does not describe a task + */ + public static function fromArray(array $data): self + { + if (!\is_string($data['taskId'] ?? null) || '' === $data['taskId']) { + throw new InvalidArgumentException('Missing or invalid "taskId" in Task data.'); + } + + $status = TaskStatus::tryFrom(\is_string($data['status'] ?? null) ? $data['status'] : ''); + if (null === $status) { + throw new InvalidArgumentException(\sprintf('Missing or invalid "status" in Task data for task "%s".', $data['taskId'])); + } + + if (!\is_string($data['createdAt'] ?? null) || !\is_string($data['lastUpdatedAt'] ?? null)) { + throw new InvalidArgumentException(\sprintf('Missing or invalid "createdAt" or "lastUpdatedAt" in Task data for task "%s".', $data['taskId'])); + } + + $error = \is_array($data['error'] ?? null) && isset($data['error']['code'], $data['error']['message']) + ? new Error(null, (int) $data['error']['code'], (string) $data['error']['message'], $data['error']['data'] ?? null) + : null; + + return new self( + $data['taskId'], + $status, + new \DateTimeImmutable($data['createdAt']), + new \DateTimeImmutable($data['lastUpdatedAt']), + \is_int($data['ttlMs'] ?? null) ? $data['ttlMs'] : null, + \is_int($data['pollIntervalMs'] ?? null) ? $data['pollIntervalMs'] : null, + \is_string($data['statusMessage'] ?? null) ? $data['statusMessage'] : null, + \is_array($data['result'] ?? null) ? $data['result'] : null, + $error, + \is_string($data['owner'] ?? null) ? $data['owner'] : null, + ); + } + + /** + * A copy moved to $status, carrying only what that status carries. + * + * @param ?array $result + * + * @throws LogicException when the task already reached a terminal status + */ + public function with( + TaskStatus $status, + \DateTimeImmutable $now, + ?array $result = null, + ?Error $error = null, + ?string $statusMessage = null, + ): self { + if ($this->status->isTerminal()) { + throw new LogicException(\sprintf('Task "%s" is already %s and cannot become %s.', $this->taskId, $this->status->value, $status->value)); + } + + return new self( + $this->taskId, + $status, + $this->createdAt, + $now, + $this->ttlMs, + $this->pollIntervalMs, + $statusMessage ?? $this->statusMessage, + TaskStatus::Completed === $status ? $result : null, + TaskStatus::Failed === $status ? $error : null, + $this->owner, + ); + } + + /** + * Whether the task is still readable at $now, given its TTL. + */ + public function isReadable(\DateTimeImmutable $now): bool + { + if (null === $this->ttlMs) { + return true; + } + + return $now < $this->createdAt->modify(\sprintf('+%d milliseconds', $this->ttlMs)); + } + + /** + * The task's own fields, without anything its status carries. + * + * @return array + */ + public function toEnvelope(): array + { + $data = [ + 'taskId' => $this->taskId, + 'status' => $this->status->value, + 'createdAt' => $this->createdAt->format(\DATE_ATOM), + 'lastUpdatedAt' => $this->lastUpdatedAt->format(\DATE_ATOM), + // Emitted even as null: null means "unlimited", absent would say nothing. + 'ttlMs' => $this->ttlMs, + ]; + + if (null !== $this->pollIntervalMs) { + $data['pollIntervalMs'] = $this->pollIntervalMs; + } + + if (null !== $this->statusMessage) { + $data['statusMessage'] = $this->statusMessage; + } + + return $data; + } + + /** + * The envelope plus whatever the current status carries. + * + * @return array + */ + public function jsonSerialize(): array + { + $data = $this->toEnvelope(); + + if (TaskStatus::Completed === $this->status) { + $data['result'] = $this->result; + } + + if (null !== $this->error) { + $error = ['code' => $this->error->code, 'message' => $this->error->message]; + + if (null !== $this->error->data) { + $error['data'] = $this->error->data; + } + + $data['error'] = $error; + } + + return $data; + } +} diff --git a/src/Schema/Enum/TaskStatus.php b/src/Schema/Extension/Tasks/TaskStatus.php similarity index 88% rename from src/Schema/Enum/TaskStatus.php rename to src/Schema/Extension/Tasks/TaskStatus.php index a2382b65e..c536c3ec0 100644 --- a/src/Schema/Enum/TaskStatus.php +++ b/src/Schema/Extension/Tasks/TaskStatus.php @@ -9,7 +9,7 @@ * file that was distributed with this source code. */ -namespace Mcp\Schema\Enum; +namespace Mcp\Schema\Extension\Tasks; /** * Where a task is in its life (SEP-2663). @@ -27,9 +27,6 @@ enum TaskStatus: string /** The work is in progress. */ case Working = 'working'; - /** The server needs client input before it can continue. */ - case InputRequired = 'input_required'; - /** The work finished; the result is what the original request would have returned. */ case Completed = 'completed'; @@ -46,7 +43,7 @@ public function isTerminal(): bool { return match ($this) { self::Completed, self::Failed, self::Cancelled => true, - self::Working, self::InputRequired => false, + self::Working => false, }; } } diff --git a/src/Schema/Request/TasksCancelRequest.php b/src/Schema/Extension/Tasks/TasksCancelRequest.php similarity index 96% rename from src/Schema/Request/TasksCancelRequest.php rename to src/Schema/Extension/Tasks/TasksCancelRequest.php index d98c00f1c..bd6325cc4 100644 --- a/src/Schema/Request/TasksCancelRequest.php +++ b/src/Schema/Extension/Tasks/TasksCancelRequest.php @@ -9,7 +9,7 @@ * file that was distributed with this source code. */ -namespace Mcp\Schema\Request; +namespace Mcp\Schema\Extension\Tasks; use Mcp\Schema\Exception\InvalidArgumentException; use Mcp\Schema\JsonRpc\Request; diff --git a/src/Schema/Request/TasksGetRequest.php b/src/Schema/Extension/Tasks/TasksGetRequest.php similarity index 96% rename from src/Schema/Request/TasksGetRequest.php rename to src/Schema/Extension/Tasks/TasksGetRequest.php index 659543a38..a62de1bc7 100644 --- a/src/Schema/Request/TasksGetRequest.php +++ b/src/Schema/Extension/Tasks/TasksGetRequest.php @@ -9,7 +9,7 @@ * file that was distributed with this source code. */ -namespace Mcp\Schema\Request; +namespace Mcp\Schema\Extension\Tasks; use Mcp\Schema\Exception\InvalidArgumentException; use Mcp\Schema\JsonRpc\Request; diff --git a/src/Schema/Request/TasksUpdateRequest.php b/src/Schema/Request/TasksUpdateRequest.php deleted file mode 100644 index 4d3b6dc57..000000000 --- a/src/Schema/Request/TasksUpdateRequest.php +++ /dev/null @@ -1,63 +0,0 @@ - - */ -final class TasksUpdateRequest extends Request -{ - /** - * @param array $inputResponses client answers, keyed as the task's inputRequests were - */ - public function __construct( - public readonly string $taskId, - public readonly array $inputResponses = [], - ) { - } - - public static function getMethod(): string - { - return 'tasks/update'; - } - - protected static function fromParams(?array $params): static - { - if (!isset($params['taskId']) || !\is_string($params['taskId']) || '' === $params['taskId']) { - throw new InvalidArgumentException('Missing or invalid "taskId" parameter for tasks/update.'); - } - - $responses = $params['inputResponses'] ?? []; - - if (!\is_array($responses)) { - throw new InvalidArgumentException('Invalid "inputResponses" parameter for tasks/update.'); - } - - return new self($params['taskId'], $responses); - } - - /** - * @return array{taskId: string, inputResponses: array} - */ - protected function getParams(): array - { - return ['taskId' => $this->taskId, 'inputResponses' => $this->inputResponses]; - } -} diff --git a/src/Schema/Result/TaskResult.php b/src/Schema/Result/TaskResult.php deleted file mode 100644 index 254680916..000000000 --- a/src/Schema/Result/TaskResult.php +++ /dev/null @@ -1,49 +0,0 @@ - - */ -class TaskResult implements ResultInterface -{ - public function __construct( - public readonly Task $task, - ) { - } - - /** - * @param array $data - */ - public static function fromArray(array $data): self - { - return new self(Task::fromArray($data)); - } - - /** - * @return array - */ - public function jsonSerialize(): array - { - return $this->task->jsonSerialize(); - } -} diff --git a/src/Schema/Task.php b/src/Schema/Task.php deleted file mode 100644 index 5eec72965..000000000 --- a/src/Schema/Task.php +++ /dev/null @@ -1,271 +0,0 @@ - - */ -class Task implements \JsonSerializable -{ - /** - * @param string $taskId server-assigned, unique and durable - * @param ?string $statusMessage human-readable progress, e.g. "42 of 100 rows" - * @param ?int $ttlMs how long the task stays readable through `tasks/get`; null means no limit - * @param ?int $pollIntervalMs how long a client should wait between polls - * @param mixed $result what the original request would have returned, once completed - * @param ?Error $error a protocol-level failure, inlined when the status is `failed` - * @param array $inputRequests what the task is waiting for, when the status is `input_required` - */ - public function __construct( - public readonly string $taskId, - public readonly TaskStatus $status = TaskStatus::Working, - public readonly ?\DateTimeImmutable $createdAt = null, - public readonly ?\DateTimeImmutable $lastUpdatedAt = null, - public readonly ?int $ttlMs = null, - public readonly ?int $pollIntervalMs = null, - public readonly ?string $statusMessage = null, - public readonly mixed $result = null, - public readonly ?Error $error = null, - public readonly array $inputRequests = [], - ) { - if ('' === $this->taskId) { - throw new InvalidArgumentException('A task must have a non-empty "taskId".'); - } - - // Both are milliseconds, and both are guidance a client acts on — a - // fractional or negative one is not guidance, it is a bug on the wire. - if (null !== $this->ttlMs && $this->ttlMs <= 0) { - throw new InvalidArgumentException(\sprintf('A task "ttlMs" must be a positive number of milliseconds or null, got %d.', $this->ttlMs)); - } - - if (null !== $this->pollIntervalMs && $this->pollIntervalMs <= 0) { - throw new InvalidArgumentException(\sprintf('A task "pollIntervalMs" must be a positive number of milliseconds, got %d.', $this->pollIntervalMs)); - } - - if (TaskStatus::Failed === $this->status && null === $this->error) { - throw new InvalidArgumentException('A failed task must carry the error that stopped it.'); - } - - if (null !== $this->error && TaskStatus::Failed !== $this->status) { - throw new InvalidArgumentException('Only a failed task carries an "error"; a tool that ran and reported a problem is completed with "isError" on its result.'); - } - } - - /** - * Reads a task back from its wire shape — what {@see self::jsonSerialize()} - * produces, or a superset of it. - * - * @param array $data - * - * @throws InvalidArgumentException when the data does not describe a task - */ - public static function fromArray(array $data): self - { - if (!\is_string($data['taskId'] ?? null) || '' === $data['taskId']) { - throw new InvalidArgumentException('Missing or invalid "taskId" in Task data.'); - } - - $status = TaskStatus::tryFrom(\is_string($data['status'] ?? null) ? $data['status'] : ''); - if (null === $status) { - throw new InvalidArgumentException(\sprintf('Missing or invalid "status" in Task data for task "%s".', $data['taskId'])); - } - - $error = \is_array($data['error'] ?? null) && isset($data['error']['code'], $data['error']['message']) - ? new Error(null, (int) $data['error']['code'], (string) $data['error']['message'], $data['error']['data'] ?? null) - : null; - - return new self( - $data['taskId'], - $status, - \is_string($data['createdAt'] ?? null) ? new \DateTimeImmutable($data['createdAt']) : null, - \is_string($data['lastUpdatedAt'] ?? null) ? new \DateTimeImmutable($data['lastUpdatedAt']) : null, - \is_int($data['ttlMs'] ?? null) ? $data['ttlMs'] : null, - \is_int($data['pollIntervalMs'] ?? null) ? $data['pollIntervalMs'] : null, - \is_string($data['statusMessage'] ?? null) ? $data['statusMessage'] : null, - $data['result'] ?? null, - $error, - self::inputRequestsFrom($data['inputRequests'] ?? []), - ); - } - - /** - * The `inputRequests` map, from bare method/params pairs or full envelopes. - * - * @return array - */ - private static function inputRequestsFrom(mixed $raw): array - { - if (!\is_array($raw)) { - return []; - } - - $requests = []; - - foreach ($raw as $key => $envelope) { - if (!\is_array($envelope) || !\is_string($envelope['method'] ?? null)) { - continue; - } - - $class = match ($envelope['method']) { - ElicitRequest::getMethod() => ElicitRequest::class, - CreateSamplingMessageRequest::getMethod() => CreateSamplingMessageRequest::class, - ListRootsRequest::getMethod() => ListRootsRequest::class, - default => null, - }; - - if (null === $class) { - continue; - } - - // On the wire the pair has no id — the map key is what answers are - // keyed by — so one is supplied to satisfy the message parser. - $requests[(string) $key] = $class::fromArray($envelope + ['jsonrpc' => MessageInterface::JSONRPC_VERSION, 'id' => 0]); - } - - return $requests; - } - - /** - * A copy with a new status and whatever that status carries. - * - * @param array $inputRequests - */ - public function with( - TaskStatus $status, - mixed $result = null, - ?Error $error = null, - array $inputRequests = [], - ?string $statusMessage = null, - ?\DateTimeImmutable $now = null, - ): self { - return new self( - $this->taskId, - $status, - $this->createdAt, - $now ?? new \DateTimeImmutable(), - $this->ttlMs, - $this->pollIntervalMs, - $statusMessage ?? $this->statusMessage, - $result ?? $this->result, - $error ?? $this->error, - [] !== $inputRequests ? $inputRequests : $this->inputRequests, - ); - } - - /** - * Whether the task is still readable, given its TTL. - */ - public function isReadable(?\DateTimeImmutable $now = null): bool - { - if (null === $this->ttlMs || null === $this->createdAt) { - return true; - } - - $expiresAt = $this->createdAt->modify(\sprintf('+%d milliseconds', $this->ttlMs)); - - return ($now ?? new \DateTimeImmutable()) < $expiresAt; - } - - /** - * The task's own fields, without anything only a detailed view carries. - * - * @return array - */ - public function toEnvelope(): array - { - $data = [ - 'taskId' => $this->taskId, - 'status' => $this->status->value, - ]; - - if (null !== $this->createdAt) { - $data['createdAt'] = $this->createdAt->format(\DATE_ATOM); - } - - if (null !== $this->lastUpdatedAt) { - $data['lastUpdatedAt'] = $this->lastUpdatedAt->format(\DATE_ATOM); - } - - // Emitted even as null: absent would mean "the server said nothing - // about how long this lives", and null means "as long as you like". - $data['ttlMs'] = $this->ttlMs; - - if (null !== $this->pollIntervalMs) { - $data['pollIntervalMs'] = $this->pollIntervalMs; - } - - if (null !== $this->statusMessage) { - $data['statusMessage'] = $this->statusMessage; - } - - return $data; - } - - /** - * The envelope plus whatever the current status carries. - * - * @return array - */ - public function jsonSerialize(): array - { - $data = $this->toEnvelope(); - - if (TaskStatus::Completed === $this->status) { - $data['result'] = $this->result; - } - - if (null !== $this->error) { - $error = ['code' => $this->error->code, 'message' => $this->error->message]; - - if (null !== $this->error->data) { - $error['data'] = $this->error->data; - } - - $data['error'] = $error; - } - - if ([] !== $this->inputRequests) { - $requests = []; - foreach ($this->inputRequests as $key => $request) { - // Values are bare method/params pairs, not messages: the client - // keys answers by the map key. getParams() is protected, so the - // envelope is built with a throwaway id and then discarded. - $params = $request->withId(0)->jsonSerialize()['params'] ?? null; - - $requests[$key] = [ - 'method' => $request::getMethod(), - // An empty PHP array would encode as `[]`, not `{}`. - 'params' => [] === $params || null === $params ? new \stdClass() : $params, - ]; - } - $data['inputRequests'] = $requests; - } - - return $data; - } -} diff --git a/src/Server/Builder.php b/src/Server/Builder.php index 35cdbd46c..aa8a850da 100644 --- a/src/Server/Builder.php +++ b/src/Server/Builder.php @@ -14,7 +14,6 @@ use Mcp\Schema\Annotations; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\Extension\AbstractExtension; -use Mcp\Schema\Extension\ArgumentProvidingExtensionInterface; use Mcp\Schema\Extension\ExtensionInterface; use Mcp\Schema\Icon; use Mcp\Schema\Implementation; @@ -30,8 +29,6 @@ use Mcp\Server\Capability\Discovery\CachedDiscoverer; use Mcp\Server\Capability\Discovery\Discoverer; use Mcp\Server\Capability\Discovery\DiscovererInterface; -use Mcp\Server\Capability\Discovery\DocBlockParser; -use Mcp\Server\Capability\Discovery\SchemaGenerator; use Mcp\Server\Capability\Discovery\SchemaGeneratorInterface; use Mcp\Server\Capability\Discovery\SchemaValidator; use Mcp\Server\Capability\Registry; @@ -60,7 +57,6 @@ use Mcp\Server\Resource\SessionSubscriptionManager; use Mcp\Server\Resource\SubscriptionManagerInterface; use Mcp\Server\Session\InMemorySessionStore; -use Mcp\Server\Session\SessionInterface; use Mcp\Server\Session\SessionLockInterface; use Mcp\Server\Session\SessionManager; use Mcp\Server\Session\SessionManagerInterface; @@ -155,9 +151,6 @@ final class Builder /** @var list|class-string<\Mcp\Schema\JsonRpc\Notification>> */ private array $extensionMessages = []; - /** @var array */ - private array $extensionArgumentProviders = []; - /** @var string|list|null */ private string|array|null $requestStateKey = null; @@ -512,10 +505,6 @@ public function enableExtension(ExtensionInterface ...$extensions): self $this->extensions[$id] = $extension->getCapabilities(); - if ($extension instanceof ArgumentProvidingExtensionInterface) { - $this->extensionArgumentProviders += $extension->getArgumentProviders(); - } - // Without this the method cannot be decoded at all, so nothing // downstream ever sees it. foreach ($extension->getMessages() as $message) { @@ -1161,7 +1150,7 @@ private function resolve(): array $this->explicitResourceTemplates, $this->explicitPrompts, ), - new ReflectedElementLoader($this->tools, $this->resources, $this->resourceTemplates, $this->prompts, $logger, $this->schemaGenerator($logger)), + new ReflectedElementLoader($this->tools, $this->resources, $this->resourceTemplates, $this->prompts, $logger, $this->schemaGenerator), ]; if (null !== $this->discoveryBasePath) { @@ -1210,7 +1199,7 @@ private function resolve(): array $serverInfo = $this->serverInfo ?? new Implementation(); $configuration = new Configuration($serverInfo, $capabilities, $this->paginationLimit, $this->instructions, $this->protocolVersion); - $referenceHandler = $this->referenceHandler ?? new ReferenceHandler($container, $this->extensionArgumentProviders); + $referenceHandler = $this->referenceHandler ?? new ReferenceHandler($container); $requestHandlers = array_merge($this->requestHandlers, [ new Handler\Request\CallToolHandler($registry, $referenceHandler, $logger, $this->schemaValidator), @@ -1289,23 +1278,9 @@ private function detectCapabilities(RegistryInterface $registry, bool $eagerlyLo ); } - /** - * The configured generator, or one that leaves the parameter types - * extensions inject out of the schemas — null when nothing needs that, - * so the loaders keep their own defaults. - */ - private function schemaGenerator(LoggerInterface $logger): ?SchemaGeneratorInterface - { - if (null !== $this->schemaGenerator || [] === $this->extensionArgumentProviders) { - return $this->schemaGenerator; - } - - return new SchemaGenerator(new DocBlockParser(logger: $logger), array_keys($this->extensionArgumentProviders)); - } - private function createDiscoverer(LoggerInterface $logger): DiscovererInterface { - $discoverer = new Discoverer($logger, null, $this->schemaGenerator($logger)); + $discoverer = new Discoverer($logger, null, $this->schemaGenerator); if (null !== $this->discoveryCache) { return new CachedDiscoverer($discoverer, $this->discoveryCache, $logger); diff --git a/src/Server/Capability/Discovery/SchemaGenerator.php b/src/Server/Capability/Discovery/SchemaGenerator.php index 4cbaf132f..4b26e7a1d 100644 --- a/src/Server/Capability/Discovery/SchemaGenerator.php +++ b/src/Server/Capability/Discovery/SchemaGenerator.php @@ -54,14 +54,8 @@ */ final class SchemaGenerator implements SchemaGeneratorInterface { - /** - * @param list $injectedTypes parameter types the runtime injects rather than the caller supplies, - * on top of {@see InjectableParameters} — an extension's, say — and - * which therefore do not belong in a schema - */ public function __construct( private readonly DocBlockParser $docBlockParser, - private readonly array $injectedTypes = [], ) { } @@ -545,12 +539,10 @@ private function parseParametersInfo(\ReflectionMethod|\ReflectionFunction $refl foreach ($reflection->getParameters() as $rp) { $reflectionType = $rp->getType(); - if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin()) { - $typeName = $reflectionType->getName(); - - if (InjectableParameters::supports($typeName) || \in_array($typeName, $this->injectedTypes, true)) { - continue; - } + if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin() + && InjectableParameters::supports($reflectionType->getName()) + ) { + continue; } $paramName = $rp->getName(); diff --git a/src/Server/Capability/Registry/ReferenceHandler.php b/src/Server/Capability/Registry/ReferenceHandler.php index 0c371de1b..a3121bf8b 100644 --- a/src/Server/Capability/Registry/ReferenceHandler.php +++ b/src/Server/Capability/Registry/ReferenceHandler.php @@ -12,7 +12,6 @@ namespace Mcp\Server\Capability\Registry; use Mcp\Schema\Json; -use Mcp\Schema\JsonRpc\Request; use Mcp\Server\Exception\InvalidArgumentException; use Mcp\Server\Exception\RegistryException; use Mcp\Server\Session\SessionInterface; @@ -23,14 +22,8 @@ */ final class ReferenceHandler implements ReferenceHandlerInterface { - /** - * @param array $argumentProviders builders for further - * injectable parameter types, - * e.g. an extension's - */ public function __construct( private readonly ?ContainerInterface $container = null, - private readonly array $argumentProviders = [], ) { } @@ -160,15 +153,6 @@ private function prepareArguments(\ReflectionFunctionAbstract $reflection, array $finalArgs[$paramPosition] = $injected; continue; } - - // An extension may contribute further injectable types; the - // core stays unaware of what they are. - $typeName = $type->getName(); - - if (isset($this->argumentProviders[$typeName], $arguments['_session'], $arguments['_request'])) { - $finalArgs[$paramPosition] = ($this->argumentProviders[$typeName])($arguments['_session'], $arguments['_request']); - continue; - } } if (isset($arguments[$paramName]) || (\array_key_exists($paramName, $arguments) && $parameter->allowsNull())) { diff --git a/src/Server/Handler/Request/GetPromptHandler.php b/src/Server/Handler/Request/GetPromptHandler.php index 5b4fae920..c1cc10aa6 100644 --- a/src/Server/Handler/Request/GetPromptHandler.php +++ b/src/Server/Handler/Request/GetPromptHandler.php @@ -14,9 +14,9 @@ use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; -use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\Request\GetPromptRequest; use Mcp\Schema\Result\GetPromptResult; +use Mcp\Schema\Result\InputRequiredResult; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\RegistryInterface; use Mcp\Server\Exception\MissingRequiredClientCapabilityException; @@ -29,7 +29,7 @@ use Psr\Log\NullLogger; /** - * @implements RequestHandlerInterface + * @implements RequestHandlerInterface * * @author Tobias Nyholm */ @@ -48,7 +48,7 @@ public function supports(Request $request): bool } /** - * @return Response|Error + * @return Response|Error */ public function handle(Request $request, SessionInterface $session): Response|Error { @@ -65,9 +65,8 @@ public function handle(Request $request, SessionInterface $session): Response|Er $result = $this->referenceHandler->handle($reference, $arguments); - // A handler that built a whole result of another kind — an - // extension's, say — keeps what it decided; it is not prompt messages. - if ($result instanceof ResultInterface) { + // An ask is a result in its own right, not prompt content. + if ($result instanceof InputRequiredResult) { return new Response($request->getId(), $result); } diff --git a/src/Server/Handler/Request/ReadResourceHandler.php b/src/Server/Handler/Request/ReadResourceHandler.php index 94169175d..def85079f 100644 --- a/src/Server/Handler/Request/ReadResourceHandler.php +++ b/src/Server/Handler/Request/ReadResourceHandler.php @@ -14,8 +14,8 @@ use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; -use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\Request\ReadResourceRequest; +use Mcp\Schema\Result\InputRequiredResult; use Mcp\Schema\Result\ReadResourceResult; use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\Registry\ResourceTemplateReference; @@ -31,7 +31,7 @@ use Psr\Log\NullLogger; /** - * @implements RequestHandlerInterface + * @implements RequestHandlerInterface * * @author Tobias Nyholm */ @@ -50,7 +50,7 @@ public function supports(Request $request): bool } /** - * @return Response|Error + * @return Response|Error */ public function handle(Request $request, SessionInterface $session): Response|Error { @@ -76,9 +76,9 @@ public function handle(Request $request, SessionInterface $session): Response|Er $result = $this->referenceHandler->handle($reference, $arguments); // An ask is a result in its own right, not resource contents; - // and a handler that built the whole result — an - // extension's kind — keeps what it decided. - if ($result instanceof ResultInterface && !$result instanceof ReadResourceResult) { + // and a handler that built the whole result keeps what it + // decided, caching hints included on the modern era. + if ($result instanceof InputRequiredResult) { return new Response($request->getId(), $result); } @@ -90,7 +90,7 @@ public function handle(Request $request, SessionInterface $session): Response|Er } else { $result = $this->referenceHandler->handle($reference, $arguments); - if ($result instanceof ResultInterface && !$result instanceof ReadResourceResult) { + if ($result instanceof InputRequiredResult) { return new Response($request->getId(), $result); } diff --git a/src/Server/Task/Handler/TasksCancelHandler.php b/src/Server/Task/Handler/TasksCancelHandler.php deleted file mode 100644 index 9607116b8..000000000 --- a/src/Server/Task/Handler/TasksCancelHandler.php +++ /dev/null @@ -1,72 +0,0 @@ - - * - * @author Christopher Hertel - */ -final class TasksCancelHandler implements RequestHandlerInterface -{ - public function __construct( - private readonly TaskStoreInterface $store, - ) { - } - - public function supports(Request $request): bool - { - return $request instanceof TasksCancelRequest; - } - - public function handle(Request $request, SessionInterface $session): Response|Error - { - \assert($request instanceof TasksCancelRequest); - - // The task surface is gated on negotiation: to a client that never - // declared the extension these methods do not exist as *its* methods, - // and -32021 says which declaration is missing. - if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { - return $refusal; - } - - $task = $this->store->get($request->taskId); - - if (null === $task) { - return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); - } - - if (!$task->status->isTerminal()) { - $this->store->save($task->with(TaskStatus::Cancelled)); - } - - return new Response($request->getId(), new EmptyResult()); - } -} diff --git a/src/Server/Task/Handler/TasksGetHandler.php b/src/Server/Task/Handler/TasksGetHandler.php deleted file mode 100644 index 6a6701133..000000000 --- a/src/Server/Task/Handler/TasksGetHandler.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * @author Christopher Hertel - */ -final class TasksGetHandler implements RequestHandlerInterface -{ - public function __construct( - private readonly TaskStoreInterface $store, - ) { - } - - public function supports(Request $request): bool - { - return $request instanceof TasksGetRequest; - } - - public function handle(Request $request, SessionInterface $session): Response|Error - { - \assert($request instanceof TasksGetRequest); - - // The task surface is gated on negotiation: to a client that never - // declared the extension these methods do not exist as *its* methods, - // and -32021 says which declaration is missing. - if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { - return $refusal; - } - - $task = $this->store->get($request->taskId); - - if (null === $task) { - // An unknown id and a lapsed one are the same answer: the spec - // reserves -32602 for exactly this, and a client cannot act on the - // difference. - return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); - } - - return new Response($request->getId(), new TaskResult($task)); - } -} diff --git a/src/Server/Task/Handler/TasksHandler.php b/src/Server/Task/Handler/TasksHandler.php new file mode 100644 index 000000000..9b7a7a2f1 --- /dev/null +++ b/src/Server/Task/Handler/TasksHandler.php @@ -0,0 +1,75 @@ + + * + * @author Antoine Bluchet + */ +final class TasksHandler implements RequestHandlerInterface +{ + public function __construct( + private readonly TaskManager $tasks, + ) { + } + + public function supports(Request $request): bool + { + return $request instanceof TasksGetRequest || $request instanceof TasksCancelRequest; + } + + /** + * @return Response|Error + */ + public function handle(Request $request, SessionInterface $session): Response|Error + { + \assert($request instanceof TasksGetRequest || $request instanceof TasksCancelRequest); + + $context = new RequestContext($session, $request); + $version = $context->getProtocolVersion(); + + // The extension does not exist below 2026-07-28 (SEP-2663, Backward Compatibility). + if (!$version->isAtLeast(ProtocolVersion::V2026_07_28)) { + return Error::forMethodNotFound(\sprintf('Method "%s" does not exist in protocol version %s.', $request::getMethod(), $version->value), $request->getId()); + } + + $task = $this->tasks->find($context, $request->taskId); + + if (null === $task) { + return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId()); + } + + if ($request instanceof TasksGetRequest) { + return new Response($request->getId(), $task); + } + + $this->tasks->cancel($task); + + return new Response($request->getId(), new EmptyResult()); + } +} diff --git a/src/Server/Task/Handler/TasksUpdateHandler.php b/src/Server/Task/Handler/TasksUpdateHandler.php deleted file mode 100644 index 3b053f521..000000000 --- a/src/Server/Task/Handler/TasksUpdateHandler.php +++ /dev/null @@ -1,80 +0,0 @@ - - * - * @author Christopher Hertel - */ -final class TasksUpdateHandler implements RequestHandlerInterface -{ - public function __construct( - private readonly TaskStoreInterface $store, - private readonly ?TaskInputHandlerInterface $inputHandler = null, - ) { - } - - public function supports(Request $request): bool - { - return $request instanceof TasksUpdateRequest; - } - - public function handle(Request $request, SessionInterface $session): Response|Error - { - \assert($request instanceof TasksUpdateRequest); - - // The task surface is gated on negotiation: to a client that never - // declared the extension these methods do not exist as *its* methods, - // and -32021 says which declaration is missing. - if (null !== $refusal = TaskCapabilityGuard::refuse($request, $session)) { - return $refusal; - } - - $task = $this->store->get($request->taskId); - - if (null === $task) { - return Error::forInvalidParams(\sprintf('Unknown task "%s".', $request->taskId), $request->getId(), ['taskId' => $request->taskId]); - } - - // Answers to something already finished, or never asked for, are - // ignored rather than refused: the spec says to drop responses for - // unknown or already-satisfied keys, and a terminal task is the same - // case one step further along. - if (TaskStatus::InputRequired === $task->status) { - $updated = $this->inputHandler?->receive($task, $request->inputResponses) - ?? $task->with(TaskStatus::Working, statusMessage: 'Input received.'); - - $this->store->save($updated); - } - - return new Response($request->getId(), new EmptyResult()); - } -} diff --git a/src/Server/Task/InMemoryTaskStore.php b/src/Server/Task/InMemoryTaskStore.php index 7ac56bb2c..47e6c77d3 100644 --- a/src/Server/Task/InMemoryTaskStore.php +++ b/src/Server/Task/InMemoryTaskStore.php @@ -11,7 +11,7 @@ namespace Mcp\Server\Task; -use Mcp\Schema\Task; +use Mcp\Schema\Extension\Tasks\Task; use Mcp\Server\Exception\InvalidArgumentException; use Mcp\Server\NativeClock; use Psr\Clock\ClockInterface; @@ -21,8 +21,8 @@ * * Correct for stdio and for persistent runtimes where the whole server is one * process. Under PHP-FPM it is not: the worker that creates a task and the - * worker polled for it are different processes, and every `tasks/get` would - * answer "no such task". {@see Psr16TaskStore} is the answer there. + * worker polled for it are different processes. {@see Psr16TaskStore} is the + * answer there. * * @author Christopher Hertel */ @@ -31,32 +31,28 @@ final class InMemoryTaskStore implements TaskStoreInterface /** @var array */ private array $tasks = []; - private readonly ClockInterface $clock; - /** - * @param int $limit how many tasks to keep before dropping the oldest, so an unbounded - * run of task creation cannot exhaust memory + * @param int $limit how many tasks to keep before dropping the least recently saved one, so an + * unbounded run of task creation cannot exhaust memory */ public function __construct( private readonly int $limit = 1000, - ?ClockInterface $clock = null, + private readonly ClockInterface $clock = new NativeClock(), ) { if ($this->limit < 1) { throw new InvalidArgumentException(\sprintf('A task store must hold at least one task, got %d.', $this->limit)); } - - $this->clock = $clock ?? new NativeClock(); } public function save(Task $task): void { - // Re-inserted rather than updated in place, so the eviction order below - // reflects last use and a task being polled is not the one dropped. + // Re-inserted rather than updated in place, so the first key is always + // the least recently saved task. unset($this->tasks[$task->taskId]); $this->tasks[$task->taskId] = $task; - while (\count($this->tasks) > $this->limit) { - array_shift($this->tasks); + if (\count($this->tasks) > $this->limit) { + unset($this->tasks[array_key_first($this->tasks)]); } } @@ -76,9 +72,4 @@ public function get(string $taskId): ?Task return $task; } - - public function delete(string $taskId): void - { - unset($this->tasks[$taskId]); - } } diff --git a/src/Server/Task/Psr16TaskStore.php b/src/Server/Task/Psr16TaskStore.php index 3b0bedf4d..fb2a8a386 100644 --- a/src/Server/Task/Psr16TaskStore.php +++ b/src/Server/Task/Psr16TaskStore.php @@ -11,8 +11,9 @@ namespace Mcp\Server\Task; -use Mcp\Schema\JsonRpc\Request; -use Mcp\Schema\Task; +use Mcp\Schema\Exception\InvalidArgumentException; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Server\Exception\RuntimeException; use Mcp\Server\NativeClock; use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; @@ -23,42 +24,39 @@ * A task store over any PSR-16 cache, so a task created in one process can be * polled from another. * - * This is the implementation PHP-FPM needs — and the reason the store is an - * interface at all. The cache's own TTL is set from the task's `ttlMs`, so an - * expired task disappears without anything having to sweep for it. - * - * Serialized as JSON rather than with PHP's serializer: the payload is written - * by one process and read by another, possibly after a deploy, and a JSON - * document survives a class definition changing shape in a way a serialized - * object does not. + * The cache's own TTL is set from the task's `ttlMs`, so an expired task + * disappears without anything having to sweep for it. Stored as JSON rather + * than with PHP's serializer: the payload is written by one process and read + * by another, possibly after a deploy. * * @author Christopher Hertel */ final class Psr16TaskStore implements TaskStoreInterface { - private readonly ClockInterface $clock; - /** - * @param string $prefix namespace for this store's keys, so one cache can carry several - * @param int $defaultTtl seconds a task with no `ttlMs` of its own is kept + * @param string $prefix namespace for this store's keys, so one cache can carry several */ public function __construct( private readonly CacheInterface $cache, private readonly string $prefix = 'mcp.tasks.', - private readonly int $defaultTtl = 3600, private readonly LoggerInterface $logger = new NullLogger(), - ?ClockInterface $clock = null, + private readonly ClockInterface $clock = new NativeClock(), ) { - $this->clock = $clock ?? new NativeClock(); } + /** + * @throws RuntimeException when the cache did not keep the task, so no handle to it is handed out + */ public function save(Task $task): void { - $ttl = null !== $task->ttlMs - ? max(1, (int) ceil($task->ttlMs / 1000)) - : $this->defaultTtl; + $ttl = null === $task->ttlMs ? null : max(1, (int) ceil($task->ttlMs / 1000)); - $this->cache->set($this->prefix.$task->taskId, json_encode(self::toArray($task), \JSON_THROW_ON_ERROR), $ttl); + // The owner is never sent on the wire, but must survive the round trip. + $payload = [...$task->jsonSerialize(), 'owner' => $task->owner]; + + if (!$this->cache->set($this->prefix.$task->taskId, json_encode($payload, \JSON_THROW_ON_ERROR), $ttl)) { + throw new RuntimeException(\sprintf('The cache refused to store task "%s".', $task->taskId)); + } } public function get(string $taskId): ?Task @@ -70,50 +68,16 @@ public function get(string $taskId): ?Task } try { - /** @var array $data */ $data = json_decode($raw, true, flags: \JSON_THROW_ON_ERROR); - $task = Task::fromArray($data); - } catch (\Throwable $e) { - // Written by an older shape, or corrupted. Unreadable and expired - // look the same to a client, and neither is worth failing on. + $task = Task::fromArray(\is_array($data) ? $data : []); + } catch (\JsonException|InvalidArgumentException $e) { + // Written by an older shape, or corrupted: to a client, the same as expired. $this->logger->warning('Dropped an unreadable task from the store.', ['taskId' => $taskId, 'exception' => $e]); return null; } - // The cache TTL is coarser than the task's own — it is whole seconds — - // so the task still has the last word on whether it is readable. + // The cache TTL is whole seconds, so the task has the last word on whether it is readable. return $task->isReadable($this->clock->now()) ? $task : null; } - - public function delete(string $taskId): void - { - $this->cache->delete($this->prefix.$taskId); - } - - /** - * @return array - */ - private static function toArray(Task $task): array - { - return [ - 'taskId' => $task->taskId, - 'status' => $task->status->value, - 'createdAt' => $task->createdAt?->format(\DATE_ATOM), - 'lastUpdatedAt' => $task->lastUpdatedAt?->format(\DATE_ATOM), - 'ttlMs' => $task->ttlMs, - 'pollIntervalMs' => $task->pollIntervalMs, - 'statusMessage' => $task->statusMessage, - 'result' => $task->result, - 'error' => null !== $task->error - ? ['code' => $task->error->code, 'message' => $task->error->message, 'data' => $task->error->data] - : null, - // Kept as the envelopes they go out as, so a parked task still - // knows what it is waiting for after a round trip through storage. - 'inputRequests' => array_map( - static fn (Request $request): array => $request->withId(0)->jsonSerialize(), - $task->inputRequests, - ), - ]; - } } diff --git a/src/Server/Task/TaskCapabilityGuard.php b/src/Server/Task/TaskCapabilityGuard.php deleted file mode 100644 index 6f258557f..000000000 --- a/src/Server/Task/TaskCapabilityGuard.php +++ /dev/null @@ -1,61 +0,0 @@ - - */ -final class TaskCapabilityGuard -{ - /** - * The refusal to return, or null when the client declared the extension. - */ - public static function refuse(Request $request, SessionInterface $session): ?Error - { - if (self::declared($session)) { - return null; - } - - return Error::forMissingRequiredClientCapability( - \sprintf('The "%s" methods need the extension the client did not declare.', TasksExtension::ID), - self::required(), - $request->getId(), - ); - } - - /** - * Whether the client declared the extension during `initialize`. - */ - public static function declared(SessionInterface $session): bool - { - $capabilities = (array) $session->get('client_capabilities', []); - $extensions = $capabilities['extensions'] ?? null; - - return TasksExtension::declaredBy(null === $extensions ? null : (array) $extensions); - } - - private static function required(): ClientCapabilities - { - return new ClientCapabilities(roots: false, extensions: [TasksExtension::ID => new \stdClass()]); - } -} diff --git a/src/Server/Task/TaskContext.php b/src/Server/Task/TaskContext.php deleted file mode 100644 index ed18a6628..000000000 --- a/src/Server/Task/TaskContext.php +++ /dev/null @@ -1,116 +0,0 @@ -isSupported()) { - * return runSynchronously(); - * } - * - * $created = $tasks->create(pollIntervalMs: 1000); - * $queue->push($created->task->taskId); - * - * return $created; - * } - * ``` - * - * @author Christopher Hertel - */ -final class TaskContext -{ - public function __construct( - private readonly SessionInterface $session, - private readonly TaskStoreInterface $store, - ) { - } - - /** - * Whether this client declared the extension during `initialize`. - * - * A handler that can work either way must ask before creating a task: a - * client that did not declare it has no polling loop, and the specification - * says such a request falls through to running synchronously rather than - * failing. - */ - public function isSupported(): bool - { - return TaskCapabilityGuard::declared($this->session); - } - - /** - * Creates a task and stores it, returning the result to hand back. - * - * The handler's own work is not started here — that is the application's, - * and in PHP it usually means enqueueing something a worker picks up. What - * this guarantees is the part the specification cares about: the task is - * durably stored *before* its id reaches the client, so the first - * `tasks/get` cannot arrive before the task exists. - * - * @param ?int $ttlMs how long the task stays readable; null for no limit - * @param ?int $pollIntervalMs how long the client should wait between polls - * - * @throws MissingRequiredClientCapabilityException when the client did not declare the extension — it has no - * `tasks/get` loop, and a handle it will never poll is worse - * than a slow answer; the server answers `-32021` instead - */ - public function create( - ?string $taskId = null, - ?int $ttlMs = 3_600_000, - ?int $pollIntervalMs = 1000, - ?string $statusMessage = null, - ): CreateTaskResult { - if (!$this->isSupported()) { - throw new MissingRequiredClientCapabilityException(new ClientCapabilities(roots: false, extensions: [TasksExtension::ID => new \stdClass()]), \sprintf('This request is served as a task, which needs the "%s" extension the client did not declare.', TasksExtension::ID)); - } - - $now = new \DateTimeImmutable(); - - $task = new Task( - $taskId ?? Uuid::v4()->toRfc4122(), - TaskStatus::Working, - $now, - $now, - $ttlMs, - $pollIntervalMs, - $statusMessage, - ); - - $this->store->save($task); - - return new CreateTaskResult($task); - } - - /** - * The store this request is served with, for a handler that needs to - * advance a task it did not create here. - */ - public function getStore(): TaskStoreInterface - { - return $this->store; - } -} diff --git a/src/Server/Task/TaskInputHandlerInterface.php b/src/Server/Task/TaskInputHandlerInterface.php deleted file mode 100644 index 0171f4e0e..000000000 --- a/src/Server/Task/TaskInputHandlerInterface.php +++ /dev/null @@ -1,35 +0,0 @@ - - */ -interface TaskInputHandlerInterface -{ - /** - * Applies $inputResponses to $task and returns its new state. - * - * Keys match the task's `inputRequests`. Anything unrecognized should be - * ignored rather than refused. - * - * @param array $inputResponses - */ - public function receive(Task $task, array $inputResponses): Task; -} diff --git a/src/Server/Task/TaskManager.php b/src/Server/Task/TaskManager.php new file mode 100644 index 000000000..ab491de44 --- /dev/null +++ b/src/Server/Task/TaskManager.php @@ -0,0 +1,158 @@ + + */ +final class TaskManager +{ + public function __construct( + private readonly TaskStoreInterface $store, + private readonly ClockInterface $clock = new NativeClock(), + ) { + } + + /** + * Whether a task can be handed to the client of this request: it declared + * the extension, on a revision the extension exists in. + */ + public function isSupported(RequestContext $context): bool + { + return $context->getProtocolVersion()->isAtLeast(ProtocolVersion::V2026_07_28) + && $context->getClientGateway()->supportsExtension(TasksExtension::ID); + } + + /** + * Stores a new task for this `tools/call` and returns the result to answer + * it with. The task is stored before its id is handed out, so the first + * `tasks/get` cannot arrive before it exists. + * + * @param ?int $ttlMs how long the task stays readable; null for no limit + * @param ?int $pollIntervalMs how long the client should wait between polls + * + * @throws MissingRequiredClientCapabilityException when the client cannot poll, answered as -32021 + * @throws LogicException when the request is not a `tools/call` + */ + public function create(RequestContext $context, ?int $ttlMs = 3_600_000, ?int $pollIntervalMs = 1000, ?string $statusMessage = null): CreateTaskResult + { + if (!$context->getRequest() instanceof CallToolRequest) { + throw new LogicException(\sprintf('Only "tools/call" can be answered with a task, not "%s".', $context->getRequest()::getMethod())); + } + + $this->requireSupport($context); + + $now = $this->clock->now(); + $task = new Task(Uuid::v4()->toRfc4122(), TaskStatus::Working, $now, $now, $ttlMs, $pollIntervalMs, $statusMessage, owner: self::ownerOf($context)); + + $this->store->save($task); + + return new CreateTaskResult($task); + } + + /** + * The task, for the client of this request only: null when there is no such + * task or when someone else created it, which the client cannot tell apart. + * + * @throws MissingRequiredClientCapabilityException when the client did not declare the extension + */ + public function find(RequestContext $context, string $taskId): ?Task + { + $this->requireSupport($context); + + $task = $this->store->get($taskId); + + if (null === $task || (null !== $task->owner && $task->owner !== self::ownerOf($context))) { + return null; + } + + return $task; + } + + /** + * The task as stored, for the application running it. + */ + public function get(string $taskId): ?Task + { + return $this->store->get($taskId); + } + + /** + * Moves a task on, for the application running it. Read back from the + * store first, so a cancellation recorded meanwhile is not overwritten. + * + * @param ?array $result the `CallToolResult` to inline once completed + * + * @throws InvalidArgumentException when there is no such task, or it expired + * @throws SchemaLogicException when the task already reached a terminal status + */ + public function transition(string $taskId, TaskStatus $status, ?array $result = null, ?Error $error = null, ?string $statusMessage = null): Task + { + $task = $this->store->get($taskId) ?? throw new InvalidArgumentException(\sprintf('Unknown task "%s".', $taskId)); + $task = $task->with($status, $this->clock->now(), $result, $error, $statusMessage); + + $this->store->save($task); + + return $task; + } + + /** + * Records a cancellation; a task already in a terminal status is left as it is. + */ + public function cancel(Task $task): void + { + if (!$task->status->isTerminal()) { + $this->store->save($task->with(TaskStatus::Cancelled, $this->clock->now())); + } + } + + private function requireSupport(RequestContext $context): void + { + if (!$this->isSupported($context)) { + throw new MissingRequiredClientCapabilityException(new ClientCapabilities(extensions: [TasksExtension::ID => new \stdClass()]), \sprintf('Tasks need the "%s" extension, which the client did not declare.', TasksExtension::ID)); + } + } + + /** + * The OAuth client and subject the request was authorized for; null when it + * was not, and the unguessable task id is then the only credential. + */ + private static function ownerOf(RequestContext $context): ?string + { + $token = $context->getAccessToken(); + + return null === $token ? null : json_encode([$token->getClientId(), $token->getSubject()], \JSON_THROW_ON_ERROR); + } +} diff --git a/src/Server/Task/TaskStoreInterface.php b/src/Server/Task/TaskStoreInterface.php index b4b9adcd0..6ee50cdac 100644 --- a/src/Server/Task/TaskStoreInterface.php +++ b/src/Server/Task/TaskStoreInterface.php @@ -11,25 +11,26 @@ namespace Mcp\Server\Task; -use Mcp\Schema\Task; +use Mcp\Schema\Extension\Tasks\Task; /** * Where tasks live between the request that created one and the polls that read * it (SEP-2663). * - * A task ID is a *durable* handle — the point of the extension is that it - * survives a dropped connection, a client restart, and in PHP's case the death - * of the process that created it. So the store is an interface rather than a - * property of the protocol object: which implementation is right depends - * entirely on whether the process that creates a task is the process that will - * be polled for it. Under PHP-FPM it is not. + * A task ID is a *durable* handle: it survives a dropped connection, a client + * restart, and in PHP's case the death of the process that created it. Which + * implementation is right depends on whether the process that creates a task + * is the process that will be polled for it. Under PHP-FPM it is not. + * + * @experimental * * @author Christopher Hertel */ interface TaskStoreInterface { /** - * Stores a task, overwriting any earlier state under the same id. + * Stores a task, overwriting any earlier state under the same id. Returns + * only once a {@see self::get()} for that id would find it. */ public function save(Task $task): void; @@ -38,9 +39,4 @@ public function save(Task $task): void; * which a client cannot tell apart and does not need to. */ public function get(string $taskId): ?Task; - - /** - * Drops a task before its TTL, if the store supports it. - */ - public function delete(string $taskId): void; } diff --git a/src/Server/Task/TasksExtension.php b/src/Server/Task/TasksExtension.php index 35c73315a..9e69bfe8b 100644 --- a/src/Server/Task/TasksExtension.php +++ b/src/Server/Task/TasksExtension.php @@ -11,47 +11,29 @@ namespace Mcp\Server\Task; -use Mcp\Schema\Extension\ArgumentProvidingExtensionInterface; use Mcp\Schema\Extension\ExtensionIdentifier; -use Mcp\Schema\JsonRpc\Request; -use Mcp\Schema\Request\TasksCancelRequest; -use Mcp\Schema\Request\TasksGetRequest; -use Mcp\Schema\Request\TasksUpdateRequest; +use Mcp\Schema\Extension\Tasks\TasksCancelRequest; +use Mcp\Schema\Extension\Tasks\TasksGetRequest; use Mcp\Server\Exception\LogicException; use Mcp\Server\Extension\ServerExtensionInterface; -use Mcp\Server\Session\SessionInterface; -use Mcp\Server\Task\Handler\TasksCancelHandler; -use Mcp\Server\Task\Handler\TasksGetHandler; -use Mcp\Server\Task\Handler\TasksUpdateHandler; +use Mcp\Server\Task\Handler\TasksHandler; /** * The `io.modelcontextprotocol/tasks` extension (SEP-2663). * - * On a server, enable it with a store and the `tasks/*` surface appears; on a - * client, enabling it without one is what declares the extension: + * On a server, enable it with the {@see TaskManager} the tools create tasks + * through; on a client, enabling it without one is what declares it. * - * ```php - * Server::builder()->enableExtension(new TasksExtension(new InMemoryTaskStore())); - * Client::builder()->enableExtension(new TasksExtension()); - * ``` - * - * Creating a task is the *server's* decision, made per request — a client opts - * in once by declaring the extension and then handles whichever result shape - * arrives. A handler creates one through the {@see TaskContext} it can declare - * as a parameter, and returns the {@see \Mcp\Schema\Result\CreateTaskResult}. + * @experimental * * @author Christopher Hertel */ -final class TasksExtension implements ServerExtensionInterface, ArgumentProvidingExtensionInterface +final class TasksExtension implements ServerExtensionInterface { public const ID = 'io.modelcontextprotocol/tasks'; - /** - * @param ?TaskStoreInterface $store where a server keeps its tasks; a client declaring the extension needs none - */ public function __construct( - private readonly ?TaskStoreInterface $store = null, - private readonly ?TaskInputHandlerInterface $inputHandler = null, + private readonly ?TaskManager $tasks = null, ) { } @@ -69,48 +51,15 @@ public function getMessages(): array { return [ TasksGetRequest::class, - TasksUpdateRequest::class, TasksCancelRequest::class, ]; } - public function getRequestHandlers(): iterable - { - $store = $this->getStore(); - - yield new TasksGetHandler($store); - yield new TasksUpdateHandler($store, $this->inputHandler); - yield new TasksCancelHandler($store); - } - - public function getArgumentProviders(): array - { - $store = $this->getStore(); - - return [ - TaskContext::class => static fn (SessionInterface $session, Request $request): TaskContext => new TaskContext($session, $store), - ]; - } - - /** - * @throws LogicException when enabled on a server without a store - */ - public function getStore(): TaskStoreInterface - { - return $this->store ?? throw new LogicException(\sprintf('The Tasks extension needs a store to serve tasks/*; enable it with new %s(new InMemoryTaskStore()) or another %s.', self::class, TaskStoreInterface::class)); - } - /** - * Whether a client's declared capabilities include this extension. - * - * The gate on task creation: a client that never declared it has no - * `tasks/get` loop and would be left holding a handle it does not know how - * to redeem. - * - * @param ?array $extensions the `extensions` member of the request's clientCapabilities + * @throws LogicException when enabled on a server without a task manager */ - public static function declaredBy(?array $extensions): bool + public function getRequestHandlers(): iterable { - return \array_key_exists(self::ID, $extensions ?? []); + yield new TasksHandler($this->tasks ?? throw new LogicException(\sprintf('The Tasks extension needs a %s to serve tasks/*.', TaskManager::class))); } } diff --git a/tests/Integration/Fixture/tasks.php b/tests/Integration/Fixture/tasks.php index 02194d4a5..594e657e7 100644 --- a/tests/Integration/Fixture/tasks.php +++ b/tests/Integration/Fixture/tasks.php @@ -10,37 +10,31 @@ */ /* - * Server for {@see \Mcp\Tests\Integration\TasksTest}. + * Server for Mcp\Tests\Integration\TasksTest. * * A stdio server is one process, so there is no worker to advance a task * between polls. The store below stands in for one: each task carries the - * states it will move through, and every `tasks/get` advances it by one. + * states it will move through, and every read advances it by one. */ -use Mcp\Schema\Content\PromptMessage; use Mcp\Schema\Content\TextContent; -use Mcp\Schema\Elicitation\ElicitationSchema; -use Mcp\Schema\Elicitation\StringSchemaDefinition; -use Mcp\Schema\Enum\Role; -use Mcp\Schema\Enum\TaskStatus; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Schema\Extension\Tasks\TaskStatus; use Mcp\Schema\JsonRpc\Error; -use Mcp\Schema\Request\ElicitRequest; use Mcp\Schema\Result\CallToolResult; -use Mcp\Schema\Result\CreateTaskResult; -use Mcp\Schema\Result\GetPromptResult; -use Mcp\Schema\Task; +use Mcp\Server\RequestContext; use Mcp\Server\Server; use Mcp\Server\Task\InMemoryTaskStore; -use Mcp\Server\Task\TaskContext; -use Mcp\Server\Task\TaskInputHandlerInterface; +use Mcp\Server\Task\TaskManager; use Mcp\Server\Task\TasksExtension; use Mcp\Server\Task\TaskStoreInterface; use Mcp\Server\Transport\StdioTransport; require_once dirname(__DIR__, 3).'/vendor/autoload.php'; -$store = new class(new InMemoryTaskStore()) implements TaskStoreInterface, TaskInputHandlerInterface { - /** @var array> what each task becomes on its next polls */ +$store = new class(new InMemoryTaskStore()) implements TaskStoreInterface { + /** @var array> what each task becomes on its next reads */ private array $plans = []; public function __construct(private readonly TaskStoreInterface $inner) @@ -48,11 +42,11 @@ public function __construct(private readonly TaskStoreInterface $inner) } /** - * @param list $states + * @param list $steps */ - public function plan(string $taskId, array $states): void + public function plan(string $taskId, array $steps): void { - $this->plans[$taskId] = $states; + $this->plans[$taskId] = $steps; } public function save(Task $task): void @@ -68,38 +62,28 @@ public function get(string $taskId): ?Task return $task; } - $next = array_shift($this->plans[$taskId]); + $next = array_shift($this->plans[$taskId])($task); $this->inner->save($next); return $next; } - - public function delete(string $taskId): void - { - $this->inner->delete($taskId); - } - - public function receive(Task $task, array $inputResponses): Task - { - $name = $inputResponses['name']['content']['name'] ?? 'nobody'; - - return $task->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('Hello, '.$name)])); - } }; +$tasks = new TaskManager($store); + Server::builder() ->setServerInfo('integration-server', '1.0.0') - ->enableExtension(new TasksExtension($store, $store)) + ->enableExtension(new TasksExtension($tasks)) ->addTool( - static function (TaskContext $tasks) use ($store): CreateTaskResult|string { - if (!$tasks->isSupported()) { + static function (RequestContext $context) use ($tasks, $store): CreateTaskResult|string { + if (!$tasks->isSupported($context)) { return 'sync'; } - $created = $tasks->create(pollIntervalMs: 10, statusMessage: 'queued'); + $created = $tasks->create($context, pollIntervalMs: 10, statusMessage: 'queued'); $store->plan($created->task->taskId, [ - $created->task->with(TaskStatus::Working, statusMessage: 'halfway'), - $created->task->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('done')])), + static fn (Task $task): Task => $task->with(TaskStatus::Working, new DateTimeImmutable(), statusMessage: 'halfway'), + static fn (Task $task): Task => $task->with(TaskStatus::Completed, new DateTimeImmutable(), result: (new CallToolResult([new TextContent('done')]))->jsonSerialize()), ]); return $created; @@ -108,45 +92,21 @@ static function (TaskContext $tasks) use ($store): CreateTaskResult|string { description: 'Runs as a task when the client can poll, synchronously otherwise.', ) ->addTool( - static fn (TaskContext $tasks): CreateTaskResult => $tasks->create(pollIntervalMs: 10), + static fn (RequestContext $context): CreateTaskResult => $tasks->create($context, pollIntervalMs: 10), name: 'task_only', description: 'Always creates a task, even for a client that cannot poll.', ) ->addTool( - static function (TaskContext $tasks) use ($store): CreateTaskResult { - $created = $tasks->create(pollIntervalMs: 10); + static function (RequestContext $context) use ($tasks, $store): CreateTaskResult { + $created = $tasks->create($context, pollIntervalMs: 10); $store->plan($created->task->taskId, [ - $created->task->with(TaskStatus::InputRequired, inputRequests: [ - 'name' => new ElicitRequest('What is your name?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])), - ]), + static fn (Task $task): Task => $task->with(TaskStatus::Failed, new DateTimeImmutable(), error: Error::forInternalError('the worker died')), ]); return $created; }, - name: 'ask_job', - description: 'Parks for the client\'s name, then greets.', - ) - ->addTool( - static function (TaskContext $tasks) use ($store): CreateTaskResult { - $created = $tasks->create(pollIntervalMs: 10); - $store->plan($created->task->taskId, [$created->task->with(TaskStatus::Failed, error: Error::forInternalError('the worker died'))]); - - return $created; - }, name: 'failing_job', description: 'Fails at the protocol level.', ) - ->addPrompt( - static function (TaskContext $tasks) use ($store): CreateTaskResult { - $created = $tasks->create(pollIntervalMs: 10); - $store->plan($created->task->taskId, [ - $created->task->with(TaskStatus::Completed, result: new GetPromptResult([new PromptMessage(Role::User, new TextContent('prompt done'))])), - ]); - - return $created; - }, - name: 'slow_prompt', - description: 'A prompt served as a task.', - ) ->build() ->run(new StdioTransport()); diff --git a/tests/Integration/TasksTest.php b/tests/Integration/TasksTest.php index a0b81859c..699152eb9 100644 --- a/tests/Integration/TasksTest.php +++ b/tests/Integration/TasksTest.php @@ -11,48 +11,37 @@ namespace Mcp\Tests\Integration; -use Mcp\Client\Client; +use Mcp\Client\Builder as ClientBuilder; use Mcp\Client\Exception\RequestException; +use Mcp\Client\Exception\RuntimeException; use Mcp\Client\Task\TaskClient; use Mcp\Schema\Content\TextContent; -use Mcp\Schema\Enum\TaskStatus; +use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Schema\Extension\Tasks\TaskStatus; use Mcp\Schema\JsonRpc\Error; -use Mcp\Schema\Request\ElicitRequest; use Mcp\Schema\Result\CallToolResult; -use Mcp\Schema\Result\CreateTaskResult; -use Mcp\Schema\Result\GetPromptResult; -use Mcp\Schema\Task; use Mcp\Server\Task\TasksExtension; use PHPUnit\Framework\Attributes\TestDox; /** - * The Tasks extension (SEP-2663), server and client together: a handle - * instead of an answer, polled until it settles. + * The Tasks extension (SEP-2663) on 2026-07-28, server and client together: + * a handle instead of an answer, polled until it settles. * * @see Fixture/tasks.php for the server under test */ final class TasksTest extends IntegrationTestCase { - #[TestDox('the server announces the extension with empty settings')] - public function testExtensionIsAnnounced(): void - { - $client = $this->connectDeclaring(); - - $result = $client->callTool('long_job'); - - $this->assertInstanceOf(CreateTaskResult::class, $result); - $this->assertSame(TaskStatus::Working, $result->task->status); - $this->assertSame('queued', $result->task->statusMessage); - $this->assertSame(10, $result->task->pollIntervalMs); - $this->assertNotNull($result->task->createdAt); - } - #[TestDox('a task is polled to completion and carries the tool result')] public function testTaskIsPolledToCompletion(): void { $client = $this->connectDeclaring(); $created = $client->callTool('long_job'); + $this->assertInstanceOf(CreateTaskResult::class, $created); + $this->assertSame(TaskStatus::Working, $created->task->status); + $this->assertSame('queued', $created->task->statusMessage); $polled = $client->get($created->task->taskId); $this->assertSame(TaskStatus::Working, $polled->status); @@ -60,70 +49,55 @@ public function testTaskIsPolledToCompletion(): void $done = $this->settle($client, $created->task->taskId); $this->assertSame(TaskStatus::Completed, $done->status); - $this->assertNull($done->error); + $this->assertNotNull($done->result); $result = CallToolResult::fromArray($done->result); $this->assertInstanceOf(TextContent::class, $result->content[0]); $this->assertSame('done', $result->content[0]->text); } - #[TestDox('a client that did not declare the extension gets the synchronous answer')] - public function testUndeclaredClientIsServedSynchronously(): void + #[TestDox('the plain client refuses a task answer and points to TaskClient')] + public function testPlainClientRefusesATask(): void { - $client = $this->connect('tasks'); + $client = $this->connect('tasks', $this->declaring()); - $result = $client->callTool('long_job'); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(TaskClient::class.'::callTool()'); - $this->assertInstanceOf(CallToolResult::class, $result); - $this->assertInstanceOf(TextContent::class, $result->content[0]); - $this->assertSame('sync', $result->content[0]->text); + $client->callTool('long_job'); } - #[TestDox('a task-only tool refuses a client that cannot poll with -32021')] - public function testUndeclaredClientIsRefusedARequiredTask(): void + #[TestDox('a client that did not declare the extension gets the synchronous answer')] + public function testUndeclaredClientIsServedSynchronously(): void { - $client = $this->connect('tasks'); + $result = $this->connect('tasks', $this->clientBuilder()->setProtocolVersion(ProtocolVersion::V2026_07_28))->callTool('long_job'); - try { - $client->callTool('task_only'); - $this->fail('Expected the task to be refused.'); - } catch (RequestException $e) { - $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $e->getError()?->code); - $this->assertArrayHasKey(TasksExtension::ID, $e->getError()->data['requiredCapabilities']['extensions']); - } + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('sync', $result->content[0]->text); } - #[TestDox('the tasks/* methods themselves are refused to a client that did not declare the extension')] - public function testUndeclaredClientCannotPoll(): void + #[TestDox('below 2026-07-28 the extension does not exist: tools answer synchronously, tasks/* is not found')] + public function testOlderRevisionHasNoTasks(): void { - $client = new TaskClient($this->connect('tasks')); + $client = new TaskClient($this->connect('tasks', $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2025_11_25) + ->enableExtension(new TasksExtension()))); - try { - $client->get('anything'); - $this->fail('Expected tasks/get to be refused.'); - } catch (RequestException $e) { - $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $e->getError()?->code); - } + $result = $client->callTool('long_job'); + $this->assertInstanceOf(CallToolResult::class, $result); + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('sync', $result->content[0]->text); + + $this->assertErrorCode(Error::METHOD_NOT_FOUND, static fn () => $client->get('anything')); } - #[TestDox('a parked task exposes what it asks for, and an answer through tasks/update completes it')] - public function testInputRequiredRoundTrip(): void + #[TestDox('a client that did not declare the extension is refused a task and the tasks/* methods with -32021')] + public function testUndeclaredClientIsRefused(): void { - $client = $this->connectDeclaring(); - $created = $client->callTool('ask_job'); - $this->assertInstanceOf(CreateTaskResult::class, $created); - - $parked = $client->get($created->task->taskId); - $this->assertSame(TaskStatus::InputRequired, $parked->status); - $this->assertArrayHasKey('name', $parked->inputRequests); - $this->assertInstanceOf(ElicitRequest::class, $parked->inputRequests['name']); - $this->assertSame('What is your name?', $parked->inputRequests['name']->message); - - $client->update($created->task->taskId, ['name' => ['action' => 'accept', 'content' => ['name' => 'Ada']]]); + $client = new TaskClient($this->connect('tasks', $this->clientBuilder()->setProtocolVersion(ProtocolVersion::V2026_07_28))); - $done = $client->get($created->task->taskId); - $this->assertSame(TaskStatus::Completed, $done->status); - $this->assertSame('Hello, Ada', CallToolResult::fromArray($done->result)->content[0]->text ?? null); + $this->assertErrorCode(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, static fn () => $client->callTool('task_only')); + $this->assertErrorCode(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, static fn () => $client->get('anything')); } #[TestDox('a failed task carries the error inline and no result')] @@ -160,31 +134,32 @@ public function testUnknownTask(): void { $client = $this->connectDeclaring(); - try { - $client->get('no-such-task'); - $this->fail('Expected tasks/get to fail.'); - } catch (RequestException $e) { - $this->assertSame(Error::INVALID_PARAMS, $e->getError()?->code); - } + $this->assertErrorCode(Error::INVALID_PARAMS, static fn () => $client->get('no-such-task')); } - #[TestDox('a prompt can be served as a task too')] - public function testPromptAsTask(): void + private function declaring(): ClientBuilder { - $client = $this->connectDeclaring(); - $created = $client->getPrompt('slow_prompt'); - $this->assertInstanceOf(CreateTaskResult::class, $created); + return $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2026_07_28) + ->enableExtension(new TasksExtension()); + } - $done = $this->settle($client, $created->task->taskId); + private function connectDeclaring(): TaskClient + { + $client = $this->connect('tasks', $this->declaring()); + $this->assertSame(ProtocolVersion::V2026_07_28, $client->getProtocolVersion()); - $this->assertSame(TaskStatus::Completed, $done->status); - $prompt = GetPromptResult::fromArray($done->result); - $this->assertSame('prompt done', $prompt->messages[0]->content->text ?? null); + return new TaskClient($client); } - private function connectDeclaring(): TaskClient + private function assertErrorCode(int $code, callable $call): void { - return new TaskClient($this->connect('tasks', $this->clientBuilder()->enableExtension(new TasksExtension()))); + try { + $call(); + $this->fail(\sprintf('Expected error %d.', $code)); + } catch (RequestException $e) { + $this->assertSame($code, $e->getError()?->code); + } } /** diff --git a/tests/Unit/Schema/Extension/Tasks/TaskTest.php b/tests/Unit/Schema/Extension/Tasks/TaskTest.php new file mode 100644 index 000000000..baf003701 --- /dev/null +++ b/tests/Unit/Schema/Extension/Tasks/TaskTest.php @@ -0,0 +1,149 @@ +jsonSerialize(); + + $this->assertSame([ + 'resultType' => 'task', + 'taskId' => 'task-1', + 'status' => 'working', + 'createdAt' => '2026-08-15T10:00:00+00:00', + 'lastUpdatedAt' => '2026-08-15T10:00:00+00:00', + 'ttlMs' => 600_000, + 'pollIntervalMs' => 250, + ], $data); + } + + #[TestDox('an unlimited TTL is emitted as null, not omitted')] + public function testNullTtlIsEmitted(): void + { + $data = (new CreateTaskResult(self::task(ttlMs: null)))->jsonSerialize(); + + $this->assertArrayHasKey('ttlMs', $data); + $this->assertNull($data['ttlMs']); + } + + /** + * @return iterable}> + */ + public static function provideStatusPayloads(): iterable + { + $now = new \DateTimeImmutable('2026-08-15T10:00:01+00:00'); + + yield 'working' => [self::task(), []]; + yield 'completed' => [self::task()->with(TaskStatus::Completed, $now, result: ['content' => []]), ['result']]; + yield 'failed' => [self::task()->with(TaskStatus::Failed, $now, error: Error::forInternalError('boom')), ['error']]; + yield 'cancelled' => [self::task()->with(TaskStatus::Cancelled, $now), []]; + } + + /** + * @param list $expected + */ + #[DataProvider('provideStatusPayloads')] + #[TestDox('a task inlines what its current status carries, and nothing a previous status did')] + public function testStatusPayloadOnTheWire(Task $task, array $expected): void + { + $data = $task->jsonSerialize(); + + foreach (['result', 'error'] as $field) { + $this->assertSame(\in_array($field, $expected, true), \array_key_exists($field, $data), $field); + } + + $this->assertArrayNotHasKey('owner', $data); + } + + /** + * @return iterable + */ + public static function provideInvalidTasks(): iterable + { + $at = new \DateTimeImmutable('2026-08-15T10:00:00+00:00'); + + yield 'failed without an error' => [static fn () => new Task('t', TaskStatus::Failed, $at, $at), 'error']; + yield 'an error on a task that did not fail' => [static fn () => new Task('t', TaskStatus::Completed, $at, $at, result: [], error: Error::forInternalError('boom')), 'isError']; + yield 'completed without a result' => [static fn () => new Task('t', TaskStatus::Completed, $at, $at), 'result']; + yield 'a negative TTL' => [static fn () => new Task('t', TaskStatus::Working, $at, $at, ttlMs: -1), 'ttlMs']; + yield 'a zero poll interval' => [static fn () => new Task('t', TaskStatus::Working, $at, $at, pollIntervalMs: 0), 'pollIntervalMs']; + } + + /** + * @param callable(): Task $build + */ + #[DataProvider('provideInvalidTasks')] + public function testInvalidTaskIsRefused(callable $build, string $mentions): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($mentions); + + $build(); + } + + /** + * @return iterable + */ + public static function provideTerminalTasks(): iterable + { + $now = new \DateTimeImmutable('2026-08-15T10:00:01+00:00'); + + yield 'completed' => [self::task()->with(TaskStatus::Completed, $now, result: [])]; + yield 'failed' => [self::task()->with(TaskStatus::Failed, $now, error: Error::forInternalError('boom'))]; + yield 'cancelled' => [self::task()->with(TaskStatus::Cancelled, $now)]; + } + + #[DataProvider('provideTerminalTasks')] + #[TestDox('a terminal task never moves again, so a late worker cannot overwrite a cancel')] + public function testTerminalTaskIsFinal(Task $task): void + { + $this->expectException(LogicException::class); + + $task->with(TaskStatus::Completed, new \DateTimeImmutable(), result: []); + } + + #[TestDox('a task stays readable for its whole TTL, and not past it; without one it always is')] + public function testTtlBoundsReadability(): void + { + $this->assertTrue(self::task()->isReadable(new \DateTimeImmutable('2026-08-15T10:09:59+00:00'))); + $this->assertFalse(self::task()->isReadable(new \DateTimeImmutable('2026-08-15T10:10:01+00:00'))); + $this->assertTrue(self::task(ttlMs: null)->isReadable(new \DateTimeImmutable('2099-01-01T00:00:00+00:00'))); + } + + #[TestDox('timestamps are required to read a task back')] + public function testFromArrayRequiresTimestamps(): void + { + $this->expectException(InvalidArgumentException::class); + + Task::fromArray(['taskId' => 't', 'status' => 'working', 'ttlMs' => null]); + } + + private static function task(?int $ttlMs = 600_000): Task + { + $at = new \DateTimeImmutable('2026-08-15T10:00:00+00:00'); + + return new Task('task-1', TaskStatus::Working, $at, $at, $ttlMs, 250); + } +} diff --git a/tests/Unit/Server/BuilderTest.php b/tests/Unit/Server/BuilderTest.php index df468075a..32acdf3a1 100644 --- a/tests/Unit/Server/BuilderTest.php +++ b/tests/Unit/Server/BuilderTest.php @@ -39,9 +39,6 @@ use Mcp\Server\Stateless\StatelessProtocol; use Mcp\Server\Subscription\InMemoryNotificationBus; use Mcp\Server\Subscription\PublishingEventDispatcher; -use Mcp\Server\Task\InMemoryTaskStore; -use Mcp\Server\Task\TaskContext; -use Mcp\Server\Task\TasksExtension; use Mcp\Server\Transport\InMemoryTransport; use Mcp\Tests\Unit\Server\Extension\ThingExtension; use Mcp\Tests\Unit\Server\Extension\ThingListHandler; @@ -193,29 +190,6 @@ public function testEnableExtensionRejectsDuplicate(): void Server::builder()->enableExtension(new McpApps(), new McpApps()); } - #[TestDox('enableExtension() lets an extension hand its own object to handlers, and keeps it out of the schema')] - public function testEnableExtensionProvidesHandlerArguments(): void - { - $server = Server::builder() - ->setServerInfo('test', '1.0.0') - ->enableExtension(new TasksExtension(new InMemoryTaskStore())) - ->addTool(static fn (TaskContext $tasks): string => $tasks->isSupported() ? 'tasks' : 'no tasks', name: 'probe') - ->build(); - - $this->assertArrayHasKey(TasksExtension::ID, $this->extractServerCapabilities($server)->extensions ?? []); - $this->assertSame('no tasks', $this->callTool($server, 'probe')); - - $protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server); - foreach ((new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol) as $handler) { - if ($handler instanceof CallToolHandler) { - $registry = (new \ReflectionClass($handler))->getProperty('registry')->getValue($handler); - $schema = $registry->getTool('probe')->tool->inputSchema; - $this->assertArrayNotHasKey('required', $schema); - $this->assertSame([], (array) ($schema['properties'] ?? [])); - } - } - } - #[TestDox('enableExtension() extensions are merged into capabilities set via setCapabilities()')] public function testEnableExtensionMergesIntoCustomCapabilities(): void { diff --git a/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php b/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php index 09848a2ed..b1ad60b7e 100644 --- a/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php +++ b/tests/Unit/Server/Capability/Registry/ReferenceHandlerTest.php @@ -12,7 +12,6 @@ namespace Mcp\Tests\Unit\Server\Capability\Registry; use Mcp\Schema\JsonRpc\Error; -use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\Request\PingRequest; use Mcp\Server\Capability\Registry\Container; use Mcp\Server\Capability\Registry\ElementReference; @@ -260,23 +259,6 @@ public function testHandleStillReflectsOrdinaryClosuresAndDoesNotInjectArgumentB $this->assertSame('value', $captured); } - public function testHandleInjectsWhatAnArgumentProviderBuildsForTheRequest(): void - { - $session = $this->createMock(SessionInterface::class); - $request = PingRequest::fromArray(['jsonrpc' => '2.0', 'id' => 7, 'method' => 'ping']); - - $closure = static fn (\ArrayObject $provided, string $kept): string => $provided['request'].':'.$kept; - $reference = new ElementReference($closure); - - $handler = new ReferenceHandler(argumentProviders: [ - \ArrayObject::class => static fn (SessionInterface $s, Request $r): \ArrayObject => new \ArrayObject(['request' => $r::getMethod().'#'.$r->getId()]), - ]); - - $result = $handler->handle($reference, ['_session' => $session, '_request' => $request, 'kept' => 'value']); - - $this->assertSame('ping#7:value', $result); - } - public function testHandleThrowsForStringHandlerThatIsNeitherFunctionNorClass(): void { $session = $this->createMock(SessionInterface::class); diff --git a/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php index 6c3cf62f1..bf63b0fe8 100644 --- a/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php +++ b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php @@ -11,7 +11,6 @@ namespace Mcp\Tests\Unit\Server\Handler\Request; -use Mcp\Schema\ClientCapabilities; use Mcp\Schema\Content\TextContent; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\JsonRpc\Error; @@ -23,7 +22,6 @@ use Mcp\Server\Capability\Registry\ReferenceHandlerInterface; use Mcp\Server\Capability\Registry\ToolReference; use Mcp\Server\Capability\RegistryInterface; -use Mcp\Server\Exception\MissingRequiredClientCapabilityException; use Mcp\Server\Exception\RegistryException; use Mcp\Server\Exception\ToolCallException; use Mcp\Server\Exception\ToolNotFoundException; @@ -125,24 +123,6 @@ public function testAResultOfAnotherKindIsPassedThroughUntouched(): void $this->assertSame($foreign, $response->result); } - public function testAMissingClientCapabilityIsLeftToTheProtocol(): void - { - // Not a tool failure: the request was unservable, and the protocol - // renders it as -32021. The handler must let it through rather than - // turn it into tool output. - $request = $this->createCallToolRequest('slow_tool', []); - $toolReference = $this->createToolReference('slow_tool', static fn () => null); - $required = new ClientCapabilities(extensions: ['io.example/thing' => new \stdClass()]); - - $this->registry->method('getTool')->willReturn($toolReference); - $this->referenceHandler->method('handle')->willThrowException(new MissingRequiredClientCapabilityException($required, 'Needs the thing.')); - - $this->expectException(MissingRequiredClientCapabilityException::class); - $this->expectExceptionMessage('Needs the thing.'); - - $this->handler->handle($request, $this->session); - } - public function testHandleToolCallWithEmptyArguments(): void { $request = $this->createCallToolRequest('simple_tool', []); diff --git a/tests/Unit/Server/ProtocolTest.php b/tests/Unit/Server/ProtocolTest.php index 292d9acc6..03849deb4 100644 --- a/tests/Unit/Server/ProtocolTest.php +++ b/tests/Unit/Server/ProtocolTest.php @@ -11,6 +11,7 @@ namespace Mcp\Tests\Unit\Server; +use Mcp\Schema\ClientCapabilities; use Mcp\Schema\Enum\LoggingLevel; use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; @@ -27,6 +28,7 @@ use Mcp\Server\Event\RequestEvent; use Mcp\Server\Event\ResponseEvent; use Mcp\Server\Event\ServerRequestEvent; +use Mcp\Server\Exception\MissingRequiredClientCapabilityException; use Mcp\Server\Exception\RuntimeException; use Mcp\Server\Exception\SessionRequiredException; use Mcp\Server\Handler\Notification\NotificationHandlerInterface; @@ -1000,6 +1002,32 @@ public function testHandlerInvalidArgumentReturnsInvalidParamsError(): void $this->assertStringContainsString('Invalid parameter', $message['error']['message']); } + public function testHandlerMissingClientCapabilityReturnsMissingRequiredClientCapabilityError(): void + { + $handler = $this->createMock(RequestHandlerInterface::class); + $handler->method('supports')->willReturn(true); + $handler->method('handle')->willThrowException(new MissingRequiredClientCapabilityException(new ClientCapabilities(roots: false, extensions: ['com.example/thing' => new \stdClass()]), 'Needs the thing.')); + + $this->sessionManager->method('createWithId')->willReturn($this->createMock(SessionInterface::class)); + $this->sessionManager->method('exists')->willReturn(true); + + $transport = new RecordingTransport(); + + $protocol = new Protocol( + requestHandlers: [$handler], + notificationHandlers: [], + messageFactory: MessageFactory::make(), + sessionManager: $this->sessionManager, + ); + + $protocol->processInput($transport, '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "test"}}', Uuid::v4()); + + $message = json_decode($transport->sent[0]['message'], true); + $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $message['error']['code']); + $this->assertSame('Needs the thing.', $message['error']['message']); + $this->assertSame(['extensions' => ['com.example/thing' => []]], $message['error']['data']['requiredCapabilities']); + } + #[TestDox('Handler throwing unexpected exception returns internal error')] public function testHandlerUnexpectedExceptionReturnsInternalError(): void { diff --git a/tests/Unit/Server/Task/TaskManagerTest.php b/tests/Unit/Server/Task/TaskManagerTest.php new file mode 100644 index 000000000..411439607 --- /dev/null +++ b/tests/Unit/Server/Task/TaskManagerTest.php @@ -0,0 +1,153 @@ +now = new \DateTimeImmutable('2026-08-15T10:00:00+00:00'); + $clock = $this->createStub(ClockInterface::class); + $clock->method('now')->willReturnCallback(fn (): \DateTimeImmutable => $this->now); + + $this->store = new InMemoryTaskStore(clock: $clock); + $this->tasks = new TaskManager($this->store, $clock); + } + + #[TestDox('a task is stored under a random UUIDv4, bound to its creator, before the handle is handed out')] + public function testCreateStoresTheTaskFirst(): void + { + $token = new AccessToken(claims: ['client_id' => 'app', 'sub' => 'alice']); + + $created = $this->tasks->create(self::context(token: $token), ttlMs: 60_000, pollIntervalMs: 500, statusMessage: 'Queued.'); + + $this->assertInstanceOf(UuidV4::class, Uuid::fromString($created->task->taskId)); + $this->assertSame(TaskStatus::Working, $created->task->status); + $this->assertEquals($this->now, $created->task->createdAt); + $this->assertEquals($this->now, $created->task->lastUpdatedAt); + $this->assertNotNull($created->task->owner); + $this->assertSame($created->task, $this->store->get($created->task->taskId)); + } + + /** + * @return iterable + */ + public static function provideClientsThatCannotPoll(): iterable + { + yield 'a client that did not declare the extension' => [self::context(declared: false)]; + yield 'a revision the extension does not exist in' => [self::context(version: ProtocolVersion::V2025_11_25)]; + } + + #[DataProvider('provideClientsThatCannotPoll')] + #[TestDox('a handle is refused to a client that could not redeem it')] + public function testCreateRefusesAClientThatCannotPoll(RequestContext $context): void + { + $this->assertFalse($this->tasks->isSupported($context)); + + try { + $this->tasks->create($context); + $this->fail('Expected the task to be refused.'); + } catch (MissingRequiredClientCapabilityException $e) { + $this->assertSame(['extensions' => [TasksExtension::ID => []]], json_decode(json_encode($e->requiredCapabilities, \JSON_THROW_ON_ERROR), true)); + } + } + + #[TestDox('only tools/call can be answered with a task')] + public function testCreateRefusesOtherMethods(): void + { + $this->expectException(LogicException::class); + + $this->tasks->create(self::context(request: new GetPromptRequest('greet'))); + } + + /** + * @return iterable + */ + public static function provideCallers(): iterable + { + yield 'the same client and subject' => [new AccessToken(claims: ['client_id' => 'app', 'sub' => 'alice', 'scope' => 'other']), true]; + yield 'another subject of the same client' => [new AccessToken(claims: ['client_id' => 'app', 'sub' => 'mallory']), false]; + yield 'the same subject through another client' => [new AccessToken(claims: ['client_id' => 'evil', 'sub' => 'alice']), false]; + yield 'an unauthenticated caller' => [null, false]; + } + + #[DataProvider('provideCallers')] + #[TestDox('a task is only found for the client and subject that created it')] + public function testFindChecksTheOwner(?AccessToken $caller, bool $found): void + { + $created = $this->tasks->create(self::context(token: new AccessToken(claims: ['client_id' => 'app', 'sub' => 'alice']))); + + $this->assertSame($found, null !== $this->tasks->find(self::context(token: $caller), $created->task->taskId)); + } + + #[TestDox('without authentication the task id is the bearer token')] + public function testUnownedTaskIsFoundByItsId(): void + { + $created = $this->tasks->create(self::context()); + + $this->assertNotNull($this->tasks->find(self::context(token: new AccessToken(claims: ['sub' => 'anyone'])), $created->task->taskId)); + } + + #[TestDox('a worker cannot overwrite a cancellation')] + public function testTransitionRefusesATerminalTask(): void + { + $created = $this->tasks->create(self::context()); + $this->now = $this->now->modify('+1 second'); + $this->tasks->cancel($created->task); + + try { + $this->tasks->transition($created->task->taskId, TaskStatus::Completed, result: ['content' => []]); + $this->fail('Expected the transition to be refused.'); + } catch (SchemaLogicException) { + } + + $this->assertSame(TaskStatus::Cancelled, $this->store->get($created->task->taskId)?->status); + $this->assertEquals($this->now, $this->store->get($created->task->taskId)->lastUpdatedAt); + } + + private static function context(bool $declared = true, ProtocolVersion $version = ProtocolVersion::V2026_07_28, ?AccessToken $token = null, ?Request $request = null): RequestContext + { + $session = new Session(new InMemorySessionStore()); + $session->set('client_capabilities', (new ClientCapabilities(extensions: $declared ? [TasksExtension::ID => new \stdClass()] : null))->jsonSerialize()); + $session->set('protocol_version', $version->value); + $session->set(AccessToken::class, $token); + + return new RequestContext($session, $request ?? new CallToolRequest('long_job', [])); + } +} diff --git a/tests/Unit/Server/Task/TaskStoreTest.php b/tests/Unit/Server/Task/TaskStoreTest.php index d0f99ea8b..d063d1d5a 100644 --- a/tests/Unit/Server/Task/TaskStoreTest.php +++ b/tests/Unit/Server/Task/TaskStoreTest.php @@ -11,21 +11,20 @@ namespace Mcp\Tests\Unit\Server\Task; -use Mcp\Schema\Elicitation\ElicitationSchema; -use Mcp\Schema\Elicitation\StringSchemaDefinition; -use Mcp\Schema\Enum\TaskStatus; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Schema\Extension\Tasks\TaskStatus; use Mcp\Schema\JsonRpc\Error; -use Mcp\Schema\Request\ElicitRequest; -use Mcp\Schema\Task; use Mcp\Server\Exception\InvalidArgumentException; +use Mcp\Server\Exception\RuntimeException; use Mcp\Server\Task\InMemoryTaskStore; use Mcp\Server\Task\Psr16TaskStore; use Mcp\Server\Task\TaskStoreInterface; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; -use Psr\Clock\ClockInterface; use Psr\SimpleCache\CacheInterface; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; class TaskStoreTest extends TestCase { @@ -35,121 +34,100 @@ class TaskStoreTest extends TestCase public static function stores(): iterable { yield 'in memory' => [new InMemoryTaskStore()]; - yield 'psr-16' => [new Psr16TaskStore(self::arrayCache())]; + yield 'psr-16' => [new Psr16TaskStore(new Psr16Cache(new ArrayAdapter()))]; } - #[DataProvider('stores')] - #[TestDox('a task round-trips through the store')] - public function testRoundTrip(TaskStoreInterface $store): void + /** + * @return iterable + */ + public static function provideRoundTrips(): iterable { - $store->save(new Task('t-1', TaskStatus::Working, new \DateTimeImmutable(), new \DateTimeImmutable(), 600_000, 250, 'halfway')); + $now = new \DateTimeImmutable(); + $working = new Task('t-1', TaskStatus::Working, $now, $now, 600_000, 250, 'halfway', owner: 'alice'); + + $tasks = [ + 'working, owned' => $working, + 'completed' => $working->with(TaskStatus::Completed, $now, result: ['content' => [['type' => 'text', 'text' => 'done']]]), + 'failed' => $working->with(TaskStatus::Failed, $now, error: Error::forInternalError('boom')), + ]; + + foreach (self::stores() as $storeName => [$store]) { + foreach ($tasks as $taskName => $task) { + yield $storeName.', '.$taskName => [$store, $task]; + } + } + } - $task = $store->get('t-1'); + #[DataProvider('provideRoundTrips')] + #[TestDox('a task round-trips through the store, owner included')] + public function testRoundTrip(TaskStoreInterface $store, Task $task): void + { + $store->save($task); - $this->assertNotNull($task); - $this->assertSame('t-1', $task->taskId); - $this->assertSame(TaskStatus::Working, $task->status); - $this->assertSame(600_000, $task->ttlMs); - $this->assertSame(250, $task->pollIntervalMs); - $this->assertSame('halfway', $task->statusMessage); + $read = $store->get($task->taskId); + + $this->assertNotNull($read); + $this->assertEquals($task->jsonSerialize(), $read->jsonSerialize()); + $this->assertSame($task->owner, $read->owner); } #[DataProvider('stores')] - #[TestDox('an unknown id reads as absent')] public function testUnknownIdIsNull(TaskStoreInterface $store): void { $this->assertNull($store->get('nope')); } #[DataProvider('stores')] - #[TestDox('a saved task overwrites the earlier state under the same id')] - public function testSaveOverwrites(TaskStoreInterface $store): void + #[TestDox('a task past its TTL reads as absent')] + public function testTtlExpiry(TaskStoreInterface $store): void { - $task = new Task('t-2', TaskStatus::Working, new \DateTimeImmutable(), new \DateTimeImmutable(), 600_000); - $store->save($task); - $store->save($task->with(TaskStatus::Cancelled)); + $created = new \DateTimeImmutable('-2 seconds'); + $store->save(new Task('t-6', TaskStatus::Working, $created, $created, 1000)); - $this->assertSame(TaskStatus::Cancelled, $store->get('t-2')?->status); + $this->assertNull($store->get('t-6')); } - #[DataProvider('stores')] - #[TestDox('a failed task keeps its error across the store')] - public function testErrorSurvives(TaskStoreInterface $store): void + #[TestDox('the PSR-16 store refuses to report a task created that the cache did not keep')] + public function testPsr16SaveFailureThrows(): void { - $task = (new Task('t-3', TaskStatus::Working, new \DateTimeImmutable(), null, 600_000)) - ->with(TaskStatus::Failed, error: Error::forInternalError('boom')); + $cache = $this->createMock(CacheInterface::class); + $cache->method('set')->willReturn(false); + $now = new \DateTimeImmutable(); - $store->save($task); + $this->expectException(RuntimeException::class); - $read = $store->get('t-3'); - $this->assertNotNull($read); - $this->assertNotNull($read->error); - $this->assertSame(Error::INTERNAL_ERROR, $read->error->code); - $this->assertSame('boom', $read->error->message); + (new Psr16TaskStore($cache))->save(new Task('t-7', TaskStatus::Working, $now, $now)); } - #[DataProvider('stores')] - #[TestDox('a parked task still knows what it is waiting for after a round trip')] - public function testInputRequestsSurvive(TaskStoreInterface $store): void + #[TestDox('the PSR-16 store keeps a task without a TTL for as long as the cache does')] + public function testPsr16UnlimitedTtl(): void { - $task = (new Task('t-4', TaskStatus::Working, new \DateTimeImmutable(), null, 600_000)) - ->with(TaskStatus::InputRequired, inputRequests: [ - 'who' => new ElicitRequest('Who?', new ElicitationSchema(['n' => new StringSchemaDefinition('N')], ['n'])), - ]); + $cache = $this->createMock(CacheInterface::class); + $cache->expects($this->once())->method('set')->with('mcp.tasks.t-8', $this->isType('string'), null)->willReturn(true); + $now = new \DateTimeImmutable(); - $store->save($task); - - $read = $store->get('t-4'); - $this->assertNotNull($read); - $this->assertArrayHasKey('who', $read->inputRequests); - $this->assertInstanceOf(ElicitRequest::class, $read->inputRequests['who']); - $this->assertSame('Who?', $read->inputRequests['who']->message); + (new Psr16TaskStore($cache))->save(new Task('t-8', TaskStatus::Working, $now, $now)); } - #[DataProvider('stores')] - #[TestDox('a deleted task is gone')] - public function testDelete(TaskStoreInterface $store): void + #[TestDox('an unreadable stored payload reads as absent rather than throwing')] + public function testCorruptPayloadIsDropped(): void { - $store->save(new Task('t-5')); - $store->delete('t-5'); + $cache = new Psr16Cache(new ArrayAdapter()); + $cache->set('mcp.tasks.t-9', 'not json at all'); - $this->assertNull($store->get('t-5')); + $this->assertNull((new Psr16TaskStore($cache))->get('t-9')); } - #[TestDox('a task past its TTL reads as absent')] - public function testTtlExpiry(): void - { - $created = new \DateTimeImmutable('2026-08-15T10:00:00+00:00'); - $clock = new class($created) implements ClockInterface { - public function __construct(public \DateTimeImmutable $now) - { - } - - public function now(): \DateTimeImmutable - { - return $this->now; - } - }; - - $store = new InMemoryTaskStore(clock: $clock); - $store->save(new Task('t-6', TaskStatus::Working, $created, $created, 1000)); - - $this->assertNotNull($store->get('t-6')); - - $clock->now = $created->modify('+2 seconds'); - $this->assertNull($store->get('t-6')); - } - - #[TestDox('the in-memory store drops the least recently used task past its limit')] + #[TestDox('the in-memory store drops the least recently saved task past its limit')] public function testInMemoryEviction(): void { + $now = new \DateTimeImmutable(); $store = new InMemoryTaskStore(limit: 2); - $store->save(new Task('a')); - $store->save(new Task('b')); - // Touching `a` makes `b` the least recently used. - $store->save(new Task('a', TaskStatus::Working)); - $store->save(new Task('c')); + $store->save(new Task('a', TaskStatus::Working, $now, $now)); + $store->save(new Task('b', TaskStatus::Working, $now, $now)); + $store->save(new Task('a', TaskStatus::Working, $now, $now)); + $store->save(new Task('c', TaskStatus::Working, $now, $now)); $this->assertNotNull($store->get('a')); $this->assertNull($store->get('b')); @@ -163,77 +141,4 @@ public function testZeroLimitIsRefused(): void new InMemoryTaskStore(limit: 0); } - - #[TestDox('an unreadable stored payload reads as absent rather than throwing')] - public function testCorruptPayloadIsDropped(): void - { - $cache = self::arrayCache(); - $cache->set('mcp.tasks.t-7', 'not json at all'); - - $this->assertNull((new Psr16TaskStore($cache))->get('t-7')); - } - - private static function arrayCache(): CacheInterface - { - return new class implements CacheInterface { - /** @var array */ - private array $values = []; - - public function get(string $key, mixed $default = null): mixed - { - return $this->values[$key] ?? $default; - } - - public function set(string $key, mixed $value, int|\DateInterval|null $ttl = null): bool - { - $this->values[$key] = $value; - - return true; - } - - public function delete(string $key): bool - { - unset($this->values[$key]); - - return true; - } - - public function clear(): bool - { - $this->values = []; - - return true; - } - - public function getMultiple(iterable $keys, mixed $default = null): iterable - { - foreach ($keys as $key) { - yield $key => $this->get($key, $default); - } - } - - public function setMultiple(iterable $values, int|\DateInterval|null $ttl = null): bool - { - foreach ($values as $key => $value) { - $this->set((string) $key, $value, $ttl); - } - - return true; - } - - public function deleteMultiple(iterable $keys): bool - { - foreach ($keys as $key) { - $this->delete($key); - } - - return true; - } - - public function has(string $key): bool - { - return \array_key_exists($key, $this->values); - } - }; - } } diff --git a/tests/Unit/Server/Task/TaskTest.php b/tests/Unit/Server/Task/TaskTest.php deleted file mode 100644 index 52ce5040f..000000000 --- a/tests/Unit/Server/Task/TaskTest.php +++ /dev/null @@ -1,173 +0,0 @@ -jsonSerialize(); - - $this->assertSame('task', $data['resultType']); - $this->assertSame('task-1', $data['taskId']); - $this->assertSame('working', $data['status']); - $this->assertSame(600_000, $data['ttlMs']); - $this->assertSame(250, $data['pollIntervalMs']); - $this->assertArrayNotHasKey('task', $data); - - // A task that was just created has nothing to report yet. - $this->assertArrayNotHasKey('result', $data); - $this->assertArrayNotHasKey('error', $data); - $this->assertArrayNotHasKey('inputRequests', $data); - } - - #[TestDox('the wire fields carry their unit in the name')] - public function testLegacyWireNamesAreGone(): void - { - $data = (new CreateTaskResult(self::task()))->jsonSerialize(); - - $this->assertArrayNotHasKey('ttl', $data); - $this->assertArrayNotHasKey('pollInterval', $data); - } - - #[TestDox('timestamps are ISO-8601')] - public function testTimestampsAreIso8601(): void - { - $data = (new CreateTaskResult(self::task()))->jsonSerialize(); - - $this->assertSame('2026-08-15T10:00:00+00:00', $data['createdAt']); - $this->assertSame('2026-08-15T10:00:00+00:00', $data['lastUpdatedAt']); - } - - #[TestDox('an unlimited TTL is emitted as null, not omitted')] - public function testNullTtlIsEmitted(): void - { - $data = (new CreateTaskResult(new Task('task-1', ttlMs: null)))->jsonSerialize(); - - $this->assertArrayHasKey('ttlMs', $data); - $this->assertNull($data['ttlMs']); - } - - #[TestDox('a completed task inlines the result the request would have returned')] - public function testCompletedTaskInlinesItsResult(): void - { - $task = self::task()->with(TaskStatus::Completed, result: new CallToolResult([new TextContent('done')])); - - $data = (new TaskResult($task))->jsonSerialize(); - - $this->assertSame('completed', $data['status']); - $this->assertSame('done', $data['result']->content[0]->text); - } - - #[TestDox('a failed task inlines the error and carries no result')] - public function testFailedTaskInlinesItsError(): void - { - $task = self::task()->with(TaskStatus::Failed, error: Error::forInternalError('boom')); - - $data = (new TaskResult($task))->jsonSerialize(); - - $this->assertSame('failed', $data['status']); - $this->assertSame(Error::INTERNAL_ERROR, $data['error']['code']); - $this->assertSame('boom', $data['error']['message']); - $this->assertArrayNotHasKey('result', $data); - } - - #[TestDox('a tool that ran and reported a problem is completed, never failed')] - public function testToolErrorCannotBeSpelledAsFailed(): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessageMatches('/isError/'); - - new Task('task-1', TaskStatus::Completed, error: Error::forInternalError('boom')); - } - - #[TestDox('a failed task without an error is refused')] - public function testFailedTaskNeedsAnError(): void - { - $this->expectException(InvalidArgumentException::class); - - new Task('task-1', TaskStatus::Failed); - } - - #[TestDox('a waiting task surfaces what it is waiting for')] - public function testInputRequiredTaskCarriesItsRequests(): void - { - $task = self::task()->with(TaskStatus::InputRequired, inputRequests: [ - 'who' => new ElicitRequest('Who?', new ElicitationSchema(['n' => new StringSchemaDefinition('N')], ['n'])), - ]); - - $data = (new TaskResult($task))->jsonSerialize(); - - $this->assertSame('input_required', $data['status']); - $this->assertSame('elicitation/create', $data['inputRequests']['who']['method']); - } - - #[TestDox('terminal states are the ones that never change again')] - public function testTerminalStates(): void - { - $this->assertTrue(TaskStatus::Completed->isTerminal()); - $this->assertTrue(TaskStatus::Failed->isTerminal()); - $this->assertTrue(TaskStatus::Cancelled->isTerminal()); - $this->assertFalse(TaskStatus::Working->isTerminal()); - $this->assertFalse(TaskStatus::InputRequired->isTerminal()); - } - - #[TestDox('a task stays readable for its whole TTL, and not past it')] - public function testTtlBoundsReadability(): void - { - $task = self::task(); - - $this->assertTrue($task->isReadable(new \DateTimeImmutable('2026-08-15T10:09:59+00:00'))); - $this->assertFalse($task->isReadable(new \DateTimeImmutable('2026-08-15T10:10:01+00:00'))); - } - - #[TestDox('a task with no TTL is always readable')] - public function testNoTtlIsAlwaysReadable(): void - { - $this->assertTrue((new Task('task-1'))->isReadable(new \DateTimeImmutable('2099-01-01T00:00:00+00:00'))); - } - - #[TestDox('a fractional or negative duration is refused: it is not guidance a client can act on')] - public function testDurationsMustBePositive(): void - { - $this->expectException(InvalidArgumentException::class); - - new Task('task-1', ttlMs: -1); - } -} diff --git a/tests/Unit/Server/Task/TasksExtensionTest.php b/tests/Unit/Server/Task/TasksExtensionTest.php index a28f870ae..d7b01c9ca 100644 --- a/tests/Unit/Server/Task/TasksExtensionTest.php +++ b/tests/Unit/Server/Task/TasksExtensionTest.php @@ -12,36 +12,28 @@ namespace Mcp\Tests\Unit\Server\Task; use Mcp\Schema\ClientCapabilities; -use Mcp\Schema\Elicitation\ElicitationSchema; -use Mcp\Schema\Elicitation\StringSchemaDefinition; -use Mcp\Schema\Enum\TaskStatus; +use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Tasks\Task; +use Mcp\Schema\Extension\Tasks\TasksCancelRequest; +use Mcp\Schema\Extension\Tasks\TasksGetRequest; +use Mcp\Schema\Extension\Tasks\TaskStatus; use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; -use Mcp\Schema\Request\ElicitRequest; -use Mcp\Schema\Request\PingRequest; -use Mcp\Schema\Request\TasksCancelRequest; -use Mcp\Schema\Request\TasksGetRequest; -use Mcp\Schema\Request\TasksUpdateRequest; use Mcp\Schema\Result\EmptyResult; -use Mcp\Schema\Result\TaskResult; -use Mcp\Schema\Task; +use Mcp\Server\Authorization\AccessToken; use Mcp\Server\Exception\LogicException; use Mcp\Server\Exception\MissingRequiredClientCapabilityException; -use Mcp\Server\Handler\Request\RequestHandlerInterface; use Mcp\Server\Session\InMemorySessionStore; use Mcp\Server\Session\Session; use Mcp\Server\Session\SessionInterface; use Mcp\Server\Task\InMemoryTaskStore; -use Mcp\Server\Task\TaskContext; -use Mcp\Server\Task\TaskInputHandlerInterface; +use Mcp\Server\Task\TaskManager; use Mcp\Server\Task\TasksExtension; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; -/** - * The `tasks/*` surface, driven the way the protocol drives it: a request and - * the session `initialize` left behind. - */ class TasksExtensionTest extends TestCase { private InMemoryTaskStore $store; @@ -53,234 +45,142 @@ protected function setUp(): void public function testDeclaresItselfWithoutSettings(): void { - $extension = new TasksExtension($this->store); + $extension = new TasksExtension(); $this->assertSame('io.modelcontextprotocol/tasks', (string) $extension->getId()); $this->assertSame([], $extension->getCapabilities()); - $this->assertSame([TasksGetRequest::class, TasksUpdateRequest::class, TasksCancelRequest::class], $extension->getMessages()); - $this->assertSame($this->store, $extension->getStore()); + $this->assertSame([TasksGetRequest::class, TasksCancelRequest::class], $extension->getMessages()); } - public function testWithoutAStoreItOnlyDeclares(): void + #[TestDox('serving tasks/* needs a task manager')] + public function testServingWithoutAManagerIsRefused(): void { - $extension = new TasksExtension(); - - $this->assertSame([], $extension->getCapabilities()); $this->expectException(LogicException::class); - $extension->getStore(); - } - - public function testProvidesATaskContextToHandlers(): void - { - $providers = (new TasksExtension($this->store))->getArgumentProviders(); - $this->assertSame([TaskContext::class], array_keys($providers)); - $context = $providers[TaskContext::class]($this->session(), PingRequest::fromArray(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'ping'])); - $this->assertInstanceOf(TaskContext::class, $context); - $this->assertSame($this->store, $context->getStore()); + iterator_to_array((new TasksExtension())->getRequestHandlers()); } - public function testTaskContextStoresTheTaskBeforeHandingOutTheHandle(): void - { - $context = new TaskContext($this->session(), $this->store); - $this->assertTrue($context->isSupported()); - - $created = $context->create(ttlMs: 60_000, pollIntervalMs: 500, statusMessage: 'Queued.'); - - $this->assertSame(TaskStatus::Working, $created->task->status); - $this->assertSame(60_000, $created->task->ttlMs); - $this->assertSame(500, $created->task->pollIntervalMs); - $this->assertSame('Queued.', $created->task->statusMessage); - $this->assertSame($created->task, $this->store->get($created->task->taskId)); - } - - public function testTaskContextRefusesAHandleToAClientThatCannotRedeemIt(): void + /** + * @return iterable + */ + public static function provideRequests(): iterable { - $context = new TaskContext($this->session(declared: false), $this->store); - $this->assertFalse($context->isSupported()); - - try { - $context->create(); - $this->fail('Expected the task to be refused.'); - } catch (MissingRequiredClientCapabilityException $e) { - $this->assertArrayHasKey(TasksExtension::ID, $e->requiredCapabilities->extensions); - $this->assertSame( - Error::MISSING_REQUIRED_CLIENT_CAPABILITY, - Error::forMissingRequiredClientCapability($e->getMessage(), $e->requiredCapabilities, 1)->code, - ); - } + yield 'tasks/get' => [new TasksGetRequest('t-1')]; + yield 'tasks/cancel' => [new TasksCancelRequest('t-1')]; } - public function testEachMethodHasAHandler(): void + #[DataProvider('provideRequests')] + #[TestDox('below 2026-07-28 the methods do not exist')] + public function testOlderRevisionIsMethodNotFound(Request $request): void { - $handlers = [...(new TasksExtension($this->store))->getRequestHandlers()]; + $this->store->save(self::task()); - $this->assertCount(3, $handlers); - foreach ([$this->get('t'), $this->update('t'), $this->cancel('t')] as $request) { - $this->assertCount(1, array_filter($handlers, static fn (RequestHandlerInterface $h): bool => $h->supports($request))); - } - } + $response = $this->handle($request, self::session(version: ProtocolVersion::V2025_11_25)); - public function testDeclaredBy(): void - { - $this->assertTrue(TasksExtension::declaredBy(['io.modelcontextprotocol/tasks' => []])); - $this->assertTrue(TasksExtension::declaredBy(['io.modelcontextprotocol/tasks' => new \stdClass()])); - $this->assertFalse(TasksExtension::declaredBy(['io.modelcontextprotocol/ui' => []])); - $this->assertFalse(TasksExtension::declaredBy(null)); + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::METHOD_NOT_FOUND, $response->code); } - public function testGetReturnsTheTaskInDetail(): void + #[DataProvider('provideRequests')] + #[TestDox('a client that did not declare the extension is refused with -32021')] + public function testUndeclaredClientIsRefused(Request $request): void { - $this->store->save((new Task('t-1', createdAt: new \DateTimeImmutable('2026-01-01T00:00:00Z'))) - ->with(TaskStatus::Completed, result: ['content' => []], now: new \DateTimeImmutable('2026-01-01T00:00:01Z'))); - - $response = $this->handle($this->get('t-1'), $this->session()); - - $this->assertInstanceOf(Response::class, $response); - $this->assertInstanceOf(TaskResult::class, $response->result); - $this->assertSame([ - 'taskId' => 't-1', - 'status' => 'completed', - 'createdAt' => '2026-01-01T00:00:00+00:00', - 'lastUpdatedAt' => '2026-01-01T00:00:01+00:00', - 'ttlMs' => null, - 'result' => ['content' => []], - ], $response->result->jsonSerialize()); - } + $this->store->save(self::task()); - public function testUnknownTaskIsInvalidParams(): void - { - foreach ([$this->get('nope'), $this->update('nope'), $this->cancel('nope')] as $request) { - $response = $this->handle($request, $this->session()); + $this->expectException(MissingRequiredClientCapabilityException::class); - $this->assertInstanceOf(Error::class, $response); - $this->assertSame(Error::INVALID_PARAMS, $response->code); - $this->assertSame(['taskId' => 'nope'], $response->data); - } + $this->handle($request, self::session(declared: false)); } - public function testUndeclaredClientIsRefusedWithMissingCapability(): void + /** + * @return iterable + */ + public static function provideUnknownTasks(): iterable { - $this->store->save(new Task('t-1')); - - foreach ([$this->get('t-1'), $this->update('t-1'), $this->cancel('t-1')] as $request) { - $response = $this->handle($request, $this->session(declared: false)); + $mallory = new AccessToken(claims: ['client_id' => 'app', 'sub' => 'mallory']); - $this->assertInstanceOf(Error::class, $response); - $this->assertSame(Error::MISSING_REQUIRED_CLIENT_CAPABILITY, $response->code); - $this->assertInstanceOf(ClientCapabilities::class, $response->data['requiredCapabilities']); - $this->assertArrayHasKey(TasksExtension::ID, $response->data['requiredCapabilities']->extensions); - } - - $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + yield 'tasks/get, no such id' => [new TasksGetRequest('nope'), null]; + yield 'tasks/cancel, no such id' => [new TasksCancelRequest('nope'), null]; + yield 'tasks/get, someone else\'s task' => [new TasksGetRequest('t-1'), $mallory]; + yield 'tasks/cancel, someone else\'s task' => [new TasksCancelRequest('t-1'), $mallory]; } - public function testCancelIsCooperativeAndIdempotent(): void + #[DataProvider('provideUnknownTasks')] + #[TestDox('an unknown task and someone else\'s task are the same invalid params')] + public function testUnknownTaskIsInvalidParams(Request $request, ?AccessToken $caller): void { - $this->store->save(new Task('t-1')); + $this->store->save(self::task(owner: 'opaque owner of alice')); - $response = $this->handle($this->cancel('t-1'), $this->session()); - $this->assertInstanceOf(Response::class, $response); - $this->assertInstanceOf(EmptyResult::class, $response->result); - $this->assertSame(TaskStatus::Cancelled, $this->store->get('t-1')?->status); + $response = $this->handle($request, self::session(token: $caller)); - // A second cancel, and a cancel of something finished, change nothing. - $this->handle($this->cancel('t-1'), $this->session()); - $this->assertSame(TaskStatus::Cancelled, $this->store->get('t-1')->status); - - $this->store->save((new Task('t-2'))->with(TaskStatus::Completed, result: 'done')); - $this->handle($this->cancel('t-2'), $this->session()); - $this->assertSame(TaskStatus::Completed, $this->store->get('t-2')?->status); + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::INVALID_PARAMS, $response->code); + $this->assertStringContainsString('Unknown task', $response->message); } - public function testUpdateHandsTheAnswersToTheInputHandler(): void + #[TestDox('tasks/get answers with the task itself')] + public function testGetReturnsTheTask(): void { - $ask = new ElicitRequest('Who?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])); - $this->store->save((new Task('t-1'))->with(TaskStatus::InputRequired, inputRequests: ['who' => $ask])); - - $inputHandler = new class implements TaskInputHandlerInterface { - /** @var array */ - public array $received = []; - - public function receive(Task $task, array $inputResponses): Task - { - $this->received = $inputResponses; + $this->store->save(self::task()); - return $task->with(TaskStatus::Completed, result: 'Hello, '.$inputResponses['who']['content']['name']); - } - }; - - $answers = ['who' => ['action' => 'accept', 'content' => ['name' => 'Ada']]]; - $response = $this->handle($this->update('t-1', $answers), $this->session(), $inputHandler); + $response = $this->handle(new TasksGetRequest('t-1'), self::session()); $this->assertInstanceOf(Response::class, $response); - $this->assertInstanceOf(EmptyResult::class, $response->result); - $this->assertSame($answers, $inputHandler->received); - $this->assertSame(TaskStatus::Completed, $this->store->get('t-1')?->status); - $this->assertSame('Hello, Ada', $this->store->get('t-1')->result); + $this->assertInstanceOf(Task::class, $response->result); + $this->assertSame('t-1', $response->result->taskId); } - public function testUpdateWithoutAnInputHandlerResumesTheTask(): void + /** + * @return iterable + */ + public static function provideCancellations(): iterable { - $ask = new ElicitRequest('Who?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])); - $this->store->save((new Task('t-1'))->with(TaskStatus::InputRequired, inputRequests: ['who' => $ask])); - - $this->handle($this->update('t-1', ['who' => ['action' => 'decline']]), $this->session()); - - $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + yield 'working' => [self::task(), TaskStatus::Cancelled]; + yield 'already completed' => [self::task()->with(TaskStatus::Completed, new \DateTimeImmutable(), result: []), TaskStatus::Completed]; + yield 'already cancelled' => [self::task()->with(TaskStatus::Cancelled, new \DateTimeImmutable()), TaskStatus::Cancelled]; } - public function testUpdateOfATaskNotWaitingIsIgnored(): void + #[DataProvider('provideCancellations')] + #[TestDox('tasks/cancel is acknowledged, and a terminal task is left as it is')] + public function testCancel(Task $task, TaskStatus $expected): void { - $this->store->save(new Task('t-1')); + $this->store->save($task); - $response = $this->handle($this->update('t-1', ['stale' => []]), $this->session()); + $response = $this->handle(new TasksCancelRequest('t-1'), self::session()); $this->assertInstanceOf(Response::class, $response); - $this->assertSame(TaskStatus::Working, $this->store->get('t-1')?->status); + $this->assertInstanceOf(EmptyResult::class, $response->result); + $this->assertSame($expected, $this->store->get('t-1')?->status); } /** * @return Response<\Mcp\Schema\JsonRpc\ResultInterface>|Error */ - private function handle(Request $request, SessionInterface $session, ?TaskInputHandlerInterface $inputHandler = null): Response|Error + private function handle(Request $request, SessionInterface $session): Response|Error { - foreach ((new TasksExtension($this->store, $inputHandler))->getRequestHandlers() as $handler) { + foreach ((new TasksExtension(new TaskManager($this->store)))->getRequestHandlers() as $handler) { if ($handler->supports($request)) { - return $handler->handle($request, $session); + return $handler->handle($request->withId(1), $session); } } $this->fail(\sprintf('No handler for "%s".', $request::getMethod())); } - /** - * A session as `initialize` leaves it, with or without the extension declared. - */ - private function session(bool $declared = true): SessionInterface + private static function task(?string $owner = null): Task { - $session = new Session(new InMemorySessionStore()); - $capabilities = new ClientCapabilities(extensions: $declared ? [TasksExtension::ID => new \stdClass()] : null); - $session->set('client_capabilities', $capabilities->jsonSerialize()); - - return $session; - } + $now = new \DateTimeImmutable(); - private function get(string $taskId): TasksGetRequest - { - return TasksGetRequest::fromArray(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tasks/get', 'params' => ['taskId' => $taskId]]); + return new Task('t-1', TaskStatus::Working, $now, $now, owner: $owner); } - /** - * @param array $inputResponses - */ - private function update(string $taskId, array $inputResponses = []): TasksUpdateRequest + private static function session(bool $declared = true, ProtocolVersion $version = ProtocolVersion::V2026_07_28, ?AccessToken $token = null): SessionInterface { - return TasksUpdateRequest::fromArray(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tasks/update', 'params' => ['taskId' => $taskId, 'inputResponses' => $inputResponses]]); - } + $session = new Session(new InMemorySessionStore()); + $session->set('client_capabilities', (new ClientCapabilities(extensions: $declared ? [TasksExtension::ID => new \stdClass()] : null))->jsonSerialize()); + $session->set('protocol_version', $version->value); + $session->set(AccessToken::class, $token); - private function cancel(string $taskId): TasksCancelRequest - { - return TasksCancelRequest::fromArray(['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tasks/cancel', 'params' => ['taskId' => $taskId]]); + return $session; } }