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|