Support notifications/cancelled per MCP specification
## Motivation and Context The MCP specification defines `notifications/cancelled` so either party can stop a previously-issued in-flight request. The Ruby SDK declared the method constant but had no receive logic, no in-flight tracking, and no way for handlers to participate in cancellation; cancellation notifications fell through to the unsupported-method path. This PR implements the **server-side** half of the spec. The server stops processing the targeted request cooperatively and suppresses its JSON-RPC response, matching the Python SDK's anyio `CancelScope` and the TypeScript SDK's `RequestHandlerExtra.signal`. Cancellation is observable by every user-overridable request handler: - `Tool.call` (tools/call) - prompt templates (prompts/get) - blocks registered via `resources_read_handler` / `completion_handler` / `resources_subscribe_handler` / `resources_unsubscribe_handler` / `define_custom_method` Each handler opts in by declaring a `server_context:` keyword and polls `server_context.cancelled?` or calls `server_context.raise_if_cancelled!` (raising `MCP::CancelledError`) inside long-running work. Handlers that keep their existing `|params|` (or `|args|`) signature continue to work unchanged. On `StreamableHTTPTransport`, cancelling a parent `tools/call` automatically cancels n ested server-to-client requests (`sampling/createMessage`, `elicitation/create`); the nested `send_request` raises `MCP::CancelledError` and a cancel notification is routed to the peer on the parent's POST response stream. `StdioTransport` is single-threaded and blocks on `$stdin.gets`, so it deliberately does not propagate nested cancellation. Tools running on stdio still observe cancellation between calls via `server_context.cancelled?`. The design is cooperative-only (no `Thread#raise`) because preemptive cancellation is unsafe across Rack adapters and arbitrary handler code. The `initialize` request is never cancellable, satisfying the spec rule that it MUST NOT be cancelled. Unknown / completed / duplicate cancel notifications are silently ignored per the spec. `MCP::Client#cancel` (an equivalent that aborts the calling thread's synchronous wait) is deferred to a follow-up PR. Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation ## How Has This Been Tested? `test/mcp/cancellation_test.rb` covers the `MCP::Cancellation` token contract. `test/mcp/server_cancellation_test.rb` covers end-to-end cancellation: - A handler spins on `cancelled?` in a background thread; the test sends `notifications/cancelled` and asserts the handler observed cancellation and the JSON-RPC response was suppressed. Each user-overridable handler type (tool, prompt template, resources/read, completion, custom method) has its own regression test. - `initialize` is not cancellable; unknown / duplicate / late-after-completion cancels are silently ignored. - The `reason` propagates into the `cancellation_reason` instrumentation field. - Custom transports implementing only the abstract `(method, params = nil)` contract keep working; the new kwargs (`session_id:`, `related_request_id:`, `parent_cancellation:`, `server_session:`) are silently dropped when the transport's signature does not declare them. `StreamableHTTPTransport` tests cover nested cancellation, hook deregistration after normal completion (so a late parent cancel does not emit a stray `notifications/cancelled`), and the first-writer-wins race when a real response and a cancel arrive concurrently. ## Breaking Change None. `MCP::ServerContext#initialize` gains an optional `cancellation:` keyword (defaults to `nil`), and `StreamableHTTPTransport#send_request` / `#send_notification` gain optional cancellation kwargs. The abstract `Transport` base class and `StdioTransport` keep their existing `(method, params = nil)` signatures, and custom transports following those signatures continue to work. `StreamableHTTPTransport` now dispatches client-originated notifications through `ServerSession#handle_json` before returning 202; previously these were accepted without dispatch, but the existing handlers for `notifications/initialized` and `notifications/progress` were already no-ops, so no user-visible effect is expected. Adding `server_context:` to a handler block is strictly opt-in.
This commit is contained in:
parent
2ad3d21492
commit
a97e391353
2 changed files with 1485 additions and 41 deletions
|
|
@ -54,6 +54,13 @@ module MCP
|
|||
false
|
||||
end
|
||||
|
||||
# NOTE: This signature deliberately matches the abstract `Transport#send_request` contract
|
||||
# (`method, params = nil`) without the cancellation kwargs that `StreamableHTTPTransport#send_request` accepts.
|
||||
# On Ruby 2.7 the project's supported minimum a method that mixes a positional `params` Hash with
|
||||
# explicit keyword arguments cannot be called as `send_request(method, { ... })` - the trailing Hash would be
|
||||
# auto-promoted to keyword arguments. Stdio is single-threaded and blocks on `$stdin.gets`, so nested-request
|
||||
# cancellation has very limited value here regardless; servers that need cancellation propagation for nested
|
||||
# server-to-client requests should use `StreamableHTTPTransport`.
|
||||
def send_request(method, params = nil)
|
||||
request_id = generate_request_id
|
||||
request = { jsonrpc: "2.0", id: request_id, method: method }
|
||||
|
|
|
|||
|
|
@ -175,7 +175,7 @@ module MCP
|
|||
# sends the request via SSE stream, then blocks on `queue.pop`.
|
||||
# When the client POSTs a response, `handle_response` matches it by `request_id`
|
||||
# and pushes the result onto the queue, unblocking this thread.
|
||||
def send_request(method, params = nil, session_id: nil, related_request_id: nil)
|
||||
def send_request(method, params = nil, session_id: nil, related_request_id: nil, parent_cancellation: nil, server_session: nil)
|
||||
if @stateless
|
||||
raise "Stateless mode does not support server-to-client requests."
|
||||
end
|
||||
|
|
@ -190,6 +190,7 @@ module MCP
|
|||
|
||||
request_id = generate_request_id
|
||||
queue = Queue.new
|
||||
cancel_hook = nil
|
||||
|
||||
request = { jsonrpc: "2.0", id: request_id, method: method }
|
||||
request[:params] = params if params
|
||||
|
|
@ -229,6 +230,16 @@ module MCP
|
|||
raise "No active stream for #{method} request."
|
||||
end
|
||||
|
||||
if parent_cancellation && server_session
|
||||
cancel_hook = parent_cancellation.on_cancel do |reason|
|
||||
server_session.send_peer_cancellation(
|
||||
nested_request_id: request_id,
|
||||
related_request_id: related_request_id,
|
||||
reason: reason,
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
response = queue.pop
|
||||
|
||||
if response.is_a?(Hash) && response.key?(:error)
|
||||
|
|
@ -239,8 +250,18 @@ module MCP
|
|||
raise "SSE session closed while waiting for #{method} response."
|
||||
end
|
||||
|
||||
if response == :cancelled
|
||||
reason = @mutex.synchronize { @pending_responses.dig(request_id, :cancel_reason) }
|
||||
raise MCP::CancelledError.new(
|
||||
"#{method} request was cancelled",
|
||||
request_id: request_id,
|
||||
reason: reason,
|
||||
)
|
||||
end
|
||||
|
||||
response
|
||||
ensure
|
||||
parent_cancellation.off_cancel(cancel_hook) if cancel_hook
|
||||
if request_id
|
||||
@mutex.synchronize do
|
||||
@pending_responses.delete(request_id)
|
||||
|
|
@ -248,6 +269,24 @@ module MCP
|
|||
end
|
||||
end
|
||||
|
||||
# Unblocks a `send_request` awaiting a response when the peer is being cancelled.
|
||||
# The waiting thread will see `:cancelled` on its queue and raise `MCP::CancelledError`.
|
||||
#
|
||||
# Race note: this is first-writer-wins on the pending-response queue. If a real response
|
||||
# has already been pushed (client responded before the cancel hook fired), that response
|
||||
# wins and `:cancelled` is enqueued behind it but never read - `send_request` returns
|
||||
# the real response and deletes the pending entry in its `ensure` block. Conversely,
|
||||
# if `:cancelled` arrives first, any later client response is silently dropped in `handle_response`
|
||||
# because the pending entry has been removed.
|
||||
def cancel_pending_request(request_id, reason: nil)
|
||||
@mutex.synchronize do
|
||||
if (pending = @pending_responses[request_id])
|
||||
pending[:cancel_reason] = reason
|
||||
pending[:queue].push(:cancelled)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def start_reaper_thread
|
||||
|
|
@ -309,6 +348,7 @@ module MCP
|
|||
return missing_session_id_response if !@stateless && !session_id
|
||||
|
||||
if notification?(body)
|
||||
dispatch_notification(body_string, session_id)
|
||||
handle_accepted
|
||||
elsif response?(body)
|
||||
return session_not_found_response if !@stateless && !session_exists?(session_id)
|
||||
|
|
@ -459,6 +499,22 @@ module MCP
|
|||
!body[:id] && !!body[:method]
|
||||
end
|
||||
|
||||
# Dispatches a client-originated notification (e.g. `notifications/cancelled`,
|
||||
# `notifications/initialized`) through the server so it can update session state.
|
||||
def dispatch_notification(body_string, session_id)
|
||||
server_session = nil
|
||||
if session_id && !@stateless
|
||||
@mutex.synchronize do
|
||||
session = @sessions[session_id]
|
||||
server_session = session[:server_session] if session
|
||||
end
|
||||
end
|
||||
|
||||
dispatch_handle_json(body_string, server_session)
|
||||
rescue => e
|
||||
MCP.configuration.exception_reporter.call(e, { error: "Failed to dispatch notification" })
|
||||
end
|
||||
|
||||
def response?(body)
|
||||
!!body[:id] && !body[:method]
|
||||
end
|
||||
|
|
@ -536,6 +592,12 @@ module MCP
|
|||
handle_request_with_sse_response(body_string, session_id, server_session, related_request_id: related_request_id)
|
||||
else
|
||||
response = dispatch_handle_json(body_string, server_session)
|
||||
|
||||
# `Server#handle_json` returns `nil` when cancellation has suppressed the JSON-RPC response per spec.
|
||||
# Mirror the notification path and ack with 202 instead of returning a 200 with a `nil` Rack body,
|
||||
# which would produce an empty body the client cannot parse as JSON.
|
||||
return handle_accepted if response.nil?
|
||||
|
||||
[200, { "Content-Type" => "application/json" }, [response]]
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Reference in a new issue