From cb6f22a02748fa63f1f6a74bfd9558ff829d0ac2 Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Fri, 20 Nov 2026 16:57:24 +0800 Subject: [PATCH] fix: refuse a duplicate SSE request that loses the stream claim ## Motivation and Context #521 refuses a POST that reuses the id of a request in flight in its session, with 409 before anything is registered. Two POSTs sent together under the same id can both pass that check, since neither is registered until its SSE body runs. Their bodies then claim the id's stream and register the id in `ServerSession` in two separate steps. The body that loses the stream claim still dispatches, and when it registers the id before the owner does, the duplicate runs the tool, its request-scoped messages (progress, server-to-client requests) go to the owner's stream, and the owner is refused. Once the duplicate finishes, the owner registers the id and runs the tool a second time. The claim is now the decision: a body that finds the id's stream taken answers on its own stream with the same Invalid Request error the 409 carries, with the request's id, and does not dispatch. Requests that reach the claim with no session or no id dispatch as before, and the stream owner is unchanged. ## How Has This Been Tested? A new test in `test/mcp/server/transports/streamable_http_transport_test.rb` answers two POSTs with the same id, holds the first after it claimed the stream and before it registered, and runs the second meanwhile. The tool runs once, for the owner, whose stream gets its progress and result, and the duplicate's stream gets the Invalid Request error with its id. It fails against the previous library, where the tool runs twice and the duplicate's progress reaches the owner's stream. Another new test guards two sessions that use the same id at the same time. Dispatching the refused request, answering it with nothing, or leaving out its id each fails a test. ## Breaking Changes None. A client that sends two requests with the same id at once (which the spec forbids) gets an Invalid Request error for the second instead of running it. --- .../transports/streamable_http_transport.rb | 27 +++++-- .../streamable_http_transport_test.rb | 81 +++++++++++++++++++ 2 files changed, 101 insertions(+), 7 deletions(-) diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 69f20a21..f83f217c 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -444,6 +444,8 @@ class StreamWriteTimeoutError < IOError; end # The reason the requests still in flight in a session are cancelled with when the session goes away: terminated by # the client's DELETE, expired, torn down with its broken GET stream, or removed by `close`. SESSION_TERMINATED_REASON = "Session terminated" + # The error message a request reusing the id of one in flight in its session is refused with. + REQUEST_ID_CONFLICT_MESSAGE = "Conflict: Request id is already in flight for this session" # Loopback hosts always accepted by DNS rebinding protection. A locally bound MCP server (the canonical pattern) is # protected out of the box; non-loopback deployments widen the list via `allowed_hosts:`. @@ -2513,28 +2515,34 @@ def handle_request_with_sse_response(body_string, session_id, server_session, re # the event store and routes a `Last-Event-ID` resume back to the request (SEP-1699). # It is minted whether or not a store is configured, so the registration has one shape. stream_id = mint_stream_id(session_id) - claimed = @mutex.synchronize do + claim = @mutex.synchronize do session = @sessions[session_id] - next false unless session && related_request_id + next unless session && related_request_id session[:post_request_streams] ||= {} session[:post_stream_entries] ||= {} # Claim the id only while it is free. `handle_regular_request` already refused the colliding request, # so reaching an occupied slot means a race got past that check; leaving the first stream in place keeps - # its messages going where they belong. - next false if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id) + # its messages going where they belong, and the request that lost the claim is refused below without + # running, since it could otherwise register the id before the owner does. + next :taken if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id) session[:post_request_streams][related_request_id] = stream session[:post_stream_entries][related_request_id] = { stream_id: stream_id, resumed: nil } - true + :claimed end + claimed = claim == :claimed write_priming_event(session_id, related_request_id, stream) if claimed begin - response = dispatch_handle_json(body_string, server_session, auth_info: auth_info) + response = if claim == :taken + request_id_conflict_message(related_request_id) + else + dispatch_handle_json(body_string, server_session, auth_info: auth_info) + end if response # Written through the registration rather than to `stream`: the response of a request whose connection was @@ -2831,10 +2839,15 @@ def request_id_conflict_response json_rpc_error_response( status: 409, code: JsonRpcHandler::ErrorCode::INVALID_REQUEST, - message: "Conflict: Request id is already in flight for this session", + message: REQUEST_ID_CONFLICT_MESSAGE, ) end + # The same refusal, for a request whose SSE response has already started. + def request_id_conflict_message(request_id) + { jsonrpc: "2.0", id: request_id, error: { code: JsonRpcHandler::ErrorCode::INVALID_REQUEST, message: REQUEST_ID_CONFLICT_MESSAGE } }.to_json + end + def setup_sse_stream(session_id, auth_info = nil) body = create_sse_body(session_id, auth_info) diff --git a/test/mcp/server/transports/streamable_http_transport_test.rb b/test/mcp/server/transports/streamable_http_transport_test.rb index d6df2192..36975eaa 100644 --- a/test/mcp/server/transports/streamable_http_transport_test.rb +++ b/test/mcp/server/transports/streamable_http_transport_test.rb @@ -3884,6 +3884,87 @@ def string assert_includes victim_stream.string, "second-frame" end + test "a duplicate request that passed the pre-dispatch check but lost the stream claim is not run" do + server = Server.new(name: "test", tools: [], prompts: [], resources: []) + transport = StreamableHTTPTransport.new(server) + server.transport = transport + + invocations = 0 + server.define_tool(name: "victim_tool") do |server_context:| + invocations += 1 + server_context.report_progress(1, message: "frame-of-run-#{invocations}") + Tool::Response.new([{ type: "text", text: "done" }]) + end + + session_id, server_session = start_session(transport) + + # Both requests are answered before either is dispatched, so both pass the in-flight check. + owner = transport.handle_request(colliding_tool_call(session_id, "req-1")) + duplicate = transport.handle_request(colliding_tool_call(session_id, "req-1")) + + # Holds the owner after it claimed the request id's stream and before `Server` registers the id. + owner_claimed = Queue.new + resume_owner = Queue.new + held = false + server_session.define_singleton_method(:handle_json) do |*args, **kwargs| + unless held + held = true + owner_claimed << true + resume_owner.pop + end + super(*args, **kwargs) + end + + owner_stream = TestStream.new + owner_thread = Thread.new { owner[2].call(owner_stream) } + owner_claimed.pop + + duplicate_stream = TestStream.new + duplicate[2].call(duplicate_stream) + + resume_owner << true + owner_thread.join + + assert_equal(1, invocations) + assert_includes(owner_stream.string, "frame-of-run-1") + assert_includes(owner_stream.string, "done") + duplicate_error = JSON.parse(duplicate_stream.string[/^data: (.+)$/, 1]) + assert_equal("req-1", duplicate_error["id"]) + assert_equal(JsonRpcHandler::ErrorCode::INVALID_REQUEST, duplicate_error.dig("error", "code")) + ensure + resume_owner&.push(true) + owner_thread&.join + end + + test "requests in two sessions may carry the same id at the same time" do + server = Server.new(name: "test", tools: [], prompts: [], resources: []) + transport = StreamableHTTPTransport.new(server) + server.transport = transport + + started = Queue.new + release = Queue.new + server.define_tool(name: "victim_tool") do |server_context:| + started << true + release.pop + Tool::Response.new([{ type: "text", text: "done" }]) + end + + first_session_id, = start_session(transport) + second_session_id, = start_session(transport) + first = transport.handle_request(colliding_tool_call(first_session_id, "req-1")) + second = transport.handle_request(colliding_tool_call(second_session_id, "req-1")) + streams = [TestStream.new, TestStream.new] + threads = [first, second].zip(streams).map { |response, stream| Thread.new { response[2].call(stream) } } + 2.times { started.pop } + 2.times { release << true } + threads.each(&:join) + + streams.each { |stream| assert_includes(stream.string, "done") } + ensure + 2.times { release&.push(true) } + threads&.each(&:join) + end + test "a finishing request leaves a stream another request registered under the same id" do server = Server.new(name: "test", tools: [], prompts: [], resources: []) transport = StreamableHTTPTransport.new(server)