diff --git a/conformance/expected_failures.yml b/conformance/expected_failures.yml index c6c76cc7..f21d5598 100644 --- a/conformance/expected_failures.yml +++ b/conformance/expected_failures.yml @@ -3,10 +3,6 @@ server: # the referee warns about each of the two; the baseline counts a warning as a failure. The resume on # `Last-Event-ID` is not exercised, since the server does not close the stream mid-call. - server-sse-polling - # SEP-2243 custom headers: the server does not bind `Mcp-Param-*` headers to `x-mcp-header` tool parameters - # (the client side sends them), so the conformance server exposes no such tool and the referee reports - # the scenario's checks as untestable. - - http-custom-header-server-validation # SEP-2663 (io.modelcontextprotocol/tasks): the server does not implement the tasks extension. # `tasks-status-notifications` is intentionally absent: the referee runs no check in it, and a baseline entry # for a scenario with no failing check is flagged stale. diff --git a/conformance/server.rb b/conformance/server.rb index 77139848..42b5f2b8 100644 --- a/conformance/server.rb +++ b/conformance/server.rb @@ -325,6 +325,24 @@ def call(**_args) end end + class TestXMcpHeader < MCP::Tool + tool_name "test_x_mcp_header" + description "A tool whose region argument is mirrored into the Mcp-Param-Region header (SEP-2243)" + input_schema( + properties: { + region: { type: "string", description: "Mirrored into the Mcp-Param-Region header", "x-mcp-header": "Region" }, + }, + ) + + class << self + # Arms the `http-custom-header-server-validation` server scenario, which the referee skips when no tool declares + # an `x-mcp-header` parameter, as the TypeScript and Python fixtures do. + def call(region: "", **_args) + MCP::Tool::Response.new([MCP::Content::Text.new("region=#{region}").to_h]) + end + end + end + class TestMissingCapability < MCP::Tool tool_name "test_missing_capability" description "A tool that requires the sampling client capability (SEP-2575)" @@ -924,6 +942,7 @@ def build_server Tools::TestElicitationSep1034Defaults, Tools::TestElicitationSep1330Enums, Tools::TestReconnection, + Tools::TestXMcpHeader, Tools::TestMissingCapability, Tools::TestInputRequiredResultElicitation, Tools::TestInputRequiredResultSampling, diff --git a/docs/_server/tools.md b/docs/_server/tools.md index 021d52e4..e2c8c198 100644 --- a/docs/_server/tools.md +++ b/docs/_server/tools.md @@ -153,6 +153,48 @@ Annotations can be set either through the class definition using the `annotation {: .note } > This **Tool Annotations** feature is supported starting from `protocol_version: '2025-03-26'`. +## Custom Headers from Tool Parameters + +On the [modern lifecycle](/server/discover/#the-stateless-modern-lifecycle) (MCP 2026-07-28, SEP-2243), a tool can designate parameters +whose values the client mirrors into `Mcp-Param-{Name}` request headers, so intermediaries can route or apply policy on them +without parsing bodies. Declare the header name with an `x-mcp-header` annotation on the parameter's property: + +```ruby +class RegionalTool < MCP::Tool + description "Runs in the region the request names" + input_schema( + properties: { + region: { type: "string", "x-mcp-header": "Region" }, + }, + required: ["region"] + ) + + class << self + def call(region:, server_context:) + MCP::Tool::Response.new([{ type: "text", text: "Running in #{region}" }]) + end + end +end +``` + +The annotation must be a non-empty HTTP token, unique among the tool's annotations regardless of case, +and sit on a `string`, `integer`, or `boolean` property reachable from the schema root through `properties` keys only +(a `number` property is accepted as well, for compatibility with the conformance referee's fixtures, although the specification does not permit it). +Prefer `-` to `_` inside the name: proxies such as nginx drop header fields whose names hold an underscore by default, +and the request is then refused for its missing header. +Conforming clients drop a tool whose annotations break these rules and send no headers for it, and the transport validates nothing for such a tool. + +`StreamableHTTPTransport` enforces the server side before the tool runs: on a `tools/call` of the modern lifecycle, +the `Mcp-Param-{Name}` header of each declared parameter must be present exactly when the body carries a value the client mirrors for it +(a string, a boolean, a finite float, or an integer within the safe JavaScript range; a value with no header rendering, such as an object, is left to argument validation) +and must agree with that value once a `=?base64?...?=` sentinel is decoded. A missing or disagreeing header, +a header whose argument is absent or `null` in the body, a header holding a byte outside the field-value set (visible ASCII, space, and tab) +without the sentinel, and a sentinel whose payload is not canonical Base64 or not UTF-8 +are refused with HTTP 400 and JSON-RPC error `-32020` (`HeaderMismatch`) naming the header and, except in the two encoding refusals, the argument, never their values. +Integer and number parameters compare numerically when the header is a canonical decimal of at most 64 bytes, so a header of `42.0` agrees with a body value of `42`; +the comparison reads plain decimals only, so a number another SDK's client mirrors in exponent form is refused unless it repeats this SDK's own rendering byte for byte. +Headers for parameters without an annotation are ignored, and the handshake lifecycle (2025-11-25 and earlier) has no such headers. + ## Tool Output Schemas Tools can optionally define an `output_schema` to specify the expected structure of their results. This works similarly to how `input_schema` is defined and can be used in three ways. diff --git a/lib/mcp.rb b/lib/mcp.rb index 99c083e4..06d947c9 100644 --- a/lib/mcp.rb +++ b/lib/mcp.rb @@ -17,6 +17,7 @@ module MCP autoload :Elicitation, "mcp/elicitation" autoload :ErrorCodes, "mcp/error_codes" autoload :Icon, "mcp/icon" + autoload :McpParamHeaders, "mcp/mcp_param_headers" autoload :Prompt, "mcp/prompt" autoload :RequestEnvelope, "mcp/request_envelope" autoload :Resource, "mcp/resource" diff --git a/lib/mcp/client.rb b/lib/mcp/client.rb index 5cdef00f..a4873389 100644 --- a/lib/mcp/client.rb +++ b/lib/mcp/client.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require_relative "client/elicitation" -require_relative "client/mcp_param_headers" require_relative "client/modern_envelope" require_relative "client/oauth" require_relative "client/stdio" @@ -20,6 +19,11 @@ class Client # every response would otherwise be followed indefinitely, growing the retained pages with it. MAX_PAGES = 1_000 + # The custom-header codec lived under this name until the server transport came to share it; + # the name stays for code that referenced it. + # @api private + McpParamHeaders = MCP::McpParamHeaders + class ServerError < StandardError attr_reader :code, :data diff --git a/lib/mcp/client/http.rb b/lib/mcp/client/http.rb index 4e728748..f2229bc6 100644 --- a/lib/mcp/client/http.rb +++ b/lib/mcp/client/http.rb @@ -6,7 +6,7 @@ require_relative "../methods" require_relative "../protocol_deprecations" require_relative "../version" -require_relative "mcp_param_headers" +require_relative "../mcp_param_headers" require_relative "modern_envelope" module MCP diff --git a/lib/mcp/client/mcp_param_headers.rb b/lib/mcp/client/mcp_param_headers.rb deleted file mode 100644 index 4aa4d54e..00000000 --- a/lib/mcp/client/mcp_param_headers.rb +++ /dev/null @@ -1,242 +0,0 @@ -# frozen_string_literal: true - -module MCP - class Client - # The custom-header half of SEP-2243 (MCP 2026-07-28): scanning a tool's `inputSchema` for - # `x-mcp-header` declarations and encoding `tools/call` argument values into `Mcp-Param-{Name}` HTTP headers, - # with the `=?base64?...?=` sentinel for values that cannot ride as plain ASCII field values. - # Mirrors the TypeScript SDK's `mcpParamHeaders` codec; the standard-header half (`Mcp-Method`, `Mcp-Name`) - # lives with the transport. - # - # https://modelcontextprotocol.io/specification/draft/basic/transports/streamable-http#custom-headers-from-tool-parameters - module McpParamHeaders - # The fixed prefix every custom-parameter header carries. - HEADER_PREFIX = "Mcp-Param-" - - # The schema-extension property name a tool's `inputSchema` carries. - X_MCP_HEADER_KEY = "x-mcp-header" - - # RFC 9110 Section 5.1 `token` syntax (`1*tchar`): rejects empty names, spaces, - # control characters (including CR/LF), and the HTTP delimiters. - RFC9110_TOKEN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/.freeze - - # The spec text admits `string`, `integer`, and `boolean`. `number` is also accepted because - # the published conformance referee annotates `type: "number"` parameters and expects them - # mirrored; the TypeScript SDK makes the same accommodation. - PERMITTED_TYPES = ["string", "integer", "boolean", "number"].freeze - - # JSON Schema keywords the SEP-2243 static-reachability constraint excludes from - # the `properties`-only chain. An `x-mcp-header` under any of these invalidates - # the tool definition rather than being silently ignored. - NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions", - ].freeze - - # Keywords whose value maps names to subschemas rather than being one subschema or a list of them. - OBJECT_VALUED_SUBSCHEMA_KEYWORDS = ["patternProperties", "dependentSchemas", "$defs", "definitions"].freeze - - # Integers beyond 2**53 - 1 lose precision in JSON number interchange, so they are not mirrored; - # the TypeScript SDK refuses unsafe integers the same way. - MAX_SAFE_INTEGER = (2**53) - 1 - - BASE64_SENTINEL_PREFIX = "=?base64?" - BASE64_SENTINEL_SUFFIX = "?=" - - class << self - # Scans a tool's `inputSchema` for `x-mcp-header` declarations and validates every constraint - # the spec places on them: RFC 9110 token names, case-insensitive uniqueness, primitive-typed - # declaring properties, and static reachability through a chain of `properties` keys only. - # Returns `{ valid: true, declarations: [...] }` with each declaration `{ path:, header_name:, type: }`, - # or `{ valid: false, reason: "..." }` on the first violation. - def scan(input_schema) - declarations = [] - fault = visit(input_schema, [], true, declarations, {}) - - fault ? { valid: false, reason: fault } : { valid: true, declarations: declarations } - end - - # Builds the `Mcp-Param-{Name}` headers for one `tools/call` from the scanned declarations and - # the call's `arguments`. A `null` or absent value omits its header (the spec's MUST-omit rows); - # a non-primitive or non-representable value is omitted rather than emitted malformed. - def build(declarations, arguments) - declarations.each_with_object({}) do |declaration, headers| - value = value_at_path(arguments, declaration[:path]) - next if value.nil? - - string_value = primitive_to_string(value) - next unless string_value - - encoded = begin - encode_value(string_value) - rescue EncodingError - # A string that cannot be represented as UTF-8 (e.g. binary data) has no header - # representation; omit it like the other non-representable values. - next - end - - headers["#{HEADER_PREFIX}#{declaration[:header_name]}"] = encoded - end - end - - # Converts a primitive argument to its header string per the spec's type-conversion rules: - # strings pass through, booleans become lowercase `"true"` / `"false"`, and numbers become - # their decimal string. `nil` means "not representable: do not emit a header". - def primitive_to_string(value) - case value - when String - value - when true - "true" - when false - "false" - when Integer - value.abs <= MAX_SAFE_INTEGER ? value.to_s : nil - when Float - return unless value.finite? - - # JSON has one number type: an integral float serializes without the fractional part, - # matching the `String(42.0)` the JavaScript reference emits. - value == value.truncate ? value.truncate.to_s : value.to_s - end - end - - # Encodes a header value per the spec's value-encoding rules: a safe plain-ASCII field value - # passes through unchanged, everything else is wrapped as `=?base64?{base64-of-UTF-8}?=`. - def encode_value(value) - return value unless needs_base64?(value) - - "#{BASE64_SENTINEL_PREFIX}#{[value.encode(Encoding::UTF_8)].pack("m0")}#{BASE64_SENTINEL_SUFFIX}" - end - - private - - def visit(node, path, reachable, declarations, seen_lower) - return unless node.is_a?(Hash) - - if key?(node, X_MCP_HEADER_KEY) - fault = validate_declaration(node, path, reachable, declarations, seen_lower) - - return fault if fault - end - - properties = read(node, "properties") - if properties.is_a?(Hash) - properties.each do |key, child| - fault = visit(child, path + [key.to_s], reachable, declarations, seen_lower) - - return fault if fault - end - end - - # Static-reachability sweep: descend the keywords the `properties` chain MUST NOT pass - # through with `reachable: false`, so an annotation under any of them is reported. - # `$defs` covers `$ref`-within-`$defs`; chasing arbitrary `$ref` URIs is out of scope. - NON_REACHABLE_SUBSCHEMA_KEYWORDS.each do |keyword| - next unless (sub = read(node, keyword)) - - branches = if sub.is_a?(Array) - sub - elsif sub.is_a?(Hash) && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.include?(keyword) - sub.values - else - [sub] - end - - branches.each do |branch| - fault = visit(branch, path + ["<#{keyword}>"], false, declarations, seen_lower) - - return fault if fault - end - end - - nil - end - - def validate_declaration(node, path, reachable, declarations, seen_lower) - if !reachable || path.empty? - return "#{path_name(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of `properties` keys" - - end - - annotation = read(node, X_MCP_HEADER_KEY) - - unless annotation.is_a?(String) && !annotation.empty? - return "#{path_name(path)}: x-mcp-header MUST be a non-empty string" - end - - unless RFC9110_TOKEN.match?(annotation) - return "#{path_name(path)}: x-mcp-header `#{annotation}` is not a valid RFC 9110 token" - end - - type = read(node, "type") - unless type.is_a?(String) && PERMITTED_TYPES.include?(type) - return "#{path_name(path)}: x-mcp-header is only permitted on primitive-typed properties " \ - "(got `#{type.inspect}`)" - end - - lower = annotation.downcase - prior = seen_lower[lower] - if prior - return "x-mcp-header `#{annotation}` is not case-insensitively unique (also declared as `#{prior}`)" - end - - seen_lower[lower] = annotation - declarations << { path: path, header_name: annotation, type: type } - nil - end - - # A value cannot ride as a plain ASCII field value when it is empty, already shaped like - # the Base64 sentinel (the spec's ambiguity rule), carries edge whitespace that field parsing - # would strip, or contains a byte outside visible ASCII plus interior tab. - def needs_base64?(value) - return true if value.empty? - return true if value.start_with?(BASE64_SENTINEL_PREFIX) && value.end_with?(BASE64_SENTINEL_SUFFIX) - return true if value != value.strip - - value.each_byte.any? { |byte| byte != 0x09 && !byte.between?(0x20, 0x7e) } - end - - def value_at_path(root, path) - path.reduce(root) do |node, key| - break unless node.is_a?(Hash) - - read(node, key) - end - end - - # Schemas and arguments arrive with string keys off the wire but may carry symbol keys - # when constructed in Ruby; read both forms like the SDK's other readers. - def read(hash, key) - value = hash[key] - - value.nil? ? hash[key.to_sym] : value - end - - def key?(hash, key) - hash.key?(key) || hash.key?(key.to_sym) - end - - def path_name(path) - path.empty? ? "" : path.join(".") - end - end - end - end -end diff --git a/lib/mcp/mcp_param_headers.rb b/lib/mcp/mcp_param_headers.rb new file mode 100644 index 00000000..582daf71 --- /dev/null +++ b/lib/mcp/mcp_param_headers.rb @@ -0,0 +1,332 @@ +# frozen_string_literal: true + +module MCP + # The custom-header half of SEP-2243 (MCP 2026-07-28), shared by the client and the server transport: scanning a tool's `inputSchema` + # for `x-mcp-header` declarations, encoding `tools/call` argument values into `Mcp-Param-{Name}` HTTP headers with + # the `=?base64?...?=` sentinel for values that cannot ride as plain ASCII field values, decoding such headers, and checking that + # the headers a request carries agree with the arguments in its body. Mirrors the TypeScript SDK's `mcpParamHeaders` codec; + # the standard-header half (`Mcp-Method`, `Mcp-Name`) lives with the transports. + # + # https://modelcontextprotocol.io/specification/draft/basic/transports/streamable-http#custom-headers-from-tool-parameters + module McpParamHeaders + # The fixed prefix every custom-parameter header carries. + HEADER_PREFIX = "Mcp-Param-" + + # The schema-extension property name a tool's `inputSchema` carries. + X_MCP_HEADER_KEY = "x-mcp-header" + + # RFC 9110 Section 5.1 `token` syntax (`1*tchar`): rejects empty names, spaces, + # control characters (including CR/LF), and the HTTP delimiters. + RFC9110_TOKEN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/.freeze + + # The spec text admits `string`, `integer`, and `boolean`. `number` is also accepted because + # the published conformance referee annotates `type: "number"` parameters and expects them mirrored; + # the TypeScript SDK makes the same accommodation. + PERMITTED_TYPES = ["string", "integer", "boolean", "number"].freeze + + # JSON Schema keywords the SEP-2243 static-reachability constraint excludes from the `properties`-only chain. + # An `x-mcp-header` under any of these invalidates the tool definition rather than being silently ignored. + NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "contentSchema", + "$defs", + "definitions", + ].freeze + + # Keywords whose value maps names to subschemas rather than being one subschema or a list of them. + OBJECT_VALUED_SUBSCHEMA_KEYWORDS = ["patternProperties", "dependentSchemas", "$defs", "definitions"].freeze + + # Integers beyond 2**53 - 1 lose precision in JSON number interchange, so they are not mirrored; + # the TypeScript SDK refuses unsafe integers the same way. + MAX_SAFE_INTEGER = (2**53) - 1 + + BASE64_SENTINEL_PREFIX = "=?base64?" + BASE64_SENTINEL_SUFFIX = "?=" + + # The decimal numerals the numeric comparison of an integer or number declaration accepts from a header: + # the rendering of an integer (`42`, `-7`), or one with a fraction, which the spec's SHOULD equates to the integer (`42.0`). + # Anything else (`0x2a`, `1e3`, `042`, ` 42`) is compared as a string and so never agrees by accident. + CANONICAL_DECIMAL = /\A-?(?:0|[1-9]\d*)(?:\.\d+)?\z/.freeze + + NUMERIC_TYPES = ["integer", "number"].freeze + + # The longest numeral the numeric comparison reads, which bounds the arbitrary-precision parsing a header can ask for. + # A longer numeral is judged by byte equality alone: that still accepts the rendering a client mirrors, + # however long (an integral double renders as its digits), and refuses every other spelling of the number. + MAX_NUMERAL_BYTES = 64 + + class << self + # Scans a tool's `inputSchema` for `x-mcp-header` declarations and validates every constraint the spec places on them: + # RFC 9110 token names, case-insensitive uniqueness, primitive-typed declaring properties, and static reachability through + # a chain of `properties` keys only. Returns `{ valid: true, declarations: [...] }` with each declaration `{ path:, header_name:, type: }`, + # or `{ valid: false, reason: "..." }` on the first violation. + def scan(input_schema) + declarations = [] + fault = visit(input_schema, [], true, declarations, {}) + + fault ? { valid: false, reason: fault } : { valid: true, declarations: declarations } + end + + # Builds the `Mcp-Param-{Name}` headers for one `tools/call` from the scanned declarations and the call's `arguments`. + # A `null` or absent value omits its header (the spec's MUST-omit rows); a non-primitive or non-representable value is + # omitted rather than emitted malformed. + def build(declarations, arguments) + declarations.each_with_object({}) do |declaration, headers| + value = value_at_path(arguments, declaration[:path]) + next if value.nil? + + string_value = primitive_to_string(value) + next unless string_value + + encoded = begin + encode_value(string_value) + rescue EncodingError + # A string that cannot be represented as UTF-8 (e.g. binary data) has no header representation; + # omit it like the other non-representable values. + next + end + + headers["#{HEADER_PREFIX}#{declaration[:header_name]}"] = encoded + end + end + + # Converts a primitive argument to its header string per the spec's type-conversion rules: strings pass through, + # booleans become lowercase `"true"` / `"false"`, and numbers become their decimal string. + # `nil` means "not representable: do not emit a header". + def primitive_to_string(value) + case value + when String + value + when true + "true" + when false + "false" + when Integer + value.abs <= MAX_SAFE_INTEGER ? value.to_s : nil + when Float + return unless value.finite? + + # JSON has one number type: an integral float serializes without the fractional part, + # matching the `String(42.0)` the JavaScript reference emits. + value == value.truncate ? value.truncate.to_s : value.to_s + end + end + + # Encodes a header value per the spec's value-encoding rules: a safe plain-ASCII field value + # passes through unchanged, everything else is wrapped as `=?base64?{base64-of-UTF-8}?=`. + def encode_value(value) + return value unless needs_base64?(value) + + "#{BASE64_SENTINEL_PREFIX}#{[value.encode(Encoding::UTF_8)].pack("m0")}#{BASE64_SENTINEL_SUFFIX}" + end + + # Decodes an `Mcp-Param-{Name}` header value: one carrying the sentinel yields its payload decoded as UTF-8, + # any other value is taken literally, as the spec's examples show. `nil` marks a value the server has to refuse rather + # than compare: one holding a byte outside the field-value set (the spec's invalid characters; a conforming client + # wraps such a value), or a sentinel whose payload is not canonical Base64 (padding, alphabet, trailing bits) or + # not valid UTF-8, since a lenient decoder would let two different header values stand for one body value. + def decode_value(value) + return unless field_value?(value) + return value unless sentinel_wrapped?(value) + + payload_size = value.bytesize - BASE64_SENTINEL_PREFIX.bytesize - BASE64_SENTINEL_SUFFIX.bytesize + decoded = value.byteslice(BASE64_SENTINEL_PREFIX.bytesize, payload_size).unpack1("m0").force_encoding(Encoding::UTF_8) + decoded.valid_encoding? ? decoded : nil + rescue ArgumentError + nil + end + + # The server side of the spec's table for custom headers: for each declaration, the `Mcp-Param-{Name}` header and + # the body value at the declared path are present together and agree once the header is decoded, or are absent together. + # The block is called with each declared header name and returns the raw field value, or `nil` when the request + # does not carry it. Returns a message naming the first disagreement by header and argument path, never by value, + # or `nil` when every declaration agrees. + def mismatch(declarations, arguments) + declarations.each do |declaration| + header_name = "#{HEADER_PREFIX}#{declaration[:header_name]}" + raw = yield(header_name) + value = value_at_path(arguments, declaration[:path]) + argument = declaration[:path].join(".") + + if value.nil? + # The spec has the server expect no header for a null or absent value. One sent anyway claims a value + # the body does not carry, which is exactly what an intermediary acting on the header would act on. + return "#{header_name} header is present but the request body carries no `#{argument}` argument" if raw + + next + end + + rendered = primitive_to_string(value) + if rendered.nil? + # A value without a header rendering (an object, an array, an integer past the safe range) is one + # a conforming client omits the header for, so a header claiming it can never agree with it. + return "#{header_name} header does not match the `#{argument}` argument" if raw + + next + end + + return "#{header_name} header is missing but the request body carries a `#{argument}` argument" if raw.nil? + return "#{header_name} header holds a character that is not allowed in a field value" unless field_value?(raw) + + decoded = decode_value(raw) + return "#{header_name} header carries a malformed Base64 value" if decoded.nil? + + unless agrees?(declaration[:type], value, rendered, decoded) + return "#{header_name} header does not match the `#{argument}` argument" + end + end + + nil + end + + private + + # A decoded header agrees with a body value when it equals the value's header rendering byte for byte, or, for + # an integer or number declaration with a numeric body value, when it is a canonical decimal of the same number + # within `MAX_NUMERAL_BYTES`: the spec's SHOULD that `42.0` equals `42`. An integer compares exactly, so a value + # past the double range still compares; a float compares as the double the header denotes. + def agrees?(type, value, rendered, decoded) + return true if decoded.b == rendered.b + return false unless NUMERIC_TYPES.include?(type) && value.is_a?(Numeric) + return false unless decoded.bytesize <= MAX_NUMERAL_BYTES && CANONICAL_DECIMAL.match?(decoded) + + value.is_a?(Integer) ? Rational(decoded) == value : Float(decoded) == value + end + + def visit(node, path, reachable, declarations, seen_lower) + return unless node.is_a?(Hash) + + if key?(node, X_MCP_HEADER_KEY) + fault = validate_declaration(node, path, reachable, declarations, seen_lower) + + return fault if fault + end + + properties = read(node, "properties") + if properties.is_a?(Hash) + properties.each do |key, child| + fault = visit(child, path + [key.to_s], reachable, declarations, seen_lower) + + return fault if fault + end + end + + # Static-reachability sweep: descend the keywords the `properties` chain MUST NOT pass through with `reachable: false`, + # so an annotation under any of them is reported. `$defs` covers `$ref`-within-`$defs`; chasing arbitrary `$ref` URIs + # is out of scope. + NON_REACHABLE_SUBSCHEMA_KEYWORDS.each do |keyword| + next unless (sub = read(node, keyword)) + + branches = if sub.is_a?(Array) + sub + elsif sub.is_a?(Hash) && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.include?(keyword) + sub.values + else + [sub] + end + + branches.each do |branch| + fault = visit(branch, path + ["<#{keyword}>"], false, declarations, seen_lower) + + return fault if fault + end + end + + nil + end + + def validate_declaration(node, path, reachable, declarations, seen_lower) + if !reachable || path.empty? + return "#{path_name(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of `properties` keys" + end + + annotation = read(node, X_MCP_HEADER_KEY) + + unless annotation.is_a?(String) && !annotation.empty? + return "#{path_name(path)}: x-mcp-header MUST be a non-empty string" + end + + unless RFC9110_TOKEN.match?(annotation) + return "#{path_name(path)}: x-mcp-header `#{annotation}` is not a valid RFC 9110 token" + end + + type = read(node, "type") + unless type.is_a?(String) && PERMITTED_TYPES.include?(type) + return "#{path_name(path)}: x-mcp-header is only permitted on primitive-typed properties (got `#{type.inspect}`)" + end + + lower = annotation.downcase + prior = seen_lower[lower] + if prior + return "x-mcp-header `#{annotation}` is not case-insensitively unique (also declared as `#{prior}`)" + end + + seen_lower[lower] = annotation + declarations << { path: path, header_name: annotation, type: type } + nil + end + + # A value cannot ride as a plain ASCII field value when it is empty, already shaped like the Base64 sentinel + # (the spec's ambiguity rule), carries edge whitespace that field parsing would strip, or contains + # a byte outside visible ASCII plus interior tab. + def needs_base64?(value) + return true if value.empty? + return true if value.start_with?(BASE64_SENTINEL_PREFIX) && value.end_with?(BASE64_SENTINEL_SUFFIX) + return true if value != value.strip + + !field_value?(value) + end + + def sentinel_wrapped?(value) + return false if value.bytesize < BASE64_SENTINEL_PREFIX.bytesize + BASE64_SENTINEL_SUFFIX.bytesize + + value.start_with?(BASE64_SENTINEL_PREFIX) && value.end_with?(BASE64_SENTINEL_SUFFIX) + end + + # The bytes RFC 9110 lets a field value carry, which the spec's value encoding keeps a plain header within: + # visible ASCII, space, and horizontal tab. Checked byte by byte, so a value of any encoding is judged the same. + def field_value?(value) + value.each_byte.all? { |byte| byte == 0x09 || byte.between?(0x20, 0x7e) } + end + + def value_at_path(root, path) + path.reduce(root) do |node, key| + break unless node.is_a?(Hash) + + read(node, key) + end + end + + # Schemas and arguments arrive with string keys off the wire but may carry symbol keys when constructed in Ruby; + # read both forms like the SDK's other readers. + def read(hash, key) + value = hash[key] + + value.nil? ? hash[key.to_sym] : value + end + + def key?(hash, key) + hash.key?(key) || hash.key?(key.to_sym) + end + + def path_name(path) + path.empty? ? "" : path.join(".") + end + end + end +end diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 86e442a0..7e8b29ff 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -923,6 +923,13 @@ 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 @@ -1031,6 +1038,39 @@ def validate_modern_headers(request, body, header_version) nil end + # 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. + # + # 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] + 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| + 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 # `notifications/subscriptions/acknowledged` with the subset of requested notification types # the server agreed to honor. Notifications delivered on the stream carry `io.modelcontextprotocol/subscriptionId` diff --git a/test/mcp/client/mcp_param_headers_test.rb b/test/mcp/client/mcp_param_headers_test.rb deleted file mode 100644 index 639a0abd..00000000 --- a/test/mcp/client/mcp_param_headers_test.rb +++ /dev/null @@ -1,208 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" -require "mcp/client/mcp_param_headers" - -module MCP - class Client - class McpParamHeadersTest < Minitest::Test - def test_scan_collects_declarations_from_properties - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { - "region" => { "type" => "string", "x-mcp-header" => "Region" }, - "priority" => { "type" => "integer", "x-mcp-header" => "Priority" }, - "verbose" => { "type" => "boolean", "x-mcp-header" => "Verbose" }, - "plain" => { "type" => "string" }, - }, - }) - - assert(scan[:valid]) - assert_equal( - [ - { path: ["region"], header_name: "Region", type: "string" }, - { path: ["priority"], header_name: "Priority", type: "integer" }, - { path: ["verbose"], header_name: "Verbose", type: "boolean" }, - ], - scan[:declarations], - ) - end - - def test_scan_collects_nested_declarations_and_symbol_keys - scan = McpParamHeaders.scan({ - type: "object", - properties: { - options: { - type: "object", - properties: { - region: { type: "string", "x-mcp-header": "Region" }, - }, - }, - }, - }) - - assert(scan[:valid]) - assert_equal([{ path: ["options", "region"], header_name: "Region", type: "string" }], scan[:declarations]) - end - - def test_scan_accepts_number_typed_declarations - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { "float_val" => { "type" => "number", "x-mcp-header" => "FloatVal" } }, - }) - - assert(scan[:valid]) - assert_equal("number", scan[:declarations].first[:type]) - end - - def test_scan_rejects_an_annotation_at_the_schema_root - scan = McpParamHeaders.scan({ "type" => "object", "x-mcp-header" => "Root" }) - - refute(scan[:valid]) - assert_includes(scan[:reason], "statically reachable") - end - - def test_scan_rejects_annotations_under_non_reachable_keywords - ["oneOf", "items", "$defs"].each do |keyword| - nested = { "type" => "string", "x-mcp-header" => "Hidden" } - sub = keyword == "$defs" ? { "entry" => nested } : [nested] - scan = McpParamHeaders.scan({ "type" => "object", keyword => sub }) - - refute(scan[:valid], "expected the annotation under #{keyword} to invalidate the schema") - end - end - - def test_scan_rejects_empty_and_non_string_annotations - ["", 42].each do |annotation| - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { "value" => { "type" => "string", "x-mcp-header" => annotation } }, - }) - - refute(scan[:valid]) - assert_includes(scan[:reason], "non-empty string") - end - end - - def test_scan_rejects_non_token_annotation_names - ["has space", "colon:name", "日本語", "line\nbreak"].each do |annotation| - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { "value" => { "type" => "string", "x-mcp-header" => annotation } }, - }) - - refute(scan[:valid], "expected #{annotation.inspect} to be rejected") - assert_includes(scan[:reason], "RFC 9110") - end - end - - def test_scan_rejects_non_primitive_declaring_properties - [{ "type" => "object" }, { "type" => "array" }, {}].each do |extra| - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { "value" => extra.merge("x-mcp-header" => "Value") }, - }) - - refute(scan[:valid]) - assert_includes(scan[:reason], "primitive-typed") - end - end - - def test_scan_rejects_case_insensitively_duplicated_names - scan = McpParamHeaders.scan({ - "type" => "object", - "properties" => { - "one" => { "type" => "string", "x-mcp-header" => "Region" }, - "two" => { "type" => "string", "x-mcp-header" => "REGION" }, - }, - }) - - refute(scan[:valid]) - assert_includes(scan[:reason], "case-insensitively unique") - end - - def test_primitive_to_string_conversions - assert_equal("us-west1", McpParamHeaders.primitive_to_string("us-west1")) - assert_equal("true", McpParamHeaders.primitive_to_string(true)) - assert_equal("false", McpParamHeaders.primitive_to_string(false)) - assert_equal("42", McpParamHeaders.primitive_to_string(42)) - assert_equal("42", McpParamHeaders.primitive_to_string(42.0)) - assert_equal("3.14159", McpParamHeaders.primitive_to_string(3.14159)) - assert_nil(McpParamHeaders.primitive_to_string(2**53 + 1)) - assert_nil(McpParamHeaders.primitive_to_string(Float::INFINITY)) - assert_nil(McpParamHeaders.primitive_to_string({ "nested" => true })) - end - - def test_encode_value_passes_safe_ascii_through - assert_equal("us-west1", McpParamHeaders.encode_value("us-west1")) - assert_equal("SELECT * FROM users", McpParamHeaders.encode_value("SELECT * FROM users")) - end - - def test_encode_value_wraps_unsafe_values_in_the_base64_sentinel - { - "" => "", - "Hello, 世界" => "Hello, 世界", - " padded " => " padded ", - "\tindented" => "\tindented", - "line1\nline2" => "line1\nline2", - "line1\r\nline2" => "line1\r\nline2", - "=?base64?Zm9v?=" => "=?base64?Zm9v?=", - }.each do |raw, decoded| - encoded = McpParamHeaders.encode_value(raw) - - assert_match(/\A=\?base64\?.*\?=\z/, encoded, "expected #{raw.inspect} to be wrapped") - payload = encoded.delete_prefix("=?base64?").delete_suffix("?=") - assert_equal(decoded, payload.unpack1("m0").force_encoding(Encoding::UTF_8)) - end - end - - def test_build_mirrors_declared_arguments_into_prefixed_headers - declarations = [ - { path: ["region"], header_name: "Region", type: "string" }, - { path: ["priority"], header_name: "Priority", type: "integer" }, - { path: ["method_val"], header_name: "Method", type: "string" }, - ] - - headers = McpParamHeaders.build(declarations, { "region" => "us-west1", priority: 42, "method_val" => "test-method" }) - - assert_equal( - { - "Mcp-Param-Region" => "us-west1", - "Mcp-Param-Priority" => "42", - "Mcp-Param-Method" => "test-method", - }, - headers, - ) - end - - def test_build_omits_null_absent_and_non_primitive_values - declarations = [ - { path: ["null_val"], header_name: "NullVal", type: "string" }, - { path: ["absent"], header_name: "Absent", type: "string" }, - { path: ["object_val"], header_name: "ObjectVal", type: "string" }, - ] - - headers = McpParamHeaders.build(declarations, { "null_val" => nil, "object_val" => { "a" => 1 } }) - - assert_empty(headers) - end - - def test_build_reads_nested_paths - declarations = [{ path: ["options", "region"], header_name: "Region", type: "string" }] - - headers = McpParamHeaders.build(declarations, { "options" => { "region" => "us-east1" } }) - - assert_equal({ "Mcp-Param-Region" => "us-east1" }, headers) - end - - def test_build_omits_values_that_cannot_be_represented_as_utf_8 - declarations = [{ path: ["blob"], header_name: "Blob", type: "string" }] - binary = (+"\xff\xfe").force_encoding(Encoding::ASCII_8BIT) - - headers = McpParamHeaders.build(declarations, { "blob" => binary }) - - assert_empty(headers) - end - end - end -end diff --git a/test/mcp/mcp_param_headers_test.rb b/test/mcp/mcp_param_headers_test.rb new file mode 100644 index 00000000..8e7d8edb --- /dev/null +++ b/test/mcp/mcp_param_headers_test.rb @@ -0,0 +1,327 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class McpParamHeadersTest < Minitest::Test + def test_scan_collects_declarations_from_properties + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { + "region" => { "type" => "string", "x-mcp-header" => "Region" }, + "priority" => { "type" => "integer", "x-mcp-header" => "Priority" }, + "verbose" => { "type" => "boolean", "x-mcp-header" => "Verbose" }, + "plain" => { "type" => "string" }, + }, + }) + + assert(scan[:valid]) + assert_equal( + [ + { path: ["region"], header_name: "Region", type: "string" }, + { path: ["priority"], header_name: "Priority", type: "integer" }, + { path: ["verbose"], header_name: "Verbose", type: "boolean" }, + ], + scan[:declarations], + ) + end + + def test_scan_collects_nested_declarations_and_symbol_keys + scan = McpParamHeaders.scan({ + type: "object", + properties: { + options: { + type: "object", + properties: { + region: { type: "string", "x-mcp-header": "Region" }, + }, + }, + }, + }) + + assert(scan[:valid]) + assert_equal([{ path: ["options", "region"], header_name: "Region", type: "string" }], scan[:declarations]) + end + + def test_scan_accepts_number_typed_declarations + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { "float_val" => { "type" => "number", "x-mcp-header" => "FloatVal" } }, + }) + + assert(scan[:valid]) + assert_equal("number", scan[:declarations].first[:type]) + end + + def test_scan_rejects_an_annotation_at_the_schema_root + scan = McpParamHeaders.scan({ "type" => "object", "x-mcp-header" => "Root" }) + + refute(scan[:valid]) + assert_includes(scan[:reason], "statically reachable") + end + + def test_scan_rejects_annotations_under_non_reachable_keywords + ["oneOf", "items", "contentSchema", "$defs"].each do |keyword| + nested = { "type" => "string", "x-mcp-header" => "Hidden" } + sub = case keyword + when "$defs" then { "entry" => nested } + when "contentSchema" then nested + else [nested] + end + scan = McpParamHeaders.scan({ "type" => "object", keyword => sub }) + + refute(scan[:valid], "expected the annotation under #{keyword} to invalidate the schema") + end + end + + def test_scan_rejects_empty_and_non_string_annotations + ["", 42].each do |annotation| + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { "value" => { "type" => "string", "x-mcp-header" => annotation } }, + }) + + refute(scan[:valid]) + assert_includes(scan[:reason], "non-empty string") + end + end + + def test_scan_rejects_non_token_annotation_names + ["has space", "colon:name", "日本語", "line\nbreak"].each do |annotation| + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { "value" => { "type" => "string", "x-mcp-header" => annotation } }, + }) + + refute(scan[:valid], "expected #{annotation.inspect} to be rejected") + assert_includes(scan[:reason], "RFC 9110") + end + end + + def test_scan_rejects_non_primitive_declaring_properties + [{ "type" => "object" }, { "type" => "array" }, {}].each do |extra| + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { "value" => extra.merge("x-mcp-header" => "Value") }, + }) + + refute(scan[:valid]) + assert_includes(scan[:reason], "primitive-typed") + end + end + + def test_scan_rejects_case_insensitively_duplicated_names + scan = McpParamHeaders.scan({ + "type" => "object", + "properties" => { + "one" => { "type" => "string", "x-mcp-header" => "Region" }, + "two" => { "type" => "string", "x-mcp-header" => "REGION" }, + }, + }) + + refute(scan[:valid]) + assert_includes(scan[:reason], "case-insensitively unique") + end + + def test_primitive_to_string_conversions + assert_equal("us-west1", McpParamHeaders.primitive_to_string("us-west1")) + assert_equal("true", McpParamHeaders.primitive_to_string(true)) + assert_equal("false", McpParamHeaders.primitive_to_string(false)) + assert_equal("42", McpParamHeaders.primitive_to_string(42)) + assert_equal("42", McpParamHeaders.primitive_to_string(42.0)) + assert_equal("3.14159", McpParamHeaders.primitive_to_string(3.14159)) + assert_nil(McpParamHeaders.primitive_to_string(2**53 + 1)) + assert_nil(McpParamHeaders.primitive_to_string(Float::INFINITY)) + assert_nil(McpParamHeaders.primitive_to_string({ "nested" => true })) + end + + def test_encode_value_passes_safe_ascii_through + assert_equal("us-west1", McpParamHeaders.encode_value("us-west1")) + assert_equal("SELECT * FROM users", McpParamHeaders.encode_value("SELECT * FROM users")) + end + + def test_encode_value_wraps_unsafe_values_in_the_base64_sentinel + { + "" => "", + "Hello, 世界" => "Hello, 世界", + " padded " => " padded ", + "\tindented" => "\tindented", + "line1\nline2" => "line1\nline2", + "line1\r\nline2" => "line1\r\nline2", + "=?base64?Zm9v?=" => "=?base64?Zm9v?=", + }.each do |raw, decoded| + encoded = McpParamHeaders.encode_value(raw) + + assert_match(/\A=\?base64\?.*\?=\z/, encoded, "expected #{raw.inspect} to be wrapped") + payload = encoded.delete_prefix("=?base64?").delete_suffix("?=") + assert_equal(decoded, payload.unpack1("m0").force_encoding(Encoding::UTF_8)) + end + end + + def test_build_mirrors_declared_arguments_into_prefixed_headers + declarations = [ + { path: ["region"], header_name: "Region", type: "string" }, + { path: ["priority"], header_name: "Priority", type: "integer" }, + { path: ["method_val"], header_name: "Method", type: "string" }, + ] + + headers = McpParamHeaders.build(declarations, { "region" => "us-west1", priority: 42, "method_val" => "test-method" }) + + assert_equal( + { + "Mcp-Param-Region" => "us-west1", + "Mcp-Param-Priority" => "42", + "Mcp-Param-Method" => "test-method", + }, + headers, + ) + end + + def test_build_omits_null_absent_and_non_primitive_values + declarations = [ + { path: ["null_val"], header_name: "NullVal", type: "string" }, + { path: ["absent"], header_name: "Absent", type: "string" }, + { path: ["object_val"], header_name: "ObjectVal", type: "string" }, + ] + + headers = McpParamHeaders.build(declarations, { "null_val" => nil, "object_val" => { "a" => 1 } }) + + assert_empty(headers) + end + + def test_build_reads_nested_paths + declarations = [{ path: ["options", "region"], header_name: "Region", type: "string" }] + + headers = McpParamHeaders.build(declarations, { "options" => { "region" => "us-east1" } }) + + assert_equal({ "Mcp-Param-Region" => "us-east1" }, headers) + end + + def test_build_omits_values_that_cannot_be_represented_as_utf_8 + declarations = [{ path: ["blob"], header_name: "Blob", type: "string" }] + binary = (+"\xff\xfe").force_encoding(Encoding::ASCII_8BIT) + + headers = McpParamHeaders.build(declarations, { "blob" => binary }) + + assert_empty(headers) + end + + def test_decode_value_takes_values_without_the_full_sentinel_literally + assert_equal("us-west1", McpParamHeaders.decode_value("us-west1")) + assert_equal("SGVsbG8=", McpParamHeaders.decode_value("SGVsbG8=")) + assert_equal("=?base64?SGVsbG8=", McpParamHeaders.decode_value("=?base64?SGVsbG8=")) + assert_equal("SGVsbG8=?=", McpParamHeaders.decode_value("SGVsbG8=?=")) + assert_equal("=?base64?=", McpParamHeaders.decode_value("=?base64?=")) + end + + def test_decode_value_decodes_the_sentinel_payload_as_utf_8 + assert_equal("Hello", McpParamHeaders.decode_value("=?base64?SGVsbG8=?=")) + assert_equal("", McpParamHeaders.decode_value("=?base64??=")) + assert_equal(" padded ", McpParamHeaders.decode_value("=?base64?IHBhZGRlZCA=?=")) + assert_equal("=?base64?literal?=", McpParamHeaders.decode_value("=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=")) + assert_equal(Encoding::UTF_8, McpParamHeaders.decode_value("=?base64?SGVsbG8sIOS4lueVjA==?=").encoding) + end + + def test_decode_value_refuses_malformed_payloads + [ + "=?base64?SGVsbG8?=", # missing padding + "=?base64?SGVs!!!bG8=?=", # characters outside the alphabet + "=?base64?SGVsbG9=?=", # non-zero trailing bits + "=?base64?SGVsbG8= ?=", # whitespace inside the payload + "=?base64?/w==?=", # a byte that is not UTF-8 + ].each do |value| + assert_nil(McpParamHeaders.decode_value(value), value) + end + end + + def test_decode_value_refuses_bytes_outside_the_field_value_set + non_ascii = (+"caf\xC3\xA9").force_encoding(Encoding::UTF_8) + + assert_nil(McpParamHeaders.decode_value(non_ascii)) + assert_nil(McpParamHeaders.decode_value(non_ascii.b)) + assert_nil(McpParamHeaders.decode_value("a\x01b")) + assert_nil(McpParamHeaders.decode_value("a\nb")) + assert_equal("a\tb", McpParamHeaders.decode_value("a\tb")) + end + + def test_mismatch_accepts_agreeing_headers_and_pairs_absent_together + declarations = [ + { path: ["region"], header_name: "Region", type: "string" }, + { path: ["priority"], header_name: "Priority", type: "integer" }, + { path: ["verbose"], header_name: "Verbose", type: "boolean" }, + { path: ["options", "zone"], header_name: "Zone", type: "string" }, + ] + headers = { + "Mcp-Param-Region" => "=?base64?IHBhZGRlZCA=?=", + "Mcp-Param-Priority" => "42.0", + "Mcp-Param-Verbose" => "true", + } + arguments = { "region" => " padded ", "priority" => 42, "verbose" => true, "options" => { "zone" => nil } } + + assert_nil(McpParamHeaders.mismatch(declarations, arguments) { |name| headers[name] }) + end + + def test_mismatch_names_the_header_and_the_argument_but_never_a_value + declarations = [{ path: ["region"], header_name: "Region", type: "string" }] + cases = { + { "Mcp-Param-Region" => "us-east1" } => "Mcp-Param-Region header does not match the `region` argument", + {} => "Mcp-Param-Region header is missing but the request body carries a `region` argument", + { "Mcp-Param-Region" => "=?base64?SGVsbG8?=" } => "Mcp-Param-Region header carries a malformed Base64 value", + # Two copies of the header joined by the HTTP server, or a value no conforming client sends unwrapped. + { "Mcp-Param-Region" => "us-west1, us-west1" } => "Mcp-Param-Region header does not match the `region` argument", + { "Mcp-Param-Region" => "us-west1é" } => "Mcp-Param-Region header holds a character that is not allowed in a field value", + } + + cases.each do |headers, message| + assert_equal(message, McpParamHeaders.mismatch(declarations, { "region" => "us-west1" }) { |name| headers[name] }) + refute_includes(message, "us-west1") + refute_includes(message, "us-east1") + end + end + + def test_mismatch_refuses_a_header_whose_argument_is_absent_null_or_unrenderable + declarations = [{ path: ["region"], header_name: "Region", type: "string" }] + present = ->(_name) { "us-west1" } + absent_message = "Mcp-Param-Region header is present but the request body carries no `region` argument" + + assert_equal(absent_message, McpParamHeaders.mismatch(declarations, {}, &present)) + assert_equal(absent_message, McpParamHeaders.mismatch(declarations, { "region" => nil }, &present)) + assert_equal( + "Mcp-Param-Region header does not match the `region` argument", + McpParamHeaders.mismatch(declarations, { "region" => { "nested" => true } }, &present), + ) + assert_nil(McpParamHeaders.mismatch(declarations, { "region" => { "nested" => true } }) { |_name| nil }) + end + + def test_mismatch_compares_numbers_numerically_only_for_canonical_decimals + integer = [{ path: ["priority"], header_name: "Priority", type: "integer" }] + { "42" => true, "42.0" => true, "42.5" => false, "043" => false, " 42" => false, "0x2a" => false, "43" => false } + .each do |header, agrees| + message = McpParamHeaders.mismatch(integer, { "priority" => 42 }) { |_name| header } + + if agrees + assert_nil(message, header) + else + assert_includes(message, "does not match", header) + end + end + + number = [{ path: ["ratio"], header_name: "Ratio", type: "number" }] + assert_nil(McpParamHeaders.mismatch(number, { "ratio" => 0.5 }) { |_name| "0.50" }) + assert_includes(McpParamHeaders.mismatch(number, { "ratio" => 0.5 }) { |_name| "0.51" }, "does not match") + # A string declaration never compares numerically, however numeric the values look. + text = [{ path: ["code"], header_name: "Code", type: "string" }] + assert_includes(McpParamHeaders.mismatch(text, { "code" => "42" }) { |_name| "42.0" }, "does not match") + assert_nil(McpParamHeaders.mismatch(integer, { "priority" => 1 }) { |_name| "1.000000" }) + # A numeral past the bound is judged by byte equality alone, so only its exact rendering agrees. + assert_nil(McpParamHeaders.mismatch(integer, { "priority" => 1 }) { |_name| "1.#{"0" * 62}" }) + assert_includes(McpParamHeaders.mismatch(integer, { "priority" => 1 }) { |_name| "1.#{"0" * 63}" }, "does not match") + end + + def test_mismatch_takes_the_overlapping_sentinel_markers_literally + declarations = [{ path: ["code"], header_name: "Code", type: "string" }] + + assert_nil(McpParamHeaders.mismatch(declarations, { "code" => "=?base64?=" }) { |_name| "=?base64?=" }) + end + end +end diff --git a/test/mcp/server/transports/streamable_http_mcp_param_test.rb b/test/mcp/server/transports/streamable_http_mcp_param_test.rb new file mode 100644 index 00000000..de18d57c --- /dev/null +++ b/test/mcp/server/transports/streamable_http_mcp_param_test.rb @@ -0,0 +1,266 @@ +# frozen_string_literal: true + +require "test_helper" +require "rack" + +module MCP + class Server + module Transports + # The server side of SEP-2243 custom headers: the `Mcp-Param-*` headers of a modern `tools/call` are checked + # against the body before the tool runs. + class StreamableHTTPMcpParamTest < ActiveSupport::TestCase + include InitializeParamsTestHelper + + setup do + @server = Server.new(name: "test_server", tools: [], prompts: [], resources: []) + @server.define_tool( + name: "regional", + input_schema: { + properties: { + region: { type: "string", "x-mcp-header": "Region" }, + priority: { type: "integer", "x-mcp-header": "Priority" }, + verbose: { type: "boolean", "x-mcp-header": "Verbose" }, + options: { type: "object", properties: { zone: { type: "string", "x-mcp-header": "Zone" } } }, + }, + }, + ) do |**args| + seen = [args[:region], args[:priority], args[:verbose], args[:options]&.dig(:zone)] + Tool::Response.new([{ type: "text", text: seen.inspect }]) + end + @transport = StreamableHTTPTransport.new(@server, listen_keepalive_interval: nil) + end + + teardown do + @transport.close + end + + test "a header agreeing with the body passes and the tool runs with the body value" do + response = call_tool({ region: "us-west1" }, { "HTTP_MCP_PARAM_REGION" => "us-west1" }) + + assert_equal '["us-west1", nil, nil, nil]', result_text(response) + end + + test "a Base64 sentinel header is decoded before the comparison" do + response = call_tool({ region: " padded " }, { "HTTP_MCP_PARAM_REGION" => "=?base64?IHBhZGRlZCA=?=" }) + + assert_equal '[" padded ", nil, nil, nil]', result_text(response) + end + + test "a header disagreeing with the body is refused without echoing either value" do + 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" + refute_includes response[2][0], "us-west1" + refute_includes response[2][0], "us-east1" + end + + test "a body value without its header is refused" do + response = call_tool({ region: "us-west1" }, {}) + + assert_header_mismatch response, "Mcp-Param-Region header is missing but the request body carries a `region` argument" + end + + test "a header whose argument is null or absent in the body is refused" do + absent = call_tool({}, { "HTTP_MCP_PARAM_REGION" => "us-west1" }) + null = call_tool({ region: nil }, { "HTTP_MCP_PARAM_REGION" => "us-west1" }) + + [absent, null].each do |response| + assert_header_mismatch response, "Mcp-Param-Region header is present but the request body carries no `region` argument" + end + end + + test "malformed Base64 sentinels are refused" do + ["=?base64?SGVsbG8?=", "=?base64?SGVs!!!bG8=?=", "=?base64?SGVsbG9=?=", "=?base64?/w==?="].each do |value| + response = call_tool({ region: "Hello" }, { "HTTP_MCP_PARAM_REGION" => value }) + + assert_header_mismatch response, "Mcp-Param-Region header carries a malformed Base64 value" + end + end + + test "values without the full sentinel are taken literally" do + { "SGVsbG8=" => "SGVsbG8=", "=?base64?SGVsbG8=" => "=?base64?SGVsbG8=", "=?base64?=" => "=?base64?=" }.each do |header, body| + response = call_tool({ region: body }, { "HTTP_MCP_PARAM_REGION" => header }) + + assert_equal "[#{body.inspect}, nil, nil, nil]", result_text(response) + end + end + + test "a header holding a byte outside the field-value set is refused even when it equals the body" do + non_ascii = (+"caf\xC3\xA9").force_encoding(Encoding::UTF_8) + + { non_ascii => non_ascii, non_ascii.b => non_ascii, "a\x01b" => "a\x01b" }.each do |header, body| + response = call_tool({ region: body }, { "HTTP_MCP_PARAM_REGION" => header }) + + assert_header_mismatch response, "Mcp-Param-Region header holds a character that is not allowed in a field value" + end + end + + test "two declarations that fold onto one Rack key must both agree with that key" do + @server.define_tool( + name: "folded", + input_schema: { + properties: { + a: { type: "string", "x-mcp-header": "Region-A" }, + b: { type: "string", "x-mcp-header": "Region_A" }, + }, + }, + ) do |**args| + Tool::Response.new([{ type: "text", text: [args[:a], args[:b]].inspect }]) + end + + response = call_tool({ a: "x", b: "x" }, { "HTTP_MCP_PARAM_REGION_A" => "x" }, name: "folded") + + assert_equal '["x", "x"]', result_text(response) + + response = call_tool({ a: "x", b: "y" }, { "HTTP_MCP_PARAM_REGION_A" => "x" }, name: "folded") + + assert_header_mismatch response, "Mcp-Param-Region_A header does not match the `b` argument" + end + + test "integer and boolean parameters compare by their header rendering" do + assert_equal '[nil, 42, nil, nil]', result_text(call_tool({ priority: 42 }, { "HTTP_MCP_PARAM_PRIORITY" => "42" })) + assert_equal '[nil, 42, nil, nil]', result_text(call_tool({ priority: 42 }, { "HTTP_MCP_PARAM_PRIORITY" => "42.0" })) + assert_equal '[nil, nil, true, nil]', result_text(call_tool({ verbose: true }, { "HTTP_MCP_PARAM_VERBOSE" => "true" })) + + assert_header_mismatch( + call_tool({ priority: 42 }, { "HTTP_MCP_PARAM_PRIORITY" => "43" }), + "Mcp-Param-Priority header does not match the `priority` argument", + ) + assert_header_mismatch( + call_tool({ verbose: true }, { "HTTP_MCP_PARAM_VERBOSE" => "True" }), + "Mcp-Param-Verbose header does not match the `verbose` argument", + ) + end + + test "a nested declaration reads the value at its property path" do + response = call_tool({ options: { zone: "b" } }, { "HTTP_MCP_PARAM_ZONE" => "b" }) + + assert_equal '[nil, nil, nil, "b"]', result_text(response) + + response = call_tool({ options: { zone: "b" } }, { "HTTP_MCP_PARAM_ZONE" => "c" }) + + assert_header_mismatch response, "Mcp-Param-Zone header does not match the `options.zone` argument" + end + + test "headers for parameters without a declaration are ignored" do + response = call_tool({ region: "us-west1" }, { "HTTP_MCP_PARAM_REGION" => "us-west1", "HTTP_MCP_PARAM_OTHER" => "x" }) + + assert_equal '["us-west1", nil, nil, nil]', result_text(response) + end + + test "a tool whose declarations are invalid is not validated" do + @server.define_tool( + name: "dup", + input_schema: { + properties: { + a: { type: "string", "x-mcp-header": "Same" }, + b: { type: "string", "x-mcp-header": "same" }, + }, + }, + ) do |**args| + Tool::Response.new([{ type: "text", text: args[:a].to_s }]) + end + + response = call_tool({ a: "one" }, { "HTTP_MCP_PARAM_SAME" => "two" }, name: "dup") + + assert_equal "one", result_text(response) + end + + test "an unknown tool is left to the dispatcher" do + response = call_tool({ region: "x" }, { "HTTP_MCP_PARAM_REGION" => "y" }, name: "nope") + + assert_equal 400, response[0] + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, JSON.parse(response[2][0]).dig("error", "code") + end + + test "the handshake lifecycle has no custom headers to check" do + init_request = create_rack_request( + "POST", + { "CONTENT_TYPE" => "application/json" }, + { jsonrpc: "2.0", method: "initialize", id: "init", params: initialize_params }.to_json, + ) + session_id = @transport.handle_request(init_request)[1]["mcp-session-id"] + + response = @transport.handle_request(create_rack_request( + "POST", + { "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id, "HTTP_MCP_PARAM_REGION" => "us-east1" }, + { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "regional", arguments: { region: "us-west1" } } }.to_json, + )) + + assert_equal 200, response[0] + assert_equal "text/event-stream", response[1]["content-type"] + io = StringIO.new + response[2].call(io) + assert_includes io.string, '[\"us-west1\", nil, nil, nil]' + end + + test "tools/list advertises the x-mcp-header annotations the server validates against" do + body = { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: envelope } }.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/list" }, + body, + )) + + assert_equal 200, response[0] + tool = JSON.parse(response[2][0]).dig("result", "tools").find { |entry| entry["name"] == "regional" } + assert_equal "Region", tool.dig("inputSchema", "properties", "region", "x-mcp-header") + assert_equal "Zone", tool.dig("inputSchema", "properties", "options", "properties", "zone", "x-mcp-header") + end + + private + + def call_tool(arguments, headers, name: "regional") + body = { + jsonrpc: "2.0", + id: 7, + method: "tools/call", + params: { name: name, arguments: arguments, _meta: envelope }, + }.to_json + base = { + "CONTENT_TYPE" => "application/json", + "HTTP_MCP_PROTOCOL_VERSION" => "2026-07-28", + "HTTP_MCP_METHOD" => "tools/call", + "HTTP_MCP_NAME" => name, + } + + @transport.handle_request(create_rack_request("POST", base.merge(headers), body)) + end + + def envelope + { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" }, + "io.modelcontextprotocol/clientCapabilities": {}, + } + end + + def result_text(response) + assert_equal 200, response[0] + assert_equal "application/json", response[1]["content-type"] + + JSON.parse(response[2][0]).dig("result", "content", 0, "text") + end + + def assert_header_mismatch(response, message) + assert_equal 400, response[0] + body = JSON.parse(response[2][0]) + assert_equal ErrorCodes::HEADER_MISMATCH, body.dig("error", "code") + assert_equal "Header mismatch: #{message}", body.dig("error", "message") + assert_equal 7, body["id"] + end + + def create_rack_request(method, headers, body) + env = { + "REQUEST_METHOD" => method, + "PATH_INFO" => "/", + "HTTP_ACCEPT" => "application/json, text/event-stream", + "rack.input" => StringIO.new(body.to_s), + }.merge(headers) + + Rack::Request.new(env) + end + end + end + end +end