Skip to content

Commit db44092

Browse files
committed
Add opt-in requireMcpHeaders and share SEP-2243 validation across servlet transports
Move the duplicated MCP-Protocol-Version / Mcp-Method / Mcp-Name validation out of both servlet transports into a package-private Sep2243RequestValidator they share. An unsupported MCP-Protocol-Version now returns INVALID_REQUEST instead of the previously incorrect METHOD_NOT_FOUND. requireMcpHeaders defaults to false, so clients that do not send the SEP-2243 headers are unaffected.
1 parent 139e144 commit db44092

5 files changed

Lines changed: 369 additions & 261 deletions

File tree

‎docs/server.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ Key features:
173173
- SEP-2243 validation: the servlet transport rejects requests whose present
174174
`Mcp-Method` / `Mcp-Name` headers do not mirror the request body, and rejects
175175
unsupported `MCP-Protocol-Version` values. Missing headers are tolerated so legacy
176-
clients keep working.
176+
clients keep working. Call `.requireMcpHeaders(true)` on the builder to also
177+
reject requests that omit them.
177178

178179
=== "Streamable HTTP WebFlux (external)"
179180

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

Lines changed: 39 additions & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,10 @@
1313

1414
import io.modelcontextprotocol.json.McpJsonDefaults;
1515
import io.modelcontextprotocol.json.McpJsonMapper;
16-
import io.modelcontextprotocol.json.TypeRef;
1716

1817
import io.modelcontextprotocol.common.McpTransportContext;
1918
import io.modelcontextprotocol.server.McpStatelessServerHandler;
2019
import io.modelcontextprotocol.server.McpTransportContextExtractor;
21-
import io.modelcontextprotocol.spec.HttpHeaders;
2220
import io.modelcontextprotocol.spec.McpError;
2321
import io.modelcontextprotocol.spec.McpSchema;
2422
import io.modelcontextprotocol.spec.McpStatelessServerTransport;
@@ -71,6 +69,12 @@ public class HttpServletStatelessServerTransport extends HttpServlet implements
7169
*/
7270
private final ServerHttpHeaderValidator httpHeaderValidator;
7371

72+
/**
73+
* Validator for the SEP-2243 {@code MCP-Protocol-Version}, {@code Mcp-Method}, and
74+
* {@code Mcp-Name} header checks that need the parsed JSON-RPC body.
75+
*/
76+
private final Sep2243RequestValidator sep2243Validator;
77+
7478
/**
7579
* Maximum size, in bytes, of a single request body accepted by this transport.
7680
*/
@@ -86,11 +90,13 @@ public class HttpServletStatelessServerTransport extends HttpServlet implements
8690
* @param httpHeaderValidator The HTTP header validator for validating HTTP requests.
8791
* @param requestMaxSize The maximum size, in bytes, of a single request body. Must be
8892
* positive.
93+
* @param requireMcpHeaders Whether a POST lacking the SEP-2243 {@code Mcp-Method} /
94+
* {@code Mcp-Name} headers is rejected instead of tolerated.
8995
* @throws IllegalArgumentException if any parameter is null
9096
*/
9197
private HttpServletStatelessServerTransport(McpJsonMapper jsonMapper, String mcpEndpoint,
9298
McpTransportContextExtractor<HttpServletRequest> contextExtractor,
93-
ServerHttpHeaderValidator httpHeaderValidator, int requestMaxSize) {
99+
ServerHttpHeaderValidator httpHeaderValidator, int requestMaxSize, boolean requireMcpHeaders) {
94100
Assert.notNull(jsonMapper, "jsonMapper must not be null");
95101
Assert.notNull(mcpEndpoint, "mcpEndpoint must not be null");
96102
Assert.notNull(contextExtractor, "contextExtractor must not be null");
@@ -102,6 +108,7 @@ private HttpServletStatelessServerTransport(McpJsonMapper jsonMapper, String mcp
102108
this.contextExtractor = contextExtractor;
103109
this.httpHeaderValidator = httpHeaderValidator;
104110
this.requestMaxSize = requestMaxSize;
111+
this.sep2243Validator = new Sep2243RequestValidator(jsonMapper, this::protocolVersions, requireMcpHeaders);
105112
}
106113

107114
@Override
@@ -195,18 +202,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
195202
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
196203

197204
// 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)) {
205+
// version has been negotiated; 'initialize' requests are exempt.
206+
HttpServletHeaderAccessor headerAccessor = new HttpServletHeaderAccessor(request);
207+
McpError protocolVersionError = this.sep2243Validator.validateProtocolVersion(headerAccessor,
208+
Sep2243RequestValidator.isInitializeRequest(message));
209+
if (protocolVersionError != null) {
210+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, protocolVersionError);
204211
return;
205212
}
206213

