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:
Koichi ITO 2026-04-21 01:15:42 +09:00
commit a97e391353
5 changed files with 1485 additions and 41 deletions

View file

@ -0,0 +1,66 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class CancellationTest < ActiveSupport::TestCase
test "starts not cancelled" do
cancellation = Cancellation.new
refute_predicate cancellation, :cancelled?
assert_nil cancellation.reason
end
test "#cancel flips state and stores reason" do
cancellation = Cancellation.new
assert cancellation.cancel(reason: "user requested")
assert_predicate cancellation, :cancelled?
assert_equal "user requested", cancellation.reason
end
test "#cancel is idempotent" do
cancellation = Cancellation.new
assert cancellation.cancel(reason: "first")
refute cancellation.cancel(reason: "second")
assert_equal "first", cancellation.reason
end
test "#on_cancel fires once on cancellation" do
cancellation = Cancellation.new
fired = []
cancellation.on_cancel { |reason| fired << reason }
cancellation.cancel(reason: "stop")
cancellation.cancel(reason: "again")
assert_equal ["stop"], fired
end
test "#on_cancel fires immediately when already cancelled" do
cancellation = Cancellation.new
cancellation.cancel(reason: "done")
fired = []
cancellation.on_cancel { |reason| fired << reason }
assert_equal ["done"], fired
end
test "#raise_if_cancelled! raises CancelledError when cancelled" do
cancellation = Cancellation.new(request_id: "req-1")
cancellation.cancel(reason: "abort")
error = assert_raises(CancelledError) { cancellation.raise_if_cancelled! }
assert_equal "req-1", error.request_id
assert_equal "abort", error.reason
end
test "#raise_if_cancelled! is a no-op when not cancelled" do
cancellation = Cancellation.new
assert_nil cancellation.raise_if_cancelled!
end
end
end

View file

