diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..d33f73609 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`), 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 989926d76..a301c137a 100644 --- a/docs/advanced/extensions.md +++ b/docs/advanced/extensions.md @@ -91,6 +91,113 @@ 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). +## Tasks (`io.modelcontextprotocol/tasks`) + +!!! 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\Server; +use Mcp\Server\Task\InMemoryTaskStore; +use Mcp\Server\Task\TaskManager; +use Mcp\Server\Task\TasksExtension; + +$tasks = new TaskManager(new InMemoryTaskStore()); + +$server = Server::builder() + ->enableExtension(new TasksExtension($tasks)) + ->build(); +``` + +`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 call. A tool takes the `RequestContext` and +asks the manager: + +```php +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Server\RequestContext; + +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($context, ttlMs: 600_000, pollIntervalMs: 1000); + $queue->push($created->task->taskId); + + return $created; +} +``` + +`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. + +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\Extension\Tasks\TaskStatus; + +$tasks->transition($taskId, TaskStatus::Completed, result: $callToolResult->jsonSerialize()); +``` + +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, then handles either result shape through `TaskClient`. The +plain `Client::callTool()` throws when the server answers with a task. + +```php +use Mcp\Client\Client; +use Mcp\Client\Task\TaskClient; +use Mcp\Schema\Extension\Tasks\CreateTaskResult; +use Mcp\Schema\Result\CallToolResult; +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 +} +``` + +`cancel($taskId)` asks the server to stop; cancellation is cooperative and the task may still +finish. + ## MCP Apps (`io.modelcontextprotocol/ui`) The [MCP Apps extension][ext-apps] lets servers expose interactive HTML UIs as @@ -206,3 +313,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..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); diff --git a/src/Client/Task/TaskClient.php b/src/Client/Task/TaskClient.php new file mode 100644 index 000000000..808192163 --- /dev/null +++ b/src/Client/Task/TaskClient.php @@ -0,0 +1,66 @@ + + */ +final class TaskClient +{ + public function __construct( + private readonly Client $client, + ) { + } + + /** + * 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->sendRequest(new CallToolRequest($name, $arguments), $onProgress)->result; + + return CreateTaskResult::describes($result) ? CreateTaskResult::fromArray($result) : CallToolResult::fromArray($result); + } + + /** + * 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 Task::fromArray($this->client->sendRequest(new TasksGetRequest($taskId))->result); + } + + /** + * Asks the server to cancel a task (`tasks/cancel`). Cooperative: the task may still finish. + */ + public function cancel(string $taskId): void + { + $this->client->sendRequest(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/Extension/Tasks/CreateTaskResult.php b/src/Schema/Extension/Tasks/CreateTaskResult.php new file mode 100644 index 000000000..2cc9d8cd3 --- /dev/null +++ b/src/Schema/Extension/Tasks/CreateTaskResult.php @@ -0,0 +1,64 @@ + + */ +final 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 (!self::describes($data)) { + 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 + { + 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/Extension/Tasks/TaskStatus.php b/src/Schema/Extension/Tasks/TaskStatus.php new file mode 100644 index 000000000..c536c3ec0 --- /dev/null +++ b/src/Schema/Extension/Tasks/TaskStatus.php @@ -0,0 +1,49 @@ + + */ +enum TaskStatus: string +{ + /** The work is in progress. */ + case Working = 'working'; + + /** 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 => false, + }; + } +} diff --git a/src/Schema/Extension/Tasks/TasksCancelRequest.php b/src/Schema/Extension/Tasks/TasksCancelRequest.php new file mode 100644 index 000000000..bd6325cc4 --- /dev/null +++ b/src/Schema/Extension/Tasks/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/Extension/Tasks/TasksGetRequest.php b/src/Schema/Extension/Tasks/TasksGetRequest.php new file mode 100644 index 000000000..a62de1bc7 --- /dev/null +++ b/src/Schema/Extension/Tasks/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/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/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/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/InMemoryTaskStore.php b/src/Server/Task/InMemoryTaskStore.php new file mode 100644 index 000000000..47e6c77d3 --- /dev/null +++ b/src/Server/Task/InMemoryTaskStore.php @@ -0,0 +1,75 @@ + + */ +final class InMemoryTaskStore implements TaskStoreInterface +{ + /** @var array */ + private array $tasks = []; + + /** + * @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, + 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)); + } + } + + public function save(Task $task): void + { + // 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; + + if (\count($this->tasks) > $this->limit) { + unset($this->tasks[array_key_first($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; + } +} diff --git a/src/Server/Task/Psr16TaskStore.php b/src/Server/Task/Psr16TaskStore.php new file mode 100644 index 000000000..fb2a8a386 --- /dev/null +++ b/src/Server/Task/Psr16TaskStore.php @@ -0,0 +1,83 @@ + + */ +final class Psr16TaskStore implements TaskStoreInterface +{ + /** + * @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 LoggerInterface $logger = new NullLogger(), + private readonly ClockInterface $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 ? null : max(1, (int) ceil($task->ttlMs / 1000)); + + // 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 + { + $raw = $this->cache->get($this->prefix.$taskId); + + if (!\is_string($raw)) { + return null; + } + + try { + $data = json_decode($raw, true, flags: \JSON_THROW_ON_ERROR); + $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 whole seconds, so the task has the last word on whether it is readable. + return $task->isReadable($this->clock->now()) ? $task : null; + } +} 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 new file mode 100644 index 000000000..6ee50cdac --- /dev/null +++ b/src/Server/Task/TaskStoreInterface.php @@ -0,0 +1,42 @@ + + */ +interface TaskStoreInterface +{ + /** + * 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; + + /** + * 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; +} diff --git a/src/Server/Task/TasksExtension.php b/src/Server/Task/TasksExtension.php new file mode 100644 index 000000000..9e69bfe8b --- /dev/null +++ b/src/Server/Task/TasksExtension.php @@ -0,0 +1,65 @@ + + */ +final class TasksExtension implements ServerExtensionInterface +{ + public const ID = 'io.modelcontextprotocol/tasks'; + + public function __construct( + private readonly ?TaskManager $tasks = null, + ) { + } + + public function getId(): ExtensionIdentifier + { + return new ExtensionIdentifier(self::ID); + } + + public function getCapabilities(): array + { + return []; + } + + public function getMessages(): array + { + return [ + TasksGetRequest::class, + TasksCancelRequest::class, + ]; + } + + /** + * @throws LogicException when enabled on a server without a task manager + */ + public function getRequestHandlers(): iterable + { + 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 new file mode 100644 index 000000000..594e657e7 --- /dev/null +++ b/tests/Integration/Fixture/tasks.php @@ -0,0 +1,112 @@ +> what each task becomes on its next reads */ + private array $plans = []; + + public function __construct(private readonly TaskStoreInterface $inner) + { + } + + /** + * @param list $steps + */ + public function plan(string $taskId, array $steps): void + { + $this->plans[$taskId] = $steps; + } + + 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])($task); + $this->inner->save($next); + + return $next; + } +}; + +$tasks = new TaskManager($store); + +Server::builder() + ->setServerInfo('integration-server', '1.0.0') + ->enableExtension(new TasksExtension($tasks)) + ->addTool( + static function (RequestContext $context) use ($tasks, $store): CreateTaskResult|string { + if (!$tasks->isSupported($context)) { + return 'sync'; + } + + $created = $tasks->create($context, pollIntervalMs: 10, statusMessage: 'queued'); + $store->plan($created->task->taskId, [ + 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; + }, + name: 'long_job', + description: 'Runs as a task when the client can poll, synchronously otherwise.', + ) + ->addTool( + 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 (RequestContext $context) use ($tasks, $store): CreateTaskResult { + $created = $tasks->create($context, pollIntervalMs: 10); + $store->plan($created->task->taskId, [ + static fn (Task $task): Task => $task->with(TaskStatus::Failed, new DateTimeImmutable(), error: Error::forInternalError('the worker died')), + ]); + + return $created; + }, + name: 'failing_job', + description: 'Fails at the protocol level.', + ) + ->build() + ->run(new StdioTransport()); diff --git a/tests/Integration/TasksTest.php b/tests/Integration/TasksTest.php new file mode 100644 index 000000000..699152eb9 --- /dev/null +++ b/tests/Integration/TasksTest.php @@ -0,0 +1,182 @@ +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); + $this->assertSame('halfway', $polled->statusMessage); + + $done = $this->settle($client, $created->task->taskId); + $this->assertSame(TaskStatus::Completed, $done->status); + $this->assertNotNull($done->result); + + $result = CallToolResult::fromArray($done->result); + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('done', $result->content[0]->text); + } + + #[TestDox('the plain client refuses a task answer and points to TaskClient')] + public function testPlainClientRefusesATask(): void + { + $client = $this->connect('tasks', $this->declaring()); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(TaskClient::class.'::callTool()'); + + $client->callTool('long_job'); + } + + #[TestDox('a client that did not declare the extension gets the synchronous answer')] + public function testUndeclaredClientIsServedSynchronously(): void + { + $result = $this->connect('tasks', $this->clientBuilder()->setProtocolVersion(ProtocolVersion::V2026_07_28))->callTool('long_job'); + + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('sync', $result->content[0]->text); + } + + #[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', $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2025_11_25) + ->enableExtension(new TasksExtension()))); + + $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 client that did not declare the extension is refused a task and the tasks/* methods with -32021')] + public function testUndeclaredClientIsRefused(): void + { + $client = new TaskClient($this->connect('tasks', $this->clientBuilder()->setProtocolVersion(ProtocolVersion::V2026_07_28))); + + $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')] + 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(); + + $this->assertErrorCode(Error::INVALID_PARAMS, static fn () => $client->get('no-such-task')); + } + + private function declaring(): ClientBuilder + { + return $this->clientBuilder() + ->setProtocolVersion(ProtocolVersion::V2026_07_28) + ->enableExtension(new TasksExtension()); + } + + private function connectDeclaring(): TaskClient + { + $client = $this->connect('tasks', $this->declaring()); + $this->assertSame(ProtocolVersion::V2026_07_28, $client->getProtocolVersion()); + + return new TaskClient($client); + } + + private function assertErrorCode(int $code, callable $call): void + { + try { + $call(); + $this->fail(\sprintf('Expected error %d.', $code)); + } catch (RequestException $e) { + $this->assertSame($code, $e->getError()?->code); + } + } + + /** + * 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/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/Handler/Request/CallToolHandlerTest.php b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php index e19ac9339..bf63b0fe8 100644 --- a/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php +++ b/tests/Unit/Server/Handler/Request/CallToolHandlerTest.php @@ -17,6 +17,7 @@ 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; @@ -104,6 +105,24 @@ 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 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 new file mode 100644 index 000000000..d063d1d5a --- /dev/null +++ b/tests/Unit/Server/Task/TaskStoreTest.php @@ -0,0 +1,144 @@ + + */ + public static function stores(): iterable + { + yield 'in memory' => [new InMemoryTaskStore()]; + yield 'psr-16' => [new Psr16TaskStore(new Psr16Cache(new ArrayAdapter()))]; + } + + /** + * @return iterable + */ + public static function provideRoundTrips(): iterable + { + $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]; + } + } + } + + #[DataProvider('provideRoundTrips')] + #[TestDox('a task round-trips through the store, owner included')] + public function testRoundTrip(TaskStoreInterface $store, Task $task): void + { + $store->save($task); + + $read = $store->get($task->taskId); + + $this->assertNotNull($read); + $this->assertEquals($task->jsonSerialize(), $read->jsonSerialize()); + $this->assertSame($task->owner, $read->owner); + } + + #[DataProvider('stores')] + public function testUnknownIdIsNull(TaskStoreInterface $store): void + { + $this->assertNull($store->get('nope')); + } + + #[DataProvider('stores')] + #[TestDox('a task past its TTL reads as absent')] + public function testTtlExpiry(TaskStoreInterface $store): void + { + $created = new \DateTimeImmutable('-2 seconds'); + $store->save(new Task('t-6', TaskStatus::Working, $created, $created, 1000)); + + $this->assertNull($store->get('t-6')); + } + + #[TestDox('the PSR-16 store refuses to report a task created that the cache did not keep')] + public function testPsr16SaveFailureThrows(): void + { + $cache = $this->createMock(CacheInterface::class); + $cache->method('set')->willReturn(false); + $now = new \DateTimeImmutable(); + + $this->expectException(RuntimeException::class); + + (new Psr16TaskStore($cache))->save(new Task('t-7', TaskStatus::Working, $now, $now)); + } + + #[TestDox('the PSR-16 store keeps a task without a TTL for as long as the cache does')] + public function testPsr16UnlimitedTtl(): void + { + $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(); + + (new Psr16TaskStore($cache))->save(new Task('t-8', TaskStatus::Working, $now, $now)); + } + + #[TestDox('an unreadable stored payload reads as absent rather than throwing')] + public function testCorruptPayloadIsDropped(): void + { + $cache = new Psr16Cache(new ArrayAdapter()); + $cache->set('mcp.tasks.t-9', 'not json at all'); + + $this->assertNull((new Psr16TaskStore($cache))->get('t-9')); + } + + #[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', 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')); + $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); + } +} diff --git a/tests/Unit/Server/Task/TasksExtensionTest.php b/tests/Unit/Server/Task/TasksExtensionTest.php new file mode 100644 index 000000000..d7b01c9ca --- /dev/null +++ b/tests/Unit/Server/Task/TasksExtensionTest.php @@ -0,0 +1,186 @@ +store = new InMemoryTaskStore(); + } + + public function testDeclaresItselfWithoutSettings(): void + { + $extension = new TasksExtension(); + + $this->assertSame('io.modelcontextprotocol/tasks', (string) $extension->getId()); + $this->assertSame([], $extension->getCapabilities()); + $this->assertSame([TasksGetRequest::class, TasksCancelRequest::class], $extension->getMessages()); + } + + #[TestDox('serving tasks/* needs a task manager')] + public function testServingWithoutAManagerIsRefused(): void + { + $this->expectException(LogicException::class); + + iterator_to_array((new TasksExtension())->getRequestHandlers()); + } + + /** + * @return iterable + */ + public static function provideRequests(): iterable + { + yield 'tasks/get' => [new TasksGetRequest('t-1')]; + yield 'tasks/cancel' => [new TasksCancelRequest('t-1')]; + } + + #[DataProvider('provideRequests')] + #[TestDox('below 2026-07-28 the methods do not exist')] + public function testOlderRevisionIsMethodNotFound(Request $request): void + { + $this->store->save(self::task()); + + $response = $this->handle($request, self::session(version: ProtocolVersion::V2025_11_25)); + + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::METHOD_NOT_FOUND, $response->code); + } + + #[DataProvider('provideRequests')] + #[TestDox('a client that did not declare the extension is refused with -32021')] + public function testUndeclaredClientIsRefused(Request $request): void + { + $this->store->save(self::task()); + + $this->expectException(MissingRequiredClientCapabilityException::class); + + $this->handle($request, self::session(declared: false)); + } + + /** + * @return iterable + */ + public static function provideUnknownTasks(): iterable + { + $mallory = new AccessToken(claims: ['client_id' => 'app', 'sub' => 'mallory']); + + 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]; + } + + #[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(self::task(owner: 'opaque owner of alice')); + + $response = $this->handle($request, self::session(token: $caller)); + + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(Error::INVALID_PARAMS, $response->code); + $this->assertStringContainsString('Unknown task', $response->message); + } + + #[TestDox('tasks/get answers with the task itself')] + public function testGetReturnsTheTask(): void + { + $this->store->save(self::task()); + + $response = $this->handle(new TasksGetRequest('t-1'), self::session()); + + $this->assertInstanceOf(Response::class, $response); + $this->assertInstanceOf(Task::class, $response->result); + $this->assertSame('t-1', $response->result->taskId); + } + + /** + * @return iterable + */ + public static function provideCancellations(): iterable + { + 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]; + } + + #[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($task); + + $response = $this->handle(new TasksCancelRequest('t-1'), self::session()); + + $this->assertInstanceOf(Response::class, $response); + $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): Response|Error + { + foreach ((new TasksExtension(new TaskManager($this->store)))->getRequestHandlers() as $handler) { + if ($handler->supports($request)) { + return $handler->handle($request->withId(1), $session); + } + } + + $this->fail(\sprintf('No handler for "%s".', $request::getMethod())); + } + + private static function task(?string $owner = null): Task + { + $now = new \DateTimeImmutable(); + + return new Task('t-1', TaskStatus::Working, $now, $now, owner: $owner); + } + + private static function session(bool $declared = true, ProtocolVersion $version = ProtocolVersion::V2026_07_28, ?AccessToken $token = null): SessionInterface + { + $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 $session; + } +}