Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
------
Expand Down
108 changes: 108 additions & 0 deletions docs/advanced/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
28 changes: 17 additions & 11 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -409,15 +406,24 @@ public function sendRootsListChanged(): void
*
* @return Response<mixed>
*
* @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);
Expand Down
66 changes: 66 additions & 0 deletions src/Client/Task/TaskClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

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\Result\CallToolResult;

/**
* The client side of the Tasks extension (SEP-2663), on top of a connected
* {@see Client} that declared it.
*
* @experimental
*
* @author Christopher Hertel <mail@christopher-hertel.de>
*/
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<string, mixed> $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));
}
}
3 changes: 3 additions & 0 deletions src/Schema/Enum/ResultType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
64 changes: 64 additions & 0 deletions src/Schema/Extension/Tasks/CreateTaskResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mcp\Schema\Extension\Tasks;

use Mcp\Schema\Enum\ResultType;
use Mcp\Schema\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\ResultInterface;

/**
* 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.
*
* @author Christopher Hertel <mail@christopher-hertel.de>
*/
final class CreateTaskResult implements ResultInterface
{
public function __construct(
public readonly Task $task,
) {
}

/**
* @param array<string, mixed> $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<string, mixed> $data
*/
public static function describes(array $data): bool
{
return ResultType::Task->value === ($data['resultType'] ?? null);
}

/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
return ['resultType' => ResultType::Task->value, ...$this->task->toEnvelope()];
}
}
Loading
Loading