From b663d52fcf0840e062a41b7b85092d29bd673574 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, keys included, such as the `uri` that `ResourceNotFoundError` carries. A `data` that holds itself is left as it is, and so is whatever lies deeper than `JSON.generate` writes, so a `data` that cannot be written still fails in the generator at once, as it did. ## 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 the check for a `data` that holds itself, the test of such a `data` ends in `SystemStackError`, and with a bound on the depth alone, or a check along one path at a time, 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 | 82 +++++++++++++++++++- test/json_rpc_handler_test.rb | 142 ++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+), 2 deletions(-) diff --git a/lib/json_rpc_handler.rb b/lib/json_rpc_handler.rb index aa566468..bbc3dcf0 100644 --- a/lib/json_rpc_handler.rb +++ b/lib/json_rpc_handler.rb @@ -210,11 +210,89 @@ 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, keys included, get the treatment of `printable_text`; anything else comes through unchanged. + # So does a `data` that holds itself, however indirectly, and whatever lies deeper than the generator writes: + # neither can be written, so they are left for the generator to refuse at once, as it would have without this. + # A key that is not a String is written as its text, so only the keys that are Strings are looked at. + def printable_data(value, depth = 0) + case value + when String + printable_text(value) + when Hash, Array + return value if depth >= MAX_PRINTABLE_DATA_DEPTH || (depth.zero? && holds_itself?(value)) + + if value.is_a?(Hash) + value.to_h { |key, member| [key.is_a?(String) ? printable_text(key) : key, printable_data(member, depth + 1)] } + else + value.map { |member| printable_data(member, depth + 1) } + end + else + value + end + end + + # Whether a Hash or Array holds itself through its values and members. One pass, without recursion: + # a container is entered once however many times it is held, so what it shares costs nothing, + # and one that is still being looked into when it is met again closes a cycle. + def holds_itself?(container) + entered = {}.compare_by_identity + entered[container] = :open + path = [[container, containers_in(container)]] + + until path.empty? + current, held = path.last + inner = held.pop + + if inner.nil? + entered[current] = :done + path.pop + elsif entered[inner] == :open + return true + elsif !entered.key?(inner) + entered[inner] = :open + path << [inner, containers_in(inner)] + end + end + + false + 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 lies 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..205c2766 100644 --- a/test/json_rpc_handler_test.rb +++ b/test/json_rpc_handler_test.rb @@ -623,6 +623,148 @@ } 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�", 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 + + [once, twice, mutual, chain.first, { held: chain.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�"], ["f�"]], @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 + + Timeout.timeout(5) { handle jsonrpc: "2.0", id: 1, method: "test_method" } + + assert_equal(-32602, @response.dig(:error, :code)) + assert_equal(["value"], @response.dig(:error, :data).values) + 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(