diff --git a/conformance/expected_failures.yml b/conformance/expected_failures.yml index 438c8cc5..8b6ee032 100644 --- a/conformance/expected_failures.yml +++ b/conformance/expected_failures.yml @@ -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. diff --git a/conformance/server.rb b/conformance/server.rb index f849d4df..b4dc1e71 100644 --- a/conformance/server.rb +++ b/conformance/server.rb @@ -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)" @@ -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 @@ -968,6 +1030,10 @@ def build_server Tools::TestLoggingTool, Tools::TestTriggerToolChange, Tools::TestTriggerPromptChange, + Tools::Greet, + Tools::SlowCompute, + Tools::FailingJob, + Tools::ProtocolErrorJob, ], prompts: [ Prompts::TestSimplePrompt, @@ -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 }, diff --git a/docs/_extensions/index.md b/docs/_extensions/index.md index 49c9dac8..b237c480 100644 --- a/docs/_extensions/index.md +++ b/docs/_extensions/index.md @@ -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 diff --git a/docs/_extensions/tasks.md b/docs/_extensions/tasks.md new file mode 100644 index 00000000..d9a5f795 --- /dev/null +++ b/docs/_extensions/tasks.md @@ -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`. diff --git a/lib/mcp.rb b/lib/mcp.rb index af3ec3c7..c46b0a69 100644 --- a/lib/mcp.rb +++ b/lib/mcp.rb @@ -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" diff --git a/lib/mcp/client.rb b/lib/mcp/client.rb index 4deeefa4..f522b85f 100644 --- a/lib/mcp/client.rb +++ b/lib/mcp/client.rb @@ -10,6 +10,7 @@ require_relative "client/skills" require_relative "client/tool" require_relative "result_type" +require_relative "tasks" module MCP class Client @@ -99,6 +100,42 @@ def initialize(message, request, original_error: nil) end end + # Base class for task lifecycle errors of the SEP-2663 tasks extension. + # `task` is the last `GetTaskResult` observed (string keys). + class TaskError < StandardError + attr_reader :task + + def initialize(message, task:) + super(message) + @task = task + end + end + + # The task reached `failed`: the underlying request raised a JSON-RPC error, + # available as `error` (`{ "code" => ..., "message" => ... }`). A tool result + # with `isError: true` is NOT a failure - it surfaces as a `completed` task. + class TaskFailedError < TaskError + def error + task["error"] if task.is_a?(Hash) + end + end + + # The task reached `cancelled` (its own `tasks/cancel` or a server decision). + class TaskCancelledError < TaskError; end + + # `wait_task` gave up after its `timeout:` with the task still not in a terminal status. + # The task itself is untouched; `task` is the last state polled. + class TaskTimeoutError < TaskError; end + + # The task reached `input_required`: the server needs `inputResponses` via + # `tasks/update` before the task can proceed. `input_requests` carries + # the outstanding server-to-client requests keyed by request id. + class TaskInputRequiredError < TaskError + def input_requests + (task.is_a?(Hash) && task["inputRequests"]) || {} + end + end + # The server's `DiscoverResult` (MCP 2026-07-28, SEP-2575): the modern protocol versions it serves, # its capabilities and identity, optional instructions, and the REQUIRED `ttlMs`/`cacheScope` cache hints. DiscoverResult = Struct.new( @@ -123,6 +160,14 @@ def initialize(message, request, original_error: nil) # The Skills extension methods (SEP-2640): `list_skills`, `get_skill`, `read_skill_resource`, `skills_capability`. include Skills + # Fallback polling interval for `wait_task` when the server supplies no `pollIntervalMs` (SEP-2663 tasks extension), + # matching the Python SDK default. + DEFAULT_TASK_POLL_INTERVAL_SECONDS = 1.0 + + # The shortest wait between two polls of `wait_task`, whatever `pollIntervalMs` the server suggests: + # a server that suggests zero must not turn the wait into a busy loop. + MIN_TASK_POLL_INTERVAL_SECONDS = 0.1 + # Initializes a new MCP::Client instance. # # @param transport [Object] The transport object to use for communication with the server. @@ -512,7 +557,13 @@ def prompts(cancellation: nil) # @param input_responses [Hash, nil] SEP-2322 answers to a previous `input_required` result's `inputRequests`, # keyed identically (manual retry legs). # @param request_state [String, nil] The opaque `requestState` echoed back byte-exactly. - def call_tool(name: nil, tool: nil, arguments: nil, progress_token: nil, meta: nil, cancellation: nil, input_responses: nil, request_state: nil) + # @param wait_for_task [Boolean] SEP-2663 tasks extension: when the server elects to return + # a `CreateTaskResult` (`resultType: "task"`), poll `tasks/get` until + # the task completes and return a response whose `"result"` is the final tool result, + # as if the call had been synchronous. The default `false` returns the `CreateTaskResult` response for + # manual driving via `get_task`/`wait_task`/ `cancel_task`. A client that declares + # the tasks extension capability MUST be prepared for either result shape on any request. + def call_tool(name: nil, tool: nil, arguments: nil, progress_token: nil, meta: nil, cancellation: nil, input_responses: nil, request_state: nil, wait_for_task: false) tool_name = name || tool&.name raise ArgumentError, "Either `name:` or `tool:` must be provided." unless tool_name @@ -526,7 +577,14 @@ def call_tool(name: nil, tool: nil, arguments: nil, progress_token: nil, meta: n params[:inputResponses] = input_responses if input_responses params[:requestState] = request_state if request_state - drive_input_required(method: "tools/call", params: params, cancellation: cancellation) + response = drive_input_required(method: "tools/call", params: params, cancellation: cancellation) + return response unless wait_for_task + + result = response.is_a?(Hash) ? response["result"] : nil + return response unless Tasks.task_result?(result) + + task = wait_task(task_id: result["taskId"], meta: meta, cancellation: cancellation) + response.merge("result" => task["result"]) end # Reads a resource from the server by URI and returns the contents. @@ -681,6 +739,95 @@ def ping(meta: nil, cancellation: nil) result end + # Fetches the current state of a task (SEP-2663 tasks extension) as a `GetTaskResult` hash: + # the `Task` fields plus, depending on `status`, the inlined `result` (completed), `error` (failed), + # or `inputRequests` (input_required). + # + # The tasks extension exists only on the modern (2026-07-28) lifecycle and must be declared in + # the client capabilities, e.g. `connect(mode: :modern, capabilities: MCP::Tasks.capability)`. + # + # @param task_id [String] The `taskId` from a `CreateTaskResult`. + # @param meta [Hash, nil] Additional `_meta` entries to send with the request. + # @param cancellation [MCP::Cancellation, nil] Optional cancellation token. + # @return [Hash] The `GetTaskResult` (string keys). + # @raise [ServerError] If the server returns a JSON-RPC error (`-32602` for an unknown or expired task). + def get_task(task_id:, meta: nil, cancellation: nil) + response = request( + method: Methods::TASKS_GET, + params: { taskId: task_id }, + meta: meta, + cancellation: cancellation, + ) + result = response.is_a?(Hash) ? response["result"] : nil + raise ValidationError, "Response validation failed: missing or invalid `result`" unless result.is_a?(Hash) + + result + end + + # Signals cooperative cancellation of a task (SEP-2663). The acknowledgement is empty and + # eventually consistent: the task may still finish with a terminal status other than `cancelled`, + # and no further polling is needed after sending this. + # + # @param task_id [String] The `taskId` from a `CreateTaskResult`. + # @return [Hash] The empty acknowledgement result. + def cancel_task(task_id:, meta: nil, cancellation: nil) + response = request( + method: Methods::TASKS_CANCEL, + params: { taskId: task_id }, + meta: meta, + cancellation: cancellation, + ) + + result_hash(response) + end + + # Polls `tasks/get` until the task reaches a terminal status, honoring + # the server-provided `pollIntervalMs` between polls (SEP-2663). + # + # @param task_id [String] The `taskId` from a `CreateTaskResult`. + # @param timeout [Numeric, nil] Seconds to keep polling for; `nil` (the default) polls until the task ends. + # @return [Hash] The `completed` task's `GetTaskResult`, with the final + # result of the underlying request inlined under `"result"`. + # @raise [TaskFailedError] When the task reaches `failed`. + # @raise [TaskCancelledError] When the task reaches `cancelled`. + # @raise [TaskTimeoutError] When `timeout` seconds pass first. + # @raise [TaskInputRequiredError] When the task reaches `input_required`; + # this server needs `tasks/update` responses the SDK does not drive yet. + def wait_task(task_id:, meta: nil, cancellation: nil, timeout: nil) + deadline = timeout && Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout + loop do + task = get_task(task_id: task_id, meta: meta, cancellation: cancellation) + + case task["status"] + when "completed" + return task + when "failed" + raise TaskFailedError.new("Task #{task_id} failed: #{task.dig("error", "message")}", task: task) + when "cancelled" + raise TaskCancelledError.new("Task #{task_id} was cancelled", task: task) + when "input_required" + raise TaskInputRequiredError.new( + "Task #{task_id} requires input via `tasks/update`, which this client does not drive yet", + task: task, + ) + end + + interval_ms = task["pollIntervalMs"] + interval = interval_ms.is_a?(Numeric) ? interval_ms / 1000.0 : DEFAULT_TASK_POLL_INTERVAL_SECONDS + interval = [interval, MIN_TASK_POLL_INTERVAL_SECONDS].max + + if deadline + remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + raise TaskTimeoutError.new("Task #{task_id} did not finish within #{timeout} seconds", task: task) if remaining <= 0 + + interval = [interval, remaining].min + end + + # A cancellation ends the wait, and the next poll then raises before anything is sent. + sleep_with_cancellation(interval, cancellation) + end + end + private def result_hash(response) diff --git a/lib/mcp/methods.rb b/lib/mcp/methods.rb index 12a62e89..e6e7feae 100644 --- a/lib/mcp/methods.rb +++ b/lib/mcp/methods.rb @@ -44,6 +44,13 @@ module Methods RESOURCES_UNSUBSCRIBE, ].freeze + # Tasks extension methods (SEP-2663, extension `io.modelcontextprotocol/tasks`). + # Servers not supporting the extension answer `-32601`; the removed experimental methods of + # the 2025-11-25 spec (`tasks/result`, `tasks/list`) get the same answer by never being registered. + TASKS_GET = "tasks/get" + TASKS_UPDATE = "tasks/update" + TASKS_CANCEL = "tasks/cancel" + ROOTS_LIST = "roots/list" SAMPLING_CREATE_MESSAGE = "sampling/createMessage" ELICITATION_CREATE = "elicitation/create" @@ -110,8 +117,10 @@ def ensure_capability!(method, capabilities) when ELICITATION_CREATE require_capability!(method, capabilities, :elicitation) when INITIALIZE, PING, SERVER_DISCOVER, NOTIFICATIONS_INITIALIZED, NOTIFICATIONS_ROOTS_LIST_CHANGED, - NOTIFICATIONS_PROGRESS, NOTIFICATIONS_CANCELLED, NOTIFICATIONS_ELICITATION_COMPLETE - # No specific capability required. + NOTIFICATIONS_PROGRESS, NOTIFICATIONS_CANCELLED, NOTIFICATIONS_ELICITATION_COMPLETE, + TASKS_GET, TASKS_UPDATE, TASKS_CANCEL + # No specific capability required. The tasks methods (SEP-2663) are gated by handler registration instead: + # a server without task support never registers them, so they answer `-32601` like any unknown method. end end diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 8a20d125..80dd1e09 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -17,7 +17,9 @@ require_relative "server/pagination" require_relative "server/pending_response" require_relative "server/request_state_security" +require_relative "server/task_manager" require_relative "server/transports" +require_relative "tasks" module MCP class ToolNotUnique < StandardError @@ -186,7 +188,7 @@ class ValidationError < StandardError; end ].freeze attr_accessor :description, :name, :title, :version, :website_url, :instructions, :tools, :prompts, :server_context, :configuration, :transport, :logging_message_notification - attr_reader :icons, :resources, :resource_templates, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security, :capabilities + attr_reader :icons, :resources, :resource_templates, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security, :capabilities, :task_manager # The skills registered with `skills:` as a frozen Array (an empty one when only `skills_handlers` configured # the extension), or nil when the server serves no skills. attr_reader :skills @@ -202,7 +204,7 @@ def icons=(value) def capabilities=(value) candidate = normalize_capabilities(value) validate_skills_capabilities!(candidate) - @capabilities = candidate + @capabilities = with_tasks_extension(candidate) end def initialize( @@ -226,6 +228,12 @@ def initialize( cache_scope: nil, request_state_security: nil, input_required_legacy_shim: true, + task_augmentation: nil, + task_store: nil, + task_executor: nil, + task_ttl_ms: TaskManager::DEFAULT_TTL_MS, + task_poll_interval_ms: TaskManager::DEFAULT_POLL_INTERVAL_MS, + max_tasks: TaskManager::DEFAULT_MAX_TASKS, transport: nil ) @description = description @@ -274,8 +282,28 @@ def initialize( # so the Skills extension rules see the final Hash. @capabilities = normalize_capabilities(capabilities) + # Tasks extension (SEP-2663): enabled by providing a `task_augmentation` predicate, + # the per-request "should this `tools/call` become a task?" decision. `task_store` (where a record of each task is kept + # for the other processes that serve the same clients, see `TaskManager#initialize`) and `task_executor` only tune + # the enabled feature, as do `task_ttl_ms` (how long a task is kept, counted from its creation; `nil` keeps it for good), + # `task_poll_interval_ms` and `max_tasks` (how many tasks are kept at once; `nil` for no bound). + @task_augmentation = task_augmentation + @task_manager = if task_augmentation + TaskManager.new( + shared_store: task_store, + executor: task_executor, + exception_reporter: ->(exception, context) { report_exception(exception, context) }, + ttl_ms: task_ttl_ms, + poll_interval_ms: task_poll_interval_ms, + max_tasks: max_tasks, + ) + elsif task_store || task_executor + raise ArgumentError, "task_store/task_executor require task_augmentation to enable the tasks extension" + end + validate! + @capabilities = with_tasks_extension(@capabilities) @client_capabilities = nil @logging_message_notification = nil @@ -298,6 +326,12 @@ def initialize( Methods::COMPLETION_COMPLETE => ->(_) { DEFAULT_COMPLETION_RESULT }, Methods::LOGGING_SET_LEVEL => method(:configure_logging_level), } + + if @task_manager + @handlers[Methods::TASKS_GET] = method(:get_task) + @handlers[Methods::TASKS_CANCEL] = method(:cancel_task) + end + # The protocol's own request methods, as opposed to the notifications above and to custom methods # registered later: these need a request id to be run. @protocol_request_methods = @handlers.keys.reject { |name| Methods.notification?(name) }.freeze @@ -902,6 +936,10 @@ def handle_request(request, method, session: nil, related_request_id: nil, auth_ when Methods::TOOLS_CALL validate_object_params!(params) call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info, tool_call_check: tool_call_check) + when Methods::TASKS_GET + get_task(params, instrumentation_data: instrumentation_data, envelope: envelope, auth_info: auth_info) + when Methods::TASKS_CANCEL + cancel_task(params, instrumentation_data: instrumentation_data, envelope: envelope, auth_info: auth_info) when Methods::PROMPTS_GET validate_object_params!(params) get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info) @@ -976,7 +1014,9 @@ def handle_request(request, method, session: nil, related_request_id: nil, auth_ reported_exception = converted raise converted rescue RequestHandlerError => e - report_exception(e.original_error || e, { request: request }) + # A task method that names no task of the caller is an ordinary answer, and one any client can provoke at will, + # so it is not an exception to report. + report_exception(e.original_error || e, { request: request }) unless e.original_error.is_a?(TaskManager::TaskNotFound) instrumentation_data.merge!(error: e.error_type) next cancelled_response(cancellation, instrumentation_data) if cancellation&.cancelled? @@ -1598,6 +1638,11 @@ def call_tool(request, instrumentation_data:, session: nil, related_request_id: end end + # The augmentation decision runs after validation so requests that would fail synchronously keep failing synchronously; + # SEP-2663 leaves creating a task at the server's discretion per request. + task_result = maybe_call_tool_as_task(tool, request, instrumentation_data: instrumentation_data, envelope: envelope, auth_info: auth_info) + return task_result if task_result + progress_token = request.dig(:_meta, :progressToken) if request[:_meta].is_a?(Hash) response = call_tool_with_args( @@ -1641,6 +1686,204 @@ def call_tool(request, instrumentation_data:, session: nil, related_request_id: ) end + # Decides whether the current `tools/call` becomes a task (SEP-2663). Creation requires all of: the feature enabled, + # the `task_augmentation` predicate electing this request, and the client declaring the tasks extension + # in its per-request capabilities. A `:required` election against a non-declaring client is rejected with `-32021` + # because the server cannot serve the request without returning `CreateTaskResult`; any other election falls back to + # the synchronous path, since a server MUST NOT return `CreateTaskResult` to a client that did not declare the extension. + def maybe_call_tool_as_task(tool, request, instrumentation_data:, envelope:, auth_info: nil) + return unless @task_manager + + election = @task_augmentation.call(request) + return unless election + + unless envelope && Tasks.declared_by_client?(envelope.client_capabilities) + if election == :required + raise MissingRequiredClientCapabilityError.new(Tasks.required_capabilities, request) + end + + return + end + + # Creating a task is at the server's discretion, so a request that cannot get one is served synchronously + # when it does not need one, and refused when it does. That is the case for a token that names neither + # a subject nor a client, whose task could not be told apart from the task of any other such token, + # while the store is full, and while the record of a new task cannot be written to the task store. + if unidentified?(auth_info) + refusal = "A task needs a token that names a subject or a client" + else + begin + task = @task_manager.create_task(method: Methods::TOOLS_CALL, owner: task_owner(auth_info)) do |created_task| + execute_tool_call_task(tool, request, task: created_task, envelope: envelope, auth_info: auth_info) + end + rescue TaskManager::CapacityExceeded, TaskManager::NotShared + refusal = "The server cannot accept another task at the moment" + end + end + + if refusal + return unless election == :required + + raise RequestHandlerError.new( + refusal, + request, + error_type: :internal_error, + error_code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, + ) + end + + instrumentation_data.merge!(task_id: task.task_id) + task.to_create_result_hash + end + + # The principal a task belongs to: the issuer, subject and client of the token that authenticated the request, + # the same three members a Streamable HTTP session is bound to. `nil` for a request that carried no token. + # A token that names neither a subject nor a client owns nothing: the value returned for it equals no owner, + # not even that of another such token, so no task is found for it. + def task_owner(auth_info) + return unless auth_info + return Object.new.freeze if unidentified?(auth_info) + + [auth_info.issuer, auth_info.subject, auth_info.client_id].freeze + end + + def unidentified?(auth_info) + return false if auth_info.nil? + + [auth_info.subject, auth_info.client_id].all? { |member| member.nil? || member.to_s.empty? } + end + + # A task-serving server MUST declare the tasks extension (SEP-2663), so enabling the feature declares it through + # the SEP-2133 `extensions` capability member, in the capabilities given at construction and in any assigned later. + def with_tasks_extension(capabilities) + return capabilities unless @task_manager + + extensions = (capabilities[:extensions] || {}).merge(Tasks::EXTENSION_ID => {}) + capabilities.merge(extensions: extensions) + end + + # The background half of a task-augmented `tools/call`, run on the task executor. `session` is `nil` on purpose: + # `notifications/progress` and `notifications/message` are not supported on tasks (SEP-2663), + # and the per-request delivery stream is gone once `CreateTaskResult` returns. + # The task reaches handlers through `server_context.task` for status messages and cooperative cancellation. + def execute_tool_call_task(tool, request, task:, envelope:, auth_info: nil) + # The work may start well after the request that created the task was authenticated: it waits its turn on the executor. + if auth_info.respond_to?(:expired?) && auth_info.expired? + raise RequestHandlerError.new( + "The authorization the task was created with has expired", + request, + error_type: :invalid_request, + ) + end + + arguments = request[:arguments] || {} + response = call_tool_with_args( + tool, + arguments, + server_context_with_meta(request, auth_info: auth_info), + envelope: envelope, + auth_info: auth_info, + retry_fields: mrtr_retry_fields(request), + task: task, + ) + + if response.is_a?(InputRequiredResult) + raise RequestHandlerError.new( + "input_required results inside tasks require `tasks/update` support, which this server does not implement yet", + request, + error_type: :internal_error, + ) + end + + result = response.to_h + validate_tool_call_result!(tool, result) + serialize_structured_content_fallback( + result, + content_provided: response.respond_to?(:content_provided?) && response.content_provided?, + ) + rescue RequestHandlerError, CancelledError + raise + rescue OAuth::InsufficientScopeError => e + raise RequestHandlerError.new(e.message, request, error_type: :invalid_request, original_error: e) + rescue *TaskManager::WORK_ERRORS => e + # The same conversion a synchronous `tools/call` applies: the task fails with a message that names the tool + # and nothing else, and the exception itself goes to the exception reporter. + raise RequestHandlerError.new( + "Internal error calling tool #{tool.name_value}", + request, + error_type: :internal_error, + original_error: e, + ) + end + + # `tasks/get` (SEP-2663): returns the `DetailedTask` for the current status, inlining `result` (completed) or `error` (failed). + def get_task(request, instrumentation_data: {}, envelope: nil, auth_info: nil) + ensure_tasks_request!(request, envelope: envelope) + + task = @task_manager.get_task(task_id: required_task_id!(request), owner: task_owner(auth_info)) + instrumentation_data.merge!(task_id: task.task_id) + + { resultType: ResultType::COMPLETE }.merge(task.to_detailed_hash) + rescue TaskManager::Error => e + raise task_params_error(e, request) + end + + # `tasks/cancel` (SEP-2663): cooperative and eventually consistent, so the acknowledgement is empty and cancelling + # an already-terminal task is not an error. + def cancel_task(request, instrumentation_data: {}, envelope: nil, auth_info: nil) + ensure_tasks_request!(request, envelope: envelope) + + task = @task_manager.cancel_task(task_id: required_task_id!(request), owner: task_owner(auth_info)) + instrumentation_data.merge!(task_id: task.task_id, cancelled: true) + + { resultType: ResultType::COMPLETE } + rescue TaskManager::Error => e + raise task_params_error(e, request) + end + + # The tasks methods exist only on the modern (2026-07-28) wire: a legacy request gets `-32601` as if the method were unknown, + # matching the Python SDK's version-scoped registration, and a modern request must declare the tasks extension in + # its per-request capabilities (`-32021` otherwise). + def ensure_tasks_request!(request, envelope:) + if envelope.nil? + raise RequestHandlerError.new( + "Method not found: the tasks extension requires the 2026-07-28 lifecycle", + request, + error_type: :method_not_found, + error_code: JsonRpcHandler::ErrorCode::METHOD_NOT_FOUND, + ) + end + + return if Tasks.declared_by_client?(envelope.client_capabilities) + + raise MissingRequiredClientCapabilityError.new(Tasks.required_capabilities, request) + end + + def required_task_id!(request) + task_id = request.is_a?(Hash) ? request[:taskId] || request["taskId"] : nil + unless task_id.is_a?(String) + raise RequestHandlerError.new( + "taskId must be a string", + request, + error_type: :invalid_params, + error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS, + ) + end + + task_id + end + + # Maps store-level task errors to `-32602` while keeping the descriptive message (the same pattern as `ResourceNotFoundError`). + def task_params_error(error, request) + RequestHandlerError.new( + error.message, + request, + error_type: :invalid_params, + error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS, + original_error: error, + ) + end + def list_prompts(request) page = paginate(@prompts.values, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h) @@ -2224,7 +2467,7 @@ def accepts_server_context?(method_object) end end - def call_tool_with_args(tool, arguments, context, progress_token: nil, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil, retry_fields: nil) + def call_tool_with_args(tool, arguments, context, progress_token: nil, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil, retry_fields: nil, task: nil) # Transports parse incoming JSON with `symbolize_names: true`, so `arguments` already arrives symbolized # at every nesting level. This top-level transform only guards callers that hand in string-keyed top-level arguments; # it does not recurse, and nested object keys remain symbols. Tools therefore receive symbol keys all the way down. @@ -2243,6 +2486,7 @@ def call_tool_with_args(tool, arguments, context, progress_token: nil, session: input_responses: retry_fields&.fetch(:input_responses, nil), request_state: retry_fields&.fetch(:request_state, nil), auth_info: auth_info, + task: task, ) tool.call(**args, server_context: server_context) else diff --git a/lib/mcp/server/task.rb b/lib/mcp/server/task.rb new file mode 100644 index 00000000..4b79b46e --- /dev/null +++ b/lib/mcp/server/task.rb @@ -0,0 +1,205 @@ +# frozen_string_literal: true + +require "monitor" +require "time" +require_relative "../result_type" +require_relative "../tasks" + +module MCP + class Server + # A task as defined by the MCP Tasks extension (SEP-2663): a durable state machine carrying the execution state of + # the request it augments, keyed by a server-generated task ID. The ID must be unguessable, and `TaskManager` generates random UUIDs + # (122 random bits), but it is not what grants access: a task also records its `owner`, the principal of the request that created it, + # and `TaskManager` serves it to that principal only. + # + # https://github.com/modelcontextprotocol/ext-tasks + class Task + STATUS_WORKING = "working" + STATUS_INPUT_REQUIRED = "input_required" + STATUS_COMPLETED = "completed" + STATUS_FAILED = "failed" + STATUS_CANCELLED = "cancelled" + + TERMINAL_STATUSES = [STATUS_COMPLETED, STATUS_FAILED, STATUS_CANCELLED].freeze + ALL_STATUSES = ([STATUS_WORKING, STATUS_INPUT_REQUIRED] + TERMINAL_STATUSES).freeze + + class IllegalStateTransition < StandardError; end + + attr_reader :task_id, + :request_method, + :owner, + :ttl_ms, + :poll_interval_ms, + :created_at, + :last_updated_at, + :status, + :status_message, + :result, + :error + + def initialize(task_id:, request_method:, owner: nil, ttl_ms: nil, poll_interval_ms: nil) + @task_id = task_id + @request_method = request_method + @owner = owner + @ttl_ms = ttl_ms + @poll_interval_ms = poll_interval_ms + now = Time.now.utc + @created_at = now + @last_updated_at = now + @status = STATUS_WORKING + @status_message = nil + @result = nil + @error = nil + @cancelled = false + @on_change = nil + @monitor = Monitor.new + @cond = @monitor.new_cond + end + + # Registers what `TaskManager` runs after each change of what `tasks/get` reports for the task. + # It runs on the thread that made the change, outside the lock of the task. + # + # @api private + def on_change(&block) + @on_change = block + end + + def transition_to(new_status, message: nil, result: nil, error: nil) + @monitor.synchronize do + validate_transition!(new_status) + @status = new_status + @status_message = message unless message.nil? + @result = result unless result.nil? + @error = error unless error.nil? + @last_updated_at = Time.now.utc + @cond.broadcast if terminal? + end + end + + # Moves the task to a terminal status unless it already has one, and says whether it did. The check and + # the change are one step, so of a completion and a cancellation that race, exactly one is recorded. + def finish(new_status, message: nil, result: nil, error: nil) + finished = @monitor.synchronize do + next false if terminal? + + transition_to(new_status, message: message, result: result, error: error) + true + end + @on_change&.call(self) if finished + + finished + end + + # Cancels the task unless it already has a terminal status, and says whether it did. The work is not interrupted: + # it sees the request through `cancelled?`, and whatever it returns afterwards is discarded. + def cancel!(message) + cancelled = @monitor.synchronize do + next false if terminal? + + @cancelled = true + transition_to(STATUS_CANCELLED, message: message) + true + end + @on_change&.call(self) if cancelled + + cancelled + end + + # The message of a task that has reached a terminal status is part of its outcome and no longer changes. + def update_status_message(message) + updated = @monitor.synchronize do + next false if terminal? + + @status_message = message + @last_updated_at = Time.now.utc + true + end + @on_change&.call(self) if updated + end + + def terminal? + @monitor.synchronize { TERMINAL_STATUSES.include?(@status) } + end + + def cancelled? + @monitor.synchronize { @cancelled || @status == STATUS_CANCELLED } + end + + # Requests cooperative cancellation. Tool handlers read this via `task.cancelled?` (or `server_context.cancelled?`). + # Does not immediately transition state; the TaskManager drives that. + def request_cancel! + @monitor.synchronize { @cancelled = true } + end + + def expired? + return false if @ttl_ms.nil? + + Time.now.utc > @created_at + (@ttl_ms / 1000.0) + end + + def wait_for_terminal + @monitor.synchronize do + @cond.wait_until { terminal? } + end + self + end + + # The SEP-2663 `Task` wire shape. `ttlMs` is required-but-nullable, so it is always emitted, `null` included; + # `statusMessage` and `pollIntervalMs` are optional and omitted when absent. + def to_wire_hash + @monitor.synchronize do + hash = { + taskId: @task_id, + status: @status, + statusMessage: @status_message, + createdAt: @created_at.iso8601, + lastUpdatedAt: @last_updated_at.iso8601, + pollIntervalMs: @poll_interval_ms, + } + hash.compact! + hash.merge(ttlMs: @ttl_ms) + end + end + + # The SEP-2663 `DetailedTask` wire shape used by `tasks/get`: the `Task` fields plus the status-specific member + # (`result` when completed, `error` when failed). A tool result with `isError: true` is a `completed` task, + # so it appears under `result`; `failed` is reserved for JSON-RPC errors. + def to_detailed_hash + @monitor.synchronize do + detailed = to_wire_hash + + case @status + when STATUS_COMPLETED + detailed[:result] = @result + when STATUS_FAILED + detailed[:error] = @error + end + + detailed + end + end + + # The SEP-2663 `CreateTaskResult` wire shape: `Result & Task`, flat, with the reserved `resultType: "task"` discriminator. + def to_create_result_hash + { resultType: Tasks::RESULT_TYPE_TASK }.merge(to_wire_hash) + end + + private + + def validate_transition!(new_status) + unless ALL_STATUSES.include?(new_status) + raise IllegalStateTransition, "Unknown task status: #{new_status.inspect}" + end + + case @status + when STATUS_WORKING + return if [STATUS_INPUT_REQUIRED, STATUS_COMPLETED, STATUS_FAILED, STATUS_CANCELLED].include?(new_status) + when STATUS_INPUT_REQUIRED + return if [STATUS_WORKING, STATUS_COMPLETED, STATUS_FAILED, STATUS_CANCELLED].include?(new_status) + end + + raise IllegalStateTransition, "Invalid transition from #{@status} to #{new_status}" + end + end + end +end diff --git a/lib/mcp/server/task_executor.rb b/lib/mcp/server/task_executor.rb new file mode 100644 index 00000000..b69d8cff --- /dev/null +++ b/lib/mcp/server/task_executor.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +module MCP + class Server + # Abstract base class that runs the background work behind a task. + # + # The default is `TaskExecutor::Thread` (a bounded number of threads). + # Swap in `TaskExecutor::Synchronous` for deterministic tests, + # or provide a custom subclass for job systems like Sidekiq/ActiveJob. + class TaskExecutor + def execute(&block) + raise NotImplementedError, "Subclasses must implement execute" + end + end + end +end diff --git a/lib/mcp/server/task_executor/synchronous.rb b/lib/mcp/server/task_executor/synchronous.rb new file mode 100644 index 00000000..01cf87a4 --- /dev/null +++ b/lib/mcp/server/task_executor/synchronous.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require_relative "../task_executor" + +module MCP + class Server + class TaskExecutor + # Runs the block inline on the calling thread. + # Useful for tests where determinism matters more than parallelism. + class Synchronous < TaskExecutor + def execute(&block) + block.call + end + end + end + end +end diff --git a/lib/mcp/server/task_executor/thread.rb b/lib/mcp/server/task_executor/thread.rb new file mode 100644 index 00000000..d614732e --- /dev/null +++ b/lib/mcp/server/task_executor/thread.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +require_relative "../task_executor" + +module MCP + class Server + class TaskExecutor + # Runs task work on a bounded number of threads. Work submitted while every thread is busy waits its turn, + # so the number of threads does not follow the number of tasks clients create; a waiting task stays `working`. + # Threads are started on demand and end when no work is left. Work that never returns keeps its thread for good, + # since a thread is not interrupted. + class Thread < TaskExecutor + DEFAULT_MAX_THREADS = 16 + + # What a block can raise without the process being at fault. A thread carries on with the waiting work + # after any of them; only an exception that is not the block's own, such as an interrupt, ends it. + BLOCK_ERRORS = [StandardError, ScriptError, SystemStackError].freeze + private_constant :BLOCK_ERRORS + + def initialize(max_threads: DEFAULT_MAX_THREADS) + super() + unless max_threads.is_a?(Integer) && max_threads.positive? + raise ArgumentError, "max_threads must be a positive Integer" + end + + @max_threads = max_threads + @mutex = Mutex.new + @pending = [] + @running = 0 + end + + def execute(&block) + @mutex.synchronize do + @pending << block + next if @running >= @max_threads + + begin + start_thread + rescue ThreadError + # The caller is told the work was not taken, so it must not run later on another thread. + @pending.delete_if { |pending| pending.equal?(block) } + raise + end + end + end + + private + + # Called with the lock held. + def start_thread + @running += 1 + ::Thread.new { drain } + rescue ThreadError + @running -= 1 + raise + end + + def drain + drained = false + while (block = next_block) + begin + block.call + rescue *BLOCK_ERRORS + # `TaskManager` records the outcome of the work it submits; a block that still raises must not + # end the thread while work is waiting. + nil + end + end + drained = true + ensure + # An exception that is not the block's own ends this thread without passing through `next_block`, + # which is where a thread gives its slot back. The slot is released here, and the work still waiting + # gets a thread of its own. + release_slot unless drained + end + + def release_slot + @mutex.synchronize do + @running -= 1 + start_thread unless @pending.empty? + end + rescue ThreadError + # The waiting work gets its thread with the next `execute`. + nil + end + + # Taking the next block and giving the slot back happen under one lock, so work submitted while + # the last thread is leaving either finds that thread still draining or starts a new one. + def next_block + @mutex.synchronize do + block = @pending.shift + @running -= 1 unless block + block + end + end + end + end + end +end diff --git a/lib/mcp/server/task_manager.rb b/lib/mcp/server/task_manager.rb new file mode 100644 index 00000000..d4a57f0e --- /dev/null +++ b/lib/mcp/server/task_manager.rb @@ -0,0 +1,357 @@ +# frozen_string_literal: true + +require "securerandom" +require_relative "../../json_rpc_handler" +require_relative "task" +require_relative "task_record" +require_relative "task_registry" +require_relative "task_registry/in_memory" +require_relative "task_executor" +require_relative "task_executor/thread" +require_relative "task_executor/synchronous" + +module MCP + class Server + # Coordinates task creation, storage, background execution, cancellation, and polling for the MCP Tasks extension (SEP-2663). + # + # Task creation is server-directed: the server decides per request whether to materialize a task, so all lifecycle parameters + # (`ttlMs`, `pollIntervalMs`) are chosen by the server rather than negotiated with the client. There is no enumeration + # (SEP-2663 removed `tasks/list`). + # + # A task belongs to the `owner` it was created for, the principal of the request that created it, and every later operation names + # the principal asking: a task is found only by its owner, so to anyone else it does not exist. + # An `owner` of `nil` is the unauthenticated principal, for servers that verify no token; there the task id is the only thing + # a caller has to present. + class TaskManager + # Default task retention, counted from creation (5 minutes). `nil` would mean unlimited retention, + # which an in-memory store should not default to. + DEFAULT_TTL_MS = 5 * 60 * 1000 + # Default polling interval advertised to clients (5 seconds). + DEFAULT_POLL_INTERVAL_MS = 5_000 + # Default bound on the tasks the store holds at once, finished ones included until their TTL passes, + # and on the work that is scheduled and has not ended. + DEFAULT_MAX_TASKS = 1000 + + # What a tool can raise besides a `StandardError` without the process being at fault: `NotImplementedError` is a `ScriptError`, + # and a runaway recursion raises `SystemStackError`. They fail the task like any other exception of the tool. + WORK_ERRORS = [StandardError, ScriptError, SystemStackError].freeze + + class Error < StandardError; end + class TaskNotFound < Error; end + class InvalidTaskRequest < Error; end + # Raised by `create_task` when the store already holds `max_tasks` tasks. + class CapacityExceeded < Error; end + # Raised by `create_task` when the record of the new task could not be written to the task store. + class NotShared < Error; end + + # The code and message `JsonRpcHandler` answers for a `RequestHandlerError` that carries no code of its own, + # by its error type; any other type is an internal error. + ERRORS_BY_TYPE = { + invalid_request: [JsonRpcHandler::ErrorCode::INVALID_REQUEST, "Invalid Request"], + invalid_params: [JsonRpcHandler::ErrorCode::INVALID_PARAMS, "Invalid params"], + parse_error: [JsonRpcHandler::ErrorCode::PARSE_ERROR, "Parse error"], + }.freeze + INTERNAL_ERROR = [JsonRpcHandler::ErrorCode::INTERNAL_ERROR, "Internal error"].freeze + private_constant :ERRORS_BY_TYPE, :INTERNAL_ERROR + + # @param shared_store [#write, #read, #delete, nil] where a record of each task is kept for the other processes + # that serve the same clients: `write(task_id, record, expires_in:)` keeps the String `record` for `expires_in` seconds, + # `read(task_id)` returns it or `nil`, and `delete(task_id)` forgets it. The store decides nothing: who may read a task + # and whether it has expired are checked here, on what `read` returns. + def initialize(store: nil, shared_store: nil, executor: nil, exception_reporter: nil, ttl_ms: DEFAULT_TTL_MS, + poll_interval_ms: DEFAULT_POLL_INTERVAL_MS, max_tasks: DEFAULT_MAX_TASKS) + if shared_store + unless [:write, :read, :delete].all? { |name| shared_store.respond_to?(name) } + raise ArgumentError, "A task store has to respond to `write`, `read` and `delete`" + end + # The record of a task whose process is gone is never updated again, so without a time limit it would say `working` for good. + raise ArgumentError, "A task store needs a `ttl_ms`" if ttl_ms.nil? + end + + @shared_store = shared_store + # What writes the record of each task this process shares, by task id, until the task is discarded. + @record_writers = {} + @record_writers_mutex = Mutex.new + @store = store || TaskRegistry::InMemory.new + @executor = executor || TaskExecutor::Thread.new + @exception_reporter = exception_reporter || ->(_exception, _context) {} + @ttl_ms = ttl_ms + @poll_interval_ms = poll_interval_ms + @max_tasks = max_tasks + @create_mutex = Mutex.new + # Work handed to the executor that has not ended. It outlives the task's place in the store when the task + # expires first, and it holds the request it serves, so it is bounded together with the store. + @scheduled = 0 + @scheduled_mutex = Mutex.new + end + + # Creates a task, persists it, and schedules `work` on the executor. + # The task is saved before this method returns, satisfying the SEP-2663 strong-consistency rule that + # a server must not return `CreateTaskResult` until a `tasks/get` for the returned `taskId` would resolve. + # + # @param method [String] the task-augmented request method (e.g. "tools/call"). + # @param owner [Object, nil] the principal the task belongs to. + # @yieldparam task [Task] the newly created task. + # @yieldreturn [Hash] the final result to record as the terminal outcome. + # @return [Task] + # @raise [CapacityExceeded] when the store already holds `max_tasks` tasks, or as much work is still scheduled. + # @raise [NotShared] when the record of the task could not be written to the task store. + def create_task(method:, owner: nil, &work) + task = Task.new( + task_id: SecureRandom.uuid, + request_method: method, + owner: owner, + ttl_ms: @ttl_ms, + poll_interval_ms: @poll_interval_ms, + ) + expired = [] + begin + @create_mutex.synchronize do + expired = @store.delete_expired + + # The place of the work is taken under the lock that checks the bound, so two creations cannot both take the last one. + unless reserve(limit: @max_tasks && [@max_tasks - @store.size, 0].max) + raise CapacityExceeded, "The server holds its maximum of #{@max_tasks} tasks" + end + + save_or_unreserve(task) + end + ensure + # Outside the lock: discarding a task may take time, and no creation has to wait for it. + discard(expired) + end + + share_or_drop(task) + schedule(task, reserved: true, &work) + task + end + + def get_task(task_id:, owner: nil) + fetch_task!(task_id, owner) + end + + # Signals cooperative cancellation (SEP-2663): the acknowledgement is eventually consistent, + # so cancelling an already-terminal task is a no-op rather than an error. The work is not interrupted; + # it reads the request through `Task#cancelled?` and its outcome is discarded. + def cancel_task(task_id:, owner: nil) + task = fetch_task!(task_id, owner) + # Only the process that runs a task can stop it. The request is acknowledged all the same: + # SEP-2663 leaves it to the server whether a cancellation takes effect. + return task if task.is_a?(RemoteTask) + + task.cancel!("The task was cancelled by request.") + task + end + + private + + # A task of another owner is reported exactly like an unknown one, so the answer does not tell a caller + # whether an id it does not own exists. + def fetch_task!(task_id, owner) + raise InvalidTaskRequest, "taskId must be a string" unless task_id.is_a?(String) + + discard(@store.delete_expired) + task = @store.find(task_id) + return task if task && task.owner == owner + + # The store is asked for every id this process does not serve, one it holds for another owner included, + # so that a store that fails answers the same for an id that exists as for one that does not. + remote = remote_task(task_id, owner) + raise TaskNotFound, "Task not found: #{task_id}" unless remote + + remote + end + + # The task of another process, from the record that process keeps in the task store. + def remote_task(task_id, owner) + return unless @shared_store + + detailed = TaskRecord.load(@shared_store.read(task_id), task_id: task_id, owner: owner) + detailed && RemoteTask.new(detailed) + end + + # Writes the record of the task before the task is announced, so that every process can answer for it from then on + # (SEP-2663: a task is durably created before its `CreateTaskResult` is returned), and again after each change. + # A task whose first record cannot be written is dropped; a later record that cannot be written is reported, + # and the other processes keep answering with the last one that was. + def share_or_drop(task) + return unless @shared_store + + write = record_writer(task) + # Known to `discard` from before the first write, so a task that expires during it leaves no writer behind. + @record_writers_mutex.synchronize { @record_writers[task.task_id] = write } + # A task that expired, and may have been discarded, before its writer was known gets no record. Looked up after + # the writer is known: a discard that comes later finds the writer, and one that came earlier is seen here. + unless @store.find(task.task_id) + @record_writers_mutex.synchronize { @record_writers.delete(task.task_id) } + return + end + + begin + write.call + rescue *WORK_ERRORS => e + # The store may have kept the record and failed afterwards, so it is asked to forget it. + begin + write.call(true) + rescue *WORK_ERRORS + nil + end + drop(task) + report(e, task) + raise NotShared, "The record of the task could not be written" + end + + task.on_change do + write.call + rescue *WORK_ERRORS => e + report(e, task) + end + end + + # One write at a time, each of the task as it is at that moment, so the store never ends up with an older state + # than the task has. An expired task has no record: it is deleted instead, whatever the store does about `expires_in`. + # Called with `true`, the writer deletes the record and never writes it again, so a write that was waiting for + # its turn cannot bring back the record of a task that has been discarded. + def record_writer(task) + mutex = Mutex.new + discarded = false + lambda do |discard = false| + mutex.synchronize do + discarded ||= discard + left = TaskRecord.expires_at(task) - Time.now.utc + if discarded || !left.positive? + @shared_store.delete(task.task_id) + else + @shared_store.write(task.task_id, TaskRecord.dump(task), expires_in: left) + end + end + end + end + + def drop(task) + @store.delete(task.task_id) + @record_writers_mutex.synchronize { @record_writers.delete(task.task_id) } + @scheduled_mutex.synchronize { @scheduled -= 1 } + end + + def delete_record(task) + write = @record_writers_mutex.synchronize { @record_writers.delete(task.task_id) } + write&.call(true) + rescue *WORK_ERRORS => e + report(e, task) + end + + # Expired tasks leave the store whether or not anyone still polls them, before a task is looked up and + # before one is created, and are discarded here. One that is still running is asked to stop, + # since nobody can read its outcome any more. + def discard(tasks) + tasks.each do |task| + task.cancel!("The task expired.") + delete_record(task) + end + end + + # Takes a place for work that is about to be scheduled. With a `limit`, the place is refused when the limit + # is zero or as much work is already scheduled as `max_tasks` allows. + def reserve(limit: nil) + @scheduled_mutex.synchronize do + next false if limit && (limit.zero? || @scheduled >= @max_tasks) + + @scheduled += 1 + true + end + end + + # A store that cannot save the task leaves no work to schedule, so the place taken for it is given back. + def save_or_unreserve(task) + saved = false + @store.save(task) + saved = true + ensure + @scheduled_mutex.synchronize { @scheduled -= 1 } unless saved + end + + # Hands the work to the executor and gives its place back once, when the work has ended or when + # the executor could not take it. In the second case the task, which is already stored, fails instead of + # staying `working` until it expires. + def schedule(task, reserved: false, &work) + reserve unless reserved + released = false + release = lambda do + @scheduled_mutex.synchronize do + next if released + + released = true + @scheduled -= 1 + end + end + + begin + @executor.execute do + run_work(task, &work) + ensure + release.call + end + rescue *WORK_ERRORS => e + release.call + + fail_unscheduled(task, e) + end + end + + def fail_unscheduled(task, exception) + report(exception, task) if task.finish(Task::STATUS_FAILED, **failure_of(exception)) + end + + def run_work(task, &work) + return if task.terminal? + + result = work.call(task) + + # A tool result with `isError: true` is still a `completed` task per SEP-2663; `failed` is reserved + # for JSON-RPC errors raised during execution. + task.finish(Task::STATUS_COMPLETED, result: result) + rescue MCP::CancelledError + task.cancel!("The task was cancelled by request.") + rescue *WORK_ERRORS => e + # The outcome is recorded before the exception is reported. An exception that loses to a cancellation is not reported: + # the outcome it would have been was discarded. + report(e, task) if task.finish(Task::STATUS_FAILED, **failure_of(e)) + end + + # What a failed task tells the client: the JSON-RPC error the request would have been answered with, had it failed synchronously + # (SEP-2663: the `error` of a failed task is that error). For a `RequestHandlerError` that is what `JsonRpcHandler` builds from it, + # its own code and message when it carries a code and the standard pair of its type otherwise, with its data, or its message, + # as `data`. Anything else is a bare internal error, since the message of an arbitrary exception can name hosts, credentials or code. + # The status message is the text meant for the client. + def failure_of(exception) + unless exception.is_a?(RequestHandlerError) + code, message = INTERNAL_ERROR + + return { message: message, error: { code: code, message: message } } + end + + if exception.error_code + code = exception.error_code + message = exception.message + else + code, message = ERRORS_BY_TYPE.fetch(exception.error_type, INTERNAL_ERROR) + end + + # Truthiness, as `JsonRpcHandler` decides it: an `error_data` of `false` gives way to the message there too. + data = exception.error_data || exception.message + + { message: exception.message, error: { code: code, message: message, data: data } } + end + + def report(exception, task) + reported = exception.is_a?(RequestHandlerError) && exception.original_error || exception + + @exception_reporter.call(reported, { task_id: task.task_id, request_method: task.request_method }) + rescue *WORK_ERRORS + # A reporter that raises must not take the executor's thread with it; the task already has its outcome. + nil + end + end + end +end diff --git a/lib/mcp/server/task_record.rb b/lib/mcp/server/task_record.rb new file mode 100644 index 00000000..400cd427 --- /dev/null +++ b/lib/mcp/server/task_record.rb @@ -0,0 +1,103 @@ +# frozen_string_literal: true + +require "json" +require_relative "task" + +module MCP + class Server + # What `TaskManager` writes to the `task_store:` of a server for each of its tasks, and reads back for a task of + # another process: a JSON document with the owner of the task, the time its retention ends, and what `tasks/get` + # answers for it. The format belongs to the SDK and may change between releases; a store keeps the string as it is. + # + # @api private + module TaskRecord + # The members a task carries in one status only, and that status. + STATUS_MEMBERS = { "result" => Task::STATUS_COMPLETED, "error" => Task::STATUS_FAILED }.freeze + + # The members of a record that are served. Nothing else it might carry is passed on to a client. + MEMBERS = (["taskId", "status", "statusMessage", "createdAt", "lastUpdatedAt", "ttlMs", "pollIntervalMs"] + STATUS_MEMBERS.keys).freeze + + class << self + def dump(task) + raise ArgumentError, "The owner of the task cannot be written to a record" unless recordable?(task.owner) + + JSON.generate(owner: task.owner, expiresAt: expires_at(task).to_f, task: task.to_detailed_hash) + end + + # What `tasks/get` answers for the task of `task_id`, read from `document`, or `nil` when the document is not + # the record of that task, names another owner, has outlived its retention, or does not have the shape of a task. + # A store keeps strings and decides nothing, so whom the record is for and how long are checked here. + # What the task says, its result included, is the word of whoever wrote the record. + def load(document, task_id:, owner:, now: Time.now.utc) + return unless document.is_a?(String) && recordable?(owner) + + record = JSON.parse(document) + return unless record.is_a?(Hash) && record.key?("owner") && record["owner"] == owner + + expires_at = record["expiresAt"] + return unless expires_at.is_a?(Numeric) && expires_at.finite? && now.to_f < expires_at + + detailed = record["task"] + return unless detailed.is_a?(Hash) && detailed["taskId"] == task_id && well_formed?(detailed) + + detailed.slice(*MEMBERS) + rescue JSON::ParserError + nil + end + + def expires_at(task) + task.created_at + (task.ttl_ms / 1000.0) + end + + private + + # An owner is `nil`, for a server that verifies no token, or the issuer, subject and client of a token. + # Only those compare equal after a round trip through JSON. + def recordable?(owner) + owner.nil? || (owner.is_a?(Array) && owner.all? { |part| part.nil? || part.is_a?(String) }) + end + + def well_formed?(detailed) + status = detailed["status"] + return false unless Task::ALL_STATUSES.include?(status) + return false unless detailed["createdAt"].is_a?(String) && detailed["lastUpdatedAt"].is_a?(String) + return false unless optional?(detailed, "ttlMs", Integer) && optional?(detailed, "pollIntervalMs", Integer) + return false unless optional?(detailed, "statusMessage", String) + + STATUS_MEMBERS.all? do |name, its_status| + detailed[name].nil? || (status == its_status && detailed[name].is_a?(Hash)) + end + end + + def optional?(detailed, name, type) + detailed[name].nil? || detailed[name].is_a?(type) + end + end + end + + # A task that another process runs, as its record reports it. It can be read, and nothing else: + # the process that runs a task is the only one that changes it. + # + # @api private + class RemoteTask + attr_reader :task_id + + def initialize(detailed) + @task_id = detailed["taskId"] + @detailed = detailed.transform_keys(&:to_sym).freeze + end + + def status + @detailed[:status] + end + + def terminal? + Task::TERMINAL_STATUSES.include?(status) + end + + def to_detailed_hash + @detailed + end + end + end +end diff --git a/lib/mcp/server/task_registry.rb b/lib/mcp/server/task_registry.rb new file mode 100644 index 00000000..5196f51e --- /dev/null +++ b/lib/mcp/server/task_registry.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module MCP + class Server + # Abstract base class for holding the live `Task` objects of this process (SEP-2663). What a server shares with + # other processes is something else: the `task_store:` of `Server.new`, which `TaskManager` writes a record of each task to. + # + # Concrete implementations must be thread-safe; TaskRegistry is accessed concurrently from request-handling threads + # and TaskExecutor threads. + # Implementations must also enforce TTL: a task whose `ttlMs` has elapsed must no longer be found. + # There is deliberately no listing operation - SEP-2663 removed `tasks/list` because a server cannot safely scope + # an enumeration, so the task ID is the only retrieval key. + # + # A store keeps `Task#owner` with the task: `TaskManager` reads it back from the task `find` returns to decide + # whether the caller may see the task at all. + # + # @api private + class TaskRegistry + def save(task) + raise NotImplementedError, "Subclasses must implement save" + end + + def find(task_id) + raise NotImplementedError, "Subclasses must implement find" + end + + def delete(task_id) + raise NotImplementedError, "Subclasses must implement delete" + end + + # Removes every task whose TTL has elapsed, whether or not it was ever looked up again, and returns the removed tasks. + # `TaskManager` calls it before it looks a task up and before it creates one, and stops the work of each task returned, + # so an expired task has to be returned here once, not dropped silently by `find`. + # + # @return [Array] + def delete_expired + raise NotImplementedError, "Subclasses must implement delete_expired" + end + + # The number of tasks held, which `TaskManager` compares with its `max_tasks`. + # + # @return [Integer] + def size + raise NotImplementedError, "Subclasses must implement size" + end + end + end +end diff --git a/lib/mcp/server/task_registry/in_memory.rb b/lib/mcp/server/task_registry/in_memory.rb new file mode 100644 index 00000000..8484713a --- /dev/null +++ b/lib/mcp/server/task_registry/in_memory.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative "../task_registry" + +module MCP + class Server + class TaskRegistry + # Default single-process store. An expired task is no longer found, and it leaves the store when + # `delete_expired` runs, which `TaskManager` does before it looks a task up or creates one, so no reaper + # thread is needed. `find` does not remove it itself: the task has to come back from `delete_expired` + # for `TaskManager` to stop its work. + class InMemory < TaskRegistry + def initialize + super + @mutex = Mutex.new + @tasks = {} + end + + def save(task) + @mutex.synchronize { @tasks[task.task_id] = task } + task + end + + def find(task_id) + @mutex.synchronize do + task = @tasks[task_id] + task unless task.nil? || task.expired? + end + end + + def delete(task_id) + @mutex.synchronize { @tasks.delete(task_id) } + end + + def delete_expired + @mutex.synchronize do + expired = @tasks.values.select(&:expired?) + expired.each { |task| @tasks.delete(task.task_id) } + expired + end + end + + def size + @mutex.synchronize { @tasks.size } + end + end + end + end +end diff --git a/lib/mcp/server_context.rb b/lib/mcp/server_context.rb index 1d0d6600..277a54b8 100644 --- a/lib/mcp/server_context.rb +++ b/lib/mcp/server_context.rb @@ -21,7 +21,11 @@ class ServerContext # This reader is the canonical accessor; when the underlying context is a Hash the same value is also reachable as `server_context[:auth_info]`. attr_reader :auth_info - def initialize(context, progress:, notification_target:, related_request_id: nil, cancellation: nil, envelope: nil, input_responses: nil, request_state: nil, auth_info: nil) + # The `MCP::Server::Task` backing the current invocation when the request was task-augmented (SEP-2663 tasks extension); `nil` otherwise. + # Handlers use it to publish progress descriptions (`task.update_status_message`) and to honor cooperative cancellation ({#cancelled?} consults it automatically). + attr_reader :task + + def initialize(context, progress:, notification_target:, related_request_id: nil, cancellation: nil, envelope: nil, input_responses: nil, request_state: nil, auth_info: nil, task: nil) @context = context @progress = progress @notification_target = notification_target @@ -31,6 +35,7 @@ def initialize(context, progress:, notification_target:, related_request_id: nil @input_responses = input_responses @request_state = request_state @auth_info = auth_info + @task = task end # Reads one entry of {#input_responses} by its `inputRequests` key, tolerating symbol or string keys. @@ -42,11 +47,15 @@ def input_response(key) end def cancelled? - !!@cancellation&.cancelled? + !!(@cancellation&.cancelled? || @task&.cancelled?) end def raise_if_cancelled! @cancellation&.raise_if_cancelled! + + if @task&.cancelled? + raise CancelledError.new(reason: "The task was cancelled by request.") + end end # Whether the current request follows the stateless modern lifecycle (SEP-2575). diff --git a/lib/mcp/tasks.rb b/lib/mcp/tasks.rb new file mode 100644 index 00000000..eb5933f8 --- /dev/null +++ b/lib/mcp/tasks.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +module MCP + # Wire vocabulary and capability helpers for the MCP Tasks extension (SEP-2663). + # + # Tasks let a server respond to a `tools/call` request with an asynchronous task handle + # (`CreateTaskResult`, discriminated by `resultType: "task"`) instead of a final result; + # the client then polls `tasks/get` and cancels via `tasks/cancel`. + # Task creation is server-directed: the client signals support by declaring the extension + # in its per-request capabilities, and the server decides per request whether to materialize a task. + # + # The extension is negotiated through the SEP-2133 `extensions` capability mechanism: + # clients declare it in the per-request `_meta` `io.modelcontextprotocol/clientCapabilities` entry, + # servers in the `server/discover` response. It replaces the experimental tasks feature + # of the 2025-11-25 specification, which is not wire-compatible. + # + # The normative specification lives in the ext-tasks repository: + # https://github.com/modelcontextprotocol/ext-tasks + # https://modelcontextprotocol.io/seps/2663-tasks-extension + module Tasks + EXTENSION_ID = "io.modelcontextprotocol/tasks" + + # The `resultType` value reserved by this extension for `CreateTaskResult`. + RESULT_TYPE_TASK = "task" + + class << self + # The `extensions` capability fragment declaring tasks support, for merging into client capabilities + # on `connect` or server capabilities: + # + # client.connect(mode: :modern, capabilities: MCP::Tasks.capability) + def capability + { extensions: { EXTENSION_ID => {} } } + end + + # The `data.requiredCapabilities` payload of the `-32021` error a server returns when a request requires + # the tasks extension the client did not declare. + def required_capabilities + { extensions: { EXTENSION_ID => {} } } + end + + # Whether the given client capabilities (from the per-request `_meta` envelope) declare the tasks extension. + # Tolerates symbol or string keys on both levels. + def declared_by_client?(client_capabilities) + return false unless client_capabilities.is_a?(Hash) + + extensions = client_capabilities[:extensions] || client_capabilities["extensions"] + return false unless extensions.is_a?(Hash) + + !(extensions[EXTENSION_ID] || extensions[EXTENSION_ID.to_sym]).nil? + end + + # Whether a client-visible result Hash is a `CreateTaskResult`. Tolerates symbol or string keys so it works + # on both server-built and JSON-parsed results. + def task_result?(result) + return false unless result.is_a?(Hash) + + (result[:resultType] || result["resultType"]) == RESULT_TYPE_TASK + end + end + end +end diff --git a/test/mcp/client_tasks_test.rb b/test/mcp/client_tasks_test.rb new file mode 100644 index 00000000..a5ac3c72 --- /dev/null +++ b/test/mcp/client_tasks_test.rb @@ -0,0 +1,215 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + # Client-side driving of the SEP-2663 Tasks extension: `get_task`, `wait_task`, `cancel_task`, + # and the transparent `call_tool(wait_for_task: true)` path. + class ClientTasksTest < Minitest::Test + TASK_ID = "786512e2-9e0d-44bd-8f29-789f320fe840" + + def test_get_task_sends_tasks_get_and_returns_the_result + transport = mock + transport.expects(:send_request).with do |args| + request = args[:request] + request[:method] == "tasks/get" && request[:params] == { taskId: TASK_ID } + end.returns(response_with(task_result("working"))).once + + result = Client.new(transport: transport).get_task(task_id: TASK_ID) + + assert_equal("working", result["status"]) + assert_equal(TASK_ID, result["taskId"]) + end + + def test_get_task_raises_server_error_for_unknown_task + transport = mock + transport.expects(:send_request).returns({ + "jsonrpc" => "2.0", + "id" => 1, + "error" => { "code" => -32602, "message" => "Task not found: #{TASK_ID}" }, + }).once + + error = assert_raises(Client::ServerError) do + Client.new(transport: transport).get_task(task_id: TASK_ID) + end + assert_equal(-32602, error.code) + end + + def test_get_task_raises_validation_error_without_result + transport = mock + transport.expects(:send_request).returns({ "jsonrpc" => "2.0", "id" => 1 }).once + + assert_raises(Client::ValidationError) do + Client.new(transport: transport).get_task(task_id: TASK_ID) + end + end + + def test_cancel_task_sends_tasks_cancel_and_returns_the_ack + transport = mock + transport.expects(:send_request).with do |args| + request = args[:request] + request[:method] == "tasks/cancel" && request[:params] == { taskId: TASK_ID } + end.returns(response_with({ "resultType" => "complete" })).once + + ack = Client.new(transport: transport).cancel_task(task_id: TASK_ID) + + assert_equal({ "resultType" => "complete" }, ack) + end + + def test_cancel_task_raises_validation_error_for_a_result_that_is_not_an_object + transport = mock + transport.expects(:send_request).returns({ "jsonrpc" => "2.0", "id" => 1, "result" => "done" }).once + + assert_raises(Client::ValidationError) do + Client.new(transport: transport).cancel_task(task_id: TASK_ID) + end + end + + def test_wait_task_ends_the_wait_between_polls_when_cancelled + transport = mock + transport.expects(:send_notification).never + transport.expects(:send_request).once.returns(response_with(task_result("working", "pollIntervalMs" => 30_000))) + + # The first hook belongs to the poll and the second to the wait that follows it, + # so cancelling as the second one is registered cancels during the wait, whatever the timing. + cancellation = MCP::Cancellation.new + registrations = 0 + register = cancellation.method(:on_cancel) + cancellation.define_singleton_method(:on_cancel) do |&block| + register.call(&block).tap { cancel(reason: "enough") if (registrations += 1) == 2 } + end + + error = assert_raises(MCP::CancelledError) do + Client.new(transport: transport).wait_task(task_id: TASK_ID, cancellation: cancellation) + end + + assert_equal("enough", error.reason) + end + + def test_wait_task_polls_until_completed_honoring_poll_interval + final_result = { "content" => [{ "type" => "text", "text" => "done" }], "isError" => false } + transport = mock + transport.expects(:send_request).twice.returns( + response_with(task_result("working", "pollIntervalMs" => 10)), + response_with(task_result("completed", "result" => final_result)), + ) + + task = Client.new(transport: transport).wait_task(task_id: TASK_ID) + + assert_equal("completed", task["status"]) + assert_equal(final_result, task["result"]) + end + + def test_wait_task_waits_at_least_the_minimum_interval_whatever_the_server_suggests + transport = mock + transport.expects(:send_request).twice.returns( + response_with(task_result("working", "pollIntervalMs" => 0)), + response_with(task_result("completed", "result" => {})), + ) + client = Client.new(transport: transport) + client.expects(:sleep).with(Client::MIN_TASK_POLL_INTERVAL_SECONDS).once + + client.wait_task(task_id: TASK_ID) + end + + def test_wait_task_gives_up_after_its_timeout + transport = mock + transport.stubs(:send_request).returns(response_with(task_result("working", "pollIntervalMs" => 20))) + + error = assert_raises(Client::TaskTimeoutError) do + Client.new(transport: transport).wait_task(task_id: TASK_ID, timeout: 0.25) + end + assert_equal("working", error.task["status"]) + end + + def test_wait_task_raises_task_failed_error_with_the_json_rpc_error + transport = mock + transport.expects(:send_request).returns( + response_with(task_result("failed", "error" => { "code" => -32603, "message" => "kaboom" })), + ).once + + error = assert_raises(Client::TaskFailedError) do + Client.new(transport: transport).wait_task(task_id: TASK_ID) + end + assert_equal(-32603, error.error["code"]) + assert_match(/kaboom/, error.message) + end + + def test_wait_task_raises_task_cancelled_error + transport = mock + transport.expects(:send_request).returns(response_with(task_result("cancelled"))).once + + assert_raises(Client::TaskCancelledError) do + Client.new(transport: transport).wait_task(task_id: TASK_ID) + end + end + + def test_wait_task_raises_task_input_required_error_with_input_requests + input_requests = { "req-1" => { "method" => "elicitation/create", "params" => {} } } + transport = mock + transport.expects(:send_request).returns( + response_with(task_result("input_required", "inputRequests" => input_requests)), + ).once + + error = assert_raises(Client::TaskInputRequiredError) do + Client.new(transport: transport).wait_task(task_id: TASK_ID) + end + assert_equal(input_requests, error.input_requests) + end + + def test_call_tool_returns_the_create_task_result_by_default + transport = mock + transport.expects(:send_request).returns(response_with(create_task_result)).once + + response = Client.new(transport: transport).call_tool(name: "slow_tool") + + assert_equal("task", response.dig("result", "resultType")) + assert_equal(TASK_ID, response.dig("result", "taskId")) + end + + def test_call_tool_with_wait_for_task_polls_to_the_final_result + final_result = { "content" => [{ "type" => "text", "text" => "done" }], "isError" => false } + transport = mock + transport.expects(:send_request).times(3).returns( + response_with(create_task_result), + response_with(task_result("working", "pollIntervalMs" => 10)), + response_with(task_result("completed", "result" => final_result)), + ) + + response = Client.new(transport: transport).call_tool(name: "slow_tool", wait_for_task: true) + + assert_equal(final_result, response["result"]) + end + + def test_call_tool_with_wait_for_task_passes_synchronous_results_through + sync_result = { "content" => [{ "type" => "text", "text" => "fast" }], "isError" => false } + transport = mock + transport.expects(:send_request).returns(response_with(sync_result)).once + + response = Client.new(transport: transport).call_tool(name: "fast_tool", wait_for_task: true) + + assert_equal(sync_result, response["result"]) + end + + private + + def response_with(result) + { "jsonrpc" => "2.0", "id" => 1, "result" => result } + end + + def task_result(status, extra = {}) + { + "resultType" => "complete", + "taskId" => TASK_ID, + "status" => status, + "createdAt" => "2026-07-03T00:00:00Z", + "lastUpdatedAt" => "2026-07-03T00:00:00Z", + "ttlMs" => 60_000, + }.merge(extra) + end + + def create_task_result + task_result("working").merge("resultType" => "task", "pollIntervalMs" => 10) + end + end +end diff --git a/test/mcp/methods_test.rb b/test/mcp/methods_test.rb index 8373d8d2..915ac119 100644 --- a/test/mcp/methods_test.rb +++ b/test/mcp/methods_test.rb @@ -26,6 +26,12 @@ def ensure_capability_does_not_raise_for(method, capabilities: {}) ensure_capability_does_not_raise_for Methods::INITIALIZE # `server/discover` (SEP-2575) must respond regardless of declared capabilities. ensure_capability_does_not_raise_for Methods::SERVER_DISCOVER + # The tasks methods (SEP-2663) are gated by handler registration, not by + # `ensure_capability!`: a server without the extension never registers them, + # so they answer -32601 like any unknown method. + ensure_capability_does_not_raise_for Methods::TASKS_GET + ensure_capability_does_not_raise_for Methods::TASKS_UPDATE + ensure_capability_does_not_raise_for Methods::TASKS_CANCEL ensure_capability_raises_error_for Methods::PROMPTS_LIST, required_capability_name: "prompts" ensure_capability_raises_error_for Methods::PROMPTS_GET, required_capability_name: "prompts" diff --git a/test/mcp/server/task_executor/thread_test.rb b/test/mcp/server/task_executor/thread_test.rb new file mode 100644 index 00000000..610fa196 --- /dev/null +++ b/test/mcp/server/task_executor/thread_test.rb @@ -0,0 +1,135 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class Server + class TaskExecutor + class ThreadTest < ActiveSupport::TestCase + test "runs no more blocks at once than max_threads, and runs them all" do + executor = Thread.new(max_threads: 2) + mutex = Mutex.new + running = 0 + peak = 0 + started = Queue.new + gate = Queue.new + done = Queue.new + + 6.times do + executor.execute do + mutex.synchronize do + running += 1 + peak = [peak, running].max + end + started << :ok + gate.pop + mutex.synchronize { running -= 1 } + done << :ok + end + end + + # Two blocks have started and wait at the gate; the other four have no thread to start on. + 2.times { started.pop } + assert_equal 2, mutex.synchronize { running } + 6.times { gate << :go } + 6.times { done.pop } + + assert_equal 2, peak + end + + test "keeps running the work that waits when a block raises" do + executor = Thread.new(max_threads: 1) + done = Queue.new + + executor.execute { raise "boom" } + executor.execute { done << :ok } + + assert_equal :ok, done.pop + end + + test "keeps its thread for the waiting work when a block raises what a tool can raise" do + executor = Thread.new(max_threads: 1) + threads = Queue.new + gate = Queue.new + + # The first block is held until the second is queued: a thread that finds no work waiting ends, + # and the second block would then rightly get a thread of its own. + executor.execute do + threads << ::Thread.current + gate.pop + raise NotImplementedError, "todo" + end + executor.execute { threads << ::Thread.current } + gate << :go + + assert_same threads.pop, threads.pop + end + + test "gives the slot back and runs the waiting work when a block raises an exception that is not its own" do + executor = Thread.new(max_threads: 1) + done = Queue.new + previous = ::Thread.report_on_exception + ::Thread.report_on_exception = false + + executor.execute { raise Interrupt, "stop" } + executor.execute { done << :ok } + + assert_equal :ok, done.pop + assert wait_until { executor.instance_variable_get(:@running).zero? }, "a slot was not given back" + ensure + ::Thread.report_on_exception = previous + end + + test "does not keep work whose thread could not be started" do + executor = Thread.new(max_threads: 1) + ran = false + ::Thread.stubs(:new).raises(ThreadError, "can't create Thread") + + assert_raises(ThreadError) { executor.execute { ran = true } } + ::Thread.unstub(:new) + + done = Queue.new + executor.execute { done << :ok } + + assert_equal :ok, done.pop + refute ran + assert_empty executor.instance_variable_get(:@pending) + ensure + ::Thread.unstub(:new) + end + + test "starts a thread again for work submitted after the earlier work ended" do + executor = Thread.new(max_threads: 1) + done = Queue.new + + executor.execute { done << :first } + assert_equal :first, done.pop + # Once the first thread has given its slot back, the next work can only run on a new one. + assert wait_until { executor.instance_variable_get(:@running).zero? }, "the first thread did not end" + executor.execute { done << :second } + + assert_equal :second, done.pop + end + + test "rejects a max_threads that is not a positive Integer" do + [0, -1, 1.5, nil].each do |value| + assert_raises(ArgumentError) { Thread.new(max_threads: value) } + end + end + + private + + # Polls for a state another thread is about to reach, for at most five seconds. + def wait_until + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + until yield + return false if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + + sleep(0.005) + end + true + end + end + end + end +end diff --git a/test/mcp/server/task_manager_test.rb b/test/mcp/server/task_manager_test.rb new file mode 100644 index 00000000..b50247bd --- /dev/null +++ b/test/mcp/server/task_manager_test.rb @@ -0,0 +1,380 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class Server + class TaskManagerTest < ActiveSupport::TestCase + setup do + @manager = TaskManager.new(executor: TaskExecutor::Synchronous.new) + end + + test "create_task stores the task, runs work, and transitions to completed" do + result = { content: [{ type: "text", text: "ok" }] } + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| result } + + assert_kind_of Task, task + assert_equal Task::STATUS_COMPLETED, task.status + assert_equal result, task.result + assert_equal TaskManager::DEFAULT_TTL_MS, task.ttl_ms + assert_equal TaskManager::DEFAULT_POLL_INTERVAL_MS, task.poll_interval_ms + assert_same task, @manager.get_task(task_id: task.task_id) + end + + test "task ids are UUIDs" do + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| {} } + assert_match(/\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/, task.task_id) + end + + test "create_task records a JSON-RPC internal error on exception" do + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise "boom" } + + assert_equal Task::STATUS_FAILED, task.status + # The message of an arbitrary exception is not for the client. + assert_equal "Internal error", task.status_message + assert_nil task.result + assert_equal({ code: -32603, message: "Internal error" }, task.error) + end + + test "create_task records the error of a typed error raised for the client as JSON-RPC answers it" do + error = Server::RequestHandlerError.new( + "Quota exceeded", + nil, + error_type: :invalid_params, + error_data: { limit: 1 }, + ) + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise error } + + assert_equal "Quota exceeded", task.status_message + assert_equal({ code: -32602, message: "Invalid params", data: { limit: 1 } }, task.error) + end + + test "create_task records the message of an error without data as its data" do + error = Server::RequestHandlerError.new("Quota exceeded", nil, error_type: :invalid_params) + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise error } + + assert_equal({ code: -32602, message: "Invalid params", data: "Quota exceeded" }, task.error) + end + + test "create_task reports the exception an error raised for the client wraps" do + reported = [] + manager = TaskManager.new( + executor: TaskExecutor::Synchronous.new, + exception_reporter: ->(exception, _context) { reported << exception }, + ) + original = RuntimeError.new("db-internal-7.corp refused the connection") + wrapped = Server::RequestHandlerError.new("Internal error calling tool boom", nil, original_error: original) + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise wrapped } + + assert_equal [original], reported + assert_equal({ code: -32603, message: "Internal error", data: "Internal error calling tool boom" }, task.error) + assert_equal "Internal error calling tool boom", task.status_message + end + + test "a task still gets its outcome when the exception reporter raises" do + manager = TaskManager.new( + executor: TaskExecutor::Synchronous.new, + exception_reporter: ->(_exception, _context) { raise "reporter is down" }, + ) + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise "boom" } + + assert_equal Task::STATUS_FAILED, task.status + end + + test "work that raises CancelledError cancels the task without a report" do + reported = [] + manager = TaskManager.new( + executor: TaskExecutor::Synchronous.new, + exception_reporter: ->(exception, _context) { reported << exception }, + ) + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise MCP::CancelledError.new(reason: "stop") } + + assert_equal Task::STATUS_CANCELLED, task.status + assert_empty reported + end + + test "an expired task that is looked up is asked to stop like one a creation purges" do + store = TaskRegistry::InMemory.new + executor = Class.new(TaskExecutor) { def execute(&block); end }.new + manager = TaskManager.new(store: store, executor: executor, ttl_ms: 5) + stale = manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + sleep 0.05 + + assert_raises(TaskManager::TaskNotFound) { manager.get_task(task_id: stale.task_id) } + + assert_equal 0, store.size + assert_predicate stale, :cancelled? + end + + test "create_task counts work that is scheduled but has not ended toward max_tasks" do + blocks = [] + executor = Class.new(TaskExecutor) do + define_method(:execute) { |&block| blocks << block } + end.new + manager = TaskManager.new(executor: executor, ttl_ms: 5, max_tasks: 2) + 2.times { manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } } + sleep 0.05 + + # Both tasks have expired and left the store, but their work is still waiting for the executor. + assert_raises(TaskManager::CapacityExceeded) do + manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + end + + blocks.each(&:call) + assert manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + end + + test "work that raises outside StandardError fails the task" do + [NotImplementedError.new("todo"), SystemStackError.new("stack level too deep")].each do |exception| + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise exception } + + assert_equal Task::STATUS_FAILED, task.status + assert_equal({ code: -32603, message: "Internal error" }, task.error) + end + end + + test "a task fails when the executor cannot take its work" do + executor = Class.new(TaskExecutor) do + def execute(&block) + raise ThreadError, "can't create Thread" + end + end.new + manager = TaskManager.new(executor: executor, max_tasks: 1) + + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + + assert_equal Task::STATUS_FAILED, task.status + # Nothing stays scheduled, so once the failed task has gone its place is free again. + assert_equal 0, manager.instance_variable_get(:@scheduled) + end + + test "create_task treats error data that is false as JSON-RPC answers it, by the message" do + error = Server::RequestHandlerError.new("Refused", nil, error_type: :invalid_params, error_data: false) + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise error } + + assert_equal({ code: -32602, message: "Invalid params", data: "Refused" }, task.error) + end + + test "a store that fails to save gives the place of the work back" do + store = Class.new(TaskRegistry::InMemory) do + def save(task) + raise IOError, "the store is down" + end + end.new + manager = TaskManager.new(store: store, executor: TaskExecutor::Synchronous.new, max_tasks: 1) + + 2.times do + assert_raises(IOError) { manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } } + end + + assert_equal 0, manager.instance_variable_get(:@scheduled) + end + + test "the place of work the executor ran and then refused is given back once" do + executor = Class.new(TaskExecutor) do + def execute(&block) + block.call + raise "the executor failed after running the work" + end + end.new + manager = TaskManager.new(executor: executor) + + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + + assert_equal Task::STATUS_COMPLETED, task.status + assert_equal 0, manager.instance_variable_get(:@scheduled) + end + + test "a reporter that raises outside StandardError does not unbalance the scheduled work" do + manager = TaskManager.new( + executor: TaskExecutor::Synchronous.new, + exception_reporter: ->(_exception, _context) { raise NotImplementedError, "no reporter" }, + ) + + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise "boom" } + + assert_equal Task::STATUS_FAILED, task.status + assert_equal 0, manager.instance_variable_get(:@scheduled) + end + + test "concurrent creations do not take more places than max_tasks" do + executor = Class.new(TaskExecutor) { def execute(&block); end }.new + manager = TaskManager.new(executor: executor, max_tasks: 5) + + outcomes = Array.new(20) do + Thread.new do + manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + :created + rescue TaskManager::CapacityExceeded + :refused + end + end.map(&:value) + + assert_equal 5, outcomes.count(:created) + assert_equal 5, manager.instance_variable_get(:@scheduled) + end + + test "every expired task is discarded even when the creation that finds them is refused" do + store = TaskRegistry::InMemory.new + executor = Class.new(TaskExecutor) { def execute(&block); end }.new + manager = TaskManager.new(store: store, executor: executor, ttl_ms: 5, max_tasks: 2) + stale = Array.new(2) { manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } } + sleep 0.05 + + # Their work is still scheduled, so the creation is refused, but they are discarded all the same. + assert_raises(TaskManager::CapacityExceeded) do + manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + end + + assert_equal 0, store.size + assert(stale.all?(&:cancelled?)) + end + + test "a task is found by its owner only" do + alice = ["https://as.example", "alice", "app"] + bob = ["https://as.example", "bob", "app"] + task = @manager.create_task(method: Methods::TOOLS_CALL, owner: alice) { |_task| { content: [] } } + + assert_same task, @manager.get_task(task_id: task.task_id, owner: alice) + [bob, nil].each do |other| + error = assert_raises(TaskManager::TaskNotFound) { @manager.get_task(task_id: task.task_id, owner: other) } + assert_equal "Task not found: #{task.task_id}", error.message + assert_raises(TaskManager::TaskNotFound) { @manager.cancel_task(task_id: task.task_id, owner: other) } + end + end + + test "a task created without an owner is not found by an authenticated principal" do + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + + assert_same task, @manager.get_task(task_id: task.task_id) + assert_raises(TaskManager::TaskNotFound) do + @manager.get_task(task_id: task.task_id, owner: ["https://as.example", "alice", "app"]) + end + end + + test "create_task refuses a task beyond max_tasks" do + manager = TaskManager.new(executor: TaskExecutor::Synchronous.new, max_tasks: 2) + 2.times { manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } } + ran = false + + assert_raises(TaskManager::CapacityExceeded) do + manager.create_task(method: Methods::TOOLS_CALL) { |_task| ran = true } + end + refute ran + end + + test "create_task drops expired tasks nobody polled and asks a running one to stop" do + store = TaskRegistry::InMemory.new + executor = Class.new(TaskExecutor) { def execute(&block); end }.new + # The executor never runs the work, so the first task's work stays scheduled next to the second's. + manager = TaskManager.new(store: store, executor: executor, ttl_ms: 5, max_tasks: 2) + stale = manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + sleep 0.05 + + fresh = manager.create_task(method: Methods::TOOLS_CALL) { |_task| { content: [] } } + + assert_equal 1, store.size + assert_same fresh, store.find(fresh.task_id) + assert_predicate stale, :cancelled? + end + + test "create_task keeps the error code of code-bearing exceptions" do + error = Server::RequestHandlerError.new( + "bad params", + nil, + error_type: :invalid_params, + error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS, + ) + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise error } + + assert_equal Task::STATUS_FAILED, task.status + assert_equal(-32602, task.error[:code]) + end + + test "create_task reports the work exception" do + reported = [] + manager = TaskManager.new( + executor: TaskExecutor::Synchronous.new, + exception_reporter: ->(exception, context) { reported << [exception, context] }, + ) + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| raise "boom" } + + assert_equal 1, reported.size + assert_equal Task::STATUS_FAILED, task.status + assert_equal "boom", reported.first.first.message + assert_equal task.task_id, reported.first.last[:task_id] + end + + test "a tool result with isError true still completes the task" do + result = { content: [{ type: "text", text: "bad" }], isError: true } + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_task| result } + + assert_equal Task::STATUS_COMPLETED, task.status + assert_equal result, task.result + end + + test "get_task raises TaskNotFound for unknown ids" do + assert_raises(TaskManager::TaskNotFound) do + @manager.get_task(task_id: "missing") + end + end + + test "get_task rejects non-string task ids" do + assert_raises(TaskManager::InvalidTaskRequest) do + @manager.get_task(task_id: 123) + end + end + + test "get_task raises TaskNotFound once the ttl elapsed" do + manager = TaskManager.new(executor: TaskExecutor::Synchronous.new, ttl_ms: 5) + task = manager.create_task(method: Methods::TOOLS_CALL) { |_task| {} } + + sleep 0.05 + + assert_raises(TaskManager::TaskNotFound) do + manager.get_task(task_id: task.task_id) + end + end + + test "cancel_task on an already-terminal task is a no-op" do + task = @manager.create_task(method: Methods::TOOLS_CALL) { |_t| { content: [] } } + + cancelled = @manager.cancel_task(task_id: task.task_id) + assert_same task, cancelled + assert_equal Task::STATUS_COMPLETED, task.status + end + + test "cancel_task raises TaskNotFound for unknown ids" do + assert_raises(TaskManager::TaskNotFound) do + @manager.cancel_task(task_id: "missing") + end + end + + test "cancel_task flips cooperative flag and transitions cancelled with async executor" do + manager = TaskManager.new(executor: TaskExecutor::Thread.new) + + gate = Queue.new + started = Queue.new + + task = manager.create_task(method: Methods::TOOLS_CALL) do |_t| + started << :ok + gate.pop + { content: [] } + end + + started.pop + + cancelled = manager.cancel_task(task_id: task.task_id) + assert_equal Task::STATUS_CANCELLED, cancelled.status + assert task.cancelled? + + gate << :go + # allow the executor thread to finish + sleep 0.05 + + # Terminal state must stick even if worker completes afterwards. + assert_equal Task::STATUS_CANCELLED, task.status + end + end + end +end diff --git a/test/mcp/server/task_registry/in_memory_test.rb b/test/mcp/server/task_registry/in_memory_test.rb new file mode 100644 index 00000000..c915aa56 --- /dev/null +++ b/test/mcp/server/task_registry/in_memory_test.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class Server + class TaskRegistry + class InMemoryTest < ActiveSupport::TestCase + def build_task(id:, ttl_ms: 60_000) + Task.new( + task_id: id, + request_method: Methods::TOOLS_CALL, + ttl_ms: ttl_ms, + ) + end + + setup do + @store = InMemory.new + end + + test "save and find returns the same task" do + task = build_task(id: "a") + @store.save(task) + assert_same task, @store.find("a") + end + + test "find returns nil for unknown id" do + assert_nil @store.find("missing") + end + + test "find does not return an expired task and leaves it for delete_expired" do + task = build_task(id: "short", ttl_ms: 5) + @store.save(task) + sleep 0.05 + + assert_nil @store.find("short") + assert_equal [task], @store.delete_expired + end + + test "find keeps tasks with null ttl_ms forever" do + task = build_task(id: "unlimited", ttl_ms: nil) + @store.save(task) + assert_same task, @store.find("unlimited") + end + + test "delete_expired removes expired tasks nobody looked up and returns them" do + expired = build_task(id: "short", ttl_ms: 5) + @store.save(expired) + @store.save(build_task(id: "long")) + sleep 0.05 + + assert_equal [expired], @store.delete_expired + assert_equal 1, @store.size + assert_empty @store.delete_expired + end + + test "size counts the tasks held" do + assert_equal 0, @store.size + @store.save(build_task(id: "a")) + @store.save(build_task(id: "b")) + + assert_equal 2, @store.size + end + + test "delete removes the task" do + @store.save(build_task(id: "x")) + @store.delete("x") + assert_nil @store.find("x") + end + end + end + end +end diff --git a/test/mcp/server/task_test.rb b/test/mcp/server/task_test.rb new file mode 100644 index 00000000..f6b20a62 --- /dev/null +++ b/test/mcp/server/task_test.rb @@ -0,0 +1,214 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class Server + class TaskTest < ActiveSupport::TestCase + def new_task + Task.new( + task_id: "task-1", + request_method: Methods::TOOLS_CALL, + ttl_ms: 60_000, + poll_interval_ms: 5_000, + ) + end + + test "initializes with working status" do + task = new_task + assert_equal Task::STATUS_WORKING, task.status + refute task.terminal? + refute task.cancelled? + assert_nil task.result + assert_kind_of Time, task.created_at + assert_equal task.created_at, task.last_updated_at + end + + test "transitions from working to input_required and back" do + task = new_task + task.transition_to(Task::STATUS_INPUT_REQUIRED, message: "need creds") + assert_equal Task::STATUS_INPUT_REQUIRED, task.status + assert_equal "need creds", task.status_message + + task.transition_to(Task::STATUS_WORKING) + assert_equal Task::STATUS_WORKING, task.status + end + + test "completed is terminal and stores result" do + task = new_task + payload = { content: [{ type: "text", text: "ok" }] } + task.transition_to(Task::STATUS_COMPLETED, result: payload) + assert task.terminal? + assert_equal payload, task.result + end + + test "rejects transitions from terminal statuses" do + task = new_task + task.transition_to(Task::STATUS_COMPLETED, result: {}) + assert_raises(Task::IllegalStateTransition) do + task.transition_to(Task::STATUS_FAILED) + end + end + + test "rejects self-transition from working to working" do + task = new_task + assert_raises(Task::IllegalStateTransition) do + task.transition_to(Task::STATUS_WORKING) + end + end + + test "rejects unknown status" do + task = new_task + assert_raises(Task::IllegalStateTransition) do + task.transition_to("bogus") + end + end + + test "expired? respects ttl_ms" do + task = Task.new( + task_id: "t", + request_method: Methods::TOOLS_CALL, + ttl_ms: 10, # 10 ms + ) + refute task.expired? + sleep 0.05 + assert task.expired? + end + + test "expired? returns false when ttl_ms is nil" do + task = Task.new(task_id: "t", request_method: Methods::TOOLS_CALL, ttl_ms: nil) + refute task.expired? + end + + test "request_cancel! sets cooperative cancel flag without transitioning" do + task = new_task + task.request_cancel! + assert task.cancelled? + assert_equal Task::STATUS_WORKING, task.status + end + + test "to_wire_hash includes required camelCase fields" do + task = new_task + task.transition_to(Task::STATUS_INPUT_REQUIRED, message: "input please") + hash = task.to_wire_hash + assert_equal "task-1", hash[:taskId] + assert_equal Task::STATUS_INPUT_REQUIRED, hash[:status] + assert_equal "input please", hash[:statusMessage] + assert_equal 60_000, hash[:ttlMs] + assert_equal 5_000, hash[:pollIntervalMs] + assert_match(/\A\d{4}-\d{2}-\d{2}T/, hash[:createdAt]) + assert_match(/\A\d{4}-\d{2}-\d{2}T/, hash[:lastUpdatedAt]) + end + + test "to_wire_hash omits nil statusMessage and pollIntervalMs but keeps null ttlMs" do + task = Task.new( + task_id: "t", + request_method: Methods::TOOLS_CALL, + ttl_ms: nil, + ) + hash = task.to_wire_hash + refute hash.key?(:statusMessage) + refute hash.key?(:pollIntervalMs) + assert hash.key?(:ttlMs) + assert_nil hash[:ttlMs] + end + + test "to_detailed_hash inlines result on completed" do + task = new_task + payload = { content: [], isError: false } + task.transition_to(Task::STATUS_COMPLETED, result: payload) + hash = task.to_detailed_hash + assert_equal Task::STATUS_COMPLETED, hash[:status] + assert_equal payload, hash[:result] + refute hash.key?(:error) + end + + test "to_detailed_hash inlines error on failed" do + task = new_task + error = { code: -32603, message: "kaboom" } + task.transition_to(Task::STATUS_FAILED, message: "kaboom", error: error) + hash = task.to_detailed_hash + assert_equal Task::STATUS_FAILED, hash[:status] + assert_equal error, hash[:error] + refute hash.key?(:result) + end + + test "to_detailed_hash carries no status-specific member while working" do + hash = new_task.to_detailed_hash + refute hash.key?(:result) + refute hash.key?(:error) + end + + test "to_create_result_hash is flat with resultType task" do + hash = new_task.to_create_result_hash + assert_equal "task", hash[:resultType] + assert_equal "task-1", hash[:taskId] + assert_equal Task::STATUS_WORKING, hash[:status] + end + + test "finish records a terminal status once" do + task = new_task + + assert task.finish(Task::STATUS_COMPLETED, result: { content: [] }) + refute task.finish(Task::STATUS_FAILED, message: "late", error: { code: -32603, message: "late" }) + assert_equal Task::STATUS_COMPLETED, task.status + assert_nil task.error + end + + test "cancel! cancels a running task and leaves a finished one alone" do + running = new_task + assert running.cancel!("stop") + assert_equal Task::STATUS_CANCELLED, running.status + assert_equal "stop", running.status_message + assert_predicate running, :cancelled? + + finished = new_task + finished.finish(Task::STATUS_COMPLETED, result: {}) + refute finished.cancel!("stop") + assert_equal Task::STATUS_COMPLETED, finished.status + refute_predicate finished, :cancelled? + end + + test "of a completion and a cancellation that race, exactly one is recorded" do + 50.times do + task = new_task + outcomes = [ + Thread.new { task.finish(Task::STATUS_COMPLETED, result: {}) }, + Thread.new { task.cancel!("stop") }, + ].map(&:value) + + assert_equal [false, true], outcomes.sort_by(&:to_s) + end + end + + test "update_status_message does not change a finished task" do + task = new_task + task.finish(Task::STATUS_FAILED, message: "Internal error", error: { code: -32603, message: "Internal error" }) + task.update_status_message("still working") + + assert_equal "Internal error", task.status_message + end + + test "a task records its owner" do + task = Task.new(task_id: "task-2", request_method: Methods::TOOLS_CALL, owner: ["https://as.example", "alice", "app"]) + + assert_equal ["https://as.example", "alice", "app"], task.owner + assert_nil new_task.owner + end + + test "wait_for_terminal blocks until terminal status is reached" do + task = new_task + + waiter = Thread.new do + task.wait_for_terminal + :done + end + Thread.pass + refute waiter.join(0.05) + + task.transition_to(Task::STATUS_COMPLETED, result: {}) + assert_equal :done, waiter.value + end + end + end +end diff --git a/test/mcp/server_task_store_test.rb b/test/mcp/server_task_store_test.rb new file mode 100644 index 00000000..33d1ca17 --- /dev/null +++ b/test/mcp/server_task_store_test.rb @@ -0,0 +1,425 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + # The `task_store:` of a server: the records it writes for its tasks, and what another server reads from them. + # Two servers that share one store stand in for two processes. + class ServerTaskStoreTest < ActiveSupport::TestCase + TASKS_CAPABILITY = { extensions: { Tasks::EXTENSION_ID => {} } }.freeze + + class Store + attr_reader :records, :expirations + attr_accessor :failing, :failing_after_write + + def initialize + @records = {} + @expirations = {} + @failing = false + end + + def write(task_id, record, expires_in:) + raise IOError, "the store is down" if failing + + @records[task_id] = record + @expirations[task_id] = expires_in + raise IOError, "the acknowledgement was lost" if failing_after_write + end + + def read(task_id) + @records[task_id] + end + + def delete(task_id) + @records.delete(task_id) + end + end + + # Holds every write after the first until the test lets it go. + class SlowStore < Store + attr_reader :entered, :release + + def initialize + super + @entered = Queue.new + @release = Queue.new + @writes = 0 + end + + def write(task_id, record, expires_in:) + if (@writes += 1) > 1 + @entered << true + @release.pop + end + super + end + end + + # Runs each work block on demand, keeping tasks in `working` until the test releases them. + class GatedExecutor < Server::TaskExecutor + def initialize + super + @blocks = Queue.new + end + + def execute(&block) + @blocks << block + end + + def run! + @blocks.pop.call until @blocks.empty? + end + end + + setup do + @store = Store.new + @reported = [] + @echo_tool = Tool.define( + name: "echo", + input_schema: { properties: { text: { type: "string" } }, required: ["text"] }, + ) do |text:, server_context: nil| + server_context&.task&.update_status_message("echoing") + Tool::Response.new([{ type: "text", text: text }]) + end + @first = build_server + @second = build_server + end + + test "another server answers tasks/get for a task from its record" do + task_id = @first.handle(tool_call(text: "hello")).dig(:result, :taskId) + + here = @first.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + there = @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal "completed", there[:status] + assert_equal "echoing", there[:statusMessage] + assert_equal "hello", there.dig(:result, "content", 0, "text") + assert_equal JSON.parse(JSON.generate(here)), JSON.parse(JSON.generate(there)) + end + + test "the record is written before the CreateTaskResult returns and again after each change" do + executor = GatedExecutor.new + first = build_server(executor: executor) + + task_id = first.handle(tool_call(text: "later")).dig(:result, :taskId) + assert_equal "working", @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + + executor.run! + assert_equal "completed", @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + end + + test "a status message a tool publishes reaches the record while the tool runs" do + store = @store + seen = [] + tool = Tool.define(name: "reporter") do |server_context:| + server_context.task.update_status_message("halfway") + seen << JSON.parse(store.read(server_context.task.task_id)).dig("task", "statusMessage") + Tool::Response.new([{ type: "text", text: "done" }]) + end + + build_server(tools: [tool]).handle(tool_call(name: "reporter", arguments: {})) + + assert_equal ["halfway"], seen + end + + test "a record is served to the principal that created the task only" do + alice = access_token(subject: "alice") + task_id = @first.handle(tool_call(text: "private"), auth_info: alice).dig(:result, :taskId) + unknown = @second.handle(tasks_request(Methods::TASKS_GET, task_id: "no-such-task"), auth_info: alice)[:error] + + others = [ + access_token(subject: "bob"), + access_token(subject: "alice", client_id: "other-app"), + access_token(subject: "alice", issuer: "https://other.example"), + nil, + ] + others.each do |other| + [Methods::TASKS_GET, Methods::TASKS_CANCEL].each do |method| + error = @second.handle(tasks_request(method, task_id: task_id), auth_info: other)[:error] + + assert_equal(-32602, error[:code]) + # Indistinguishable from an id that does not exist. + assert_equal unknown[:message].sub("no-such-task", task_id), error[:message] + end + end + + result = @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id), auth_info: alice)[:result] + assert_equal "completed", result[:status] + end + + test "the record of a task created without a token is not served to a token" do + task_id = @first.handle(tool_call(text: "open")).dig(:result, :taskId) + + error = @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id), auth_info: access_token(subject: "alice"))[:error] + + assert_equal(-32602, error[:code]) + end + + test "a record that has outlived its retention is not served, whatever the store kept" do + task_id = @first.handle(tool_call(text: "old")).dig(:result, :taskId) + record = JSON.parse(@store.records[task_id]) + @store.records[task_id] = JSON.generate(record.merge("expiresAt" => Time.now.to_f - 1)) + + error = @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:error] + + assert_equal(-32602, error[:code]) + end + + test "what a store returns is served only when it is the record of the task asked for" do + task_id = @first.handle(tool_call(text: "real")).dig(:result, :taskId) + record = JSON.parse(@store.records[task_id]) + # Apart from the first, which is the record of another task, each names the task asked for, + # so it is refused for its own defect. + renamed = record.merge("task" => record["task"].merge("taskId" => "another-id")) + bad_records = [ + @store.records[task_id], + "not json", + "[]", + "{}", + renamed, + JSON.generate(renamed.merge("task" => renamed["task"].merge("status" => "paused"))), + JSON.generate(renamed.reject { |key, _value| key == "owner" }), + JSON.generate(renamed.reject { |key, _value| key == "expiresAt" }), + JSON.generate(renamed.merge("owner" => ["https://as.example", "alice", "app"])), + JSON.generate(renamed).sub(/"expiresAt":[^,}]+/, "\"expiresAt\":1e400"), + JSON.generate(renamed.merge("task" => renamed["task"].merge("result" => 5))), + JSON.generate(renamed.merge("task" => renamed["task"].merge("status" => "working"))), + JSON.generate(renamed.merge("task" => renamed["task"].merge("error" => { "code" => -32603 }))), + JSON.generate(renamed.merge("task" => renamed["task"].merge("ttlMs" => "forever"))), + JSON.generate(renamed.merge("task" => renamed["task"].reject { |key, _value| key == "createdAt" })), + ] + @store.records["another-id"] = JSON.generate(renamed) + assert_equal "completed", @second.handle(tasks_request(Methods::TASKS_GET, task_id: "another-id")).dig(:result, :status) + + bad_records.each do |bad_record| + @store.records["another-id"] = bad_record + + error = @second.handle(tasks_request(Methods::TASKS_GET, task_id: "another-id"))[:error] + + assert_equal(-32602, error[:code], "served #{bad_record.inspect}") + end + end + + test "tasks/cancel for a task of another server is acknowledged and changes nothing" do + executor = GatedExecutor.new + first = build_server(executor: executor) + task_id = first.handle(tool_call(text: "running")).dig(:result, :taskId) + + result = @second.handle(tasks_request(Methods::TASKS_CANCEL, task_id: task_id))[:result] + + assert_equal({ resultType: "complete" }, result) + assert_equal "working", first.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + executor.run! + assert_equal "completed", @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + end + + test "a task whose record cannot be written is not created, and its place is given back" do + server = build_server(max_tasks: 1) + @store.failing = true + + result = server.handle(tool_call(text: "now"))[:result] + + assert_equal "complete", result[:resultType] + assert_equal "now", result.dig(:content, 0, :text) + assert_equal ["the store is down"], @reported.map(&:message) + + @store.failing = false + assert_equal "task", server.handle(tool_call(text: "again")).dig(:result, :resultType) + end + + test "a first write that fails after the store kept the record leaves no record" do + @store.failing_after_write = true + + result = @first.handle(tool_call(text: "now"))[:result] + + assert_equal "complete", result[:resultType] + assert_empty @store.records + end + + test "a task that is gone before its record is written gets no record and leaves no writer" do + Server::TaskRegistry::InMemory.any_instance.stubs(:find).returns(nil) + + result = @first.handle(tool_call(text: "gone"))[:result] + + assert_equal "task", result[:resultType] + assert_empty @store.records + assert_empty @first.instance_variable_get(:@task_manager).instance_variable_get(:@record_writers) + end + + test "a request that requires a task is refused while its record cannot be written" do + server = build_server(augmentation: ->(_request) { :required }) + @store.failing = true + + error = server.handle(tool_call(text: "now"))[:error] + + assert_equal(-32603, error[:code]) + assert_empty @store.records + end + + test "a later record that cannot be written is reported and leaves the task as it is" do + executor = GatedExecutor.new + first = build_server(executor: executor) + task_id = first.handle(tool_call(text: "running")).dig(:result, :taskId) + @store.failing = true + + executor.run! + + assert_includes @reported.map(&:message), "the store is down" + assert_equal "completed", first.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + assert_equal "working", @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :status) + end + + test "a record is kept for the time the task has left" do + task_id = build_server(task_ttl_ms: 60_000).handle(tool_call(text: "hi")).dig(:result, :taskId) + + assert_operator @store.expirations[task_id], :>, 0 + assert_operator @store.expirations[task_id], :<=, 60 + end + + test "the record of an expired task is deleted when the task is discarded" do + task_id = @first.handle(tool_call(text: "old")).dig(:result, :taskId) + assert @store.records.key?(task_id) + Server::Task.any_instance.stubs(:expired?).returns(true) + + error = @first.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:error] + + assert_equal(-32602, error[:code]) + refute @store.records.key?(task_id) + end + + test "a change of a task whose retention has ended deletes the record instead of writing it" do + executor = GatedExecutor.new + first = build_server(executor: executor) + task_id = first.handle(tool_call(text: "late")).dig(:result, :taskId) + Server::TaskRecord.stubs(:expires_at).returns(Time.now.utc - 1) + + executor.run! + + refute @store.records.key?(task_id) + end + + test "a write that was waiting when its task was discarded does not bring the record back" do + store = SlowStore.new + executor = GatedExecutor.new + # The tool publishes nothing, so the only write after the first is that of the finished task. + quiet_tool = Tool.define(name: "quiet") { |**| Tool::Response.new([{ type: "text", text: "done" }]) } + server = build_server(tools: [quiet_tool], store: store, executor: executor) + task_id = server.handle(tool_call(name: "quiet", arguments: {})).dig(:result, :taskId) + writing = Thread.new { executor.run! } + wait_until { !store.entered.empty? } + Server::Task.any_instance.stubs(:expired?).returns(true) + + # The task has finished, so discarding it changes nothing about it and only deletes its record, + # which has to wait for the write in progress instead of being overtaken by it. + discarding = Thread.new { server.handle(tasks_request(Methods::TASKS_GET, task_id: "another-id")) } + wait_until { discarding.status == "sleep" || !discarding.alive? } + store.release << true + + assert writing.join(5), "the write did not finish" + assert discarding.join(5), "the discard did not finish" + refute store.records.key?(task_id) + ensure + [writing, discarding].compact.each(&:kill) + end + + test "a store that fails is an internal error for an id of another owner as for an unknown id" do + alice = access_token(subject: "alice") + task_id = @first.handle(tool_call(text: "private"), auth_info: alice).dig(:result, :taskId) + @store.stubs(:read).raises(IOError, "the store is down") + + [task_id, "no-such-task"].each do |id| + error = @first.handle(tasks_request(Methods::TASKS_GET, task_id: id), auth_info: access_token(subject: "bob"))[:error] + + assert_equal(-32603, error[:code]) + end + end + + test "a record is served through the members of a task only" do + task_id = @first.handle(tool_call(text: "plain")).dig(:result, :taskId) + record = JSON.parse(@store.records[task_id]) + record["task"].merge!("resultType" => "task", "extra" => "smuggled") + @store.records[task_id] = JSON.generate(record) + + result = @second.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal "complete", result[:resultType] + refute result.key?(:extra) + end + + test "a task store has to respond to write, read and delete" do + incomplete = Class.new do + def write(task_id, record, expires_in:); end + + def delete(task_id); end + end + + error = assert_raises(ArgumentError) { build_server(store: incomplete.new) } + + assert_match(/`write`, `read` and `delete`/, error.message) + end + + test "a task store is refused for tasks that are kept without a time limit" do + error = assert_raises(ArgumentError) { build_server(task_ttl_ms: nil) } + + assert_match(/ttl_ms/, error.message) + end + + private + + def build_server( + tools: [@echo_tool], + store: @store, + augmentation: ->(_request) { true }, + executor: Server::TaskExecutor::Synchronous.new, + **options + ) + configuration = MCP::Configuration.new + configuration.exception_reporter = ->(exception, _context) { @reported << exception } + Server.new( + name: "task_store_test_server", + tools: tools, + configuration: configuration, + task_augmentation: augmentation, + task_store: store, + task_executor: executor, + **options, + ) + end + + def wait_until + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + until yield + flunk("the condition was not met in time") if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + sleep(0.005) + end + end + + def tool_call(text: nil, name: "echo", arguments: nil) + arguments ||= { text: text } + modern_request(Methods::TOOLS_CALL, { name: name, arguments: arguments }) + end + + def access_token(subject:, client_id: "app", issuer: "https://as.example") + Server::OAuth::AccessToken.new(token: "token-of-#{subject}", client_id: client_id, subject: subject, issuer: issuer) + end + + def tasks_request(method, task_id:) + modern_request(method, { taskId: task_id }) + end + + def modern_request(method, params) + { + jsonrpc: "2.0", + method: method, + id: 1, + params: params.merge( + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" }, + "io.modelcontextprotocol/clientCapabilities": TASKS_CAPABILITY, + }, + ), + } + end + end +end diff --git a/test/mcp/server_tasks_extension_test.rb b/test/mcp/server_tasks_extension_test.rb new file mode 100644 index 00000000..0d04503c --- /dev/null +++ b/test/mcp/server_tasks_extension_test.rb @@ -0,0 +1,488 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + # Integration tests for the SEP-2663 Tasks extension over `Server#handle`. + class ServerTasksExtensionTest < ActiveSupport::TestCase + TASKS_CAPABILITY = { extensions: { Tasks::EXTENSION_ID => {} } }.freeze + + setup do + @echo_tool = Tool.define( + name: "echo", + input_schema: { properties: { text: { type: "string" } }, required: ["text"] }, + ) do |text:, server_context: nil| + server_context&.task&.update_status_message("echoing") + Tool::Response.new([{ type: "text", text: text }]) + end + + @server = build_server(tools: [@echo_tool]) + end + + test "a task-augmented tools/call returns a CreateTaskResult" do + response = @server.handle(tool_call(text: "hi")) + result = response[:result] + + assert_equal "task", result[:resultType] + assert_kind_of String, result[:taskId] + assert_match(/\A\d{4}-\d{2}-\d{2}T/, result[:createdAt]) + assert_match(/\A\d{4}-\d{2}-\d{2}T/, result[:lastUpdatedAt]) + assert result.key?(:ttlMs) + assert_kind_of Integer, result[:pollIntervalMs] + end + + test "tasks/get inlines the final tool result on completed" do + task_id = @server.handle(tool_call(text: "hello")).dig(:result, :taskId) + + response = @server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)) + result = response[:result] + + assert_equal "complete", result[:resultType] + assert_equal "completed", result[:status] + assert_equal "echoing", result[:statusMessage] + assert_equal "hello", result.dig(:result, :content, 0, :text) + refute result.key?(:error) + end + + test "a raising tool surfaces as failed with the JSON-RPC error inlined" do + boom = Tool.define(name: "boom") { |**| raise "kaboom" } + server = build_server(tools: [boom]) + + task_id = server.handle(tool_call(name: "boom", arguments: {})).dig(:result, :taskId) + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal "failed", result[:status] + # As for a synchronous `tools/call`, the exception's own message does not reach the client. + assert_equal({ code: -32603, message: "Internal error", data: "Internal error calling tool boom" }, result[:error]) + assert_equal "Internal error calling tool boom", result[:statusMessage] + refute result.key?(:result) + end + + test "the error of a failed task is the JSON-RPC error the same call answers synchronously" do + tools = [ + Tool.define(name: "boom") { |**| raise "kaboom" }, + Tool.define(name: "refusing") do |**| + raise Server::RequestHandlerError.new("Quota exceeded", nil, error_type: :invalid_params, error_data: { limit: 1 }) + end, + Tool.define(name: "plain") { |**| raise Server::RequestHandlerError.new("Not now", nil, error_type: :invalid_request) }, + Tool.define(name: "coded") do |**| + raise Server::RequestHandlerError.new("Too busy", nil, error_type: :internal_error, error_code: -32001) + end, + Tool.define(name: "false_data") do |**| + raise Server::RequestHandlerError.new("Refused", nil, error_type: :invalid_params, error_data: false) + end, + ] + as_tasks = build_server(tools: tools) + synchronous = build_server(tools: tools, augmentation: ->(_request) { false }) + + tools.map(&:name_value).each do |name| + task_id = as_tasks.handle(tool_call(name: name, arguments: {})).dig(:result, :taskId) + task_error = as_tasks.handle(tasks_request(Methods::TASKS_GET, task_id: task_id)).dig(:result, :error) + + assert_equal synchronous.handle(tool_call(name: name, arguments: {}))[:error], task_error, "tool: #{name}" + end + end + + test "an error a tool raises for the client keeps its code, message and data in the failed task" do + refusing = Tool.define(name: "refusing") do |**| + raise Server::RequestHandlerError.new("Quota exceeded", nil, error_type: :invalid_params, error_data: { limit: 1 }) + end + server = build_server(tools: [refusing]) + + task_id = server.handle(tool_call(name: "refusing", arguments: {})).dig(:result, :taskId) + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal({ code: -32602, message: "Invalid params", data: { limit: 1 } }, result[:error]) + assert_equal "Quota exceeded", result[:statusMessage] + end + + test "a task is served to the principal that created it only" do + alice = access_token(subject: "alice") + bob = access_token(subject: "bob") + server = build_server(tools: [@echo_tool], executor: GatedExecutor.new) + task_id = server.handle(tool_call(text: "private"), auth_info: alice).dig(:result, :taskId) + unknown = server.handle(tasks_request(Methods::TASKS_GET, task_id: "no-such-task"), auth_info: bob)[:error] + + [bob, access_token(subject: "alice", client_id: "other-app"), access_token(subject: "alice", issuer: "https://other.example"), nil].each do |other| + [Methods::TASKS_GET, Methods::TASKS_CANCEL].each do |method| + error = server.handle(tasks_request(method, task_id: task_id), auth_info: other)[:error] + + assert_equal(-32602, error[:code]) + # Indistinguishable from an id that does not exist. + assert_equal unknown[:message].sub("no-such-task", task_id), error[:message] + end + end + + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id), auth_info: alice)[:result] + assert_equal "working", result[:status] + end + + test "a token that names neither a subject nor a client gets no task" do + anonymous_token = Server::OAuth::AccessToken.new(token: "opaque", scopes: ["mcp"]) + other_anonymous_token = Server::OAuth::AccessToken.new(token: "another", scopes: ["mcp"]) + server = build_server(tools: [@echo_tool], executor: GatedExecutor.new) + + result = server.handle(tool_call(text: "sync"), auth_info: anonymous_token)[:result] + assert_equal "complete", result[:resultType] + assert_equal "sync", result.dig(:content, 0, :text) + + required = build_server(tools: [@echo_tool], augmentation: ->(_request) { :required }) + error = required.handle(tool_call(text: "refused"), auth_info: anonymous_token)[:error] + assert_equal(-32603, error[:code]) + assert_equal "A task needs a token that names a subject or a client", error[:message] + + # Nor does such a token find a task: not one created without a token, and not one "of" another such token. + task_id = server.handle(tool_call(text: "hi")).dig(:result, :taskId) + [anonymous_token, other_anonymous_token].each do |token| + error = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id), auth_info: token)[:error] + assert_equal "Task not found: #{task_id}", error[:message] + end + end + + test "a task whose work starts after the creator's token expired fails" do + ran = false + tool = Tool.define(name: "late") do |**| + ran = true + Tool::Response.new([{ type: "text", text: "done" }]) + end + token = access_token(subject: "alice") + executor = GatedExecutor.new + server = build_server(tools: [tool], executor: executor) + task_id = server.handle(tool_call(name: "late", arguments: {}), auth_info: token).dig(:result, :taskId) + + token.stubs(:expired?).returns(true) + executor.run! + + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id), auth_info: token)[:result] + assert_equal "failed", result[:status] + assert_equal "The authorization the task was created with has expired", result.dig(:error, :data) + refute ran + end + + test "a token whose subject and client are blank gets no task either" do + blank = Server::OAuth::AccessToken.new(token: "opaque", subject: "", client_id: "") + server = build_server(tools: [@echo_tool], executor: GatedExecutor.new) + + result = server.handle(tool_call(text: "sync"), auth_info: blank)[:result] + + assert_equal "complete", result[:resultType] + end + + test "a task method that finds no task is not reported as an exception" do + reported = [] + configuration = MCP::Configuration.new + configuration.exception_reporter = ->(exception, _context) { reported << exception } + server = Server.new( + name: "tasks_test_server", + tools: [@echo_tool], + configuration: configuration, + task_augmentation: ->(_request) { true }, + task_executor: Server::TaskExecutor::Synchronous.new, + ) + + [Methods::TASKS_GET, Methods::TASKS_CANCEL].each do |method| + error = server.handle(tasks_request(method, task_id: "no-such-task"))[:error] + + assert_equal(-32602, error[:code]) + end + assert_empty reported + + # Any other invalid request to a task method still is. + server.handle(tasks_request(Methods::TASKS_GET, task_id: 7)) + assert_equal 1, reported.size + end + + test "a tool that runs as a task sees the authorization of the request that created it" do + seen = nil + tool = Tool.define(name: "whoami") do |server_context:| + seen = server_context.auth_info + Tool::Response.new([{ type: "text", text: "ok" }]) + end + alice = access_token(subject: "alice") + + build_server(tools: [tool]).handle(tool_call(name: "whoami", arguments: {}), auth_info: alice) + + assert_same alice, seen + end + + test "a request that does not require a task runs synchronously while the store is full" do + server = Server.new( + name: "tasks_test_server", + tools: [@echo_tool], + task_augmentation: ->(_request) { true }, + task_executor: Server::TaskExecutor::Synchronous.new, + max_tasks: 1, + ) + assert_equal "task", server.handle(tool_call(text: "first")).dig(:result, :resultType) + + result = server.handle(tool_call(text: "second"))[:result] + + assert_equal "complete", result[:resultType] + assert_equal "second", result.dig(:content, 0, :text) + end + + test "a request that requires a task is refused while the store is full" do + server = Server.new( + name: "tasks_test_server", + tools: [@echo_tool], + task_augmentation: ->(_request) { :required }, + task_executor: Server::TaskExecutor::Synchronous.new, + max_tasks: 1, + ) + server.handle(tool_call(text: "first")) + + error = server.handle(tool_call(text: "second"))[:error] + + assert_equal(-32603, error[:code]) + assert_equal "The server cannot accept another task at the moment", error[:message] + end + + test "task_ttl_ms and task_poll_interval_ms set what a task advertises" do + server = Server.new( + name: "tasks_test_server", + tools: [@echo_tool], + task_augmentation: ->(_request) { true }, + task_executor: Server::TaskExecutor::Synchronous.new, + task_ttl_ms: 60_000, + task_poll_interval_ms: 250, + ) + + result = server.handle(tool_call(text: "hi"))[:result] + + assert_equal 60_000, result[:ttlMs] + assert_equal 250, result[:pollIntervalMs] + end + + test "capabilities assigned later still declare the extension" do + @server.capabilities = { tools: { listChanged: true } } + + assert_equal({}, @server.capabilities.dig(:extensions, Tasks::EXTENSION_ID)) + assert_equal({ listChanged: true }, @server.capabilities[:tools]) + end + + test "a tool result with isError true completes the task" do + failing = Tool.define(name: "reports_error") do |**| + Tool::Response.new([{ type: "text", text: "bad" }], error: true) + end + server = build_server(tools: [failing]) + + task_id = server.handle(tool_call(name: "reports_error", arguments: {})).dig(:result, :taskId) + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal "completed", result[:status] + assert result.dig(:result, :isError) + end + + test "the CreateTaskResult is durably readable before it returns" do + server = build_server(tools: [@echo_tool], executor: gated_executor = GatedExecutor.new) + + task_id = server.handle(tool_call(text: "later")).dig(:result, :taskId) + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + + assert_equal "working", result[:status] + refute result.key?(:result) + + gated_executor.run! + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + assert_equal "completed", result[:status] + end + + test "tasks/cancel acknowledges with an empty result and cancels cooperatively" do + server = build_server(tools: [@echo_tool], executor: gated_executor = GatedExecutor.new) + task_id = server.handle(tool_call(text: "never")).dig(:result, :taskId) + + response = server.handle(tasks_request(Methods::TASKS_CANCEL, task_id: task_id)) + assert_equal({ resultType: "complete" }, response[:result]) + + gated_executor.run! + result = server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + assert_equal "cancelled", result[:status] + end + + test "tasks/cancel on an already-terminal task still acknowledges" do + task_id = @server.handle(tool_call(text: "done")).dig(:result, :taskId) + + response = @server.handle(tasks_request(Methods::TASKS_CANCEL, task_id: task_id)) + assert_equal({ resultType: "complete" }, response[:result]) + + result = @server.handle(tasks_request(Methods::TASKS_GET, task_id: task_id))[:result] + assert_equal "completed", result[:status] + end + + test "an unknown taskId answers -32602" do + response = @server.handle(tasks_request(Methods::TASKS_GET, task_id: "missing")) + assert_equal(-32602, response.dig(:error, :code)) + assert_match(/Task not found/, response.dig(:error, :message)) + end + + test "a non-string taskId answers -32602" do + response = @server.handle(tasks_request(Methods::TASKS_GET, task_id: 42)) + assert_equal(-32602, response.dig(:error, :code)) + end + + test "a legacy request to a tasks method answers -32601" do + response = @server.handle( + { jsonrpc: "2.0", id: 1, method: Methods::TASKS_GET, params: { taskId: "x" } }, + ) + assert_equal(-32601, response.dig(:error, :code)) + end + + test "a modern request without the extension declared answers -32021" do + response = @server.handle( + modern_request(Methods::TASKS_GET, { taskId: "x" }, capabilities: {}), + ) + assert_equal(-32021, response.dig(:error, :code)) + assert_equal( + { extensions: { Tasks::EXTENSION_ID => {} } }, + response.dig(:error, :data, :requiredCapabilities), + ) + end + + test "tools/call from a non-declaring client runs synchronously" do + response = @server.handle( + modern_request(Methods::TOOLS_CALL, { name: "echo", arguments: { text: "sync" } }, capabilities: {}), + ) + assert_equal "sync", response.dig(:result, :content, 0, :text) + # A synchronous modern result is the standard shape, not a task handle. + assert_equal "complete", response.dig(:result, :resultType) + end + + test "a legacy tools/call runs synchronously even when augmentation elects the request" do + response = @server.handle( + { jsonrpc: "2.0", id: 1, method: Methods::TOOLS_CALL, params: { name: "echo", arguments: { text: "legacy" } } }, + ) + assert_equal "legacy", response.dig(:result, :content, 0, :text) + end + + test "a required election against a non-declaring client answers -32021" do + server = build_server(tools: [@echo_tool], augmentation: ->(_request) { :required }) + + response = server.handle( + modern_request(Methods::TOOLS_CALL, { name: "echo", arguments: { text: "x" } }, capabilities: {}), + ) + assert_equal(-32021, response.dig(:error, :code)) + end + + test "the augmentation predicate elects per request" do + server = build_server( + tools: [@echo_tool], + augmentation: ->(request) { request.dig(:arguments, :text) == "async" }, + ) + + async_response = server.handle(tool_call(text: "async", server: server)) + sync_response = server.handle(tool_call(text: "sync", server: server)) + + assert_equal "task", async_response.dig(:result, :resultType) + assert_equal "sync", sync_response.dig(:result, :content, 0, :text) + end + + test "requests failing validation keep failing synchronously" do + response = @server.handle(tool_call(name: "echo", arguments: {})) + assert response.dig(:result, :isError) + assert_match(/Missing required arguments/, response.dig(:result, :content, 0, :text)) + end + + test "a server without task support answers -32601 for tasks methods" do + server = Server.new(name: "plain", tools: [@echo_tool]) + response = server.handle(tasks_request(Methods::TASKS_GET, task_id: "x")) + assert_equal(-32601, response.dig(:error, :code)) + end + + test "the removed experimental methods answer -32601" do + ["tasks/result", "tasks/list"].each do |method| + response = @server.handle( + modern_request(method, { taskId: "x" }, capabilities: TASKS_CAPABILITY), + ) + assert_equal(-32601, response.dig(:error, :code), "expected -32601 for #{method}") + end + end + + test "enabling tasks declares the extension capability" do + assert_equal({}, @server.capabilities.dig(:extensions, Tasks::EXTENSION_ID)) + end + + test "server/discover advertises the tasks extension" do + response = @server.handle({ jsonrpc: "2.0", id: 1, method: Methods::SERVER_DISCOVER }) + assert_equal({}, response.dig(:result, :capabilities, :extensions, Tasks::EXTENSION_ID)) + end + + test "task_store without task_augmentation is rejected" do + assert_raises(ArgumentError) do + Server.new(name: "misconfigured", task_store: Object.new) + end + end + + test "server_context.cancelled? reflects cooperative task cancellation" do + statuses = Queue.new + observing_tool = Tool.define(name: "observer") do |server_context:| + statuses << server_context.cancelled? + server_context.task.request_cancel! + statuses << server_context.cancelled? + Tool::Response.new([{ type: "text", text: "done" }]) + end + server = build_server(tools: [observing_tool]) + + server.handle(tool_call(name: "observer", arguments: {})) + + refute(statuses.pop) + assert(statuses.pop) + end + + private + + # Runs each work block on demand instead of at submission, keeping tasks + # in `working` until the test releases them. + class GatedExecutor < Server::TaskExecutor + def initialize + super + @blocks = Queue.new + end + + def execute(&block) + @blocks << block + end + + def run! + @blocks.pop.call until @blocks.empty? + end + end + + def build_server(tools:, augmentation: ->(_request) { true }, executor: Server::TaskExecutor::Synchronous.new) + Server.new( + name: "tasks_test_server", + tools: tools, + task_augmentation: augmentation, + task_executor: executor, + ) + end + + def tool_call(text: nil, name: "echo", arguments: nil, server: nil) + arguments ||= { text: text } + modern_request(Methods::TOOLS_CALL, { name: name, arguments: arguments }, capabilities: TASKS_CAPABILITY) + end + + def access_token(subject:, client_id: "app", issuer: "https://as.example") + Server::OAuth::AccessToken.new(token: "token-of-#{subject}", client_id: client_id, subject: subject, issuer: issuer) + end + + def tasks_request(method, task_id:) + modern_request(method, { taskId: task_id }, capabilities: TASKS_CAPABILITY) + end + + # Builds a request carrying the SEP-2575 modern `_meta` envelope. + def modern_request(method, params, version: "2026-07-28", capabilities: {}) + { + jsonrpc: "2.0", + method: method, + id: 1, + params: params.merge( + _meta: { + "io.modelcontextprotocol/protocolVersion": version, + "io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" }, + "io.modelcontextprotocol/clientCapabilities": capabilities, + }, + ), + } + end + end +end