Skip to content
Merged
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
4 changes: 3 additions & 1 deletion lib/mcp/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,9 @@ def exclude_invalid_x_mcp_header?(tool)
scan = McpParamHeaders.scan(tool["inputSchema"])
return false if scan[:valid]

warn("MCP::Client: excluding tool #{tool["name"].inspect} from tools/list: #{scan[:reason]}")
name = tool["name"]
# Both pieces are the server's: `dump` keeps control characters and bidirectional overrides out of the log line.
warn("MCP::Client: excluding tool #{(name.is_a?(String) ? name : name.inspect).dump} from tools/list: #{scan[:reason].dump}")
true
end

Expand Down
22 changes: 16 additions & 6 deletions lib/mcp/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1547,15 +1547,15 @@ def get_skill(request, server_context: nil)
request,
error_type: :invalid_params,
error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
error_data: { uri: uri },
error_data: refused_uri_data(uri),
)
end

skill = if @skills_get_handler
result = invoke_skills_handler(@skills_get_handler, request, server_context)
unless result.nil?
raise invalid_skills_result(request, "skills/get returned #{result.class}") unless result.is_a?(Skill)
raise invalid_skills_result(request, "skills/get returned #{result.uri} for #{uri}") unless result.uri == uri
raise invalid_skills_result(request, "skills/get returned #{result.uri.dump} for #{uri.dump}") unless result.uri == uri

problem = skills_problem([result])
raise invalid_skills_result(request, problem) if problem
Expand All @@ -1567,11 +1567,11 @@ def get_skill(request, server_context: nil)

if skill.nil?
raise RequestHandlerError.new(
"Skill not found: #{uri}",
"Skill not found: #{uri.dump}",
request,
error_type: :invalid_params,
error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
error_data: { uri: uri },
error_data: refused_uri_data(uri),
)
end

Expand Down Expand Up @@ -1763,11 +1763,11 @@ def read_resource(request, server_context: nil)
# is not served, and the Skills extension asks for `-32602` where the base reader keeps its `[]`.
if resource.nil? && uri.is_a?(String) && @skill_file_roots.any? { |root| Skill::Uri.under?(uri, root) }
raise RequestHandlerError.new(
"Skill file not found: #{uri}",
"Skill file not found: #{uri.dump}",
request,
error_type: :invalid_params,
error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
error_data: { uri: uri },
error_data: refused_uri_data(uri),
)
end

Expand Down Expand Up @@ -2089,5 +2089,15 @@ def normalize_completion_result(result)

{ completion: { values: values, total: total, hasMore: has_more }.compact }
end

# The error data of a Skills refusal: the request URI when it is a String, read as UTF-8 with its invalid bytes
# replaced, so that the response can be generated whatever bytes the request held; nothing for another value,
# which could hold such bytes anywhere, so the data falls back to the message. The messages quote the URI with
# `dump` for the same reason, and so that the exception reporter gets one printable line.
def refused_uri_data(uri)
return unless uri.is_a?(String)

{ uri: uri.dup.force_encoding(Encoding::UTF_8).scrub }
end
end
end
6 changes: 3 additions & 3 deletions lib/mcp/skill.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ def resolvable?(uri)
uri.bytesize <= MAX_RESOLVED_BYTES && uri.count("/") <= MAX_RESOLVED_SEGMENTS + 1
end

# The path segments of a `skill://` URI, or nil when it is not structurally valid: a String in
# an ASCII-compatible encoding with at least one segment, none empty, none `.` or `..`.
# The path segments of a `skill://` URI, or nil when it is not structurally valid: a validly encoded String
# in an ASCII-compatible encoding with at least one segment, none empty, none `.` or `..`.
def segments(uri)
return unless uri.is_a?(String) && uri.encoding.ascii_compatible? && uri.start_with?(SCHEME)
return unless uri.is_a?(String) && uri.encoding.ascii_compatible? && uri.valid_encoding? && uri.start_with?(SCHEME)

