From 1c4ac125e1e6ec742cef09fc0527c9596a0bb27b Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 14 Nov 2025 13:50:38 +0900 Subject: [PATCH] Refactor to extract duplicate error tool response in `MCP::Server` Consolidates four identical constructions of error `Tool::Response` in `handle_call_tool_request` into a single private `error_tool_response` method, reducing duplication and improving maintainability. No behavior change. --- lib/mcp/server.rb | 46 ++++++++++++++++++---------------------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 3a2dd9fe..e7c37bf1 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -262,13 +262,8 @@ def call_tool(request) tool = tools[tool_name] unless tool add_instrumentation_data(tool_name:, error: :tool_not_found) - return Tool::Response.new( - [{ - type: "text", - text: "Tool not found: #{tool_name}", - }], - error: true, - ).to_h + + return error_tool_response("Tool not found: #{tool_name}") end arguments = request[:arguments] || {} @@ -276,14 +271,9 @@ def call_tool(request) if tool.input_schema&.missing_required_arguments?(arguments) add_instrumentation_data(error: :missing_required_arguments) + missing = tool.input_schema.missing_required_arguments(arguments).join(", ") - return Tool::Response.new( - [{ - type: "text", - text: "Missing required arguments: #{missing}", - }], - error: true, - ).to_h + return error_tool_response("Missing required arguments: #{missing}") end if configuration.validate_tool_call_arguments && tool.input_schema @@ -291,13 +281,8 @@ def call_tool(request) tool.input_schema.validate_arguments(arguments) rescue Tool::InputSchema::ValidationError => e add_instrumentation_data(error: :invalid_schema) - return Tool::Response.new( - [{ - type: "text", - text: e.message, - }], - error: true, - ).to_h + + return error_tool_response(e.message) end end @@ -305,13 +290,8 @@ def call_tool(request) call_tool_with_args(tool, arguments) rescue => e report_exception(e, { request: request }) - Tool::Response.new( - [{ - type: "text", - text: "Internal error calling tool #{tool_name}: #{e.message}", - }], - error: true, - ).to_h + + error_tool_response("Internal error calling tool #{tool_name}: #{e.message}") end end @@ -359,6 +339,16 @@ def index_resources_by_uri(resources) 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) parameters = method_object.parameters