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
14 changes: 13 additions & 1 deletion lib/json_rpc_handler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ def process_request(request, id_validation_pattern:, &method_finder)
# and a notification carries no id member at all. Refused rather than run as a notification,
# since a sender that wrote an id meant to be answered.
"Request ID must not be null"
elsif oversized_integer_id?(id)
"Request ID must be an integer of at most #{MAX_INTEGER_ID_BITS} bits"
elsif !valid_id?(id, id_validation_pattern)
if id_validation_pattern
"Request ID must be a string matching the validation pattern, or an integer"
Expand Down Expand Up @@ -217,8 +219,18 @@ def valid_version?(version)
version == Version::V2_0
end

# An integer id is written back into the response, and writing an integer out in decimal takes time that grows
# faster than its length: one of a few million digits, which fits in a request body, costs a minute of CPU.
# 128 bits leaves room for any counter and for a UUID carried as a number.
MAX_INTEGER_ID_BITS = 128

def oversized_integer_id?(id)
id.is_a?(Integer) && id.bit_length > MAX_INTEGER_ID_BITS
end

def valid_id?(id, pattern = nil)
return true if id.nil? || id.is_a?(Integer)
return true if id.nil?
return !oversized_integer_id?(id) if id.is_a?(Integer)
# A string that is not valid in its encoding cannot be written into the response,
# and matching a pattern against it raises, so it is refused before the method runs.
return false unless id.is_a?(String) && id.valid_encoding?
Expand Down
5 changes: 3 additions & 2 deletions lib/mcp/client/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,9 @@ def feed(chunk)
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.
@on_request&.call(parsed)
# 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"])
end
end
end
Expand Down
9 changes: 6 additions & 3 deletions lib/mcp/client/stdio.rb
Original file line number Diff line number Diff line change
Expand Up @@ -496,10 +496,13 @@ def answerable_ping?(parsed)
parsed["method"] == MCP::Methods::PING && json_rpc_id?(parsed["id"]) && JsonRpcHandler.valid_version?(parsed["jsonrpc"])
end

# An id the pong could not write back is skipped too: a String that is not valid UTF-8, or a number
# such as `1e400`, which the parser reads as an infinite Float that JSON cannot represent.
# An id the pong could not write back is skipped too: a String that is not valid UTF-8,
# 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 json_rpc_id?(id)
(id.is_a?(String) && id.valid_encoding?) || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
return !JsonRpcHandler.oversized_integer_id?(id) if id.is_a?(Integer)

(id.is_a?(String) && id.valid_encoding?) || (id.is_a?(Float) && id.finite?)
end

def ensure_running!
Expand Down
2 changes: 1 addition & 1 deletion lib/mcp/server/transports/stdio_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def send_response(message)
def internal_error_response(parsed)
response = { jsonrpc: JsonRpcHandler::Version::V2_0 }
id = parsed[:id] if parsed.is_a?(Hash)
response[:id] = id if id.is_a?(Integer) || (id.is_a?(String) && id.valid_encoding?)
response[:id] = id if !id.nil? && JsonRpcHandler.valid_id?(id)
response[:error] = { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal error" }
response
end
Expand Down
9 changes: 9 additions & 0 deletions lib/mcp/server/transports/streamable_http_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,8 @@ def handle_modern(request, header_version, body_string: nil)
return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
end

return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])

# The version check precedes everything else that depends on request content,
# so a client probing with an unknown future version always receives the `-32022` signal
# (with the supported list to select from) rather than an incidental error.
Expand Down Expand Up @@ -1329,6 +1331,11 @@ def echoable_id(id)
nil
end

# Answered before anything echoes the id: every refusal and response below writes it back.
def oversized_id_response
invalid_request_response("Invalid Request: id must be an integer of at most #{JsonRpcHandler::MAX_INTEGER_ID_BITS} bits")
end

def listen_subscriptions_full?
return false unless @max_listen_subscriptions

Expand Down Expand Up @@ -1848,6 +1855,8 @@ def handle_post(request, body_string: nil)
return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
end

return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])

