Skip to content

Commit f0c9665

Browse files
authored
Merge pull request #498 from koic/mirror_x_mcp_header_params_into_headers
Mirror `x-mcp-header` tool parameters into `Mcp-Param-*` headers per SEP-2243
2 parents 6dfef81 + 3511375 commit f0c9665

7 files changed

Lines changed: 723 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2510,6 +2510,20 @@ Troubleshooting: if `server_info["protocolVersion"]` starts returning `nil` afte
25102510
the server now serves the modern lifecycle and the automatic negotiation adopted it.
25112511
Pass `mode: :legacy` for an immediate return to the previous behavior, or switch to the readers above for a permanent fix.
25122512

2513+
### Custom Headers from Tool Parameters (SEP-2243)
2514+
2515+
On a modern `MCP::Client::HTTP` connection, `tools/call` mirrors arguments whose `inputSchema` property carries
2516+
an `x-mcp-header` annotation into `Mcp-Param-{Name}` request headers, so intermediaries can route
2517+
on the values without parsing bodies. The declarations are learned from `tools/list` responses:
2518+
list the tools before calling one to enable the mirroring. Values that cannot ride as plain ASCII header values
2519+
(non-ASCII, control characters, edge whitespace, empty strings) are wrapped as `=?base64?...?=`,
2520+
and a `null` or absent argument omits its header.
2521+
2522+
Per the specification, a tool definition whose `x-mcp-header` annotations are invalid (empty or non-token names,
2523+
duplicate names, non-primitive properties, annotations outside a chain of `properties` keys) is excluded from
2524+
`tools/list` results on modern connections, with a warning naming the tool.
2525+
Legacy connections are unaffected: nothing is learned, mirrored, or excluded.
2526+
25132527
## Transport Layer Interface
25142528

25152529
If the transport layer you need is not included in the gem, you can build and pass your own instances so long as they conform to the following interface:

‎lib/mcp/client.rb‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: true
22

33
require_relative "client/elicitation"
4+
require_relative "client/mcp_param_headers"
45
require_relative "client/modern_envelope"
56
require_relative "client/oauth"
67
require_relative "client/stdio"
@@ -248,7 +249,9 @@ def list_tools(cursor: nil, meta: nil, cancellation: nil)
248249
response = request(method: "tools/list", params: params, meta: meta, cancellation: cancellation)
249250
result = response["result"] || {}
250251

