From f0b252a31a066ee362c0ec81b428d538beb70fcd Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 22 Nov 2026 12:18:18 +0800 Subject: [PATCH] fix: honor cancellation throughout the legacy input_required shim ## Motivation and Context When a handler returns `input_required` on the legacy wire, `Server#handle_request` checks the request's cancellation once and then hands the result to `run_legacy_input_required_shim`, which sends each fulfilment request, re-runs the handler and returns its result with no further check. A cancellation that arrives after the client answered a leg, or while the handler re-runs, is therefore not honored: the handler runs again, further legs are still sent to the client, and the final result is returned. Over Streamable HTTP the result is written to the request's SSE stream after the client's `notifications/cancelled`, although the re-run handler itself sees `server_context.cancelled?` true. A request the shim is not involved in is suppressed in the same situation. The shim now checks the request's cancellation before each leg, before re-running the handler, and before returning its result. A cancelled request raises `CancelledError`, which reaches the rescue a cancelled nested request already reaches, so no response is sent and the cancellation is recorded in the instrumentation. Uncancelled replays, the round cap, capability checks and the first-writer-wins handling of a nested response are unchanged. ## How Has This Been Tested? New tests in `test/mcp/server_input_required_legacy_shim_test.rb`, with a fixture transport that cancels the originating request right after answering a leg: a request cancelled once its fulfilment request is answered does not re-run its handler, gets no response, and records the cancellation and its reason; a request cancelled between the two fulfilment requests of one round does not send the second; a request cancelled while its handler re-runs gets no response, for `tools/call`, `prompts/get` and `resources/read`. All three fail against the previous library, and dropping any one of the three checks fails one of them. ## Breaking Changes None. A legacy `input_required` request cancelled during its replay is no longer answered. Fixes #706. --- lib/mcp/server.rb | 7 ++ .../server_input_required_legacy_shim_test.rb | 110 ++++++++++++++++++ 2 files changed, 117 insertions(+) diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 864dbe10..5651204a 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -1104,7 +1104,12 @@ def run_legacy_input_required_shim(result, instrumentation_data:, method:, param ) end + # `handle_request` checks for cancellation only before the shim starts, so the shim checks again before each leg, + # before re-running the handler, and before returning its result: a client's `notifications/cancelled` can arrive + # after it answered a leg or while the handler re-runs. `CancelledError` reaches the rescue a cancelled nested + # request does, which suppresses the response. responses = (result.input_requests || {}).each_with_object({}) do |(key, entry), collected| + cancellation&.raise_if_cancelled! collected[key] = session.fulfill_input_request( entry[:method], legacy_leg_params(entry), @@ -1116,6 +1121,7 @@ def run_legacy_input_required_shim(result, instrumentation_data:, method:, param retry_params[:inputResponses] = responses unless responses.empty? retry_params[:requestState] = result.request_state if result.request_state + cancellation&.raise_if_cancelled! result = redispatch_mrtr_method( method, retry_params, @@ -1124,6 +1130,7 @@ def run_legacy_input_required_shim(result, instrumentation_data:, method:, param related_request_id: related_request_id, cancellation: cancellation, ) + cancellation&.raise_if_cancelled! return result unless result.is_a?(InputRequiredResult) rounds += 1 diff --git a/test/mcp/server_input_required_legacy_shim_test.rb b/test/mcp/server_input_required_legacy_shim_test.rb index ce0f4b4b..f8a9911c 100644 --- a/test/mcp/server_input_required_legacy_shim_test.rb +++ b/test/mcp/server_input_required_legacy_shim_test.rb @@ -47,6 +47,23 @@ def send_notification(method, params = nil, session_id: nil, related_request_id: end end + # Answers like `AnsweringTransport`, then cancels the originating request once `cancel_after` fulfilment requests + # have been answered, as a client's `notifications/cancelled` arriving right after its answer does. + class CancellingTransport < AnsweringTransport + attr_writer :session + + def initialize(cancel_after: 1) + super() + @cancel_after = cancel_after + end + + def send_request(method, params = nil, related_request_id: nil) + answer = super + @session.cancel_incoming(request_id: related_request_id, reason: "user aborted") if @sent.size == @cancel_after + answer + end + end + setup do @greeting_tool = Tool.define(name: "greeter") do |server_context:| answer = server_context.input_response("who") @@ -238,6 +255,99 @@ def send_notification(method, params = nil, session_id: nil, related_request_id: assert_equal "mine", transport.sent.first[:params][:elicitationId] end + test "a request cancelled once its fulfilment request is answered does not re-run its handler or answer" do + runs = 0 + tool = Tool.define(name: "counted") do |server_context:| + runs += 1 + if server_context.input_response("who") + Tool::Response.new([{ type: "text", text: "done" }]) + else + Server::InputRequiredResult.new( + input_requests: { "who" => { method: Methods::ELICITATION_CREATE, params: { message: "Who?" } } }, + ) + end + end + server = Server.new(name: "shim_test", tools: [tool]) + recorded = nil + server.configuration.instrumentation_callback = ->(data) { recorded = data } + transport = CancellingTransport.new + session = ServerSession.new(server: server, transport: transport, session_id: "legacy") + session.store_client_info(client: { name: "legacy" }, capabilities: { elicitation: { form: {} } }) + transport.session = session + + response = session.handle(tool_call_request(name: "counted")) + + assert_nil response + assert_equal 1, runs + assert recorded[:cancelled] + assert_equal "user aborted", recorded[:cancellation_reason] + end + + test "a request cancelled between the fulfilment requests of a round sends no further one" do + tool = Tool.define(name: "two_questions") do |server_context:| + if server_context.input_responses + Tool::Response.new([{ type: "text", text: "done" }]) + else + Server::InputRequiredResult.new( + input_requests: { + "first" => { method: Methods::ELICITATION_CREATE, params: { message: "1?" } }, + "second" => { method: Methods::ELICITATION_CREATE, params: { message: "2?" } }, + }, + ) + end + end + transport = CancellingTransport.new(cancel_after: 1) + session = legacy_session(tools: [tool], transport: transport) + transport.session = session + + response = session.handle(tool_call_request(name: "two_questions")) + + assert_nil response + assert_equal [{ message: "1?" }], transport.sent.map { |sent| sent[:params] } + end + + test "a request cancelled while its handler re-runs gets no response, for each shimmed method" do + session = nil + cancel_self = ->(request_id) { session.cancel_incoming(request_id: request_id, reason: "user aborted") } + tool = Tool.define(name: "greeter") do |server_context:| + if server_context.input_response("who") + cancel_self.call(1) + Tool::Response.new([{ type: "text", text: "done" }]) + else + Server::InputRequiredResult.new( + input_requests: { "who" => { method: Methods::ELICITATION_CREATE, params: { message: "Who?" } } }, + ) + end + end + prompt = Prompt.define(name: "greeting_prompt") do |_args, server_context:| + if server_context.input_response("who") + cancel_self.call(10) + Prompt::Result.new(messages: [Prompt::Message.new(role: "user", content: Content::Text.new("hi"))]) + else + Server::InputRequiredResult.new( + input_requests: { "who" => { method: Methods::ELICITATION_CREATE, params: { message: "Who?" } } }, + ) + end + end + server = Server.new(name: "shim_test", tools: [tool], prompts: [prompt], resources: []) + server.resources_read_handler do |params| + if params[:inputResponses] + cancel_self.call(11) + [{ uri: params[:uri], mimeType: "text/plain", text: "read" }] + else + Server::InputRequiredResult.new( + input_requests: { "who" => { method: Methods::ELICITATION_CREATE, params: { message: "Who?" } } }, + ) + end + end + session = ServerSession.new(server: server, transport: AnsweringTransport.new, session_id: "legacy") + session.store_client_info(client: { name: "legacy" }, capabilities: { elicitation: { form: {} } }) + + assert_nil session.handle(tool_call_request) + assert_nil session.handle({ jsonrpc: "2.0", id: 10, method: Methods::PROMPTS_GET, params: { name: "greeting_prompt" } }) + assert_nil session.handle({ jsonrpc: "2.0", id: 11, method: Methods::RESOURCES_READ, params: { uri: "file:///a.txt" } }) + end + test "a client answering a fulfilment leg with an error fails the original request" do session = legacy_session(tools: [@greeting_tool], transport: RejectingTransport.new)