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
4 changes: 3 additions & 1 deletion docs/protocol-versions.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ Also gone: `Mcp-Session-Id`, the HTTP `GET` stream, and SSE resumability (`Last-
A broken response stream loses the request; the client re-issues it with a new id.

This revision also removes `notifications/elicitation/complete` and the `elicitationId` field, and
moves tasks to the `io.modelcontextprotocol/tasks` extension. The SDK implements none of these.
moves tasks to the `io.modelcontextprotocol/tasks` extension. A client can enable it with
`Client::builder()->enableExtension(new TasksExtension())` and use `TaskClient` to poll handle
status, answer input requests and cancel tasks.

Error code `-32002` (resource not found) is retired in favour of `-32602`, and must not be
emitted by a server of this revision. The SDK picks the code from the revision serving the
Expand Down
2 changes: 1 addition & 1 deletion docs/run/protocol-eras.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Plus `Mcp-Method` on every request, and `Mcp-Name` on `tools/call`, `prompts/get
with the body is refused with `-32020`; a missing required `_meta` member with `-32602`; an
unsupported version with `-32022`, carrying the supported set for the client to retry from.

The SDK only checks the `Mcp-Name` header of the `tasks/*` methods. It doesn't implement these methods.
The SDK's `TaskClient` sends the `tasks/*` requests. The server validates their `Mcp-Name` headers.

What a handler can read off all this is
[Talking back to the client](../handlers/client-communication.md#request-metadata).
Expand Down
2 changes: 1 addition & 1 deletion src/Client/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public function setCapabilities(ClientCapabilities $capabilities): self

/**
* Enable one or more MCP protocol extensions, announced to the server under
* `capabilities.extensions` in the initialize request.
* `capabilities.extensions` in modern request metadata or in the initialize request.
*
* @throws InvalidArgumentException if the identifier is not a valid `_meta` prefix
* @throws LogicException if the same extension is enabled more than once
Expand Down
49 changes: 30 additions & 19 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,23 +236,6 @@ public function listTools(?string $cursor = null): ListToolsResult
*/
public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult
{
if ($cancellation?->isCancellationRequested()) {
throw new RequestCancelledException('The client cancelled the request.');
}

if (null !== $timeoutSeconds && (!is_finite($timeoutSeconds) || $timeoutSeconds <= 0)) {
throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.');
}

$catalog = $this->protocol->getToolCatalog();

// A tool the listing showed to be malformed is refused here rather than
// sent: the client cannot produce the headers its annotations demand,
// so the call could only go out misdescribed (SEP-2243).
if ($catalog->isRejected($name)) {
throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $name, $catalog->reasonFor($name)));
}

$request = new CallToolRequest($name, $arguments);

$response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds);
Expand Down Expand Up @@ -403,16 +386,44 @@ public function sendRootsListChanged(): void
}

/**
* Send a request to the server and wait for response.
* Send a core or extension request and return the server response.
*
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*
* @return Response<mixed>
*
* @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException
* @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException|RuntimeException
* @throws RequestCancelledException|Exception\TimeoutException
*/
public function request(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response
{
return $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds);
}

/**
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*
* @return Response<mixed>
*/
private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response
{
if ($cancellation?->isCancellationRequested()) {
throw new RequestCancelledException('The client cancelled the request.');
}

if (null !== $timeoutSeconds && (!is_finite($timeoutSeconds) || $timeoutSeconds <= 0)) {
throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.');
}

if ($request instanceof CallToolRequest) {
$catalog = $this->protocol->getToolCatalog();

// A tool with invalid annotations cannot be sent with the headers it requires (SEP-2243).
if ($catalog->isRejected($request->name)) {
throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $request->name, $catalog->reasonFor($request->name)));
}
}