parts = uri[SCHEME.length..-1].split("/", -1)
return if parts.empty? || parts.any? { |part| part.empty? || part == "." || part == ".." }
Expand Down
62 changes: 62 additions & 0 deletions test/mcp/client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,68 @@ def test_tools_excludes_invalid_x_mcp_header_definitions_on_a_modern_connection
assert_includes(warning, "invalid_tool")
end

def test_tools_exclusion_warning_quotes_the_strings_the_server_chose
# The tool name, the property names, and the `x-mcp-header` values in the warning are the server's; control
# characters and bidirectional overrides in them could forge or reorder the line, so each piece is dumped.
transport = mock
transport.stubs(:modern?).returns(true)
mock_response = {
"result" => {
"tools" => [
{
"name" => "tool\nMCP::Client: forged",
"inputSchema" => {
"type" => "object",
"properties" => { "\u202Eeulav" => { "type" => "string", "x-mcp-header" => "X-Bad Name\e[0m" } },
},
},
],
},
}
transport.expects(:send_request).returns(mock_response).once
client = Client.new(transport: transport)

original_verbose = $VERBOSE
$VERBOSE = false
tools = nil
_out, warning = capture_io { tools = client.tools }
$VERBOSE = original_verbose

assert_empty(tools)
assert_equal(
"MCP::Client: excluding tool \"tool\\nMCP::Client: forged\" from tools/list: " \
"\"\\u202Eeulav: x-mcp-header `X-Bad Name\\e[0m` is not a valid RFC 9110 token\"\n",
warning,
)
end

def test_tools_exclusion_warning_dumps_a_tool_name_that_is_not_a_string
transport = mock
transport.stubs(:modern?).returns(true)
mock_response = {
"result" => {
"tools" => [
{
"name" => { "x" => "\u202E" },
"inputSchema" => { "type" => "object", "properties" => { "v" => { "type" => "string", "x-mcp-header" => "bad name" } } },
},
],
},
}
transport.expects(:send_request).returns(mock_response).once
client = Client.new(transport: transport)

original_verbose = $VERBOSE
$VERBOSE = false
_out, warning = capture_io { client.tools }
$VERBOSE = original_verbose

# `inspect` leaves a printable character such as U+202E inside a nested String as it is, so the whole is dumped.
assert_equal(1, warning.lines.size)
refute_match(/[^\x00-\x7F]/, warning)
assert_includes(warning, "\\u202E")
end

def test_tools_keeps_invalid_x_mcp_header_definitions_on_a_legacy_connection
transport = mock
transport.stubs(:modern?).returns(false)
Expand Down
62 changes: 58 additions & 4 deletions test/mcp/server_skills_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def initialize_capabilities(server)
assert_equal({ skills: [] }, server.handle(request("skills/list"))[:result])
response = server.handle(request("skills/get", { uri: "skill://x/SKILL.md" }))
assert_equal(-32602, response[:error][:code])
assert_equal "Skill not found: skill://x/SKILL.md", response[:error][:message]
assert_equal 'Skill not found: "skill://x/SKILL.md"', response[:error][:message]
assert_equal({ uri: "skill://x/SKILL.md" }, response[:error][:data])
end

Expand Down Expand Up @@ -139,12 +139,65 @@ def initialize_capabilities(server)
test "skills/get refuses a URI that does not name a SKILL.md before any lookup" do
server = Server.new(name: "catalog", skills: [pdf_skill])

["skill://pdf-processing/references/FORMS.md", "skill://pdf-processing", "http://x/SKILL.md", nil, 42].each do |uri|
["skill://pdf-processing/references/FORMS.md", "skill://pdf-processing", "http://x/SKILL.md"].each do |uri|
response = server.handle(request("skills/get", { uri: uri }))
assert_equal(-32602, response[:error][:code], uri.inspect)
assert_equal(-32602, response[:error][:code], uri)
assert_equal "Invalid params: uri is not a skill SKILL.md URI", response[:error][:message]
assert_equal({ uri: uri }, response[:error][:data])
end

