Skip to content

Commit b859714

Browse files
authored
Validate SEP-2243 Mcp-Param headers in the modern server (#1286)
- Tools can mark inputSchema arguments with x-mcp-header, so clients mirror them into Mcp-Param-{Name} headers. Servers MUST reject a request whose headers and body disagree, with 400 / -32020. - Since only tools/call use those header, they are not part of the McpRequestHandler interface, and rather are carried through the McpTransportContext. - The HTTP transport extracts and decodes Mcp-Param-* headers and puts them in the context. STDIO puts a marker "not mirrored" value instead. - Validation happens in ToolsFeature, where we have both the tool definition (including x-mcp-header annotations in the schema) and the values for the tool call. - McpHeaderDecoder and McpParamHeaders are public, so other HTTP transports can reuse them. - Mcp-Name now uses the same strict decoder. Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
1 parent 6ce6a28 commit b859714

18 files changed

Lines changed: 2841 additions & 45 deletions

File tree

‎conformance-tests/VALIDATION_RESULTS.md‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,8 @@ These run but don't count: the frozen requirement set marks extensions and anyth
4040
in the anchor release (`0.2.0-alpha.10`) as `not_scored`. Pending scenarios are still spec requirements.
4141

4242
- **Passing:** `json-schema-2020-12` (8/8 checks, including the SEP-2106 `allOf`/`anyOf`,
43-
`if`/`then`/`else` and `$anchor` checks), `http-header-validation` (14/14)
44-
- **Failing — `http-custom-header-server-validation` (SEP-2243 custom headers):** not implemented,
45-
see [Known Limitations](#known-limitations)
43+
`if`/`then`/`else` and `$anchor` checks), `http-header-validation` (14/14),
44+
`http-custom-header-server-validation` (10/10, SEP-2243 custom headers, against the `test_x_mcp_header` tool)
4645
- **Failing — tasks extension (`tasks-*`, SEP-2663):** not implemented
4746

4847
## Server Test Results
@@ -97,25 +96,6 @@ of the 0.2.0-alpha auth suite.
9796

9897
1. **Client SSE Retry:** client doesn't parse or respect the `retry:` field,
9998
reconnects immediately, and doesn't send the `Last-Event-ID` header
100-
2. **Modern server: SEP-2243 custom headers (`Mcp-Param-{Name}`) are not supported.** SEP-2243 is part
101-
of 2026-07-28 and the server-side requirements are MUSTs; only the scenario's pending status keeps
102-
it out of the score. Today the five custom-header checks report "not testable" because no tool
103-
carries `x-mcp-header`. Adding such a tool would turn them into real failures, because nothing
104-
validates the headers yet. Supporting it needs SDK work:
105-
- **Tool definitions:** `Tool.inputSchema` is a free-form map, so `x-mcp-header` can already be
106-
written, but nothing enforces the definition rules: value non-empty, ASCII without space or `:`,
107-
case-insensitively unique per tool, only on `integer`/`string`/`boolean` parameters (not `number`).
108-
- **Request validation on `tools/call`:** for each designated parameter, Base64-decode
109-
`=?base64?…?=` values, check the header matches the body value (integers as decimal strings,
110-
booleans as `true`/`false`), reject headers with invalid characters, don't expect a header when
111-
the value is null or omitted, and reject a missing required parameter. Failures are answered with
112-
`400` and `-32020`.
113-
- **Where it lives:** the check needs the called tool's `inputSchema`, which
114-
`HttpServletMcpTransport` doesn't have. `ToolsFeature` already looks the `Tool` up through
115-
`McpSyncToolRepository#find` / `McpAsyncToolRepository#find` and validates the arguments against
116-
`inputSchema` before calling the tool, so the header check fits there. What's missing is a way to
117-
get the raw `Mcp-Param-*` headers from the transport to the feature (e.g. through the
118-
`McpTransportContext` on `McpRequestContext`).
11999

120100
## Running Tests
121101

‎conformance-tests/server-servlet-modern/README.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,5 @@ Besides the standard `test_*` tools, resources and prompts, the server exposes t
2929
`test_trigger_tool_change`, `test_trigger_prompt_change`
3030
- **SEP-2322 MRTR:** `test_input_required_result_*` tools and the `test_input_required_result_prompt` prompt
3131
- **SEP-1613 / SEP-2106:** `json_schema_2020_12_tool`
32-
33-
SEP-2243 custom headers (`x-mcp-header` / `Mcp-Param-{Name}`) are not supported yet; see
34-
[Known Limitations](../VALIDATION_RESULTS.md#known-limitations).
32+
- **SEP-2243 custom headers:** `test_x_mcp_header`, whose `region` argument is mirrored into `Mcp-Param-Region`.
33+
The scenario exercises the first tool carrying `x-mcp-header`, so it must stay the only annotated tool.

‎conformance-tests/server-servlet-modern/src/main/java/io/modelcontextprotocol/conformance/server/modern/ModernConformanceServlet.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,16 @@ public class ModernConformanceServlet {
116116
}
117117
""";
118118

119+
private static final String X_MCP_HEADER_INPUT = """
120+
{
121+
"type": "object",
122+
"properties": {
123+
"region": { "type": "string", "description": "mirrored into Mcp-Param-Region", "x-mcp-header": "Region" },
124+
"level": { "type": "integer", "description": "non-mirrored argument" }
125+
}
126+
}
127+
""";
128+
119129
private static final Pattern TEMPLATE_URI = Pattern.compile("test://template/(.+)/data");
120130

121131
private static final McpJsonMapper JSON = McpJsonDefaults.getMapper();
@@ -323,6 +333,15 @@ private static final class ConformanceTools implements McpSyncToolRepository {
323333
.description("Tool with JSON Schema 2020-12 features (SEP-1613, SEP-2106)")
324334
.build(), respond((ctx, req) -> text("ok")));
325335

336+
// SEP-2243 custom headers: the scenario exercises the first tool with an
337+
// x-mcp-header annotation, so this must stay the only annotated tool.
338+
add(Tool.builder("test_x_mcp_header", JSON, X_MCP_HEADER_INPUT)
339+
.description("Tests SEP-2243 Mcp-Param-* server-side validation")
340+
.build(), respond((ctx, req) -> {
341+
Object region = req.arguments() != null ? req.arguments().get("region") : null;
342+
return text("region=" + (region != null ? region : "<none>"));
343+
}));
344+
326345
// SEP-2575 diagnostic tools
327346
add("test_missing_capability", "Test tool requiring sampling", SAMPLING,
328347
respond((ctx, req) -> text("Success")));
Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern;
6+
7+
import java.util.ArrayList;
8+
import java.util.LinkedHashMap;
9+
import java.util.List;
10+
import java.util.Locale;
11+
import java.util.Map;
12+
import java.util.regex.Pattern;
13+
14+
import io.modelcontextprotocol.modern.McpSchema.Tool;
15+
16+
/**
17+
* Reads the {@code x-mcp-header} annotations of a tool's {@code inputSchema}, which ask
18+
* clients to mirror an argument into an {@code Mcp-Param-{Name}} header.
19+
*
20+
* @author Daniel Garnier-Moiroux
21+
* @see <a href="https://modelcontextprotocol.io/seps/2243-http-standardization">SEP-2243:
22+
* HTTP Standardization</a>
23+
*/
24+
public final class ToolParamHeaderAnnotations {
25+
26+
/**
27+
* The JSON Schema keyword that annotates an argument with its header name.
28+
*/
29+
public static final String KEYWORD = "x-mcp-header";
30+
31+
// RFC 9110 token: 1*tchar
32+
private static final Pattern TOKEN = Pattern.compile("[!#$%&'*+\\-.^_`|~0-9A-Za-z]+");
33+
34+
private final List<Annotation> valid;
35+
36+
private final List<InvalidAnnotation> invalid;
37+
38+
private ToolParamHeaderAnnotations(List<Annotation> valid, List<InvalidAnnotation> invalid) {
39+
this.valid = List.copyOf(valid);
40+
this.invalid = List.copyOf(invalid);
41+
}
42+
43+
/**
44+
* An argument mirrored into a header.
45+
*
46+
* @param name the {@code {Name}} of {@code Mcp-Param-{Name}}, as declared
47+
* @param path the {@code properties} keys leading from the schema root to the
48+
* argument
49+
* @param type the declared type of the argument
50+
*/
51+
public record Annotation(String name, List<String> path, Type type) {
52+
53+
public Annotation {
54+
path = List.copyOf(path);
55+
}
56+
57+
/**
58+
* The argument's path joined with dots, for messages.
59+
* @return the dotted path, such as {@code location.region}
60+
*/
61+
public String argument() {
62+
return String.join(".", this.path);
63+
}
64+
65+
}
66+
67+
/**
68+
* An annotation that can't be enforced, and the reasons why.
69+
*
70+
* @param name the value of the {@code x-mcp-header} keyword, which may not be a
71+
* string
72+
* @param path the {@code properties} keys leading from the schema root to the
73+
* argument
74+
* @param problems why the annotation is invalid, in human-readable form, with
75+
* characters outside printable ASCII written as Unicode escapes
76+
*/
77+
public record InvalidAnnotation(Object name, List<String> path, List<String> problems) {
78+
79+
public InvalidAnnotation {
80+
path = List.copyOf(path);
81+
problems = List.copyOf(problems);
82+
}
83+
84+
/**
85+
* The argument's path joined with dots, for messages.
86+
* @return the dotted path, such as {@code location.region}
87+
*/
88+
public String argument() {
89+
return String.join(".", this.path);
90+
}
91+
92+
/**
93+
* Describes the annotation and its problems, with characters outside printable
94+
* ASCII written as Unicode escapes, so the description can safely be logged.
95+
* @return a description such as
96+
* {@code 'Score' on argument 'score' (unsupported type number)}
97+
*/
98+
public String describe() {
99+
return ToolParamHeaderAnnotations.describe(this.name, this.path) + " (" + String.join(", ", this.problems)
100+
+ ")";
101+
}
102+
103+
}
104+
105+
/** The argument types an annotation may declare. */
106+
public enum Type {
107+
108+
STRING, INTEGER, BOOLEAN
109+
110+
}
111+
112+
/**
113+
* Parses the {@code x-mcp-header} annotations of the tool's input schema.
114+
* <p>
115+
* Only chains of {@code properties} keys are followed from the schema root, so
116+
* annotations under {@code items}, {@code allOf}, {@code $ref} or any other keyword
117+
* are ignored. An annotation is invalid if:
118+
* <ul>
119+
* <li>its name is not a string, is empty, or isn't an RFC 9110 token;</li>
120+
* <li>its name equals another annotation's ignoring case, in which case both are
121+
* invalid;</li>
122+
* <li>its {@code type} is missing or isn't one of the strings {@code string},
123+
* {@code integer} or {@code boolean}; a type array, even {@code ["string", "null"]},
124+
* is invalid.</li>
125+
* </ul>
126+
* @param tool the tool
127+
* @return the tool's valid and invalid annotations
128+
*/
129+
public static ToolParamHeaderAnnotations parse(Tool tool) {
130+
List<Candidate> candidates = new ArrayList<>();
131+
collect(tool.inputSchema(), List.of(), candidates);
132+
flagCollisions(candidates);
133+
List<Annotation> valid = new ArrayList<>();
134+
List<InvalidAnnotation> invalid = new ArrayList<>();
135+
for (Candidate candidate : candidates) {
136+
if (candidate.problems().isEmpty()) {
137+
valid.add(new Annotation((String) candidate.name(), candidate.path(), candidate.type()));
138+
}
139+
else {
140+
invalid.add(new InvalidAnnotation(candidate.name(), candidate.path(), candidate.problems()));
141+
}
142+
}
143+
return new ToolParamHeaderAnnotations(valid, invalid);
144+
}
145+
146+
/**
147+
* The valid annotations, in schema order: depth-first, a parent before its children.
148+
* @return the valid annotations, empty if there are none
149+
*/
150+
public List<Annotation> valid() {
151+
return this.valid;
152+
}
153+
154+
/**
155+
* The invalid annotations, in schema order: depth-first, a parent before its
156+
* children.
157+
* @return the invalid annotations, empty if there are none
158+
*/
159+
public List<InvalidAnnotation> invalid() {
160+
return this.invalid;
161+
}
162+
163+
/**
164+
* Whether every annotation is valid. A compliant client drops a tool with invalid
165+
* annotations from {@code tools/list}.
166+
* @return {@code true} if there are no invalid annotations, including when the tool
167+
* declares none
168+
*/
169+
public boolean isValid() {
170+
return this.invalid.isEmpty();
171+
}
172+
173+
// Depth-first in schema order, following only properties keys.
174+
private static void collect(Map<?, ?> schema, List<String> parent, List<Candidate> candidates) {
175+
if (!(schema.get("properties") instanceof Map<?, ?> properties)) {
176+
return;
177+
}
178+
for (Map.Entry<?, ?> entry : properties.entrySet()) {
179+
if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof Map<?, ?> property)) {
180+
continue;
181+
}
182+
List<String> path = new ArrayList<>(parent);
183+
path.add(key);
184+
if (property.containsKey(KEYWORD)) {
185+
candidates.add(candidate(List.copyOf(path), property));
186+
}
187+
collect(property, path, candidates);
188+
}
189+
}
190+
191+
private static Candidate candidate(List<String> path, Map<?, ?> property) {
192+
Object name = property.get(KEYWORD);
193+
List<String> problems = new ArrayList<>();
194+
if (!(name instanceof String string)) {
195+
problems.add("name is not a string");
196+
}
197+
else if (string.isEmpty()) {
198+
problems.add("empty name");
199+
}
200+
else if (!TOKEN.matcher(string).matches()) {
201+
problems.add("name is not an RFC 9110 token");
202+
}
203+
Object typeKeyword = property.get("type");
204+
Type type = type(typeKeyword);
205+
if (type == null) {
206+
problems.add(typeKeyword == null ? "missing type" : "unsupported type " + escape(typeKeyword));
207+
}
208+
return new Candidate(name, path, type, problems);
209+
}
210+
211+
private static void flagCollisions(List<Candidate> candidates) {
212+
Map<String, List<Candidate>> byName = new LinkedHashMap<>();
213+
for (Candidate candidate : candidates) {
214+
if (candidate.name() instanceof String name && !name.isEmpty()) {
215+
byName.computeIfAbsent(name.toLowerCase(Locale.ROOT), k -> new ArrayList<>()).add(candidate);
216+
}
217+
}
218+
for (List<Candidate> collision : byName.values()) {
219+
if (collision.size() < 2) {
220+
continue;
221+
}
222+
for (Candidate candidate : collision) {
223+
List<String> others = new ArrayList<>();
224+
for (Candidate other : collision) {
225+
if (other != candidate) {
226+
others.add(other.describe());
227+
}
228+
}
229+
candidate.problems().add("name collides ignoring case with " + String.join(" and ", others));
230+
}
231+
}
232+
}
233+
234+
// Names come from user schemas: escape them so they can't break log lines.
235+
private static String escape(Object value) {
236+
String string = String.valueOf(value);
237+
StringBuilder escaped = new StringBuilder(string.length());
238+
for (char c : string.toCharArray()) {
239+
if (c >= 0x20 && c < 0x7F) {
240+
escaped.append(c);
241+
}
242+
else {
243+
escaped.append(String.format("\\u%04x", (int) c));
244+
}
245+
}
246+
return escaped.toString();
247+
}
248+
249+
private record Candidate(Object name, List<String> path, Type type, List<String> problems) {
250+
251+
String describe() {
252+
return ToolParamHeaderAnnotations.describe(this.name, this.path);
253+
}
254+
255+
}
256+
257+
private static String describe(Object name, List<String> path) {
258+
return "'" + escape(name) + "' on argument '" + escape(String.join(".", path)) + "'";
259+
}
260+
261+
// null if the type can't be mirrored. The spec only admits a single primitive type,
262+
// so type arrays such as ["string", "null"] are rejected, as the TypeScript SDK does.
263+
private static Type type(Object type) {
264+
if (!(type instanceof String name)) {
265+
return null;
266+
}
267+
return switch (name) {
268+
case "string" -> Type.STRING;
269+
case "integer" -> Type.INTEGER;
270+
case "boolean" -> Type.BOOLEAN;
271+
default -> null;
272+
};
273+
}
274+
275+
}

0 commit comments

Comments
 (0)