251-
tools = (result["tools"] || []).map do |tool|
252+
tools = (result["tools"] || []).filter_map do |tool|
253+
next if exclude_invalid_x_mcp_header?(tool)
254+
252255
Tool.new(
253256
name: tool["name"],
254257
description: tool["description"],
@@ -573,6 +576,20 @@ def ping(meta: nil, cancellation: nil)
573576

574577
private
575578

579+
# SEP-2243: on the modern lifecycle, a tool definition whose `x-mcp-header` annotations violate
580+
# the spec constraints MUST be excluded from `tools/list` results, so one malformed definition
581+
# does not block the valid tools. The TypeScript and Python SDKs filter their listings the same way.
582+
# Legacy connections, and transports without a lifecycle notion, list everything as before.
583+
def exclude_invalid_x_mcp_header?(tool)
584+
return false unless transport.respond_to?(:modern?) && transport.modern?
585+
586+
scan = McpParamHeaders.scan(tool["inputSchema"])
587+
return false if scan[:valid]
588+
589+
warn("MCP::Client: excluding tool #{tool["name"].inspect} from tools/list: #{scan[:reason]}")
590+
true
591+
end
592+
576593
# Resolves the effective SEP-2575 lifecycle mode for `connect`:
577594
#
578595
# - An explicit `protocol_version` from a legacy generation pins the legacy handshake without a probe,

‎lib/mcp/client/http.rb‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
require_relative "../methods"
77
require_relative "../protocol_deprecations"
88
require_relative "../version"
9+
require_relative "mcp_param_headers"
910
require_relative "modern_envelope"
1011

1112
module MCP
@@ -39,6 +40,12 @@ class HTTP
3940
# and the server transports' request cap.
4041
MAX_MESSAGE_BYTES = 4 * 1024 * 1024
4142

43+
# Upper bound on the tools whose `x-mcp-header` declarations are retained for
44+
# `Mcp-Param-*` mirroring (SEP-2243). Past the cap, newly listed tools mirror nothing
45+
# (the spec's guidance to send without custom headers), so a server rotating tool names across
46+
# `tools/list` responses cannot grow the registry without bound.
47+
MAX_MCP_PARAM_TOOLS = 1000
48+
4249
# Raised when an `oauth:` provider is paired with an MCP URL that is neither HTTPS nor
4350
# a loopback `http://` URL, since a bearer token sent over plain HTTP to a remote host
4451
# is trivially observed and stolen.
@@ -255,6 +262,7 @@ def initialize(url:, headers: {}, oauth: nil, max_message_bytes: MAX_MESSAGE_BYT
255262
@listener_thread = nil
256263
@modern_client_info = nil
257264
@modern_capabilities = nil
265+
@mcp_param_declarations = {}
258266
end
259267

260268
# Registers a handler for a server-to-client request (e.g. `elicitation/create`) delivered on an SSE stream.
@@ -380,6 +388,7 @@ def send_request(request:)
380388
body = resolve_response_body(stream, response, method, params)
381389

382390
capture_session_info(method, response, body) if response
391+
capture_mcp_param_declarations(method, params, body)
383392

384393
body
385394
rescue MessageTooLargeError => e
@@ -712,11 +721,56 @@ def request_metadata_headers(method, params)
712721
name = params[:name] || params["name"]
713722
name = params[:uri] || params["uri"] unless name.is_a?(String)
714723
metadata_headers[NAME_HEADER] = encode_header_value(name) if name.is_a?(String)
724+
725+
if method == MCP::Methods::TOOLS_CALL && (declarations = @mcp_param_declarations[params[:name] || params["name"]])
726+
arguments = params[:arguments] || params["arguments"]
727+
728+
metadata_headers.merge!(McpParamHeaders.build(declarations, arguments))
729+
end
715730
end
716731

717732
metadata_headers
718733
end
719734

735+
# Learns the `x-mcp-header` declarations of the tools a `tools/list` response advertises,
736+
# so later `tools/call` requests can mirror the annotated arguments into `Mcp-Param-*` headers (SEP-2243).
737+
# The custom headers exist on the modern lifecycle only, matching the TypeScript and Python SDKs,
738+
# so legacy connections learn nothing. Only a valid, non-empty declaration set is kept:
739+
# an invalid tool definition mirrors nothing,
740+
# following the spec's guidance to send without custom headers when no reliable declarations are available.
741+
def capture_mcp_param_declarations(method, params, body)
742+
return unless modern?
743+
return unless method.to_s == MCP::Methods::TOOLS_LIST && body.is_a?(Hash)
744+
745+
tools = body.dig("result", "tools")
746+
return unless tools.is_a?(Array)
747+
748+
# An uncursored request answered without `nextCursor` is the complete tool universe,
749+
# so knowledge about unlisted tools is stale; the registry is rebuilt from this listing,
750+
# the same pruning the Python SDK applies to complete listings.
751+
cursor = params.is_a?(Hash) && (params[:cursor] || params["cursor"])
752+
complete = !cursor && body.dig("result", "nextCursor").nil?
753+
registry = complete ? {} : @mcp_param_declarations
754+
755+
tools.each do |tool|
756+
next unless tool.is_a?(Hash)
757+
758+
name = tool["name"]
759+
next unless name.is_a?(String)
760+
761+
scan = McpParamHeaders.scan(tool["inputSchema"])
762+
if scan[:valid] && !scan[:declarations].empty?
763+
next if !registry.key?(name) && registry.size >= MAX_MCP_PARAM_TOOLS
764+
765+
registry[name] = scan[:declarations]
766+
else
767+
registry.delete(name)
768+
end
769+
end
770+
771+
@mcp_param_declarations = registry if complete
772+
end
773+
720774
# A header value that is not safe to transmit as-is - non-ASCII, control characters (including CR/LF,
721775
# which would otherwise allow header injection), or significant leading/trailing whitespace - is wrapped as
722776
# `=?base64?<base64>?=`. Safe ASCII values are sent unchanged.
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
# frozen_string_literal: true
2+
3+
module MCP
4+
class Client
5+
# The custom-header half of SEP-2243 (MCP 2026-07-28): scanning a tool's `inputSchema` for
6+
# `x-mcp-header` declarations and encoding `tools/call` argument values into `Mcp-Param-{Name}` HTTP headers,
7+
# with the `=?base64?...?=` sentinel for values that cannot ride as plain ASCII field values.
8+
# Mirrors the TypeScript SDK's `mcpParamHeaders` codec; the standard-header half (`Mcp-Method`, `Mcp-Name`)
9+
# lives with the transport.
10+
#
11+
# https://modelcontextprotocol.io/specification/draft/basic/transports/streamable-http#custom-headers-from-tool-parameters
12+
module McpParamHeaders
13+
# The fixed prefix every custom-parameter header carries.
14+
HEADER_PREFIX = "Mcp-Param-"
15+
16+
# The schema-extension property name a tool's `inputSchema` carries.
17+
X_MCP_HEADER_KEY = "x-mcp-header"
18+
19+
# RFC 9110 Section 5.1 `token` syntax (`1*tchar`): rejects empty names, spaces,
20+
# control characters (including CR/LF), and the HTTP delimiters.
21+
RFC9110_TOKEN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/.freeze
22+
23+
# The spec text admits `string`, `integer`, and `boolean`. `number` is also accepted because
24+
# the published conformance referee annotates `type: "number"` parameters and expects them
25+
# mirrored; the TypeScript SDK makes the same accommodation.
26+
PERMITTED_TYPES = ["string", "integer", "boolean", "number"].freeze
27+
28+
# JSON Schema keywords the SEP-2243 static-reachability constraint excludes from
29+
# the `properties`-only chain. An `x-mcp-header` under any of these invalidates
30+
# the tool definition rather than being silently ignored.
31+
NON_REACHABLE_SUBSCHEMA_KEYWORDS = [
32+
"items",
33+
"prefixItems",
34+
"contains",
35+
"additionalProperties",
36+
"unevaluatedProperties",
37+
"unevaluatedItems",
38+
"propertyNames",
39+
"patternProperties",
40+
"dependentSchemas",
41+
"oneOf",
42+
"anyOf",
43+
"allOf",
44+
"not",
45+
"if",
46+
"then",
47+
"else",
48+
"$defs",
49+
"definitions",
50+
].freeze
51+
52+
# Keywords whose value maps names to subschemas rather than being one subschema or a list of them.
53+
OBJECT_VALUED_SUBSCHEMA_KEYWORDS = ["patternProperties", "dependentSchemas", "$defs", "definitions"].freeze
54+
55+
# Integers beyond 2**53 - 1 lose precision in JSON number interchange, so they are not mirrored;
56+
# the TypeScript SDK refuses unsafe integers the same way.
57+
MAX_SAFE_INTEGER = (2**53) - 1
58+
59+
BASE64_SENTINEL_PREFIX = "=?base64?"
60+
BASE64_SENTINEL_SUFFIX = "?="
61+
62+
class << self
63+
# Scans a tool's `inputSchema` for `x-mcp-header` declarations and validates every constraint
64+
# the spec places on them: RFC 9110 token names, case-insensitive uniqueness, primitive-typed
65+
# declaring properties, and static reachability through a chain of `properties` keys only.
66+
# Returns `{ valid: true, declarations: [...] }` with each declaration `{ path:, header_name:, type: }`,
67+
# or `{ valid: false, reason: "..." }` on the first violation.
68+
def scan(input_schema)
69+
declarations = []
70+
fault = visit(input_schema, [], true, declarations, {})
71+
72+
fault ? { valid: false, reason: fault } : { valid: true, declarations: declarations }
73+
end
74+
75+
# Builds the `Mcp-Param-{Name}` headers for one `tools/call` from the scanned declarations and
76+
# the call's `arguments`. A `null` or absent value omits its header (the spec's MUST-omit rows);
77+
# a non-primitive or non-representable value is omitted rather than emitted malformed.
78+
def build(declarations, arguments)
79+
declarations.each_with_object({}) do |declaration, headers|
80+
value = value_at_path(arguments, declaration[:path])
81+
next if value.nil?
82+
83+
string_value = primitive_to_string(value)
84+
next unless string_value
85+
86+
encoded = begin
87+
encode_value(string_value)
88+
rescue EncodingError
89+
# A string that cannot be represented as UTF-8 (e.g. binary data) has no header
90+
# representation; omit it like the other non-representable values.
91+
next
92+
end
93+
94+
headers["#{HEADER_PREFIX}#{declaration[:header_name]}"] = encoded
95+
end
96+
end
97+
98+
# Converts a primitive argument to its header string per the spec's type-conversion rules:
99+
# strings pass through, booleans become lowercase `"true"` / `"false"`, and numbers become
100+
# their decimal string. `nil` means "not representable: do not emit a header".
101+
def primitive_to_string(value)
102+
case value
103+
when String
104+
value
105+
when true
106+
"true"
107+
when false
108+
"false"
109+
when Integer
110+
value.abs <= MAX_SAFE_INTEGER ? value.to_s : nil
111+
when Float
112+
return unless value.finite?
113+
114+
# JSON has one number type: an integral float serializes without the fractional part,
115+
# matching the `String(42.0)` the JavaScript reference emits.
116+
value == value.truncate ? value.truncate.to_s : value.to_s
117+
end
118+
end
119+
120+
# Encodes a header value per the spec's value-encoding rules: a safe plain-ASCII field value
121+
# passes through unchanged, everything else is wrapped as `=?base64?{base64-of-UTF-8}?=`.
122+
def encode_value(value)
123+
return value unless needs_base64?(value)
124+
125+
"#{BASE64_SENTINEL_PREFIX}#{[value.encode(Encoding::UTF_8)].pack("m0")}#{BASE64_SENTINEL_SUFFIX}"
126+
end
127+
128+
private
129+
130+
def visit(node, path, reachable, declarations, seen_lower)
131+
return unless node.is_a?(Hash)
132+
133+
if key?(node, X_MCP_HEADER_KEY)
134+
fault = validate_declaration(node, path, reachable, declarations, seen_lower)
135+
136+
return fault if fault
137+
end
138+
139+
properties = read(node, "properties")
140+
if properties.is_a?(Hash)
141+
properties.each do |key, child|
142+
fault = visit(child, path + [key.to_s], reachable, declarations, seen_lower)
143+
144+
return fault if fault
145+
end
146+
end
147+
148+
# Static-reachability sweep: descend the keywords the `properties` chain MUST NOT pass
149+
# through with `reachable: false`, so an annotation under any of them is reported.
150+
# `$defs` covers `$ref`-within-`$defs`; chasing arbitrary `$ref` URIs is out of scope.
151+
NON_REACHABLE_SUBSCHEMA_KEYWORDS.each do |keyword|
152+
next unless (sub = read(node, keyword))
153+
154+
branches = if sub.is_a?(Array)
155+
sub
156+
elsif sub.is_a?(Hash) && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.include?(keyword)
157+
sub.values
158+
else
159+
[sub]
160+
end
161+
162+
branches.each do |branch|
163+
fault = visit(branch, path + ["<#{keyword}>"], false, declarations, seen_lower)
164+
165+
return fault if fault
166+
end
167+
end
168+
169+
nil
170+
end
171+
172+
def validate_declaration(node, path, reachable, declarations, seen_lower)
173+
if !reachable || path.empty?
174+
return "#{path_name(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of `properties` keys"
175+
176+
end
177+
178+
annotation = read(node, X_MCP_HEADER_KEY)
179+
180+
unless annotation.is_a?(String) && !annotation.empty?
181+
return "#{path_name(path)}: x-mcp-header MUST be a non-empty string"
182+
end
183+
184+
unless RFC9110_TOKEN.match?(annotation)
185+
return "#{path_name(path)}: x-mcp-header `#{annotation}` is not a valid RFC 9110 token"
186+
end
187+
188+
type = read(node, "type")
189+
unless type.is_a?(String) && PERMITTED_TYPES.include?(type)
190+
return "#{path_name(path)}: x-mcp-header is only permitted on primitive-typed properties " \
191+
"(got `#{type.inspect}`)"
192+
end
193+
194+
lower = annotation.downcase
195+
prior = seen_lower[lower]
196+
if prior
197+
return "x-mcp-header `#{annotation}` is not case-insensitively unique (also declared as `#{prior}`)"
198+
end
199+
200+
seen_lower[lower] = annotation
201+
declarations << { path: path, header_name: annotation, type: type }
202+
nil
203+
end
204+
205+
# A value cannot ride as a plain ASCII field value when it is empty, already shaped like
206+
# the Base64 sentinel (the spec's ambiguity rule), carries edge whitespace that field parsing
207+
# would strip, or contains a byte outside visible ASCII plus interior tab.
208+
def needs_base64?(value)
209+
return true if value.empty?
210+
return true if value.start_with?(BASE64_SENTINEL_PREFIX) && value.end_with?(BASE64_SENTINEL_SUFFIX)
211+
return true if value != value.strip
212+
213+
value.each_byte.any? { |byte| byte != 0x09 && !byte.between?(0x20, 0x7e) }
214+
end
215+
216+
def value_at_path(root, path)
217+
path.reduce(root) do |node, key|
218+
break unless node.is_a?(Hash)
219+
220+
read(node, key)
221+
end
222+
end
223+
224+
# Schemas and arguments arrive with string keys off the wire but may carry symbol keys
225+
# when constructed in Ruby; read both forms like the SDK's other readers.
226+
def read(hash, key)
227+
value = hash[key]
228+
229+
value.nil? ? hash[key.to_sym] : value
230+
end
231+
232+
def key?(hash, key)
233+
hash.key?(key) || hash.key?(key.to_sym)
234+
end
235+
236+
def path_name(path)
237+
path.empty? ? "<root>" : path.join(".")
238+
end
239+
end
240+
end
241+
end
242+
end

0 commit comments

Comments
 (0)