Skip to content
Merged
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
21 changes: 12 additions & 9 deletions lib/mcp/server/transports/streamable_http_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1946,8 +1946,8 @@ def handle_post(request, body_string: nil)
# dispatching it against the shared `Server`. Mirrors the response and regular-request
# branches; without it a custom notification handler could run without a live session.
return session_not_found_response if !@stateless && !session_active?(session_id)
return session_not_found_response unless dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])

dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
handle_accepted
elsif response?(body)
return session_not_found_response if !@stateless && !session_exists?(session_id)
Expand Down Expand Up @@ -2335,20 +2335,22 @@ def notification?(body)

# Dispatches a client-originated notification (e.g. `notifications/cancelled`,
# `notifications/initialized`) through the server so it can update session state.
# Returns false, without dispatching, when the session was removed after the caller checked it,
# and true otherwise, including when the dispatch raised.
def dispatch_notification(body_string, session_id, auth_info: nil)
server_session = nil
if @stateless
server_session = ephemeral_session
elsif session_id
@mutex.synchronize do
session = @sessions[session_id]
server_session = session[:server_session] if session
end
server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
return false unless server_session
end

dispatch_handle_json(body_string, server_session, auth_info: auth_info)
true
rescue => e
MCP.configuration.exception_reporter.call(e, { error: "Failed to dispatch notification" })
true
end

def response?(body)
Expand Down Expand Up @@ -2476,10 +2478,11 @@ def handle_regular_request(body_string, session_id, related_request_id: nil, aut
error_response = validate_and_touch_session(session_id)
return error_response if error_response

@mutex.synchronize do
session = @sessions[session_id]
server_session = session[:server_session] if session
end
server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
# The session may have been removed since the check above, by a `DELETE` from another connection or by `close`.
# The request is refused as one naming an unknown session: dispatched without one, it would run against
# the shared `Server`, outside the session whose termination cancels it.
return session_not_found_response unless server_session
end

# `Server` refuses a duplicate id as well, but only once the request reaches it. The SSE branch below
Expand Down
80 changes: 80 additions & 0 deletions test/mcp/server/transports/streamable_http_transport_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4248,6 +4248,66 @@ def string
transport&.close
end

[false, true].each do |json_response|
test "a request whose session is terminated after its session check is refused, not run (json_response: #{json_response})" do
server = Server.new(name: "test", tools: [], prompts: [], resources: [])
transport = StreamableHTTPTransport.new(server, enable_json_response: json_response)
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)
checked, resume = hold_after_session_check(transport, :validate_and_touch_session)

call = Thread.new { transport.handle_request(effect_tool_call(session_id, "call-1")) }
checked.pop
transport.handle_request(create_rack_request("DELETE", "/", { "HTTP_MCP_SESSION_ID" => session_id }))
resume << true
status, _, body = call.value

assert_equal(404, status)
assert_equal(0, invocations)
assert_equal("Session not found", JSON.parse(body.first).dig("error", "message"))
ensure
resume&.push(true)
call&.join
transport&.close
end
end

test "a notification whose session is terminated after its session check is refused, not run" do
server = Server.new(name: "test", tools: [], prompts: [], resources: [])
transport = StreamableHTTPTransport.new(server)
server.transport = transport
deliveries = 0
server.define_custom_method(method_name: "notifications/custom") do |_params|
deliveries += 1
nil
end
session_id, = start_session(transport)
checked, resume = hold_after_session_check(transport, :session_active?)

notification = create_rack_request(
"POST",
"/",
{ "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id },
{ jsonrpc: "2.0", method: "notifications/custom", params: {} }.to_json,
)
call = Thread.new { transport.handle_request(notification) }
checked.pop
transport.handle_request(create_rack_request("DELETE", "/", { "HTTP_MCP_SESSION_ID" => session_id }))
resume << true

assert_equal(404, call.value[0])
assert_equal(0, deliveries)
ensure
resume&.push(true)
call&.join
transport&.close
end

test "every other path that removes a session cancels the requests in flight in it" do
attach_get_stream = ->(transport, session_id) do
TestStream.new.tap { |stream| transport.instance_variable_get(:@sessions)[session_id][:get_sse_stream] = stream }
Expand Down Expand Up @@ -9148,6 +9208,26 @@ def define_held_tool(server, cancellations:, started:, release:)
end
end

# Holds the first request through the transport's `check` (a session check that passes) once it has passed, which is
# where a `DELETE` from another connection can land before the request looks its session up.
# Returns the queue the held request pushes to and the one that releases it.
def hold_after_session_check(transport, check)
checked = Queue.new
resume = Queue.new
held = false
transport.define_singleton_method(check) do |*args, **kwargs|
result = super(*args, **kwargs)
unless held
held = true
checked << true
resume.pop
end
result
end

[checked, resume]
end

def effect_tool_call(session_id, request_id)
create_rack_request(
"POST",
Expand Down