From e33ba0c6cac524350592c8848423e5724e18726e 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. ## 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. ## 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 | 36 ++++++++++++++++++-- test/json_rpc_handler_test.rb | 64 +++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/lib/json_rpc_handler.rb b/lib/json_rpc_handler.rb index aa566468..ddf8a83a 100644 --- a/lib/json_rpc_handler.rb +++ b/lib/json_rpc_handler.rb @@ -210,11 +210,43 @@ 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. + def printable_data(value) + case value + when String then printable_text(value) + when Hash then value.to_h { |key, member| [printable_data(key), printable_data(member)] } + when Array then value.map { |member| printable_data(member) } + else value + end + end + 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..f7c3e6a3 100644 --- a/test/json_rpc_handler_test.rb +++ b/test/json_rpc_handler_test.rb @@ -623,6 +623,70 @@ } 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 "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(