diff --git a/lib/mcp/client.rb b/lib/mcp/client.rb index a4873389..92fa448a 100644 --- a/lib/mcp/client.rb +++ b/lib/mcp/client.rb @@ -312,7 +312,7 @@ def connected? def list_tools(cursor: nil, meta: nil, cancellation: nil) params = cursor ? { cursor: cursor } : nil response = request(method: "tools/list", params: params, meta: meta, cancellation: cancellation) - result = response["result"] || {} + result = result_hash(response) tools = (result["tools"] || []).filter_map do |tool| next if exclude_invalid_x_mcp_header?(tool) @@ -372,7 +372,7 @@ def tools(cancellation: nil) def list_resources(cursor: nil, meta: nil, cancellation: nil) params = cursor ? { cursor: cursor } : nil response = request(method: "resources/list", params: params, meta: meta, cancellation: cancellation) - result = response["result"] || {} + result = result_hash(response) ListResourcesResult.new( resources: result["resources"] || [], @@ -408,7 +408,7 @@ def resources(cancellation: nil) def list_resource_templates(cursor: nil, meta: nil, cancellation: nil) params = cursor ? { cursor: cursor } : nil response = request(method: "resources/templates/list", params: params, meta: meta, cancellation: cancellation) - result = response["result"] || {} + result = result_hash(response) ListResourceTemplatesResult.new( resource_templates: result["resourceTemplates"] || [], @@ -444,7 +444,7 @@ def resource_templates(cancellation: nil) def list_prompts(cursor: nil, meta: nil, cancellation: nil) params = cursor ? { cursor: cursor } : nil response = request(method: "prompts/list", params: params, meta: meta, cancellation: cancellation) - result = response["result"] || {} + result = result_hash(response) ListPromptsResult.new( prompts: result["prompts"] || [], @@ -539,7 +539,7 @@ def read_resource(uri:, meta: nil, cancellation: nil, input_responses: nil, requ response = drive_input_required(method: "resources/read", params: params, cancellation: cancellation) - response.dig("result", "contents") || [] + result_hash(response)["contents"] || [] end # Gets a prompt from the server by name and returns its details. @@ -557,7 +557,7 @@ def get_prompt(name:, meta: nil, cancellation: nil, input_responses: nil, reques response = drive_input_required(method: "prompts/get", params: params, cancellation: cancellation) - response.fetch("result", {}) + result_hash(response) end # Requests completion suggestions from the server for a prompt argument or resource template URI. @@ -576,7 +576,7 @@ def complete(ref:, argument:, context: nil, meta: nil, cancellation: nil) response = request(method: "completion/complete", params: params, meta: meta, cancellation: cancellation) - response.dig("result", "completion") || { "values" => [], "hasMore" => false } + result_hash(response)["completion"] || { "values" => [], "hasMore" => false } end # Registers a handler for `elicitation/create` requests the server sends while one of @@ -678,6 +678,16 @@ def ping(meta: nil, cancellation: nil) private + def result_hash(response) + if response.is_a?(Hash) + result = response["result"] + return {} if result.nil? + return result if result.is_a?(Hash) + end + + raise ValidationError, "Response validation failed: missing or invalid `result`" + end + # Records a handler for one of the three kinds of input a server can ask this client for, and wires it to # the transport when the transport can carry server-to-client requests. One registration serves both routes: # the real request a 2025-11-25 server sends mid-call, and the request embedded in a SEP-2322 diff --git a/lib/mcp/client/http.rb b/lib/mcp/client/http.rb index 6131d99e..65d579f2 100644 --- a/lib/mcp/client/http.rb +++ b/lib/mcp/client/http.rb @@ -837,14 +837,17 @@ def capture_mcp_param_declarations(method, params, body) return unless modern? return unless method.to_s == MCP::Methods::TOOLS_LIST && body.is_a?(Hash) - tools = body.dig("result", "tools") + result = body["result"] + return unless result.is_a?(Hash) + + tools = result["tools"] return unless tools.is_a?(Array) # An uncursored request answered without `nextCursor` is the complete tool universe, # so knowledge about unlisted tools is stale; the registry is rebuilt from this listing, # the same pruning the Python SDK applies to complete listings. cursor = params.is_a?(Hash) && (params[:cursor] || params["cursor"]) - complete = !cursor && body.dig("result", "nextCursor").nil? + complete = !cursor && result["nextCursor"].nil? registry = complete ? {} : @mcp_param_declarations tools.each do |tool| diff --git a/test/mcp/client/http_test.rb b/test/mcp/client/http_test.rb index 36093d5c..135dc5f7 100644 --- a/test/mcp/client/http_test.rb +++ b/test/mcp/client/http_test.rb @@ -3453,6 +3453,25 @@ def test_send_request_raises_error_for_a_response_that_is_not_json_rpc_2_0_on_a_ assert_predicate(client, :modern?) end + def test_list_tools_rejects_a_non_object_result_on_a_modern_connection + # The transport reads the `x-mcp-header` declarations out of a `tools/list` body before the client validates it, + # so a result that is not an object must get past it for the client to refuse. + stub_discover + client.connect(mode: :modern) + + [[], "bad", 123, true, false].each do |result| + stub_request(:post, url).with(body: hash_including(method: "tools/list")).to_return do |request| + { + status: 200, + headers: { "Content-Type" => "application/json" }, + body: { jsonrpc: "2.0", id: JSON.parse(request.body)["id"], result: result }.to_json, + } + end + + assert_raises(MCP::Client::ValidationError, result.inspect) { MCP::Client.new(transport: client).list_tools } + end + end + def test_send_request_learns_no_x_mcp_header_declarations_from_a_rejected_tools_list call_headers = nil stubs = Faraday::Adapter::Test::Stubs.new do |stub| diff --git a/test/mcp/client_test.rb b/test/mcp/client_test.rb index 8cf56ee0..f37aee02 100644 --- a/test/mcp/client_test.rb +++ b/test/mcp/client_test.rb @@ -5,6 +5,45 @@ module MCP class ClientTest < Minitest::Test + { + list_tools: {}, + list_resources: {}, + list_resource_templates: {}, + list_prompts: {}, + read_resource: { uri: "test://example" }, + get_prompt: { name: "example" }, + complete: { ref: { type: "ref/prompt", name: "example" }, argument: { name: "arg", value: "" } }, + }.each do |method, params| + define_method("test_#{method}_rejects_non_object_results") do + transport = mock + client = Client.new(transport: transport) + + [[], "bad", 123, true, false].each do |invalid| + transport.expects(:send_request).returns({ "result" => invalid }) + assert_raises(Client::ValidationError) { client.public_send(method, **params) } + end + + transport.expects(:send_request).returns([]) + assert_raises(Client::ValidationError) { client.public_send(method, **params) } + end + end + + def test_missing_and_null_results_keep_the_empty_defaults + transport = mock + client = Client.new(transport: transport) + + [{}, { "result" => nil }].each do |response| + transport.stubs(:send_request).returns(response) + assert_empty client.list_tools.tools + assert_empty client.list_resources.resources + assert_empty client.list_resource_templates.resource_templates + assert_empty client.list_prompts.prompts + assert_equal([], client.read_resource(uri: "test://example")) + assert_equal({}, client.get_prompt(name: "example")) + assert_equal({ "values" => [], "hasMore" => false }, client.complete(ref: {}, argument: {})) + end + end + def test_connect_delegates_to_transport_and_forwards_keyword_args transport = mock init_result = {