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
7 changes: 2 additions & 5 deletions conformance/expected_failures.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
server:
# SEP-2663 (io.modelcontextprotocol/tasks): the server does not implement the tasks extension.
# SEP-2663 (io.modelcontextprotocol/tasks): the server serves the core of the tasks extension only. These scenarios
# also need `tasks/update` with the `input_required` status, or the `Mcp-Name` header of the task methods.
# `tasks-status-notifications` is intentionally absent: the referee runs no check in it, and a baseline entry
# for a scenario with no failing check is flagged stale.
- tasks-lifecycle
- tasks-capability-negotiation
- tasks-wire-fields
- tasks-request-state-removal
- tasks-mrtr-input
- tasks-request-headers
- tasks-dispatch-and-envelope
- tasks-required-task-error
- tasks-mrtr-composition
client:
# Unimplemented authorization extensions.
Expand Down
67 changes: 67 additions & 0 deletions conformance/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,57 @@ def call(server_context:, **_args)
end
end

# SEP-2663 Tasks fixtures: the tools the referee's `tasks-*` scenarios call. Which of them become tasks
# is decided by `Server::TASK_AUGMENTATION`, not by the tools.
class Greet < MCP::Tool
tool_name "greet"
description "A tool that greets by name and never becomes a task (SEP-2663)"
input_schema(properties: { name: { type: "string" } }, required: ["name"])

class << self
def call(name:, **_args)
MCP::Tool::Response.new([MCP::Content::Text.new("Hello, #{name}!").to_h])
end
end
end

class SlowCompute < MCP::Tool
tool_name "slow_compute"
description "A tool that runs as a task and sleeps for the given number of seconds (SEP-2663)"
input_schema(properties: { seconds: { type: "number" }, label: { type: "string" } })

class << self
def call(server_context:, seconds: 0, label: nil, **_args)
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds.to_f
sleep(0.05) until server_context.cancelled? || Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline

MCP::Tool::Response.new([MCP::Content::Text.new("slow_compute #{label} finished after #{seconds}s").to_h])
end
end
end

class FailingJob < MCP::Tool
tool_name "failing_job"
description "A tool that requires a task and completes with a tool execution error (SEP-2663)"

class << self
def call(**_args)
MCP::Tool::Response.new([MCP::Content::Text.new("failing_job failed as designed").to_h], error: true)
end
end
end

class ProtocolErrorJob < MCP::Tool
tool_name "protocol_error_job"
description "A tool that runs as a task and fails it with a protocol error (SEP-2663)"

class << self
def call(**_args)
raise "protocol_error_job raised as designed"
end
end
end

class TestTriggerPromptChange < MCP::Tool
tool_name "test_trigger_prompt_change"
description "A diagnostic tool that broadcasts notifications/prompts/list_changed to listen streams (SEP-2575)"
Expand Down Expand Up @@ -862,6 +913,17 @@ def template(_args, server_context: nil)
class Server
DEFAULT_PORT = 9292

# Which `tools/call` requests of the SEP-2663 fixtures become tasks. `failing_job` requires one, so a client
# that did not declare the extension is refused.
TASK_AUGMENTATION = lambda do |request|
case request[:name]
when "slow_compute", "protocol_error_job"
true
when "failing_job"
:required
end
end

class DnsRebindingProtection
LOCALHOST_PATTERNS = /\A(localhost|127\.0\.0\.1|\[::1\]|::1)(:\d+)?\z/i.freeze