@ -2168,6 +2168,239 @@ module MCP
assert_equal "correct", result[:content][:text]
end
test "send_request with parent_cancellation unblocks with MCP::CancelledError when cancelled" do
init_request = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json" },
{ jsonrpc: "2.0", method: "initialize", id: "init" }.to_json,
)
init_response = @transport.handle_request(init_request)
session_id = init_response[1]["Mcp-Session-Id"]
io = StringIO.new
get_request = create_rack_request("GET", "/", { "HTTP_MCP_SESSION_ID" => session_id })
response = @transport.handle_request(get_request)
response[2].call(io) if response[2].is_a?(Proc)
sleep(0.1)
cancellation = MCP::Cancellation.new(request_id: "parent-1")
server_session = @transport.instance_variable_get(:@sessions)[session_id][:server_session]
result_queue = Queue.new
Thread.new do
@transport.send_request(
"sampling/createMessage",
{ messages: [] },
session_id: session_id,
parent_cancellation: cancellation,
server_session: server_session,
)
rescue => e
result_queue.push(e)
end
sleep(0.1)
cancellation.cancel(reason: "parent cancelled")
error = result_queue.pop
assert_kind_of MCP::CancelledError, error
end
test "send_request deregisters on_cancel hook after completion so late parent cancel is a no-op" do
init_request = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json" },
{ jsonrpc: "2.0", method: "initialize", id: "init" }.to_json,
)
init_response = @transport.handle_request(init_request)
session_id = init_response[1]["Mcp-Session-Id"]
io = StringIO.new
get_request = create_rack_request("GET", "/", { "HTTP_MCP_SESSION_ID" => session_id })
response = @transport.handle_request(get_request)
response[2].call(io) if response[2].is_a?(Proc)
sleep(0.1)
cancellation = MCP::Cancellation.new(request_id: "parent-x")
server_session = @transport.instance_variable_get(:@sessions)[session_id][:server_session]
result_queue = Queue.new
Thread.new do
result = @transport.send_request(
"sampling/createMessage",
{ messages: [] },
session_id: session_id,
parent_cancellation: cancellation,
server_session: server_session,
)
result_queue.push(result)
end
sleep(0.1)
io.rewind
data_lines = io.read.lines.select { |line| line.start_with?("data: ") }
request_data = JSON.parse(data_lines.first.sub("data: ", ""))
nested_request_id = request_data["id"]
# Client responds successfully; send_request completes normally.
client_response = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id },
{ jsonrpc: "2.0", id: nested_request_id, result: { role: "assistant", content: { type: "text", text: "ok" } } }.to_json,
)
@transport.handle_request(client_response)
result = result_queue.pop
assert_equal "ok", result[:content][:text]
# Snapshot what was written to the SSE stream before late cancel.
io.rewind
before_cancel = io.read
# Parent is cancelled after the nested request already completed. The hook must
# have been deregistered, so no `notifications/cancelled` should go to the peer
# for the already-completed nested request.
cancellation.cancel(reason: "late")
sleep(0.05) # Give any stray callback time to fire (none should).
io.rewind
after_cancel = io.read
refute_includes after_cancel.sub(before_cancel, ""), "notifications/cancelled"
end
test "cancel_pending_request is no-op when a real response is already queued (race)" do
init_request = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json" },
{ jsonrpc: "2.0", method: "initialize", id: "init" }.to_json,
)
init_response = @transport.handle_request(init_request)
session_id = init_response[1]["Mcp-Session-Id"]
io = StringIO.new
get_request = create_rack_request("GET", "/", { "HTTP_MCP_SESSION_ID" => session_id })
response = @transport.handle_request(get_request)
response[2].call(io) if response[2].is_a?(Proc)
sleep(0.1)
result_queue = Queue.new
Thread.new do
result = @transport.send_request(
"sampling/createMessage",
{ messages: [] },
session_id: session_id,
)
result_queue.push(result)
end
sleep(0.1)
io.rewind
data_lines = io.read.lines.select { |line| line.start_with?("data: ") }
request_data = JSON.parse(data_lines.first.sub("data: ", ""))
request_id = request_data["id"]
# Client responded first.
client_response = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id },
{ jsonrpc: "2.0", id: request_id, result: { role: "assistant", content: { type: "text", text: "ok" } } }.to_json,
)
@transport.handle_request(client_response)
# Cancel arrives after the response was already enqueued. Must not clobber the result.
@transport.cancel_pending_request(request_id, reason: "late cancel")
result = result_queue.pop
assert_equal "ok", result[:content][:text]
end
test "JSON response mode returns accepted when cancellation suppresses response" do
server = Server.new(name: "test", tools: [], prompts: [], resources: [])
transport = StreamableHTTPTransport.new(server, enable_json_response: true)
server.transport = transport
server.define_tool(name: "slow_tool") do |server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
Tool::Response.new([{ type: "text", text: "done" }])
end
init_request = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json" },
{
jsonrpc: "2.0",
method: "initialize",
id: "init",
params: { protocolVersion: "2025-11-25", clientInfo: { name: "test" } },
}.to_json,
)
init_response = transport.handle_request(init_request)
session_id = init_response[1]["Mcp-Session-Id"]
server_session = transport.instance_variable_get(:@sessions)[session_id][:server_session]
tool_request = create_rack_request(
"POST",
"/",
{
"CONTENT_TYPE" => "application/json",
"HTTP_MCP_SESSION_ID" => session_id,
},
{
jsonrpc: "2.0",
id: "call-1",
method: "tools/call",
params: { name: "slow_tool", arguments: {} },
}.to_json,
)
response_queue = Queue.new
request_thread = Thread.new { response_queue.push(transport.handle_request(tool_request)) }
sleep(0.01) until server_session.lookup_in_flight("call-1")
cancel_request = create_rack_request(
"POST",
"/",
{
"CONTENT_TYPE" => "application/json",
"HTTP_MCP_SESSION_ID" => session_id,
},
{
jsonrpc: "2.0",
method: MCP::Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: "call-1", reason: "user cancelled" },
}.to_json,
)
cancel_response = transport.handle_request(cancel_request)
assert_equal(202, cancel_response[0])
response = response_queue.pop
assert_equal(202, response[0])
assert_empty(response[1])
assert_empty(response[2])
ensure
request_thread.kill if request_thread.alive?
transport.close
end
test "send_request raises on error response from client" do
# Create session.
init_request = create_rack_request(

View file

@ -0,0 +1,627 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class ServerCancellationTest < ActiveSupport::TestCase
include InstrumentationTestHelper
class MockTransport < Transport
attr_reader :requests, :notifications, :cancelled_request_ids
def initialize(server)
super
@requests = []
@notifications = []
@cancelled_request_ids = []
end
def send_request(method, params = nil, **_kwargs)
@requests << { method: method, params: params }
{}
end
def send_notification(method, params = nil, **_kwargs)
@notifications << { method: method, params: params }
true
end
def cancel_pending_request(request_id, reason: nil)
@cancelled_request_ids << request_id
end
def send_response(response); 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_id: "sess-1")
end
test "cooperative cancellation via server_context suppresses response" do
observed_cancelled = false
@server.define_tool(name: "slow") do |server_context:|
20.times do
break if server_context.cancelled?
sleep(0.01)
end
observed_cancelled = server_context.cancelled?
Tool::Response.new([{ type: "text", text: "ok" }])
end
request_id = 42
call_thread = Thread.new do
@session.handle(
jsonrpc: "2.0",
id: request_id,
method: Methods::TOOLS_CALL,
params: { name: "slow", arguments: {} },
)
end
sleep(0.02) until @session.lookup_in_flight(request_id)
@session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "user aborted" },
)
response = call_thread.value
assert observed_cancelled, "tool handler should observe cancellation"
assert_nil response, "cancelled request must not emit a JSON-RPC response"
end
test "tool raising CancelledError via raise_if_cancelled! suppresses the JSON-RPC response" do
@server.define_tool(name: "raising") do |server_context:|
50.times do
server_context.raise_if_cancelled!
sleep(0.01)
end
Tool::Response.new([{ type: "text", text: "ok" }])
end
request_id = 99
call_thread = Thread.new do
@session.handle(
jsonrpc: "2.0",
id: request_id,
method: Methods::TOOLS_CALL,
params: { name: "raising", arguments: {} },
)
end
sleep(0.02) until @session.lookup_in_flight(request_id)
@session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "raised" },
)
response = call_thread.value
assert_nil response, "raise_if_cancelled! must result in no JSON-RPC response"
end
test "CancelledError raised from nested server-to-client call suppresses response" do
@server.define_tool(name: "nesting") do |server_context:| # rubocop:disable Lint/UnusedBlockArgument
# Simulate a transport-level CancelledError coming back from a nested
# send_request (e.g. sampling/createMessage after parent was cancelled).
raise MCP::CancelledError.new(request_id: "nested-xyz", reason: "parent aborted")
end
response = @session.handle(
jsonrpc: "2.0",
id: 123,
method: Methods::TOOLS_CALL,
params: { name: "nesting", arguments: {} },
)
assert_nil response, "CancelledError propagating from a nested call must suppress the JSON-RPC response"
end
test "cancellation with unknown request id is silently ignored" do
response = @session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: "does-not-exist" },
)
assert_nil response
end
test "duplicate cancellation for the same in-flight request is idempotent" do
@server.define_tool(name: "slow_dup") do |server_context:|
20.times do
break if server_context.cancelled?
sleep(0.01)
end
Tool::Response.new([{ type: "text", text: "ok" }])
end
request_id = 51
call_thread = Thread.new do
@session.handle(
jsonrpc: "2.0",
id: request_id,
method: Methods::TOOLS_CALL,
params: { name: "slow_dup", arguments: {} },
)
end
sleep(0.02) until @session.lookup_in_flight(request_id)
first = @session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "first" },
)
second = @session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "second" },
)
response = call_thread.value
assert_nil first
assert_nil second, "duplicate cancel must not emit a response"
assert_nil response, "cancelled request must not emit a response"
end
test "cancellation arriving after the request already completed is silently ignored" do
@server.define_tool(name: "quick") do
Tool::Response.new([{ type: "text", text: "done" }])
end
request_id = 61
response = @session.handle(
jsonrpc: "2.0",
id: request_id,
method: Methods::TOOLS_CALL,
params: { name: "quick", arguments: {} },
)
assert response, "the tool should have completed successfully before the cancel arrives"
assert_nil @session.lookup_in_flight(request_id), "completed request must be unregistered"
late = @session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "late" },
)
assert_nil late, "late cancel for a completed request must be silently ignored"
end
test "initialize request cannot be cancelled" do
init_params = {
protocolVersion: Configuration::LATEST_STABLE_PROTOCOL_VERSION,
clientInfo: { name: "test", version: "1.0" },
capabilities: {},
}
response = @session.handle(
jsonrpc: "2.0",
id: "init-1",
method: Methods::INITIALIZE,
params: init_params,
)
assert response, "initialize returns a response"
assert response[:result][:protocolVersion]
# The initialize request is not registered in the in-flight map.
assert_nil @session.lookup_in_flight("init-1")
end
test "ServerSession#cancel_request sends notification and cancels pending" do
@session.cancel_request(request_id: "req-9", reason: "timeout")
notification = @mock_transport.notifications.last
assert_equal Methods::NOTIFICATIONS_CANCELLED, notification[:method]
assert_equal "req-9", notification[:params][:requestId]
assert_equal "timeout", notification[:params][:reason]
assert_includes @mock_transport.cancelled_request_ids, "req-9"
end
test "parent cancellation propagates to nested server-to-client requests" do
@session.instance_variable_set(:@client_capabilities, { elicitation: {} })
parent_request_id = 101
cancellation = @session.register_in_flight(parent_request_id)
# Simulate a nested sampling/elicitation send via ServerSession. The transport
# is expected to receive `parent_cancellation:` and `server_session:` kwargs so
# it can install an `on_cancel` hook. Here we assert those kwargs are forwarded.
recorded = {}
(class << @mock_transport; self; end).define_method(:send_request) do |method, _params = nil, **kwargs|
recorded[:method] = method
recorded[:kwargs] = kwargs
{}
end
@session.create_form_elicitation(
message: "ignored",
requested_schema: { type: "object", properties: {} },
related_request_id: parent_request_id,
)
assert_equal Methods::ELICITATION_CREATE, recorded[:method]
assert_equal parent_request_id, recorded[:kwargs][:related_request_id]
assert_same cancellation, recorded[:kwargs][:parent_cancellation]
assert_same @session, recorded[:kwargs][:server_session]
end
test "cancellation reason is recorded in instrumentation data" do
recorded_data = nil
@server.configuration.instrumentation_callback = ->(data) { recorded_data = data }
@server.define_tool(name: "slow_with_reason") do |server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
Tool::Response.new([{ type: "text", text: "ok" }])
end
request_id = 77
call_thread = Thread.new do
@session.handle(
jsonrpc: "2.0",
id: request_id,
method: Methods::TOOLS_CALL,
params: { name: "slow_with_reason", arguments: {} },
)
end
sleep(0.02) until @session.lookup_in_flight(request_id)
@session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "explicit reason string" },
)
call_thread.value
assert recorded_data
assert recorded_data[:cancelled]
assert_equal "explicit reason string", recorded_data[:cancellation_reason]
end
# Helper for the non-tools cancellation regression tests below. Spawns a background
# request, waits for the in-flight entry, sends `notifications/cancelled`, and
# returns [response, thread_result_flag_yielded_by_block].
def drive_cancellation(request_id:, method:, params:)
result_flag = { observed: false }
call_thread = Thread.new do
@session.handle(jsonrpc: "2.0", id: request_id, method: method, params: params)
end
sleep(0.02) until @session.lookup_in_flight(request_id)
yield(result_flag) if block_given?
@session.handle(
jsonrpc: "2.0",
method: Methods::NOTIFICATIONS_CANCELLED,
params: { requestId: request_id, reason: "caller aborted" },
)
[call_thread.value, result_flag]
end
test "resources/read handler that opts in to server_context observes cancellation" do
observed = false
@server.resources_read_handler do |_params, server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
observed = server_context.cancelled?
[{ uri: "test://resource", text: "done" }]
end
response, = drive_cancellation(
request_id: 201,
method: Methods::RESOURCES_READ,
params: { uri: "test://resource" },
)
assert observed, "resources/read handler should observe cancellation via server_context"
assert_nil response, "cancelled resources/read must not emit a JSON-RPC response"
end
test "completion/complete handler that opts in to server_context observes cancellation" do
observed = false
@server.capabilities[:completions] = {}
@server.completion_handler do |_params, server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
observed = server_context.cancelled?
{ completion: { values: ["v"], hasMore: false } }
end
# completion/complete requires a known ref; register a dummy prompt.
@server.define_prompt(name: "dummy") { MCP::Prompt::Result.new(messages: []) }
response, = drive_cancellation(
request_id: 202,
method: Methods::COMPLETION_COMPLETE,
params: { ref: { type: "ref/prompt", name: "dummy" }, argument: { name: "arg", value: "" } },
)
assert observed, "completion/complete handler should observe cancellation via server_context"
assert_nil response, "cancelled completion/complete must not emit a JSON-RPC response"
end
test "prompts/get template that opts in to server_context observes cancellation" do
observed = false
prompt_class = Class.new(MCP::Prompt) do
prompt_name "slow_prompt"
define_singleton_method(:template) do |_args, server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
observed = server_context.cancelled?
MCP::Prompt::Result.new(messages: [])
end
end
@server.prompts[prompt_class.name_value] = prompt_class
# Share `observed` between the closure above and the test scope.
@server.singleton_class.define_method(:_test_observed) { observed }
response, = drive_cancellation(
request_id: 203,
method: Methods::PROMPTS_GET,
params: { name: "slow_prompt" },
)
assert observed, "prompt template should observe cancellation via server_context"
assert_nil response, "cancelled prompts/get must not emit a JSON-RPC response"
end
test "send_to_transport (notifications) works with a custom transport that only implements the abstract signature" do
# Regression: `ServerSession#send_to_transport` must not assume the
# transport's `send_notification` accepts the new kwargs
# (`session_id:` / `related_request_id:`). Custom transports that
# implement the abstract `Transport#send_notification(method, params = nil)`
# contract must keep working - this is exercised via `cancel_request` /
# `send_peer_cancellation` which the cancellation feature relies on.
minimal_transport = Class.new(Transport) do
attr_reader :recorded
def initialize(server)
super
@recorded = []
end
def send_notification(method, params = nil)
@recorded << [method, params]
true
end
def send_request(method, params = nil)
@recorded << [method, params]
{}
end
def send_response(_); end
def open; end
def close; end
end.new(@server)
session = ServerSession.new(server: @server, transport: minimal_transport)
assert_nothing_raised do
session.cancel_request(request_id: "req-1", reason: "timeout")
end
recorded = minimal_transport.recorded.last
assert_equal Methods::NOTIFICATIONS_CANCELLED, recorded[0]
assert_equal "req-1", recorded[1][:requestId]
assert_equal "timeout", recorded[1][:reason]
end
test "send_to_transport_request works with a custom transport that only implements the abstract signature" do
# Regression: `ServerSession#send_to_transport_request` must not assume
# the transport's `send_request` accepts the new kwargs
# (`session_id:` / `related_request_id:` / `parent_cancellation:` /
# `server_session:`). Custom transports that implement the abstract
# `Transport#send_request(method, params = nil)` contract must keep working.
minimal_transport = Class.new(Transport) do
attr_reader :recorded
def initialize(server)
super
@recorded = []
end
def send_request(method, params = nil)
@recorded << [method, params]
{} # fake response
end
def send_notification(method, params = nil)
@recorded << [method, params]
true
end
def send_response(_); end
def open; end
def close; end
end.new(@server)
session = ServerSession.new(server: @server, transport: minimal_transport)
session.instance_variable_set(:@client_capabilities, { sampling: {} })
assert_nothing_raised do
session.create_sampling_message(
messages: [{ role: "user", content: { type: "text", text: "hi" } }],
max_tokens: 10,
)
end
recorded = minimal_transport.recorded.last
assert_equal Methods::SAMPLING_CREATE_MESSAGE, recorded[0]
refute_nil recorded[1]
end
test "tool with positional `server_context` parameter is not auto-opted-in" do
# Regression: `accepts_server_context?` (used by tool/prompt dispatch) must
# require `server_context` as a *keyword* parameter. A tool whose `call`
# signature is `def self.call(arg, server_context)` (positional name collision)
# would previously have been opt-in, and `tool.call(**args, server_context: ctx)`
# would have blown up or passed the wrapped Hash to the wrong slot.
tool = Class.new(MCP::Tool) do
tool_name "positional_collision"
input_schema(properties: { a: { type: "string" } }, required: ["a"])
class << self
def call(a, server_context)
[a, server_context]
end
end
end
@server.tools[tool.name_value] = tool
# Should dispatch without `server_context:` kwarg - the positional arg collision
# must NOT trigger opt-in. The tool receives only its declared positional (a).
response = @session.handle(
jsonrpc: "2.0",
id: 303,
method: Methods::TOOLS_CALL,
params: { name: "positional_collision", arguments: { a: "hello" } },
)
# Because the tool signature isn't opt-in, `tool.call(**args)` is called
# (without `server_context:`). The method has `server_context` as a required
# positional, so missing it raises ArgumentError - caught as an internal error.
# The key assertion is that we do NOT pass `server_context:` kwarg that would
# flow into the positional slot as a Hash.
assert response.dig(:error), "dispatch should not silently inject server_context kwarg"
end
test "handler with positional `server_context` parameter is not auto-opted-in" do
# Regression: `handler_declares_server_context?` must require `server_context`
# as a *keyword* parameter. A positional parameter that happens to be named
# `server_context` (rare but possible) would previously have been treated as
# opt-in, and the dispatch site would call `handler.call(params, server_context: ctx)`
# - the second positional argument would become the Hash `{server_context: ctx}`,
# which is never what the user intended.
received_args = nil
@server.define_custom_method(method_name: "custom/positional_name") do |params, server_context|
received_args = [params, server_context]
{ ok: true }
end
response = @session.handle(
jsonrpc: "2.0",
id: 302,
method: "custom/positional_name",
params: { hello: "world" },
)
assert_equal [{ hello: "world" }, nil],
received_args,
"positional `server_context` must receive the single `params` argument, not an auto-wrapped context"
assert_equal({ ok: true }, response[:result])
end
test "handler with **kwargs-only signature is not auto-opted-in to server_context" do
# Regression: a block like `|**opts|` would have triggered opt-in under the
# looser `accepts_server_context?` check used by tools, and the dispatch site
# would then call `handler.call(params, server_context:)` - but a proc that
# only declares `**opts` cannot accept the positional `params` (lambdas raise
# ArgumentError, non-lambda procs silently drop it). The stricter
# `handler_declares_server_context?` check requires `server_context` as a
# named keyword to opt in, so a kwargs-only handler receives only `params`.
received_positional = nil
@server.define_custom_method(method_name: "custom/kwargs_only") do |params, **_opts|
received_positional = params
{ ok: true }
end
response = @session.handle(
jsonrpc: "2.0",
id: 301,
method: "custom/kwargs_only",
params: { hello: "world" },
)
assert_equal({ hello: "world" }, received_positional)
assert_equal({ ok: true }, response[:result])
end
test "custom method handler that opts in to server_context observes cancellation" do
observed = false
@server.define_custom_method(method_name: "custom/slow") do |_params, server_context:|
50.times do
break if server_context.cancelled?
sleep(0.01)
end
observed = server_context.cancelled?
{ ok: true }
end
response, = drive_cancellation(
request_id: 204,
method: "custom/slow",
params: {},
)
assert observed, "custom method handler should observe cancellation via server_context"
assert_nil response, "cancelled custom method must not emit a JSON-RPC response"
end
test "send_peer_cancellation routes notification on parent stream via related_request_id" do
recorded_notifications = []
(class << @mock_transport; self; end).define_method(:send_notification) do |method, params = nil, **kwargs|
recorded_notifications << { method: method, params: params, kwargs: kwargs }
true
end
@session.send_peer_cancellation(
nested_request_id: "nested-1",
related_request_id: 42,
reason: "parent aborted",
)
notif = recorded_notifications.last
assert_equal Methods::NOTIFICATIONS_CANCELLED, notif[:method]
assert_equal "nested-1", notif[:params][:requestId]
assert_equal "parent aborted", notif[:params][:reason]
# Crucially, the cancel notification targets the parent's stream, not the GET SSE stream.
assert_equal 42, notif[:kwargs][:related_request_id]
end
end
end

View file

@ -15,14 +15,14 @@ module MCP
@notifications = []
end
def send_request(method, params = nil)
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)
def send_notification(method, params = nil, **_kwargs)
@notifications << { method: method, params: params }
end

View file

@ -14,7 +14,7 @@ module MCP
@requests = []
end
def send_request(method, params = nil)
def send_request(method, params = nil, **_kwargs)
@requests << { method: method, params: params }
{
role: "assistant",
@ -25,7 +25,7 @@ module MCP
end
def send_response(response); end
def send_notification(method, params = nil); end
def send_notification(method, params = nil, **_kwargs); end
def open; end
def close; end
end