From c54cc1724bb1ba3a9a40f83374f82ba209fced53 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Wed, 11 Nov 2026 03:12:26 +0900 Subject: [PATCH] Keep the error code of a refusal that quotes bytes that are not valid UTF-8 ## Motivation and Context The text of a `RequestHandlerError` often quotes what the client sent: "Tool not found: ", "Invalid log level ". The JSON parser passes bytes that are not valid UTF-8 through, and generating the response from such a text raises, so `JsonRpcHandler` fell back to its replacement for a response it cannot generate. A `tools/call` naming a tool with such bytes on a legacy session was answered `-32603` Internal error where an unknown tool gets `-32602` Invalid params, and the generation error went to the exception reporter as if the server had failed. `JsonRpcHandler` now replaces those bytes with U+FFFD in the `message` and `data` of a request handler error, as the Streamable HTTP transport does for the values its own refusals quote, so the error keeps its code and its text. The texts inside a structured `data` are treated the same way, String keys included, such as the `uri` that `ResourceNotFoundError` carries. A `data` that cannot be written, because a Hash or Array in it holds itself or because it nests deeper than `JSON.generate` goes, is left as it is and still fails in the generator at once, as it did. In one that can be written, a Hash or Array held many times is converted once. ## How Has This Been Tested? `test/json_rpc_handler_test.rb`. Against the previous library the tests of bytes that are not valid UTF-8, in the message and in `data`, get `-32603` and a `JSON::GeneratorError` report, and the tests of a text in another encoding get that text back untranscoded. Without any check, the test of a `data` that cannot be written ends in `SystemStackError`, and with a bound on the depth alone, a check along one path at a time, or a check for cycles alone, it does not end within its time limit. ## Breaking Changes None. A valid UTF-8 text comes through unchanged, and a text valid in another encoding is transcoded to UTF-8 where Ruby has a converter for it. --- lib/json_rpc_handler.rb | 96 +++++++++++++++++- test/json_rpc_handler_test.rb | 177 ++++++++++++++++++++++++++++++++++ 2 files changed, 271 insertions(+), 2 deletions(-) diff --git a/lib/json_rpc_handler.rb b/lib/json_rpc_handler.rb index aa566468..ff52f3b9 100644 --- a/lib/json_rpc_handler.rb +++ b/lib/json_rpc_handler.rb @@ -210,11 +210,103 @@ def handle_request_error(error, id, id_validation_pattern) error_response(id: id, id_validation_pattern: id_validation_pattern, error: { code: code, - message: message, - data: data, + message: printable_text(message), + data: printable_data(data), }) end + # The text of a request handler error often quotes what the client sent, such as the name of a tool that does not exist, + # and the parser passes bytes that are not valid UTF-8 through. Generating the response from such a text raises, + # which would replace the error and its code with Internal error. Those bytes are replaced with U+FFFD; a valid UTF-8 text, + # and `data` that is not a String, come through unchanged. A text in another encoding is transcoded. + # A binary one has no characters to transcode, and Ruby has no converter for some encodings, such as UTF-7; + # those are read as UTF-8, so that this never raises in place of the error it is writing. + def printable_text(value) + return value unless value.is_a?(String) + return value if value.encoding == Encoding::UTF_8 && value.valid_encoding? + + unless value.encoding == Encoding::UTF_8 || value.encoding == Encoding::BINARY + begin + return value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace) + rescue EncodingError + # Falls through to the bytes read as UTF-8. + end + end + + value.dup.force_encoding(Encoding::UTF_8).scrub + end + + # `data` can quote the request as well, inside a structure: `ResourceNotFoundError` carries `{ uri: }`. + # The texts in it, String keys included, get the treatment of `printable_text`; anything else comes through unchanged. + # A key that is not a String is written as its text, so it is left as it is. + # + # A `data` in which a Hash or Array holds itself, or that nests deeper than `MAX_PRINTABLE_DATA_DEPTH`, cannot be written + # and comes through unchanged as a whole: the generator refuses it at once, as it would have without this, + # and following it here could take far longer than that. In one that can be written, a Hash or Array is converted once, + # however many times it is held; `converted` maps each to its copy. + def printable_data(value, converted = nil) + case value + when String + printable_text(value) + when Hash, Array + if converted.nil? + return value unless nests_within?(value, MAX_PRINTABLE_DATA_DEPTH) + + converted = {}.compare_by_identity + end + + converted[value] ||= if value.is_a?(Hash) + value.to_h { |key, member| [key.is_a?(String) ? printable_text(key) : key, printable_data(member, converted)] } + else + value.map { |member| printable_data(member, converted) } + end + else + value + end + end + + # Whether the Hashes and Arrays that `container` holds through its values and members, itself included, nest + # at most `limit` deep and never hold themselves. One pass, without recursion: a Hash or Array is entered once + # however many times it is held, and `depths` keeps how deep the nesting goes below each, or `:open` while it is + # being looked into. Meeting one that is `:open` closes a cycle. + def nests_within?(container, limit) + depths = {}.compare_by_identity + depths[container] = :open + # Each entry: a Hash or Array, those it holds that are still to be looked at, and how deep it nests as far as is known. + path = [[container, containers_in(container), 1]] + + until path.empty? + entry = path.last + inner = entry[1].pop + + if inner.nil? + return false if entry[2] > limit + + depths[entry[0]] = entry[2] + path.pop + path.last[2] = [path.last[2], entry[2] + 1].max unless path.empty? + elsif depths[inner] == :open + return false + elsif depths.key?(inner) + entry[2] = [entry[2], depths[inner] + 1].max + else + depths[inner] = :open + path << [inner, containers_in(inner), 1] + end + end + + true + end + + def containers_in(container) + (container.is_a?(Hash) ? container.values : container).select { |member| member.is_a?(Hash) || member.is_a?(Array) } + end + + # `JSON.generate` writes 100 levels by default, and `data` already sits two levels down in a response, + # so nothing that can be written nests deeper than this. + MAX_PRINTABLE_DATA_DEPTH = 100 + private_constant :MAX_PRINTABLE_DATA_DEPTH + def valid_version?(version) version == Version::V2_0 end diff --git a/test/json_rpc_handler_test.rb b/test/json_rpc_handler_test.rb index 1236b7fb..9f397175 100644 --- a/test/json_rpc_handler_test.rb +++ b/test/json_rpc_handler_test.rb @@ -623,6 +623,183 @@ } end + it "keeps the code of a RequestHandlerError whose message holds bytes that are not valid UTF-8" do + errors = [] + name = [0x6E, 0xFF].pack("C*").force_encoding(Encoding::UTF_8) + registry = { + "test_method" => ->(_params) { raise MCP::Server::RequestHandlerError.new("Tool not found: #{name}", {}, error_type: :invalid_params) }, + } + + response_json = JsonRpcHandler.handle_json( + { jsonrpc: "2.0", id: 1, method: "test_method" }.to_json, + on_generate_error: ->(error) { errors << error.class }, + ) { |method_name, _request_id| registry[method_name] } + + assert_equal( + { code: -32602, message: "Invalid params", data: "Tool not found: n\uFFFD" }, + JSON.parse(response_json, symbolize_names: true)[:error], + ) + assert_empty(errors) + end + + it "keeps the code of a RequestHandlerError whose data holds bytes that are not valid UTF-8" do + errors = [] + uri = [0x66, 0xFF].pack("C*").force_encoding(Encoding::UTF_8) + registry = { + "test_method" => lambda do |_params| + raise MCP::Server::RequestHandlerError.new( + "Resource not found", + {}, + error_type: :invalid_params, + error_data: { uri: uri, "#{uri}key" => [uri, 1] }, + ) + end, + } + + response_json = JsonRpcHandler.handle_json( + { jsonrpc: "2.0", id: 1, method: "test_method" }.to_json, + on_generate_error: ->(error) { errors << error.class }, + ) { |method_name, _request_id| registry[method_name] } + + assert_equal( + { code: -32602, message: "Invalid params", data: { uri: "f�", "f�key": ["f�", 1] } }, + JSON.parse(response_json, symbolize_names: true)[:error], + ) + assert_empty(errors) + end + + it "replaces the bytes that are not valid UTF-8 as deep inside the data of a RequestHandlerError as a response can hold them" do + uri = [0x66, 0xFF].pack("C*").force_encoding(Encoding::UTF_8) + # A response holds `data` two levels down, and the generator writes 100 levels. + nested = 98.times.inject(uri) { |inner, _| [inner] } + errors = [] + registry = { + "test_method" => lambda do |_params| + raise MCP::Server::RequestHandlerError.new("Resource not found", {}, error_type: :invalid_params, error_data: nested) + end, + } + + response_json = JsonRpcHandler.handle_json( + { jsonrpc: "2.0", id: 1, method: "test_method" }.to_json, + on_generate_error: ->(error) { errors << error.class }, + ) { |method_name, _request_id| registry[method_name] } + + error = JSON.parse(response_json, symbolize_names: true)[:error] + assert_equal(-32602, error[:code]) + assert_equal("f\uFFFD", error[:data].flatten.first) + assert_empty(errors) + end + + it "leaves the data of a RequestHandlerError that contains itself to the generator, which refuses it at once" do + once = {} + once[:itself] = once + twice = [] + twice << twice << twice + mutual = [[]] + mutual.first << mutual + # Each holds the next twice and the last holds the first: one cycle, reached along a great many paths. + chain = Array.new(30) { [] } + chain.each_cons(2) { |holder, held| holder << held << held } + chain.last << chain.first + # The same without the cycle, and deeper than a response can be written: no end to the paths, and none can be written. + deep = Array.new(120) { [] } + deep.each_cons(2) { |holder, held| holder << held << held } + # A few levels held twice each, over a run too long to write. + tailed = Array.new(24) { [] } + tailed.each_cons(2) { |holder, held| holder << held << held } + tailed.last << 90.times.inject("x") { |inner, _| [inner] } + + [once, twice, mutual, chain.first, { held: chain.first }, deep.first, tailed.first].each do |data| + registry = { + "test_method" => lambda do |_params| + raise MCP::Server::RequestHandlerError.new("Resource not found", {}, error_type: :invalid_params, error_data: data) + end, + } + + # Not a stack overflow, and not a walk down every path either: the structure fails the way it did + # before its texts were looked at. The time limit only keeps a regression from hanging the suite. + Timeout.timeout(5) do + assert_raises(JSON::NestingError) do + JsonRpcHandler.handle_json({ jsonrpc: "2.0", id: 1, method: "test_method" }.to_json) do |method_name, _request_id| + registry[method_name] + end + end + end + end + end + + it "replaces the bytes that are not valid UTF-8 in a value the data of a RequestHandlerError holds twice" do + uri = [0x66, 0xFF].pack("C*").force_encoding(Encoding::UTF_8) + shared = [uri] + register("test_method") do + raise MCP::Server::RequestHandlerError.new("Resource not found", {}, error_type: :invalid_params, error_data: [shared, shared]) + end + + handle jsonrpc: "2.0", id: 1, method: "test_method" + + assert_equal([["f\uFFFD"], ["f\uFFFD"]], @response.dig(:error, :data)) + end + + it "answers a RequestHandlerError whose data is keyed by a value that holds itself, which is written as its text" do + key = [] + key << key + register("test_method") do + raise MCP::Server::RequestHandlerError.new("Resource not found", {}, error_type: :invalid_params, error_data: { key => "value" }) + end + + response_json = Timeout.timeout(5) do + JsonRpcHandler.handle_json({ jsonrpc: "2.0", id: 1, method: "test_method" }.to_json) do |_method_name, _request_id| + ->(_params) { raise MCP::Server::RequestHandlerError.new("Resource not found", {}, error_type: :invalid_params, error_data: { key => "value" }) } + end + end + + error = JSON.parse(response_json)["error"] + assert_equal(-32602, error["code"]) + assert_equal({ key.to_s => "value" }, error["data"]) + end + + it "converts a value the data of a RequestHandlerError holds many times once, and writes it in every place" do + uri = [0x66, 0xFF].pack("C*").force_encoding(Encoding::UTF_8) + # Fourteen levels, each holding the next twice: 8,192 places for the one text, in fourteen Arrays. + levels = Array.new(14) { [] } + levels.each_cons(2) { |holder, held| holder << held << held } + levels.last << uri + conversions = 0 + counting = JsonRpcHandler.method(:printable_text) + JsonRpcHandler.define_singleton_method(:printable_text) do |value| + conversions += 1 + counting.call(value) + end + + begin + converted = JsonRpcHandler.printable_data(levels.first) + ensure + JsonRpcHandler.singleton_class.send(:remove_method, :printable_text) + end + + assert_equal(1, conversions) + assert_equal(8192, JSON.parse(JSON.generate(converted)).flatten.count("f\uFFFD")) + end + + it "transcodes the message of a RequestHandlerError that is valid in another encoding" do + latin1 = [0x63, 0x61, 0x66, 0xE9].pack("C*").force_encoding(Encoding::ISO_8859_1) + register("test_method") { raise MCP::Server::RequestHandlerError.new(latin1, {}, error_type: :invalid_params) } + + handle jsonrpc: "2.0", id: 1, method: "test_method" + + assert_rpc_error expected_error: { code: -32602, message: "Invalid params", data: latin1.encode(Encoding::UTF_8) } + end + + it "keeps the code of a RequestHandlerError whose message is in an encoding Ruby cannot convert" do + unconvertible = "Tool not found".dup.force_encoding(Encoding::UTF_7) + register("test_method") { raise MCP::Server::RequestHandlerError.new(unconvertible, {}, error_type: :invalid_params) } + + handle jsonrpc: "2.0", id: 1, method: "test_method" + + assert_rpc_error expected_error: { code: -32602, message: "Invalid params", data: "Tool not found" } + assert_equal 1, @response[:id] + end + it "returns an error with the code set to -32700 when error_type of RequestHandlerError is :parse_error" do register("test_method") do raise MCP::Server::RequestHandlerError.new(