# Header-primary routing sends sessionless modern traffic to `handle_modern` before this method runs,
# so a body carrying the modern `_meta` triple (SEP-2575) arrives here in two shapes only.
# Bound to a session under a dual-era header (2026-07-28), it is a lifecycle violation: the session
Expand Down
25 changes: 25 additions & 0 deletions test/json_rpc_handler_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,31 @@
refute called
end

it "returns an error and does not call the method when the integer request id is beyond 128 bits" do
called = false
register("add") { called = true }

handle jsonrpc: "2.0", id: 2**128, method: "add", params: { a: 1, b: 2 }

assert_rpc_error expected_error: {
code: -32600,
message: "Invalid Request",
data: "Request ID must be an integer of at most 128 bits",
}
assert_nil @response[:id]
refute called
end

it "accepts an integer request id of 128 bits" do
register("add") { |params| params[:a] + params[:b] }
id = 2**128 - 1

handle jsonrpc: "2.0", id: id, method: "add", params: { a: 1, b: 2 }

assert_rpc_success expected_result: 3
assert_equal id, @response[:id]
end

it "accepts string id with alphanumerics, dashes, and underscores" do
register("add") { |params| params[:a] + params[:b] }
id = "request-123_ABC"
Expand Down
23 changes: 23 additions & 0 deletions test/mcp/client/http_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1733,6 +1733,29 @@ def test_send_request_answers_a_server_ping_with_an_empty_result
assert_requested(pong_stub)
end

def test_a_server_request_whose_integer_id_is_beyond_128_bits_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: [] } }
sse_body = <<~BODY
event: message
data: {"jsonrpc":"2.0","id":#{2**128},"method":"ping"}

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 pong would be a POST that no stub matches, which WebMock raises on.
response = client.send_request(request: request)

assert_equal({ "content" => [] }, response["result"])
end

def test_a_registered_ping_handler_overrides_the_default_pong
request = {
jsonrpc: "2.0",
Expand Down
8 changes: 8 additions & 0 deletions test/mcp/client/stdio_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,14 @@ def test_a_ping_whose_id_is_not_valid_utf_8_is_not_answered
assert(transport.send(:answerable_ping?, ping.merge("id" => "p")))
end

def test_a_ping_whose_integer_id_is_beyond_128_bits_is_not_answered
transport = Stdio.new(command: "ruby", args: ["server.rb"])
ping = { "jsonrpc" => "2.0", "id" => 2**128, "method" => "ping" }

refute(transport.send(:answerable_ping?, ping))
assert(transport.send(:answerable_ping?, ping.merge("id" => 2**128 - 1)))
end

def test_a_ping_whose_id_parses_to_an_infinite_float_is_not_answered_and_the_request_completes
written = []
server = lambda do |requests, frames|
Expand Down
21 changes: 21 additions & 0 deletions test/mcp/server/transports/streamable_http_transport_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6531,6 +6531,27 @@ def string
end
end

test "a POST whose integer id is beyond 128 bits is refused with no id on either lifecycle" do
# Every refusal and response writes the id back, and writing a huge integer out is what costs the time,
# so the refusal comes before anything echoes it and carries no id itself.
@server.expects(:handle).never
modern = modern_body("ping", {}).sub('"id":1', "\"id\":#{2**128}")
legacy = { jsonrpc: "2.0", method: "initialize", id: 1, params: initialize_params }.to_json.sub('"id":1', "\"id\":#{2**128}")

responses = [
@transport.handle_request(modern_rack_request(modern)),
@transport.handle_request(create_rack_request("POST", "/", { "CONTENT_TYPE" => "application/json" }, legacy)),
]

responses.each do |response|
assert_equal 400, response[0]
parsed = JSON.parse(response[2][0])
assert_equal JsonRpcHandler::ErrorCode::INVALID_REQUEST, parsed.dig("error", "code")
assert_equal "Invalid Request: id must be an integer of at most 128 bits", parsed.dig("error", "message")
refute parsed.key?("id")
end
end

test "modern POST without the Mcp-Method header returns 400 with -32020" do
# The header is required on every modern POST; a missing required standard header is
# a validation failure, matching the TypeScript SDK's enforcement.
Expand Down
Loading