diff --git a/docs/_server/tools.md b/docs/_server/tools.md index 9e16046e..f62e3d33 100644 --- a/docs/_server/tools.md +++ b/docs/_server/tools.md @@ -106,9 +106,9 @@ The block is invoked once per `tools/list` page and once per `tools/call`, with and must return a stable ordering across the pages of one query; the cursor is a positional offset into the returned collection. When no handler is set, the registered tools are used unchanged. -{: .note } -> The [custom header](#custom-headers-from-tool-parameters) check runs in the transport against the registered tools, -> so it is skipped for a tool that only the `tools_list_handler` returns. +The [custom header](#custom-headers-from-tool-parameters) check uses the tool that same invocation resolved: +a `tools/call` is checked against the schema the block returns for its tool, and a tool the block leaves out is not found, +whatever headers the request carries. Icons for tools are documented on the [Icons](/server/icons/) page. diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 1da6e8fc..140a46f8 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -312,10 +312,14 @@ def initialize( # @param auth_info [Server::OAuth::AccessToken, nil] The verified access token # for the current request, passed by the transport layer and exposed to # handlers as `server_context.auth_info`. + # @param tool_call_check [#call, nil] For a transport that has to compare a `tools/call` with the schema of + # its tool (the custom header check of the streamable HTTP transport): called with the tool the call resolved to + # and the request params, after the tool is found and before its arguments are examined. A message it returns + # refuses the call with `-32020` Header mismatch, and the tool does not run. Not part of the public API. # @return [Hash, nil] The JSON-RPC response, or `nil` for notifications. - def handle(request, session: nil, auth_info: nil) + def handle(request, session: nil, auth_info: nil, tool_call_check: nil) JsonRpcHandler.handle(request, id_validation_pattern: nil) do |method, request_id| - handle_request(request, method, session: session, related_request_id: request_id, auth_info: auth_info) + handle_request(request, method, session: session, related_request_id: request_id, auth_info: auth_info, tool_call_check: tool_call_check) end end @@ -740,7 +744,7 @@ def schema_contains_ref?(schema) end end - def handle_request(request, method, session: nil, related_request_id: nil, auth_info: nil) + def handle_request(request, method, session: nil, related_request_id: nil, auth_info: nil, tool_call_check: nil) # A well-formed notification carries no JSON-RPC id and receives no response. # If a client erroneously sends a notification-only method with an id, the message # is framed as a request; since notification methods have no request handler, @@ -858,7 +862,7 @@ def handle_request(request, method, session: nil, related_request_id: nil, auth_ subscription_result(handler_result) when Methods::TOOLS_CALL - call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info) + call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info, tool_call_check: tool_call_check) when Methods::PROMPTS_GET get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info) when Methods::COMPLETION_COMPLETE @@ -1469,7 +1473,7 @@ def resolve_tool(request, session:, related_request_id:, cancellation:, envelope invoke_tools_list_handler(request, server_context).find { |tool| tool.name_value == request[:name] } end - def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil) + def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil, tool_call_check: nil) tool_name = request[:name] tool = resolve_tool(request, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info) @@ -1479,6 +1483,21 @@ def call_tool(request, instrumentation_data:, session: nil, related_request_id: raise RequestHandlerError.new("Tool not found: #{tool_name}", request, error_type: :invalid_params) end + # The transport's check runs here, on the tool this very call resolved to, rather than on a lookup of its own: + # with a `tools_list_handler`, a second resolution could see another context and answer for a schema the caller + # was not served, or for a tool the caller cannot see. It comes after the lookup, so a tool that is not found + # answers the same whatever the request carries, and before the arguments are examined or the tool runs. + if tool_call_check && (mismatch = tool_call_check.call(tool, request)) + instrumentation_data.merge!(tool_name: tool_name) + + raise RequestHandlerError.new( + "Header mismatch: #{mismatch}", + request, + error_type: :invalid_request, + error_code: ErrorCodes::HEADER_MISMATCH, + ) + end + arguments = request[:arguments] || {} instrumentation_data.merge!(tool_name: tool_name, tool_arguments: arguments) diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 69f20a21..41823300 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -1080,13 +1080,6 @@ def handle_modern(request, header_version, body_string: nil) mismatch_error = validate_modern_headers(request, body, header_version) return mismatch_error if mismatch_error - # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body here, - # before dispatch, so a disagreement is refused without the tool ever running. - if body[:method] == Methods::TOOLS_CALL - param_error = validate_mcp_param_headers(request, body) - return param_error if param_error - end - # `subscriptions/listen` is a long-lived notification stream served at the transport layer; # it never dispatches through `Server#handle`. A transport constructed with # `serve_subscriptions_listen: false` skips the interception, so the method falls through @@ -1096,14 +1089,24 @@ def handle_modern(request, header_version, body_string: nil) return handle_subscriptions_listen(body, auth_info: request.env[OAuth::ENV_KEY]) end + # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body by + # the dispatcher, on the tool it resolved for this call, so a disagreement is refused without the tool ever running. + # The refusal is answered from here, as a plain JSON 400 whatever the handler had emitted until then. + header_mismatch = nil + tool_call_check = lambda do |tool, params| + header_mismatch = mcp_param_header_mismatch(tool, params, request) + end + session = modern_session notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] } begin - response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY]) + response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY], tool_call_check: tool_call_check) ensure @mutex.synchronize { @modern_request_sinks.delete(session.session_id) } end + return header_mismatch_response(header_mismatch, body[:id]) if header_mismatch + # `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path. return handle_accepted if response.nil? @@ -1198,34 +1201,29 @@ def validate_modern_headers(request, body, header_version) # Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each # `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body # carries a value for it, agreeing with that value once a `=?base64?...?=` sentinel is decoded, and a malformed - # sentinel is refused outright. The comparison runs before the tool does, on the schema the server itself serves - # in `tools/list`, so the body a handler acts on is the one an intermediary routed on. A tool the server does not - # know, or one whose declarations are invalid (a conforming client drops such a tool and sends no headers for it), - # is left to the dispatcher, and headers for parameters no declaration names are ignored, as the spec asks of any - # server that does not recognize them. The refusal names the header and the argument, not their values. + # sentinel is refused outright. The comparison runs before the tool does, on the schema the server serves this caller + # in `tools/list`, so the body a handler acts on is the one an intermediary routed on: the dispatcher calls this + # with the tool it resolved for the call, which with a `tools_list_handler` is the one the block returned. + # A tool that is not found never reaches it, one whose declarations are invalid (a conforming client drops such + # a tool and sends no headers for it) is not checked, and headers for parameters no declaration names are ignored, + # as the spec asks of any server that does not recognize them. The message names the header and the argument, + # not their values; `nil` means the headers agree. # # Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land # on one key; a token that differs only in that way is the schema author's choice, and the value still has to # agree with the body. - def validate_mcp_param_headers(request, body) - params = body[:params] + def mcp_param_header_mismatch(tool, params, request) return unless params.is_a?(Hash) - tool = @server.tools[params[:name]] - return unless tool - scan = McpParamHeaders.scan(tool.input_schema.to_h) return unless scan[:valid] && !scan[:declarations].empty? arguments = params[:arguments] || {} return unless arguments.is_a?(Hash) - message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name| + McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name| header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}") end - return unless message - - header_mismatch_response(message, body[:id]) end # Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is diff --git a/test/mcp/server/transports/streamable_http_mcp_param_test.rb b/test/mcp/server/transports/streamable_http_mcp_param_test.rb index de18d57c..25311326 100644 --- a/test/mcp/server/transports/streamable_http_mcp_param_test.rb +++ b/test/mcp/server/transports/streamable_http_mcp_param_test.rb @@ -208,14 +208,141 @@ class StreamableHTTPMcpParamTest < ActiveSupport::TestCase assert_equal "Zone", tool.dig("inputSchema", "properties", "options", "properties", "zone", "x-mcp-header") end + test "a registered tool the tools_list_handler leaves out answers as an unknown tool does" do + @server.tools_list_handler { |_params| [] } + + [{}, { "HTTP_MCP_PARAM_REGION" => "us-east1" }].each do |headers| + hidden = call_tool({ region: "us-west1" }, headers) + unknown = call_tool({ region: "us-west1" }, headers, name: "nope") + + assert_equal 400, hidden[0] + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, JSON.parse(hidden[2][0]).dig("error", "code") + assert_equal unknown[2][0].sub("nope", "regional"), hidden[2][0] + end + end + + test "a tool the tools_list_handler returns under a registered name is checked on the schema it returns" do + replacement = Tool.define(name: "regional", input_schema: { properties: { region: { type: "string" } } }) do |region: nil, **| + Tool::Response.new([{ type: "text", text: "replacement #{region}" }]) + end + @server.tools_list_handler { |_params| [replacement] } + + # The schema this caller is served declares no header, so a call without one is what `tools/list` describes. + response = call_tool({ region: "us-west1" }, {}) + + assert_equal "replacement us-west1", result_text(response) + end + + test "a tool only the tools_list_handler returns has its custom headers checked, and does not run on a mismatch" do + runs = [] + handler_only = Tool.define( + name: "handler_only", + input_schema: { properties: { region: { type: "string", "x-mcp-header": "Region" } } }, + ) do |region: nil, **| + runs << region + Tool::Response.new([{ type: "text", text: "handler_only #{region}" }]) + end + @server.tools_list_handler { |_params| [handler_only] } + + disagreeing = call_tool({ region: "us-west1" }, { "HTTP_MCP_PARAM_REGION" => "us-east1" }, name: "handler_only") + missing = call_tool({ region: "us-west1" }, {}, name: "handler_only") + + assert_header_mismatch disagreeing, "Mcp-Param-Region header does not match the `region` argument" + assert_header_mismatch missing, "Mcp-Param-Region header is missing but the request body carries a `region` argument" + assert_empty runs + + agreeing = call_tool({ region: "us-west1" }, { "HTTP_MCP_PARAM_REGION" => "us-west1" }, name: "handler_only") + + assert_equal "handler_only us-west1", result_text(agreeing) + assert_equal ["us-west1"], runs + end + + test "the header check uses the tool resolved for the caller's token and declared capabilities" do + registered = @server.tools.fetch("regional") + contexts = [] + @server.tools_list_handler do |_params, server_context:| + contexts << [server_context.auth_info&.subject, server_context.client_capabilities] + server_context.auth_info&.subject == "admin" && server_context.client_capabilities&.key?(:elicitation) ? [registered] : [] + end + admin = { OAuth::ENV_KEY => OAuth::AccessToken.new(token: "t", subject: "admin") } + + visible = call_tool({ region: "us-west1" }, admin, capabilities: { elicitation: {} }) + without_capability = call_tool({ region: "us-west1" }, admin) + without_token = call_tool({ region: "us-west1" }, {}, capabilities: { elicitation: {} }) + + assert_header_mismatch visible, "Mcp-Param-Region header is missing but the request body carries a `region` argument" + [without_capability, without_token].each do |response| + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, JSON.parse(response[2][0]).dig("error", "code") + end + # One invocation per call, each with the context the call is dispatched in. + assert_equal [["admin", { elicitation: {} }], ["admin", {}], [nil, { elicitation: {} }]], contexts + end + + test "a tools_list_handler that raises answers Internal error whatever headers the request carries" do + @server.tools_list_handler { |_params| raise "boom" } + + [{}, { "HTTP_MCP_PARAM_REGION" => "us-east1" }].each do |headers| + response = call_tool({ region: "us-west1" }, headers) + + assert_equal JsonRpcHandler::ErrorCode::INTERNAL_ERROR, JSON.parse(response[2][0]).dig("error", "code") + assert_equal 7, JSON.parse(response[2][0])["id"] + end + end + + test "an error the dispatcher raises before it looks the tool up comes ahead of a header mismatch" do + body = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "regional", arguments: { region: "us-west1" }, _meta: "x" } }.to_json + response = @transport.handle_request(create_rack_request( + "POST", + { + "CONTENT_TYPE" => "application/json", + "HTTP_MCP_PROTOCOL_VERSION" => "2026-07-28", + "HTTP_MCP_METHOD" => "tools/call", + "HTTP_MCP_NAME" => "regional", + "HTTP_MCP_PARAM_REGION" => "us-east1", + }, + body, + )) + + assert_equal 400, response[0] + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, JSON.parse(response[2][0]).dig("error", "code") + end + + test "a header mismatch reaches instrumentation and the exception reporter as a refused tools/call" do + reported = [] + instrumented = [] + @server.configuration.exception_reporter = ->(error, _context) { reported << [error.class, error.message] } + @server.configuration.around_request = ->(data, &request) do + request.call + ensure + instrumented << data.slice(:method, :tool_name, :error) + end + + response = call_tool({ region: "us-west1" }, { "HTTP_MCP_PARAM_REGION" => "us-east1" }) + + assert_header_mismatch response, "Mcp-Param-Region header does not match the `region` argument" + assert_equal [[Server::RequestHandlerError, "Header mismatch: Mcp-Param-Region header does not match the `region` argument"]], reported + assert_equal [{ method: "tools/call", tool_name: "regional", error: :invalid_request }], instrumented + end + + test "Server#handle called without the transport has no custom headers to check" do + response = @server.handle({ + jsonrpc: "2.0", + id: 7, + method: "tools/call", + params: { name: "regional", arguments: { region: "us-west1" }, _meta: envelope }, + }) + + assert_equal '["us-west1", nil, nil, nil]', response.dig(:result, :content, 0, :text) + end + private - def call_tool(arguments, headers, name: "regional") + def call_tool(arguments, headers, name: "regional", capabilities: {}) body = { jsonrpc: "2.0", id: 7, method: "tools/call", - params: { name: name, arguments: arguments, _meta: envelope }, + params: { name: name, arguments: arguments, _meta: envelope.merge("io.modelcontextprotocol/clientCapabilities": capabilities) }, }.to_json base = { "CONTENT_TYPE" => "application/json",