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
36 changes: 34 additions & 2 deletions lib/json_rpc_handler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: <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
Expand Down
64 changes: 64 additions & 0 deletions test/json_rpc_handler_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down