Expand Down Expand Up @@ -968,6 +1030,10 @@ def build_server
Tools::TestLoggingTool,
Tools::TestTriggerToolChange,
Tools::TestTriggerPromptChange,
Tools::Greet,
Tools::SlowCompute,
Tools::FailingJob,
Tools::ProtocolErrorJob,
],
prompts: [
Prompts::TestSimplePrompt,
Expand All @@ -983,6 +1049,7 @@ def build_server
# within one server process, and sealing keeps the fixture's `requestState` values
# tamper-evident without any tool-level verification code.
request_state_security: MCP::Server::RequestStateSecurity.new(key: SecureRandom.bytes(32)),
task_augmentation: TASK_AUGMENTATION,
capabilities: {
tools: { listChanged: true },
prompts: { listChanged: true },
Expand Down
1 change: 1 addition & 0 deletions docs/_extensions/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ The extensions this SDK ships support for:

- [MCP Apps](/extensions/mcp-apps/) (SEP-1865) - interactive HTML user interfaces rendered by the host for tool results
- [Skills](/extensions/skills/) (SEP-2640) - Agent Skills served over MCP resources, with digest-verified reads on the client
- [Tasks](/extensions/tasks/) (SEP-2663) - long-running tool calls answered with a task that the client polls
165 changes: 165 additions & 0 deletions docs/_extensions/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
---
layout: default
title: Tasks
nav_order: 5
---

# Tasks

The SDK implements the [MCP Tasks extension](https://github.com/modelcontextprotocol/ext-tasks) (`io.modelcontextprotocol/tasks`, SEP-2663),
which lets a server answer a `tools/call` request with a task handle instead of a final result.
The client then polls the task until it ends.
The [Tasks overview](https://modelcontextprotocol.io/extensions/tasks/overview) of the specification describes the protocol.

{: .important }
> The extension is Beta and may change with its specification, and so may this API.
> It exists on the 2026-07-28 lifecycle only, and it replaces the experimental tasks of the 2025-11-25 specification,
> which were removed from the core protocol and are not wire-compatible.

A client opts in by declaring the extension in the capabilities of each request.
The server then decides per request whether to answer with a `CreateTaskResult` (`resultType: "task"`);
there is no `task` request parameter and no negotiation per tool.

With the SDK's client, `call_tool` returns the task, `get_task` reads its status and its result once it has ended,
and `cancel_task` stops it.
`wait_task` does the polling.

## Serving tasks

Enable the extension by passing `task_augmentation:`, a callable that decides whether a `tools/call` becomes a task:

```ruby
server = MCP::Server.new(
name: "my_server",
tools: [SlowTool],
# A truthy value creates a task. `:required` also refuses, with error -32021,
# a client that did not declare the extension.
task_augmentation: ->(request) { request[:name] == "slow_tool" },
)
```

This registers `tasks/get` and `tasks/cancel`, and declares the extension in the server's capabilities.
A request from a client that did not declare the extension runs synchronously, unless the callable answered `:required`.

These options tune the feature:

- `task_store:` keeps a record of each task where the other processes of the server can read it. Without one, a task is known only to the process that created it. See [Running several processes](#running-several-processes).
- `task_executor:` runs the work. The default, `MCP::Server::TaskExecutor::Thread`, uses at most 16 threads (`max_threads:`) and makes further work wait its turn; a tool that never returns keeps its thread. `MCP::Server::TaskExecutor::Synchronous` runs the work inline, for tests.
- `task_ttl_ms:` is how long a task is kept, counted from its creation (5 minutes by default). After that it can no longer be read, and if it is still running it is asked to stop the next time a task is looked up or created. `nil` keeps every task until the process ends, so set `max_tasks:` to `nil` as well or the store fills up for good.
- `task_poll_interval_ms:` is the polling interval suggested to clients (5 seconds by default).
- `max_tasks:` bounds the tasks kept at once in this process, finished ones included, and the work that is scheduled and has not ended (1000 by default; `nil` for no bound). It is one bound for all clients. While it is reached, a request runs synchronously instead, and one that requires a task is refused.

A tool reaches its task through `server_context.task`, to publish a status message, and sees a cancellation through `server_context.cancelled?`:

```ruby
class SlowTool < MCP::Tool
def self.call(server_context:)
server_context.task&.update_status_message("crunching")
return MCP::Tool::Response.new([{ type: "text", text: "stopped" }]) if server_context.cancelled?

MCP::Tool::Response.new([{ type: "text", text: "done" }])
end
end
```

Cancellation is cooperative: `tasks/cancel` marks a task that has not ended `cancelled` at once, the tool is not interrupted,
and whatever it returns afterwards is discarded.
Progress and log notifications are not delivered from a tool that runs as a task.

A tool result with `isError: true` is a `completed` task.
A task is `failed` when the tool raises, and its `error` is the JSON-RPC error a synchronous call would have answered:
that of an `MCP::Server::RequestHandlerError` the tool raised,
and an internal error that names the tool and nothing else for any other exception, which goes to the exception reporter.

## Running several processes

A task lives in the process that created it, which is also the one that runs its tool.
A server that runs as several processes, such as Puma with workers or several instances behind a load balancer,
answers "Task not found" from every other process unless the processes share a task store:

```ruby
class RedisTaskStore
def initialize(redis)
@redis = redis
end

def write(task_id, record, expires_in:)
@redis.set("mcp:task:#{task_id}", record, px: (expires_in * 1000).ceil)
end

def read(task_id)
@redis.get("mcp:task:#{task_id}")
end

def delete(task_id)
@redis.del("mcp:task:#{task_id}")
end
end

server = MCP::Server.new(
name: "my_server",
tools: [SlowTool],
task_augmentation: ->(_request) { true },
task_store: RedisTaskStore.new(Redis.new),
)
```

The server writes a record of each task to the store before it answers the request that created the task, and again after each change.
A record is a String whose format belongs to the SDK, and `expires_in` is the number of seconds the task has left.
The store decides nothing: the server checks the owner and the retention of a task on the record it reads.
No store is bundled.

With a task store, any process answers `tasks/get`. The work itself does not move:

- `tasks/cancel` stops a task only in the process that runs it. Any other process acknowledges the request and changes nothing, which the specification allows: a cancellation is a request.
- The record of a task whose process has stopped keeps its last status until the retention of the task ends, so a task store needs a `task_ttl_ms:`.

{: .important }
> A task store holds the results of the tools of every client, and needs the same protection as the server itself:
> whoever can write to it can change what any client reads.

## Who may access a task

A task belongs to the principal that created it:
the issuer, subject and client of the token that authenticated the `tools/call`, as `server_context.auth_info` reports them.
`tasks/get` and `tasks/cancel` answer "Task not found" to anyone else, the same answer as for an id that does not exist.

A token that names neither a subject nor a client, or names them as empty strings, gets no task,
since its tasks could not be told apart from those of any other such token:
its requests run synchronously, and one that requires a task is refused.
A custom token verifier makes tasks available by setting `subject:` or `client_id:` on the `MCP::Server::OAuth::AccessToken` it returns.

{: .important }
> A server that verifies no token has no principal to bind a task to.
> There the task id, a random UUID, is all a caller needs, so it must be kept as secret as the result it leads to.

The tool runs with the authorization of the request that created the task. If that token has expired by the time the tool starts, the task fails instead.
Access is decided by the principal alone: the scopes a tool requires are checked when the tool runs, not on the task methods.

## Using tasks from the client

Declare the extension when connecting, then either let `call_tool` wait for the task or drive it yourself:

```ruby
client.connect(mode: :modern, capabilities: MCP::Tasks.capability)

# Polls `tasks/get` until the task ends and returns the tool result.
response = client.call_tool(name: "slow_tool", wait_for_task: true)

# Or take the `CreateTaskResult` and drive the task.
response = client.call_tool(name: "slow_tool")
task_id = response.dig("result", "taskId")
task = client.wait_task(task_id: task_id, timeout: 60)
task.dig("result", "content")
```

`get_task` and `cancel_task` send the two task methods.
`wait_task` waits between polls for the interval the server suggests, and for at least 0.1 seconds unless `timeout:` ends sooner.
It raises `MCP::Client::TaskFailedError`, `MCP::Client::TaskCancelledError`,
or `MCP::Client::TaskTimeoutError` once `timeout:` seconds have passed, which it checks between polls.


## Not implemented yet

- `tasks/update` and the `input_required` status. A tool that returns an `input_required` result while it runs as a task fails the task.
- `notifications/tasks`. A client learns of a status change by polling `tasks/get`.
1 change: 1 addition & 0 deletions lib/mcp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module MCP
autoload :ServerContext, "mcp/server_context"
autoload :ServerSession, "mcp/server_session"
autoload :Skill, "mcp/skill"
autoload :Tasks, "mcp/tasks"
autoload :Tool, "mcp/tool"
autoload :TraceContext, "mcp/trace_context"

Expand Down
Loading