# A value that is not a String is not echoed, since it could hold bytes JSON cannot generate anywhere.
[nil, 42, { "k" => "\xFF" }, ["\xFF"]].each do |uri|
response = server.handle(request("skills/get", { uri: uri }))
assert_equal(-32602, response[:error][:code], uri.inspect)
assert_equal "Invalid params: uri is not a skill SKILL.md URI", response[:error][:message]
assert_equal response[:error][:message], response[:error][:data], uri.inspect
end
json = server.handle_json(%({"jsonrpc":"2.0","id":1,"method":"skills/get","params":{"uri":{"k":"\xFF"}}}))
assert_equal(-32602, JSON.parse(json, symbolize_names: true)[:error][:code])
end

test "skills/get refuses a URI that is not valid UTF-8 as invalid params, with an answer JSON can generate" do
server = Server.new(name: "catalog", skills: [pdf_skill])
uri = "skill://pdf-processing\xFF/SKILL.md"

response = server.handle(request("skills/get", { uri: uri }))
assert_equal(-32602, response[:error][:code])
assert_equal "Invalid params: uri is not a skill SKILL.md URI", response[:error][:message]
assert_equal "skill://pdf-processing\uFFFD/SKILL.md", response[:error][:data][:uri]

# The parser passes the bytes through inside a string, and the refusal has to be generated around them.
json = server.handle_json(%({"jsonrpc":"2.0","id":1,"method":"skills/get","params":{"uri":"#{uri}"}}))
response = JSON.parse(json, symbolize_names: true)
assert_equal(-32602, response[:error][:code])
assert_equal "skill://pdf-processing\uFFFD/SKILL.md", response[:error][:data][:uri]
end

test "the Skill not found message quotes the URI, so the exception reporter gets one printable line" do
reported = []
configuration = Configuration.new(exception_reporter: ->(exception, _context) { reported << exception })
server = Server.new(name: "catalog", skills: [pdf_skill], configuration: configuration)
uri = "skill://x\r\nforged: line\e[0m/SKILL.md"

response = server.handle(request("skills/get", { uri: uri }))
assert_equal(-32602, response[:error][:code])
assert_equal 'Skill not found: "skill://x\r\nforged: line\e[0m/SKILL.md"', response[:error][:message]
assert_equal({ uri: uri }, response[:error][:data])
assert_equal [response[:error][:message]], reported.map(&:message)
end

test "a URI given to handle as a binary String is read as UTF-8 for the error data" do
server = Server.new(name: "catalog", skills: [pdf_skill])

# Validly encoded, so a manifest URI that names no skill. json 3.1 refuses to generate a binary String holding
# high bytes (json 3.0 generates this one with a deprecation warning, since its bytes are valid UTF-8), so the
# error data carries the same bytes read as UTF-8.
response = server.handle(request("skills/get", { uri: "skill://x\xC3\xA9/SKILL.md".b }))
assert_equal(-32602, response[:error][:code])
assert_equal 'Skill not found: "skill://x\xC3\xA9/SKILL.md"', response[:error][:message]
assert_equal "skill://x\xC3\xA9/SKILL.md", response[:error][:data][:uri]
assert_equal Encoding::UTF_8, response[:error][:data][:uri].encoding
assert_equal "skill://x\xC3\xA9/SKILL.md", JSON.parse(JSON.generate(response), symbolize_names: true)[:error][:data][:uri]
end

