Skip to content

Commit 50b67c2

Browse files
committed
fix(transport): exempt initialize requests from MCP-Protocol-Version checks
Per the Streamable HTTP spec the MCP-Protocol-Version header is required only after initialization completes; version selection for initialize happens through body-level negotiation, not header validation. * Client: stop sending MCP-Protocol-Version on initialize requests * Servlet servers: skip strict header validation for initialize so clients advertising an unsupported version negotiate instead of getting 400 * Tests: pin client omission and server tolerance for initialize; make version-negotiation test contextExtractor null-safe for absent headers
1 parent 763bdba commit 50b67c2

6 files changed

Lines changed: 112 additions & 16 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/client/transport/HttpClientStreamableHttpTransport.java‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,9 +499,17 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sentMessage) {
499499
var builder = requestBuilder.uri(uri)
500500
.header(HttpHeaders.ACCEPT, APPLICATION_JSON + ", " + TEXT_EVENT_STREAM)
501501
.header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_UTF8)
502-
.header(HttpHeaders.CACHE_CONTROL, "no-cache")
503-
.header(HttpHeaders.PROTOCOL_VERSION, ctx.getOrDefault(McpAsyncClient.NEGOTIATED_PROTOCOL_VERSION,
504-
this.latestSupportedProtocolVersion));
502+
.header(HttpHeaders.CACHE_CONTROL, "no-cache");
503+
// Per the Streamable HTTP transport spec, the MCP-Protocol-Version header
504+
// is required on all requests after initialization completes. The
505+
// initialize request itself carries no negotiated version yet -- the
506+
// client's supported versions are conveyed in the request body for
507+
// server-side negotiation -- so the header must not be sent.
508+
if (!(sentMessage instanceof McpSchema.JSONRPCRequest jsonrpcMessage
509+
&& McpSchema.METHOD_INITIALIZE.equals(jsonrpcMessage.method()))) {
510+
builder = builder.header(HttpHeaders.PROTOCOL_VERSION, ctx
511+
.getOrDefault(McpAsyncClient.NEGOTIATED_PROTOCOL_VERSION, this.latestSupportedProtocolVersion));
512+
}
505513
// Per SEP-2243, mirror the JSON-RPC method and, where applicable, the
506514
// target name/URI in dedicated headers so the server can validate
507515
// them without parsing the body.

‎mcp-core/src/main/java/io/modelcontextprotocol/server/transport/HttpServletStatelessServerTransport.java‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
162162
return;
163163
}
164164

165-
if (!validateProtocolVersion(request, response)) {
166-
return;
167-
}
168-
169165
try {
170166
this.httpHeaderValidator.validate(new HttpServletHeaderAccessor(request));
171167
}
@@ -198,6 +194,16 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
198194

199195
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
200196

197+
// The MCP-Protocol-Version header can only be strictly validated once a
198+
// version has been negotiated; during 'initialize' the client advertises its
199+
// versions in the request body and any header value is resolved by regular
200+
// version negotiation instead of being rejected.
201+
boolean initializationRequest = message instanceof McpSchema.JSONRPCRequest initRequestCheck
202+
&& McpSchema.METHOD_INITIALIZE.equals(initRequestCheck.method());
203+
if (!initializationRequest && !validateProtocolVersion(request, response)) {
204+
return;
205+
}
206+
201207
// Per SEP-2243, reject header/body mismatches (missing headers are tolerated
202208
// so legacy clients keep working).
203209
if (!validateMcpHeaders(request, response, message)) {
@@ -288,7 +294,9 @@ private void responseError(HttpServletResponse response, int httpCode, McpError
288294
* Validates the {@code MCP-Protocol-Version} header against the protocol versions
289295
* supported by this transport. A missing header is allowed and falls back to the
290296
* negotiated protocol version, while a header carrying an unsupported version is
291-
* rejected with a 400 Bad Request.
297+
* rejected with a 400 Bad Request. Initialize requests are exempt: no version has
298+
* been negotiated yet, so any header value carried on them is resolved through
299+
* regular body-based version negotiation.
292300
* @param request the HTTP servlet request
293301
* @param response the HTTP servlet response
294302
* @return true if the header is missing or contains a supported version, false if a

‎mcp-core/src/main/java/io/modelcontextprotocol/server/transport/HttpServletStreamableServerTransportProvider.java‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -489,10 +489,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
489489
return;
490490
}
491491

492-
if (!validateProtocolVersion(request, response)) {
493-
return;
494-
}
495-
496492
try {
497493
this.httpHeaderValidator.validate(new HttpServletHeaderAccessor(request));
498494
}
@@ -526,6 +522,16 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
526522

527523
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
528524

525+
// The MCP-Protocol-Version header can only be strictly validated once a
526+
// version has been negotiated; during 'initialize' the client advertises its
527+
// versions in the request body and any header value is resolved by the
528+
// regular version negotiation below instead of being rejected.
529+
boolean initializationRequest = message instanceof McpSchema.JSONRPCRequest initRequestCheck
530+
&& McpSchema.METHOD_INITIALIZE.equals(initRequestCheck.method());
531+
if (!initializationRequest && !validateProtocolVersion(request, response)) {
532+
return;
533+
}
534+
529535
// Per SEP-2243, reject header/body mismatches (missing headers are tolerated
530536
// so
531537
// legacy clients keep working).
@@ -765,7 +771,9 @@ public void responseError(HttpServletResponse response, int httpCode, McpError m
765771
* Validates the {@code MCP-Protocol-Version} header against the protocol versions
766772
* supported by this transport. A missing header is allowed and falls back to the
767773
* negotiated protocol version, while a header carrying an unsupported version is
768-
* rejected with a 400 Bad Request.
774+
* rejected with a 400 Bad Request. Initialize requests are exempt: no version has
775+
* been negotiated yet, so any header value carried on them is resolved through
776+
* regular body-based version negotiation.
769777
* @param request the HTTP servlet request
770778
* @param response the HTTP servlet response
771779
* @return true if the header is missing or contains a supported version, false if a

‎mcp-test/src/test/java/io/modelcontextprotocol/client/transport/Sep2243ClientRequestHeaderTests.java‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import com.sun.net.httpserver.HttpServer;
88
import io.modelcontextprotocol.spec.HttpHeaders;
99
import io.modelcontextprotocol.spec.McpSchema;
10+
import io.modelcontextprotocol.spec.ProtocolVersions;
1011
import java.io.IOException;
1112
import java.net.InetSocketAddress;
1213
import java.util.Map;
@@ -93,4 +94,43 @@ void emitsMcpMethodForNotification() throws IOException {
9394
}
9495
}
9596

96-
}
97+
@Test
98+
void omitsMcpProtocolVersionHeaderOnInitializeRequest() throws IOException {
99+
var seenProtocolVersions = new java.util.concurrent.CopyOnWriteArrayList<String>();
100+
var server = HttpServer.create(new InetSocketAddress(0), 0);
101+
102+
try {
103+
server.createContext("/mcp", exchange -> {
104+
seenProtocolVersions.add(exchange.getRequestHeaders().getFirst(HttpHeaders.PROTOCOL_VERSION));
105+
exchange.getRequestBody().readAllBytes();
106+
exchange.sendResponseHeaders(202, -1);
107+
exchange.close();
108+
});
109+
server.start();
110+
111+
var transport = HttpClientStreamableHttpTransport
112+
.builder("http://localhost:" + server.getAddress().getPort())
113+
.endpoint("/mcp")
114+
.supportedProtocolVersions(java.util.List.of(ProtocolVersions.MCP_2025_11_25, "2263-03-18"))
115+
.build();
116+
117+
try {
118+
// The initialize request carries the client's latest supported version in
119+
// its body for negotiation; sending an MCP-Protocol-Version header would
120+
// make strict servers reject it before negotiation happens.
121+
var initRequest = new McpSchema.JSONRPCRequest(McpSchema.METHOD_INITIALIZE, "test-id",
122+
Map.of("protocolVersion", "2263-03-18"));
123+
StepVerifier.create(transport.sendMessage(initRequest)).verifyComplete();
124+
}
125+
finally {
126+
StepVerifier.create(transport.closeGracefully()).verifyComplete();
127+
}
128+
129+
assertThat(seenProtocolVersions).containsNull();
130+
}
131+
finally {
132+
server.stop(0);
133+
}
134+
}
135+
136+
}

