Skip to content

Commit 26bbdfc

Browse files
authored
Merge pull request #180 from koic/refactor_mcp_server
Refactor to extract duplicate error tool response in `MCP::Server`
2 parents 3c452b8 + 1c4ac12 commit 26bbdfc

File tree

1 file changed

+18
-28
lines changed

1 file changed

+18
-28
lines changed

lib/mcp/server.rb

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -262,56 +262,36 @@ def call_tool(request)
262262
tool = tools[tool_name]
263263
unless tool
264264
add_instrumentation_data(tool_name:, error: :tool_not_found)
265-
return Tool::Response.new(
266-
[{
267-
type: "text",
268-
text: "Tool not found: #{tool_name}",
269-
}],
270-
error: true,
271-
).to_h
265+
266+
return error_tool_response("Tool not found: #{tool_name}")
272267
end
273268

274269
arguments = request[:arguments] || {}
275270
add_instrumentation_data(tool_name:)
276271

277272
if tool.input_schema&.missing_required_arguments?(arguments)
278273
add_instrumentation_data(error: :missing_required_arguments)
274+
279275
missing = tool.input_schema.missing_required_arguments(arguments).join(", ")
280-
return Tool::Response.new(
281-
[{
282-
type: "text",
283-
text: "Missing required arguments: #{missing}",
284-
}],
285-
error: true,
286-
).to_h
276+
return error_tool_response("Missing required arguments: #{missing}")
287277
end
288278

289279
if configuration.validate_tool_call_arguments && tool.input_schema
290280
begin
291281
tool.input_schema.validate_arguments(arguments)
292282
rescue Tool::InputSchema::ValidationError => e
293283
add_instrumentation_data(error: :invalid_schema)
294-
return Tool::Response.new(
295-
[{
296-
type: "text",
297-
text: e.message,
298-
}],
299-
error: true,
300-
).to_h
284+
285+
return error_tool_response(e.message)
301286
end
302287
end
303288

304289
begin
305290
call_tool_with_args(tool, arguments)
306291
rescue => e
307292
report_exception(e, { request: request })
308-
Tool::Response.new(
309-
[{
310-
type: "text",
311-
text: "Internal error calling tool #{tool_name}: #{e.message}",
312-
}],
313-
error: true,
314-
).to_h
293+
294+
error_tool_response("Internal error calling tool #{tool_name}: #{e.message}")
315295
end
316296
end
317297

@@ -359,6 +339,16 @@ def index_resources_by_uri(resources)
359339
end
360340
end
361341

342+
def error_tool_response(text)
343+
Tool::Response.new(
344+
[{
345+
type: "text",
346+
text: text,
347+
}],
348+
error: true,
349+
).to_h
350+
end
351+
362352
def accepts_server_context?(method_object)
363353
parameters = method_object.parameters
364354

0 commit comments

Comments
 (0)