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