207214
// Per SEP-2243, reject header/body mismatches (missing headers are tolerated
208-
// so legacy clients keep working).
209-
if (!validateMcpHeaders(request, response, message)) {
215+
// by default so legacy clients keep working).
216+
McpError mirroringError = this.sep2243Validator.validateMirroringHeaders(headerAccessor, message);
217+
if (mirroringError != null) {
218+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, mirroringError);
210219
return;
211220
}
212221

@@ -290,124 +299,6 @@ private void responseError(HttpServletResponse response, int httpCode, McpError
290299
writer.flush();
291300
}
292301

293-
/**
294-
* Validates the {@code MCP-Protocol-Version} header against the protocol versions
295-
* supported by this transport. A missing header is allowed and falls back to the
296-
* negotiated protocol version, while a header carrying an unsupported version is
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.
300-
* @param request the HTTP servlet request
301-
* @param response the HTTP servlet response
302-
* @return true if the header is missing or contains a supported version, false if a
303-
* 400 error response has been written
304-
* @throws IOException if an I/O error occurs
305-
*/
306-
private boolean validateProtocolVersion(HttpServletRequest request, HttpServletResponse response)
307-
throws IOException {
308-
String protocolVersion = request.getHeader(HttpHeaders.PROTOCOL_VERSION);
309-
if (protocolVersion == null || this.protocolVersions().contains(protocolVersion)) {
310-
return true;
311-
}
312-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
313-
McpError.builder(McpSchema.ErrorCodes.METHOD_NOT_FOUND)
314-
.message("Unsupported protocol version (supported versions: "
315-
+ String.join(", ", this.protocolVersions()) + ")")
316-
.build());
317-
return false;
318-
}
319-
320-
/**
321-
* Validates the SEP-2243 {@code Mcp-Method} and {@code Mcp-Name} request headers
322-
* against the deserialized message body. Missing headers are permitted for backwards
323-
* compatibility with legacy clients, but any header that is supplied must match the
324-
* corresponding payload attribute. Mismatches are rejected with a 400 Bad Request.
325-
* @param request the incoming servlet request
326-
* @param response the servlet response used to write an error payload if validation
327-
* fails
328-
* @param message the parsed JSON-RPC message
329-
* @return {@code true} if validation passed, {@code false} if a 400 response was
330-
* written
331-
* @throws IOException if writing the error response fails
332-
*/
333-
private boolean validateMcpHeaders(HttpServletRequest request, HttpServletResponse response,
334-
McpSchema.JSONRPCMessage message) throws IOException {
335-
String method = message instanceof McpSchema.JSONRPCRequest req ? req.method()
336-
: message instanceof McpSchema.JSONRPCNotification notif ? notif.method() : null;
337-
338-
if (method == null) {
339-
return true;
340-
}
341-
342-
String methodHeader = request.getHeader(HttpHeaders.MCP_METHOD);
343-
if (methodHeader != null && !methodHeader.isBlank() && !method.equals(methodHeader)) {
344-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
345-
McpError.builder(McpSchema.ErrorCodes.HEADER_MISMATCH)
346-
.message("Mcp-Method header mismatch: expected '" + method + "' but was '" + methodHeader + "'")
347-
.build());
348-
return false;
349-
}
350-
351-
Object params = message instanceof McpSchema.JSONRPCRequest req ? req.params()
352-
: message instanceof McpSchema.JSONRPCNotification notif ? notif.params() : null;
353-
String name = extractNameFromParams(method, params);
354-
if (name != null) {
355-
String nameHeader = request.getHeader(HttpHeaders.MCP_NAME);
356-
if (nameHeader != null && !nameHeader.isBlank()) {
357-
String decodedName = HttpHeaders.decodeHeaderValue(nameHeader);
358-
if (!name.equals(decodedName)) {
359-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
360-
McpError.builder(McpSchema.ErrorCodes.HEADER_MISMATCH)
361-
.message("Mcp-Name header mismatch: expected '" + name + "' but was '" + nameHeader
362-
+ "'")
363-
.build());
364-
return false;
365-
}
366-
}
367-
}
368-
369-
return true;
370-
}
371-
372-
/**
373-
* Extracts the name or URI of the tool, prompt, or resource referenced by a request,
374-
* as used to validate the SEP-2243 {@code Mcp-Name} header.
375-
* @param method the JSON-RPC method of the request
376-
* @param params the request parameters
377-
* @return the target name or URI when the method references one, otherwise
378-
* {@code null}
379-
*/
380-
private String extractNameFromParams(String method, Object params) {
381-
if (params == null) {
382-
return null;
383-
}
384-
385-
try {
386-
return switch (method) {
387-
case McpSchema.METHOD_TOOLS_CALL ->
388-
this.jsonMapper.convertValue(params, new TypeRef<McpSchema.CallToolRequest>() {
389-
}).name();
390-
case McpSchema.METHOD_PROMPT_GET ->
391-
this.jsonMapper.convertValue(params, new TypeRef<McpSchema.GetPromptRequest>() {
392-
}).name();
393-
case McpSchema.METHOD_RESOURCES_READ ->
394-
this.jsonMapper.convertValue(params, new TypeRef<McpSchema.ReadResourceRequest>() {
395-
}).uri();
396-
case McpSchema.METHOD_RESOURCES_SUBSCRIBE ->
397-
this.jsonMapper.convertValue(params, new TypeRef<McpSchema.SubscribeRequest>() {
398-
}).uri();
399-
case McpSchema.METHOD_RESOURCES_UNSUBSCRIBE ->
400-
this.jsonMapper.convertValue(params, new TypeRef<McpSchema.UnsubscribeRequest>() {
401-
}).uri();
402-
default -> null;
403-
};
404-
}
405-
catch (Exception e) {
406-
logger.debug("Failed to extract name from params for method {}: {}", method, e.getMessage());
407-
return null;
408-
}
409-
}
410-
411302
/**
412303
* Cleans up resources when the servlet is being destroyed.
413304
* <p>
@@ -446,6 +337,8 @@ public static class Builder {
446337

447338
private int requestMaxSize = DEFAULT_REQUEST_MAX_SIZE;
448339

340+
private boolean requireMcpHeaders = false;
341+
449342
private Builder() {
450343
// used by a static method
451344
}
@@ -531,6 +424,22 @@ public Builder maxRequestSize(int requestMaxSize) {
531424
return this;
532425
}
533426

427+
/**
428+
* Opt-in strict mode for SEP-2243. When enabled, a POST whose JSON-RPC request or
429+
* notification carries no {@code Mcp-Method} header, or targets a tool, prompt or
430+
* resource without an {@code Mcp-Name} header, is rejected with HTTP 400 and
431+
* error code {@code HEADER_MISMATCH} (-32020). Disabled by default so that
432+
* clients that do not send these headers keep working. A present header that
433+
* mismatches the body is always rejected regardless of this setting.
434+
* @param requireMcpHeaders whether to require the SEP-2243 {@code Mcp-Method} /
435+
* {@code Mcp-Name} headers
436+
* @return this builder instance
437+
*/
438+
public Builder requireMcpHeaders(boolean requireMcpHeaders) {
439+
this.requireMcpHeaders = requireMcpHeaders;
440+
return this;
441+
}
442+
534443
/**
535444
* Builds a new instance of {@link HttpServletStatelessServerTransport} with the
536445
* configured settings.
@@ -541,7 +450,7 @@ public HttpServletStatelessServerTransport build() {
541450
Assert.notNull(mcpEndpoint, "Message endpoint must be set");
542451
return new HttpServletStatelessServerTransport(
543452
jsonMapper == null ? McpJsonDefaults.getMapper() : jsonMapper, mcpEndpoint, contextExtractor,
544-
httpHeaderValidator, requestMaxSize);
453+
httpHeaderValidator, requestMaxSize, requireMcpHeaders);
545454
}
546455

547456
}

0 commit comments

Comments
 (0)