test "refuses a registry with duplicate URIs and accepts an enclosing skill that lists a nested skill's files" do
Expand Down Expand Up @@ -187,7 +240,7 @@ def initialize_capabilities(server)
assert_equal pdf_skill.to_h, server.handle(request("skills/get", { uri: "skill://pdf-processing/SKILL.md" })).dig(:result, :skill)
response = server.handle(request("skills/get", { uri: "skill://git/SKILL.md" }))
assert_equal(-32602, response[:error][:code])
assert_equal "Skill not found: skill://git/SKILL.md", response[:error][:message]
assert_equal 'Skill not found: "skill://git/SKILL.md"', response[:error][:message]
assert_equal [], server.skills
end

Expand Down Expand Up @@ -276,6 +329,7 @@ def initialize_capabilities(server)
assert_equal(-32603, server.handle(request("skills/get", { uri: "skill://pdf-processing/SKILL.md" }))[:error][:code])
results[:get] = git_skill
assert_equal(-32603, server.handle(request("skills/get", { uri: "skill://pdf-processing/SKILL.md" }))[:error][:code])
assert_equal 'skills/get returned "skill://git/SKILL.md" for "skill://pdf-processing/SKILL.md"', reported.last.message
assert_equal 5, reported.size
assert reported.all? { |exception| exception.is_a?(StandardError) && !exception.is_a?(Server::RequestHandlerError) }

Expand Down
18 changes: 16 additions & 2 deletions test/mcp/skill/directory_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def read_request(uri)
assert_equal "n\n", server.handle(read_request("skill://acme/outer/inner/notes.txt")).dig(:result, :contents, 0, :text)
response = server.handle(read_request("skill://acme/outer/missing.md"))
assert_equal(-32602, response[:error][:code])
assert_equal "Skill file not found: skill://acme/outer/missing.md", response[:error][:message]
assert_equal 'Skill file not found: "skill://acme/outer/missing.md"', response[:error][:message]
assert_equal [], server.handle(read_request("skill://elsewhere/x"))[:result][:contents]

listed = server.handle({ jsonrpc: "2.0", id: 1, method: "resources/list" })[:result][:resources]
Expand Down Expand Up @@ -281,11 +281,25 @@ def read_request(uri)
["skill://pdf-processing/.env", "skill://pdf-processing/../pdf-processing/SKILL.md", "skill://pdf-processing/references/FORMS.md/"].each do |uri|
response = server.handle(read_request(uri))
assert_equal(-32602, response[:error][:code], uri)
assert_equal "Skill file not found: #{uri}", response[:error][:message]
assert_equal "Skill file not found: \"#{uri}\"", response[:error][:message]
end
end
end

test "a URI under a skill root that is not valid UTF-8 is refused with an answer JSON can generate" do
with_root do |root|
pdf_root(root)
server = Server.new(name: "catalog", skills: Skill.from_directory(root))
uri = "skill://pdf-processing/\xFF.md"

json = server.handle_json(%({"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"#{uri}"}}))
response = JSON.parse(json, symbolize_names: true)
assert_equal(-32602, response[:error][:code])
assert_equal 'Skill file not found: "skill://pdf-processing/\xFF.md"', response[:error][:message]
assert_equal "skill://pdf-processing/\uFFFD.md", response[:error][:data][:uri]
end
end

test "a file that changed since registration is refused with one generic error and the detail goes to the reporter" do
with_root do |root|
pdf_root(root)
Expand Down
3 changes: 3 additions & 0 deletions test/mcp/skill_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ def build(uri: "skill://pdf-processing/SKILL.md", frontmatter: { name: "pdf-proc
assert uri.structural?("skill://a/b")
refute uri.structural?("skill://a//b")
refute uri.structural?("skill://")
refute uri.structural?("skill://a\xFF/b"), "a String that is not validly encoded has no segments"
assert uri.structural?("skill://a/b".b)
assert_empty uri.candidate_skill_uris("skill://a\xFF/b/c")
assert uri.manifest_uri?("skill://a/b/SKILL.md")
refute uri.manifest_uri?("skill://SKILL.md")
refute uri.manifest_uri?("skill://a/b/skill.md")
Expand Down
Loading