## 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.
199 lines
6.6 KiB
Ruby
199 lines
6.6 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require "test_helper"
|
|
|
|
module MCP
|
|
class ServerElicitationTest < ActiveSupport::TestCase
|
|
include InstrumentationTestHelper
|
|
|
|
class MockTransport < Transport
|
|
attr_reader :requests, :notifications
|
|
|
|
def initialize(server)
|
|
super
|
|
@requests = []
|
|
@notifications = []
|
|
end
|
|
|
|
def send_request(method, params = nil, **_kwargs)
|
|
@requests << { method: method, params: params }
|
|
{ action: "accept" }
|
|
end
|
|
|
|
def send_response(response); end
|
|
|
|
def send_notification(method, params = nil, **_kwargs)
|
|
@notifications << { method: method, params: params }
|
|
end
|
|
|
|
def open; end
|
|
def close; end
|
|
def handle_request(request); end
|
|
end
|
|
|
|
setup do
|
|
configuration = MCP::Configuration.new
|
|
configuration.instrumentation_callback = instrumentation_helper.callback
|
|
|
|
@server = Server.new(
|
|
name: "test_server",
|
|
version: "1.0.0",
|
|
configuration: configuration,
|
|
)
|
|
|
|
@mock_transport = MockTransport.new(@server)
|
|
@server.transport = @mock_transport
|
|
|
|
@session = ServerSession.new(server: @server, transport: @mock_transport)
|
|
@session.instance_variable_set(:@client_capabilities, { elicitation: {} })
|
|
end
|
|
|
|
test "#create_form_elicitation sends request through transport" do
|
|
result = @session.create_form_elicitation(
|
|
message: "Please provide your name",
|
|
requested_schema: {
|
|
type: "object",
|
|
properties: {
|
|
name: { type: "string" },
|
|
},
|
|
required: ["name"],
|
|
},
|
|
)
|
|
|
|
assert_equal 1, @mock_transport.requests.size
|
|
|
|
request = @mock_transport.requests.first
|
|
|
|
assert_equal Methods::ELICITATION_CREATE, request[:method]
|
|
assert_equal "form", request[:params][:mode]
|
|
assert_equal "Please provide your name", request[:params][:message]
|
|
assert_equal "object", request[:params][:requestedSchema][:type]
|
|
assert_equal({ action: "accept" }, result)
|
|
end
|
|
|
|
test "#create_form_elicitation raises error when client does not support elicitation" do
|
|
@session.instance_variable_set(:@client_capabilities, {})
|
|
|
|
error = assert_raises(RuntimeError) do
|
|
@session.create_form_elicitation(
|
|
message: "Please provide your name",
|
|
requested_schema: { type: "object", properties: { name: { type: "string" } } },
|
|
)
|
|
end
|
|
|
|
assert_equal(
|
|
"Client does not support elicitation. The client must declare the `elicitation` capability during initialization.",
|
|
error.message,
|
|
)
|
|
end
|
|
|
|
test "#create_form_elicitation raises error when client capabilities are nil" do
|
|
@session.instance_variable_set(:@client_capabilities, nil)
|
|
@server.instance_variable_set(:@client_capabilities, nil)
|
|
|
|
error = assert_raises(RuntimeError) do
|
|
@session.create_form_elicitation(
|
|
message: "Please provide your name",
|
|
requested_schema: { type: "object", properties: { name: { type: "string" } } },
|
|
)
|
|
end
|
|
|
|
assert_equal(
|
|
"Client does not support elicitation. The client must declare the `elicitation` capability during initialization.",
|
|
error.message,
|
|
)
|
|
end
|
|
|
|
test "#create_url_elicitation sends url mode request through transport" do
|
|
@session.instance_variable_set(:@client_capabilities, { elicitation: { url: {} } })
|
|
|
|
result = @session.create_url_elicitation(
|
|
message: "Please authorize access",
|
|
url: "https://example.com/oauth",
|
|
elicitation_id: "abc-123",
|
|
)
|
|
|
|
assert_equal 1, @mock_transport.requests.size
|
|
|
|
request = @mock_transport.requests.first
|
|
|
|
assert_equal Methods::ELICITATION_CREATE, request[:method]
|
|
assert_equal "url", request[:params][:mode]
|
|
assert_equal "Please authorize access", request[:params][:message]
|
|
assert_equal "https://example.com/oauth", request[:params][:url]
|
|
assert_equal "abc-123", request[:params][:elicitationId]
|
|
assert_equal({ action: "accept" }, result)
|
|
end
|
|
|
|
test "#create_url_elicitation raises error when client does not support url mode" do
|
|
error = assert_raises(RuntimeError) do
|
|
@session.create_url_elicitation(
|
|
message: "Please authorize access",
|
|
url: "https://example.com/oauth",
|
|
elicitation_id: "abc-123",
|
|
)
|
|
end
|
|
|
|
assert_equal(
|
|
"Client does not support URL mode elicitation. The client must declare the `elicitation.url` capability during initialization.",
|
|
error.message,
|
|
)
|
|
end
|
|
|
|
test "#create_url_elicitation raises error when client capabilities are nil" do
|
|
@session.instance_variable_set(:@client_capabilities, nil)
|
|
@server.instance_variable_set(:@client_capabilities, nil)
|
|
|
|
error = assert_raises(RuntimeError) do
|
|
@session.create_url_elicitation(
|
|
message: "Please authorize access",
|
|
url: "https://example.com/oauth",
|
|
elicitation_id: "abc-123",
|
|
)
|
|
end
|
|
|
|
assert_equal(
|
|
"Client does not support URL mode elicitation. The client must declare the `elicitation.url` capability during initialization.",
|
|
error.message,
|
|
)
|
|
end
|
|
|
|
test "#notify_elicitation_complete sends notification through transport" do
|
|
@session.notify_elicitation_complete(elicitation_id: "abc-123")
|
|
|
|
assert_equal 1, @mock_transport.notifications.size
|
|
|
|
notification = @mock_transport.notifications.first
|
|
|
|
assert_equal Methods::NOTIFICATIONS_ELICITATION_COMPLETE, notification[:method]
|
|
assert_equal "abc-123", notification[:params][:elicitationId]
|
|
end
|
|
|
|
test "URLElicitationRequiredError can be raised from a tool handler" do
|
|
@server.define_tool(name: "needs_auth", description: "Needs OAuth") do
|
|
raise Server::URLElicitationRequiredError, [
|
|
{ mode: "url", elicitationId: "abc-123", url: "https://example.com/oauth", message: "Auth required" },
|
|
]
|
|
end
|
|
|
|
response = JSON.parse(@server.handle_json(JSON.generate({
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method: "tools/call",
|
|
params: { name: "needs_auth", arguments: {} },
|
|
})))
|
|
|
|
assert_equal(-32042, response["error"]["code"])
|
|
assert_equal "URL elicitation required", response["error"]["message"]
|
|
|
|
elicitations = response["error"]["data"]["elicitations"]
|
|
|
|
assert_equal 1, elicitations.size
|
|
assert_equal "abc-123", elicitations.first["elicitationId"]
|
|
|
|
assert_instrumentation_data(
|
|
method: "tools/call", tool_name: "needs_auth", tool_arguments: {}, error: :url_elicitation_required,
|
|
)
|
|
end
|
|
end
|
|
end
|