From 67dab994b7cdc1c434298e83b5bd647e236120ec Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Thu, 26 Nov 2026 18:43:47 +0800 Subject: [PATCH] fix: check the ids of SSE messages in the HTTP client ## Motivation and Context `MCP::Client::HTTP` reads the SSE stream a POST is answered with through `SSEStream`, which has two gaps that `MCP::Client::Stdio` does not have. It takes the first event carrying `result` or `error` as the response, whatever its `id`. A response to another request on the stream is returned as the answer to the request being sent, and the stream is closed before the real response arrives. `Client::Stdio` only returns a response whose `id` is the awaited one. It answers a server-to-client request on the stream unless its integer id is beyond 128 bits. An id such as `1e400`, which the JSON parser reads as `Infinity`, passes that check, and writing the answer raises `JSON::GeneratorError` out of `send_request`, so the request being sent fails because of a message the client could never answer. `Client::Stdio` already skips a ping whose id cannot be written back (#628). `SSEStream` now gets the id of the request being sent and skips a response that carries a different id. A response carrying no id is still taken: it is how a server refuses a request whose id it could not read, and the POST stream answers only that request. Server-to-client requests whose id is a non-finite number are dropped unanswered, like those with an oversized integer id. A request with an id that is malformed but can be written back (an object, for example) is still answered with Method not found, as an existing test requires. ## How Has This Been Tested? New tests in `test/mcp/client/http_test.rb`: a response carrying another request's id is skipped and the request's own response is returned (the other one was returned before); `ping` and `elicitation/create` requests with the ids `1e400` and `-1e400` are not answered and the request being sent still gets its response (it raised `JSON::GeneratorError` before); an error response carrying no id is still returned. The first two fail against the previous library; the third passed before and guards the id-less case. The SSE fixture of `test_connect_raises_on_an_initialize_response_that_is_not_json_rpc_2_0` answered `initialize` with the id `"1"`, while the client sends a UUID. The fixture now carries no id, so the test still checks the missing `jsonrpc` member rather than the id. Not passing the request id, dropping the id check, also skipping responses carrying no id, or skipping only oversized integer ids each fails one of these tests. ## Breaking Changes None for a server that answers each request with its own id. Fixes #717. --- lib/mcp/client/http.rb | 20 ++++++++--- test/mcp/client/http_test.rb | 69 +++++++++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 5 deletions(-) diff --git a/lib/mcp/client/http.rb b/lib/mcp/client/http.rb index 10243ae2..6fe7beb9 100644 --- a/lib/mcp/client/http.rb +++ b/lib/mcp/client/http.rb @@ -123,10 +123,11 @@ class SSEStream attr_reader :buffer, :response, :response_headers, :last_event_id, :retry_ms attr_accessor :abortable - def initialize(abortable:, max_message_bytes: MAX_MESSAGE_BYTES, on_request: nil) + def initialize(abortable:, max_message_bytes: MAX_MESSAGE_BYTES, on_request: nil, request_id: nil) @abortable = abortable @max_message_bytes = max_message_bytes @on_request = on_request + @request_id = request_id @buffer = +"" @parser = nil @response = nil @@ -213,17 +214,27 @@ def feed(chunk) next unless parsed.is_a?(Hash) if parsed.key?("result") || parsed.key?("error") + # A response carrying the id of another request does not answer this one. One carrying no id + # still does: it is how a server refuses a request whose id it could not read. + next if @request_id && !parsed["id"].nil? && parsed["id"] != @request_id + @response ||= parsed elsif parsed["method"] && parsed.key?("id") && JsonRpcHandler.valid_version?(parsed["jsonrpc"]) # A server-to-client request (e.g. `elicitation/create`) delivered on the stream while # the original request is still pending. One that is not JSON-RPC 2.0 is dropped unanswered, - # as the TypeScript client drops it at schema validation, and so is one whose integer id is - # too large to write back at a reasonable cost. - @on_request&.call(parsed) unless JsonRpcHandler.oversized_integer_id?(parsed["id"]) + # as the TypeScript client drops it at schema validation, and so is one whose id cannot be written back. + @on_request&.call(parsed) unless unwritable_id?(parsed["id"]) end end end + # An id the answer could not carry, as `Client::Stdio` skips a ping with one: a number such as `1e400`, + # which the parser reads as an infinite Float that JSON cannot represent, or an integer too large to write back + # at a reasonable cost. + def unwritable_id?(id) + JsonRpcHandler.oversized_integer_id?(id) || (id.is_a?(Float) && !id.finite?) + end + # Bytes the parser has buffered for a not-yet-dispatched event: the partial line # and the accumulated `data:` field values (plus the small event type and last event id buffers). # External byte counting cannot tell consumed-and-discarded bytes (comments, field names, delimiters) @@ -430,6 +441,7 @@ def send_request(request:) abortable: true, max_message_bytes: @max_message_bytes, on_request: ->(message) { dispatch_server_request(message) }, + request_id: request_id, ) yield if block_given? diff --git a/test/mcp/client/http_test.rb b/test/mcp/client/http_test.rb index 34b9ff49..8d995a39 100644 --- a/test/mcp/client/http_test.rb +++ b/test/mcp/client/http_test.rb @@ -1756,6 +1756,73 @@ def test_a_server_request_whose_integer_id_is_beyond_128_bits_is_not_answered assert_equal({ "content" => [] }, response["result"]) end + def test_a_server_request_whose_id_cannot_be_written_back_is_not_answered + request = { jsonrpc: "2.0", id: "test_id", method: "tools/call", params: { name: "some_tool", arguments: {} } } + tool_result = { jsonrpc: "2.0", id: "test_id", result: { content: [] } } + + # `1e400` parses as an infinite Float, which JSON cannot write back. + ["1e400", "-1e400"].each do |id| + ["ping", "elicitation/create"].each do |method| + sse_body = <<~BODY + event: message + data: {"jsonrpc":"2.0","id":#{id},"method":"#{method}","params":{}} + + event: message + data: #{tool_result.to_json} + + BODY + stub_request(:post, url).with(body: request.to_json).to_return( + status: 200, + headers: { "Content-Type" => "text/event-stream" }, + body: sse_body, + ) + + # Any answer would be a POST that no stub matches, which WebMock raises on. + response = client.send_request(request: request) + + assert_equal({ "content" => [] }, response["result"], "id: #{id}, method: #{method}") + end + end + end + + def test_send_request_skips_a_response_carrying_another_request_id + request = { jsonrpc: "2.0", id: "test_id", method: "tools/call", params: { name: "some_tool", arguments: {} } } + other_result = { jsonrpc: "2.0", id: "other_id", result: { content: [{ type: "text", text: "other" }] } } + tool_result = { jsonrpc: "2.0", id: "test_id", result: { content: [] } } + sse_body = <<~BODY + event: message + data: #{other_result.to_json} + + event: message + data: #{tool_result.to_json} + + BODY + stub_request(:post, url).with(body: request.to_json).to_return( + status: 200, + headers: { "Content-Type" => "text/event-stream" }, + body: sse_body, + ) + + response = client.send_request(request: request) + + assert_equal("test_id", response["id"]) + assert_equal({ "content" => [] }, response["result"]) + end + + def test_send_request_takes_an_error_response_carrying_no_id + request = { jsonrpc: "2.0", id: "test_id", method: "tools/call", params: { name: "some_tool", arguments: {} } } + error_response = { jsonrpc: "2.0", id: nil, error: { code: -32600, message: "Invalid Request" } } + stub_request(:post, url).with(body: request.to_json).to_return( + status: 200, + headers: { "Content-Type" => "text/event-stream" }, + body: "event: message\ndata: #{error_response.to_json}\n\n", + ) + + response = client.send_request(request: request) + + assert_equal({ "code" => -32600, "message" => "Invalid Request" }, response["error"]) + end + def test_a_registered_ping_handler_overrides_the_default_pong request = { jsonrpc: "2.0", @@ -3302,7 +3369,7 @@ def test_connect_raises_on_an_initialize_response_that_is_not_json_rpc_2_0 answers = { "application/json" => { result: { protocolVersion: "2025-11-25" } }.to_json, # The `initialize` stream is read to its end instead of being aborted at the response. - "text/event-stream" => %(data: {"id":"1","result":{"protocolVersion":"2025-11-25"}}\n\n), + "text/event-stream" => %(data: {"result":{"protocolVersion":"2025-11-25"}}\n\n), } answers.each do |content_type, body| stub_request(:post, url).with { |req|