From b301ecf496ee83a340e29627b3589f483dc7c23f Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 22 Nov 2026 12:27:49 +0800 Subject: [PATCH] fix: cancel a terminated session's requests before closing its streams ## Motivation and Context When the Streamable HTTP transport removes a session, `cleanup_session_unsafe` wakes the threads waiting on the session's server-to-client requests with `:session_closed`, and `release_session` then closes the session's GET and POST streams before it cancels the session's requests. A close can block for up to `stream_write_timeout:` (10 seconds by default) on a stalled peer, and the cancellation waits behind it. Two documented guarantees of the Cancellation page fail meanwhile: - A request that reaches the session as it ends (#698) is admitted and run: its tool runs with `server_context.cancelled?` false, and over SSE its result is written to its POST stream after the `DELETE`. - A request waiting on a nested server-to-client request is woken with `:session_closed` before its own token is cancelled: the nested call raises "SSE session closed while waiting", the handler sees `cancelled?` false, and the request is recorded as an internal error instead of a cancellation. The wake-up runs first even without a stalled stream, so this outcome depends on thread scheduling. `release_session` now cancels the session's requests first, then wakes the remaining waits with `:session_closed`, then closes the streams. `cleanup_session_unsafe` collects the waits under the lock instead of waking them; no wait is added for a session once it is removed. A nested request is now woken through its parent's cancellation hook, so it raises `MCP::CancelledError` as it does for `notifications/cancelled`. Cancellations still run outside `@mutex`. ## How Has This Been Tested? New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`, with a GET stream whose close blocks until released: an SSE request whose body runs while the `DELETE` is held up closing that stream does not run its tool and writes nothing; a request waiting on an elicitation when its session is terminated sees `MCP::CancelledError` with `cancelled?` true and is recorded as cancelled with the reason "Session terminated". Both fail against the previous library. Closing the streams before cancelling fails both, waking the waits before cancelling fails the second, and dropping the wake-up hangs the existing "send_request unblocks when session is cleaned up" test. ## Breaking Changes None. `on_cancel` hooks of a terminated session's requests now run before its streams are closed rather than after. Fixes #708. --- .../transports/streamable_http_transport.rb | 35 +++++--- .../streamable_http_transport_test.rb | 88 +++++++++++++++++++ 2 files changed, 109 insertions(+), 14 deletions(-) diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 6fb0808f..68d0ff9b 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -2041,17 +2041,16 @@ def cleanup_session(session_id) session end - # Removes a session from `@sessions` and returns it. Does not close the stream or cancel the in-flight requests. - # Callers must `release_session` it outside the mutex to avoid holding the lock during - # potentially blocking I/O and the requests' cancellation hooks. + # Removes a session from `@sessions` and returns it. Does not close the stream, cancel the in-flight requests, or wake + # the threads waiting on the session's server-to-client requests: it collects those waits for `release_session`, + # which callers must run outside the mutex to avoid holding the lock during potentially blocking I/O and + # the requests' cancellation hooks. No wait is added once the session is gone, since `send_request` registers one + # only for a session it finds under the lock. def cleanup_session_unsafe(session_id) - session = @sessions.delete(session_id) + return unless (session = @sessions.delete(session_id)) - # Unblock threads waiting on pending responses for this session. - @pending_responses.each_value do |pending_response| - if pending_response[:session_id] == session_id - pending_response[:queue].push(:session_closed) - end + session[:pending_response_queues] = @pending_responses.each_value.filter_map do |pending_response| + pending_response[:queue] if pending_response[:session_id] == session_id end session @@ -2064,14 +2063,22 @@ def cleanup_and_collect_session(session_id, removed_sessions) removed_sessions << removed end - # Ends what a removed session still has running: closes its streams and cancels its in-flight requests, whose handlers - # observe the termination through `server_context.cancelled?` and whose responses are suppressed as for - # `notifications/cancelled`. Runs outside `@mutex`: a close can block, and a cancellation fires the request's - # `on_cancel` hooks synchronously, which may call back into the transport. + # Ends what a removed session still has running: cancels its in-flight requests, whose handlers observe + # the termination through `server_context.cancelled?` and whose responses are suppressed as for `notifications/cancelled`, + # wakes the threads still waiting on its server-to-client requests, and closes its streams. Runs outside `@mutex`: + # a close can block, and a cancellation fires the request's `on_cancel` hooks synchronously, which may call back into + # the transport. + # + # The cancellation comes first. A close can block for up to `stream_write_timeout:` on a stalled peer, and until + # the cancellation runs, a request the session still receives is admitted and run as usual. Waking the waits first + # would likewise tell a request waiting on a nested request only that the session closed, before its own token is + # cancelled. Cancelling first wakes that wait through the request's cancellation hook, so the request ends cancelled; + # `:session_closed` then wakes the waits that belong to no request of the session. def release_session(session) + session[:server_session]&.cancel_all_incoming(reason: SESSION_TERMINATED_REASON) + session[:pending_response_queues]&.each { |queue| queue.push(:session_closed) } close_stream_safely(session[:get_sse_stream]) close_post_request_streams(session) - session[:server_session]&.cancel_all_incoming(reason: SESSION_TERMINATED_REASON) end def release_sessions(sessions) diff --git a/test/mcp/server/transports/streamable_http_transport_test.rb b/test/mcp/server/transports/streamable_http_transport_test.rb index e064ae8f..9e8040fc 100644 --- a/test/mcp/server/transports/streamable_http_transport_test.rb +++ b/test/mcp/server/transports/streamable_http_transport_test.rb @@ -34,6 +34,24 @@ def string end end + # A stream whose `close` blocks until released, as a socket close can while it flushes to a stalled peer. + # Pushes to `closing` once its close has started. + class StalledCloseStream < TestStream + attr_reader :closing, :release + + def initialize + super + @closing = Queue.new + @release = Queue.new + end + + def close + @closing << true + @release.pop + super + end + end + setup do @server = Server.new( name: "test_server", @@ -4448,6 +4466,76 @@ def string transport&.close end + test "a request reaching a session while its termination is held up closing a stalled stream does not run its tool" do + server = Server.new(name: "test", tools: [], prompts: [], resources: []) + transport = StreamableHTTPTransport.new(server) + server.transport = transport + invocations = 0 + server.define_tool(name: "effect") do |server_context:| + invocations += 1 + Tool::Response.new([{ type: "text", text: "done" }]) + end + session_id, = start_session(transport) + stalled = StalledCloseStream.new + transport.instance_variable_get(:@sessions)[session_id][:get_sse_stream] = stalled + + _, _, body = transport.handle_request(effect_tool_call(session_id, "call-1")) + delete = Thread.new { transport.handle_request(create_rack_request("DELETE", "/", { "HTTP_MCP_SESSION_ID" => session_id })) } + stalled.closing.pop + stream = TestStream.new + body.call(stream) + + assert_equal(0, invocations) + assert_empty(stream.string) + ensure + stalled&.release&.push(true) + delete&.join + transport&.close + end + + test "a request waiting on a server-to-client request when its session is terminated ends cancelled" do + server = Server.new(name: "test", tools: [], prompts: [], resources: []) + transport = StreamableHTTPTransport.new(server) + server.transport = transport + raised = [] + server.define_tool(name: "asker") do |server_context:| + server_context.create_form_elicitation(message: "Who?", requested_schema: { type: "object", properties: {} }) + Tool::Response.new([{ type: "text", text: "answered" }]) + rescue => e + raised << [e.class, server_context.cancelled?] + raise + end + recorded = nil + server.configuration.instrumentation_callback = ->(data) { recorded = data if data[:method] == "tools/call" } + session_id, server_session = start_session(transport) + server_session.store_client_info(client: { name: "test" }, capabilities: { elicitation: { form: {} } }) + stalled = StalledCloseStream.new + transport.instance_variable_get(:@sessions)[session_id][:get_sse_stream] = stalled + + _, _, body = transport.handle_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: "asker", arguments: {} } }.to_json, + ), + ) + call = Thread.new { body.call(TestStream.new) } + sleep(0.01) until transport.instance_variable_get(:@pending_responses).any? + delete = Thread.new { transport.handle_request(create_rack_request("DELETE", "/", { "HTTP_MCP_SESSION_ID" => session_id })) } + stalled.closing.pop + call.join + + assert_equal([[CancelledError, true]], raised) + assert(recorded[:cancelled]) + assert_equal("Session terminated", recorded[:cancellation_reason]) + ensure + stalled&.release&.push(true) + call&.join + delete&.join + transport&.close + end + test "send_request raises on error response from client" do # Create session. init_request = create_rack_request(