$transport = $this->transport;
if (null === $transport || !$this->protocol->getState()->isInitialized()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
Expand Down
102 changes: 102 additions & 0 deletions src/Client/Task/TaskClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?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\CancellationTokenInterface;
use Mcp\Client\Client;
use Mcp\Client\Exception\InvalidArgumentException;
use Mcp\Schema\Extension\Tasks\CancelTaskRequest;
use Mcp\Schema\Extension\Tasks\CreateTaskResult;
use Mcp\Schema\Extension\Tasks\GetTaskRequest;
use Mcp\Schema\Extension\Tasks\Task;
use Mcp\Schema\Extension\Tasks\TasksExtension;
use Mcp\Schema\Extension\Tasks\UpdateTaskRequest;
use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Request\GetPromptRequest;
use Mcp\Schema\Request\ReadResourceRequest;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\GetPromptResult;
use Mcp\Schema\Result\ReadResourceResult;

/**
* Client facade for a connection configured with {@see TasksExtension}.
*
* @author OpenAI
*/
final class TaskClient
{
public function __construct(
private readonly Client $client,
) {
}

/**
* @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, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult|CreateTaskResult
{
$result = $this->client->request(new CallToolRequest($name, $arguments), $onProgress, $cancellation, $timeoutSeconds)->result;

return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null)
? CreateTaskResult::fromArray($result)
: CallToolResult::fromArray($result);
}

/**
* @param array<string, string> $arguments
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*/
public function getPrompt(string $name, array $arguments = [], ?callable $onProgress = null): GetPromptResult|CreateTaskResult
{
$result = $this->client->request(new GetPromptRequest($name, $arguments), $onProgress)->result;

return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null)
? CreateTaskResult::fromArray($result)
: GetPromptResult::fromArray($result);
}

/**
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*/
public function readResource(string $uri, ?callable $onProgress = null): ReadResourceResult|CreateTaskResult
{
if ('' === $uri) {
throw new InvalidArgumentException('Resource URI must not be empty.');
}

$result = $this->client->request(new ReadResourceRequest($uri), $onProgress)->result;

return CreateTaskResult::RESULT_TYPE === ($result['resultType'] ?? null)
? CreateTaskResult::fromArray($result)
: ReadResourceResult::fromArray($result);
}

public function get(string $taskId): Task
{
return Task::fromArray($this->client->request(new GetTaskRequest($taskId))->result);
}

/**
* @param array<array-key, array<string, mixed>|ResultInterface> $inputResponses responses keyed by the server's input request IDs
*/
public function update(string $taskId, array $inputResponses): void
{
$this->client->request(new UpdateTaskRequest($taskId, $inputResponses));
}

public function cancel(string $taskId): void
{
$this->client->request(new CancelTaskRequest($taskId));
}
}
48 changes: 48 additions & 0 deletions src/Schema/Extension/Tasks/CancelTaskRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?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\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\Request;

/**
* @author OpenAI
*/
final class CancelTaskRequest 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 (!\is_string($params['taskId'] ?? null)) {
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];
}
}
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\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\ResultInterface;

/**
* The server's initial task snapshot in place of a synchronous result.
*
* @author OpenAI
*/
final class CreateTaskResult implements ResultInterface
{
public const RESULT_TYPE = 'task';

/**
* @param array<string, mixed>|null $meta
*/
public function __construct(
public readonly Task $task,
public readonly ?array $meta = null,
) {
}

/**
* @param array<string, mixed> $data
*/
public static function fromArray(array $data): self
{
if (self::RESULT_TYPE !== ($data['resultType'] ?? null)) {
throw new InvalidArgumentException('Missing or invalid "resultType" in task creation result.');
}

if (isset($data['_meta']) && !\is_array($data['_meta']) && !$data['_meta'] instanceof \stdClass) {
throw new InvalidArgumentException('Invalid "_meta" in task creation result.');
}

return new self(Task::fromArray($data), isset($data['_meta']) ? (array) $data['_meta'] : null);
}

/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
$data = ['resultType' => self::RESULT_TYPE, ...$this->task->jsonSerialize()];

if (null !== $this->meta) {
$data['_meta'] = (object) $this->meta;
}

return $data;
}
}
48 changes: 48 additions & 0 deletions src/Schema/Extension/Tasks/GetTaskRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?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\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\Request;

/**
* @author OpenAI
*/
final class GetTaskRequest 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 (!\is_string($params['taskId'] ?? null)) {
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];
}
}
Loading