Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions lib/mcp/server/transports/streamable_http_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
88 changes: 88 additions & 0 deletions test/mcp/server/transports/streamable_http_transport_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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(
Expand Down