‎mcp-test/src/test/java/io/modelcontextprotocol/common/HttpClientStreamableHttpVersionNegotiationIntegrationTests.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import java.util.List;
88
import java.util.Map;
9+
import java.util.Objects;
910
import java.util.function.BiFunction;
1011

1112
import io.modelcontextprotocol.client.McpClient;
@@ -42,8 +43,10 @@ class HttpClientStreamableHttpVersionNegotiationIntegrationTests {
4243

4344
private static final HttpServletStreamableServerTransportProvider transport = HttpServletStreamableServerTransportProvider
4445
.builder()
45-
.contextExtractor(
46-
req -> McpTransportContext.create(Map.of("protocol-version", req.getHeader("MCP-protocol-version"))))
46+
// The MCP-Protocol-Version header may legitimately be absent on initialize
47+
// requests, so a missing header must not break context extraction.
48+
.contextExtractor(req -> McpTransportContext
49+
.create(Map.of("protocol-version", Objects.requireNonNullElse(req.getHeader("MCP-protocol-version"), ""))))
4750
.build();
4851

4952
private final McpSchema.Tool toolSpec = McpSchema.Tool.builder("test-tool")

‎mcp-test/src/test/java/io/modelcontextprotocol/server/transport/Sep2243ServerHeaderValidationTests.java‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,33 @@ void statelessToleratesAbsentHeaders() throws Exception {
138138
"Mcp-Name header");
139139
}
140140

141+
// --- Initialize requests must not be rejected on MCP-Protocol-Version ------------
142+
143+
private static byte[] initializeBody() throws Exception {
144+
var request = new McpSchema.JSONRPCRequest(McpSchema.METHOD_INITIALIZE, "test-id",
145+
Map.of("protocolVersion", "2263-03-18"));
146+
return McpJsonMapperUtils.JSON_MAPPER.writeValueAsString(request).getBytes(StandardCharsets.UTF_8);
147+
}
148+
149+
@Test
150+
void streamableToleratesUnsupportedProtocolVersionOnInitialize() throws Exception {
151+
var provider = HttpServletStreamableServerTransportProvider.builder().mcpEndpoint("/mcp").build();
152+
153+
// During initialization no protocol version has been negotiated yet, so any
154+
// header value must be resolved through regular version negotiation instead of
155+
// a hard 400.
156+
var resp = invoke(provider, "/mcp", Map.of(HttpHeaders.PROTOCOL_VERSION, "junk"), initializeBody());
157+
158+
assertThat(resp.getContentAsString()).doesNotContain("Unsupported protocol version");
159+
}
160+
161+
@Test
162+
void statelessToleratesUnsupportedProtocolVersionOnInitialize() throws Exception {
163+
var transport = HttpServletStatelessServerTransport.builder().messageEndpoint("/mcp").build();
164+
165+
var resp = invoke(transport, "/mcp", Map.of(HttpHeaders.PROTOCOL_VERSION, "junk"), initializeBody());
166+
167+
assertThat(resp.getContentAsString()).doesNotContain("Unsupported protocol version");
168+
}
169+
141170
}

0 commit comments

Comments
 (0)