Merge pull request #180 from koic/refactor_mcp_server

Refactor to extract duplicate error tool response in `MCP::Server`
This commit is contained in:
Koichi ITO 2025-11-21 02:43:05 +09:00 • committed by GitHub
commit 26bbdfc28c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -262,13 +262,8 @@ module MCP
tool = tools[tool_name] tool = tools[tool_name]
unless tool unless tool
add_instrumentation_data(tool_name:, error: :tool_not_found) add_instrumentation_data(tool_name:, error: :tool_not_found)
return Tool::Response.new(
[{ return error_tool_response("Tool not found: #{tool_name}")
type: "text",
text: "Tool not found: #{tool_name}",
}],
error: true,
).to_h
end end
arguments = request[:arguments] || {} arguments = request[:arguments] || {}
@ -276,14 +271,9 @@ module MCP
if tool.input_schema&.missing_required_arguments?(arguments) if tool.input_schema&.missing_required_arguments?(arguments)
add_instrumentation_data(error: :missing_required_arguments) add_instrumentation_data(error: :missing_required_arguments)
missing = tool.input_schema.missing_required_arguments(arguments).join(", ") missing = tool.input_schema.missing_required_arguments(arguments).join(", ")
return Tool::Response.new( return error_tool_response("Missing required arguments: #{missing}")
[{
type: "text",
text: "Missing required arguments: #{missing}",
}],
error: true,
).to_h
end end
if configuration.validate_tool_call_arguments && tool.input_schema if configuration.validate_tool_call_arguments && tool.input_schema
@ -291,13 +281,8 @@ module MCP
tool.input_schema.validate_arguments(arguments) tool.input_schema.validate_arguments(arguments)
rescue Tool::InputSchema::ValidationError => e rescue Tool::InputSchema::ValidationError => e
add_instrumentation_data(error: :invalid_schema) add_instrumentation_data(error: :invalid_schema)
return Tool::Response.new(
[{ return error_tool_response(e.message)
type: "text",
text: e.message,
}],
error: true,
).to_h
end end
end end
@ -305,13 +290,8 @@ module MCP
call_tool_with_args(tool, arguments) call_tool_with_args(tool, arguments)
rescue => e rescue => e
report_exception(e, { request: request }) report_exception(e, { request: request })
Tool::Response.new(
[{ error_tool_response("Internal error calling tool #{tool_name}: #{e.message}")
type: "text",
text: "Internal error calling tool #{tool_name}: #{e.message}",
}],
error: true,
).to_h
end end
end end
@ -359,6 +339,16 @@ module MCP
end end
end end
def error_tool_response(text)
Tool::Response.new(
[{
type: "text",
text: text,
}],
error: true,
).to_h
end
def accepts_server_context?(method_object) def accepts_server_context?(method_object)
parameters = method_object.parameters parameters = method_object.parameters