Skip to content

Commit c3fdc48

Browse files
committed
feat(mcp-core): support Mcp-Name header for Streamable HTTP (SEP-2243)
Add MCP_NAME header constant and inject it in the streamable HTTP client transport (HttpClientStreamableHttpTransport)
1 parent c8ab341 commit c3fdc48

7 files changed

Lines changed: 398 additions & 6 deletions

File tree

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

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -483,14 +483,35 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sentMessage) {
483483
transportSession.sessionId().get());
484484
}
485485

486+
// Extract method and params for Mcp-Name header
487+
String method = null;
488+
Object params = null;
489+
if (sentMessage instanceof McpSchema.JSONRPCRequest request) {
490+
method = request.method();
491+
params = request.params();
492+
}
493+
else if (sentMessage instanceof McpSchema.JSONRPCNotification notification) {
494+
method = notification.method();
495+
params = notification.params();
496+
}
497+
486498
var builder = requestBuilder.uri(uri)
487499
.header(HttpHeaders.ACCEPT, APPLICATION_JSON + ", " + TEXT_EVENT_STREAM)
488500
.header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_UTF8)
489501
.header(HttpHeaders.CACHE_CONTROL, "no-cache")
490-
.header(HttpHeaders.PROTOCOL_VERSION,
491-
ctx.getOrDefault(McpAsyncClient.NEGOTIATED_PROTOCOL_VERSION,
492-
this.latestSupportedProtocolVersion))
493-
.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
502+
.header(HttpHeaders.PROTOCOL_VERSION, ctx.getOrDefault(McpAsyncClient.NEGOTIATED_PROTOCOL_VERSION,
503+
this.latestSupportedProtocolVersion));
504+
505+
// Add MCP-specific headers if applicable
506+
if (method != null) {
507+
builder = builder.header(HttpHeaders.MCP_METHOD, method);
508+
String name = extractNameFromParams(method, params);
509+
if (name != null) {
510+
builder = builder.header(HttpHeaders.MCP_NAME, name);
511+
}
512+
}
513+
514+
builder = builder.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
494515
var transportContext = ctx.getOrDefault(McpTransportContext.KEY, McpTransportContext.EMPTY);
495516
return Mono
496517
.from(this.httpRequestCustomizer.customize(builder, "POST", uri, jsonBody, transportContext));
@@ -675,6 +696,48 @@ public <T> T unmarshalFrom(Object data, TypeRef<T> typeRef) {
675696
return this.jsonMapper.convertValue(data, typeRef);
676697
}
677698

699+
/**
700+
* Extracts the name/URI from the request params based on the method type.
701+
* @param method the MCP method name
702+
* @param params the request parameters
703+
* @return the name/URI if applicable for the method, or null otherwise
704+
*/
705+
private String extractNameFromParams(String method, Object params) {
706+
if (params == null) {
707+
return null;
708+
}
709+
710+
try {
711+
switch (method) {
712+
case McpSchema.METHOD_TOOLS_CALL -> {
713+
McpSchema.CallToolRequest request = this.jsonMapper.convertValue(params,
714+
new TypeRef<McpSchema.CallToolRequest>() {
715+
});
716+
return request.name();
717+
}
718+
case McpSchema.METHOD_RESOURCES_READ -> {
719+
McpSchema.ReadResourceRequest request = this.jsonMapper.convertValue(params,
720+
new TypeRef<McpSchema.ReadResourceRequest>() {
721+
});
722+
return request.uri();
723+
}
724+
case McpSchema.METHOD_PROMPT_GET -> {
725+
McpSchema.GetPromptRequest request = this.jsonMapper.convertValue(params,
726+
new TypeRef<McpSchema.GetPromptRequest>() {
727+
});
728+
return request.name();
729+
}
730+
default -> {
731+
return null;
732+
}
733+
}
734+
}
735+
catch (Exception e) {
736+
logger.debug("Failed to extract name from params for method {}: {}", method, e.getMessage());
737+
return null;
738+
}
739+
}
740+
678741
/**
679742
* Builder for {@link HttpClientStreamableHttpTransport}.
680743
*/

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

Lines changed: 150 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,10 @@ public class HttpServletStreamableServerTransportProvider extends HttpServlet
126126
*/
127127
private final ServerTransportSecurityValidator securityValidator;
128128

129+
private final boolean requireMcpNameHeader;
130+
131+
private final boolean requireMcpMethodHeader;
132+
129133
/**
130134
* Constructs a new HttpServletStreamableServerTransportProvider instance.
131135
* @param jsonMapper The JsonMapper to use for JSON serialization/deserialization of
@@ -141,7 +145,8 @@ public class HttpServletStreamableServerTransportProvider extends HttpServlet
141145
*/
142146
private HttpServletStreamableServerTransportProvider(McpJsonMapper jsonMapper, String mcpEndpoint,
143147
boolean disallowDelete, McpTransportContextExtractor<HttpServletRequest> contextExtractor,
144-
Duration keepAliveInterval, ServerTransportSecurityValidator securityValidator) {
148+
Duration keepAliveInterval, ServerTransportSecurityValidator securityValidator,
149+
boolean requireMcpNameHeader, boolean requireMcpMethodHeader) {
145150
Assert.notNull(jsonMapper, "JsonMapper must not be null");
146151
Assert.notNull(mcpEndpoint, "MCP endpoint must not be null");
147152
Assert.notNull(contextExtractor, "Context extractor must not be null");
@@ -152,6 +157,8 @@ private HttpServletStreamableServerTransportProvider(McpJsonMapper jsonMapper, S
152157
this.disallowDelete = disallowDelete;
153158
this.contextExtractor = contextExtractor;
154159
this.securityValidator = securityValidator;
160+
this.requireMcpNameHeader = requireMcpNameHeader;
161+
this.requireMcpMethodHeader = requireMcpMethodHeader;
155162

156163
if (keepAliveInterval != null) {
157164

@@ -390,6 +397,101 @@ public void onStartAsync(jakarta.servlet.AsyncEvent event) throws IOException {
390397
* @throws ServletException If a servlet-specific error occurs
391398
* @throws IOException If an I/O error occurs
392399
*/
400+
private String extractNameFromParams(String method, Object params) {
401+
if (params == null) {
402+
return null;
403+
}
404+
405+
try {
406+
switch (method) {
407+
case McpSchema.METHOD_TOOLS_CALL -> {
408+
McpSchema.CallToolRequest request = jsonMapper.convertValue(params,
409+
new TypeRef<McpSchema.CallToolRequest>() {
410+
});
411+
return request.name();
412+
}
413+
case McpSchema.METHOD_RESOURCES_READ -> {
414+
McpSchema.ReadResourceRequest request = jsonMapper.convertValue(params,
415+
new TypeRef<McpSchema.ReadResourceRequest>() {
416+
});
417+
return request.uri();
418+
}
419+
case McpSchema.METHOD_PROMPT_GET -> {
420+
McpSchema.GetPromptRequest request = jsonMapper.convertValue(params,
421+
new TypeRef<McpSchema.GetPromptRequest>() {
422+
});
423+
return request.name();
424+
}
425+
default -> {
426+
return null;
427+
}
428+
}
429+
}
430+
catch (Exception e) {
431+
logger.debug("Failed to extract name from params for method {}: {}", method, e.getMessage());
432+
return null;
433+
}
434+
}
435+
436+
private boolean validateMcpMethodHeader(HttpServletRequest request, HttpServletResponse response, String method)
437+
throws IOException {
438+
if (!this.requireMcpMethodHeader) {
439+
return true;
440+
}
441+
442+
String headerMethod = request.getHeader(HttpHeaders.MCP_METHOD);
443+
if (headerMethod == null || headerMethod.isBlank()) {
444+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
445+
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
446+
.message("Mcp-Method header required for method " + method)
447+
.build());
448+
return false;
449+
}
450+
451+
if (!method.equals(headerMethod)) {
452+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
453+
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
454+
.message("Mcp-Method header mismatch: expected '" + method + "' but was '" + headerMethod + "'")
455+
.build());
456+
return false;
457+
}
458+
459+
return true;
460+
}
461+
462+
private boolean validateMcpNameHeader(HttpServletRequest request, HttpServletResponse response, String method,
463+
Object params) throws IOException {
464+
if (!this.requireMcpNameHeader) {
465+
return true;
466+
}
467+
468+
String expectedName = extractNameFromParams(method, params);
469+
String headerName = request.getHeader(HttpHeaders.MCP_NAME);
470+
if (headerName == null || headerName.isBlank()) {
471+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
472+
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
473+
.message("Mcp-Name header required for method " + method)
474+
.build());
475+
return false;
476+
}
477+
478+
if (expectedName == null || !headerName.equals(expectedName)) {
479+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
480+
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
481+
.message("Mcp-Name header mismatch: expected '" + expectedName + "' but was '" + headerName
482+
+ "'")
483+
.build());
484+
return false;
485+
}
486+
487+
return true;
488+
}
489+
490+
private boolean isNameHeaderMethod(String method) {
491+
return McpSchema.METHOD_TOOLS_CALL.equals(method) || McpSchema.METHOD_RESOURCES_READ.equals(method)
492+
|| McpSchema.METHOD_PROMPT_GET.equals(method);
493+
}
494+
393495
@Override
394496
protected void doPost(HttpServletRequest request, HttpServletResponse response)
395497
throws ServletException, IOException {
@@ -436,6 +538,23 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
436538

437539
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body.toString());
438540

541+
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest) {
542+
String method = jsonrpcRequest.method();
543+
if (!validateMcpMethodHeader(request, response, method)) {
544+
return;
545+
}
546+
if (isNameHeaderMethod(method)
547+
&& !validateMcpNameHeader(request, response, method, jsonrpcRequest.params())) {
548+
return;
549+
}
550+
}
551+
else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
552+
String method = jsonrpcNotification.method();
553+
if (!validateMcpMethodHeader(request, response, method)) {
554+
return;
555+
}
556+
}
557+
439558
// Handle initialization request
440559
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest
441560
&& jsonrpcRequest.method().equals(McpSchema.METHOD_INITIALIZE)) {
@@ -830,6 +949,10 @@ public static class Builder {
830949

831950
private boolean disallowDelete = false;
832951

952+
private boolean requireMcpNameHeader = false;
953+
954+
private boolean requireMcpMethodHeader = false;
955+
833956
private McpTransportContextExtractor<HttpServletRequest> contextExtractor = (
834957
serverRequest) -> McpTransportContext.EMPTY;
835958

@@ -908,6 +1031,30 @@ public Builder securityValidator(ServerTransportSecurityValidator securityValida
9081031
return this;
9091032
}
9101033

1034+
/**
1035+
* Sets whether the server should reject requests that do not include the
1036+
* {@code Mcp-Name} header for methods that may include it.
1037+
* @param requireMcpNameHeader true to reject missing headers, false to accept
1038+
* requests from older clients by default
1039+
* @return this builder instance
1040+
*/
1041+
public Builder requireMcpNameHeader(boolean requireMcpNameHeader) {
1042+
this.requireMcpNameHeader = requireMcpNameHeader;
1043+
return this;
1044+
}
1045+
1046+
/**
1047+
* Sets whether the server should reject requests that do not include the
1048+
* {@code Mcp-Method} header for requests and notifications.
1049+
* @param requireMcpMethodHeader true to reject missing or mismatched method
1050+
* headers, false to accept requests from older clients by default
1051+
* @return this builder instance
1052+
*/
1053+
public Builder requireMcpMethodHeader(boolean requireMcpMethodHeader) {
1054+
this.requireMcpMethodHeader = requireMcpMethodHeader;
1055+
return this;
1056+
}
1057+
9111058
/**
9121059
* Builds a new instance of {@link HttpServletStreamableServerTransportProvider}
9131060
* with the configured settings.
@@ -918,7 +1065,8 @@ public HttpServletStreamableServerTransportProvider build() {
9181065
Assert.notNull(this.mcpEndpoint, "MCP endpoint must be set");
9191066
return new HttpServletStreamableServerTransportProvider(
9201067
jsonMapper == null ? McpJsonDefaults.getMapper() : jsonMapper, mcpEndpoint, disallowDelete,
921-
contextExtractor, keepAliveInterval, securityValidator);
1068+
contextExtractor, keepAliveInterval, securityValidator, requireMcpNameHeader,
1069+
requireMcpMethodHeader);
9221070
}
9231071

9241072
}

‎mcp-core/src/main/java/io/modelcontextprotocol/spec/HttpHeaders.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ public interface HttpHeaders {
2626
*/
2727
String PROTOCOL_VERSION = "MCP-Protocol-Version";
2828

29+
/**
30+
* The name or URI of the resource/tool/prompt being accessed.
31+
*/
32+
String MCP_NAME = "Mcp-Name";
33+
34+
/**
35+
* The MCP method name for the current request or notification.
36+
*/
37+
String MCP_METHOD = "Mcp-Method";
38+
2939
/**
3040
* The HTTP Content-Length header.
3141
* @see <a href=

‎mcp-json-jackson2/pom.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
Import-Package: io.modelcontextprotocol.json,io.modelcontextprotocol.json.schema, \
4343
*;
4444
Service-Component: OSGI-INF/io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapperSupplier.xml,OSGI-INF/io.modelcontextprotocol.json.schema.jackson2.JacksonJsonSchemaValidatorSupplier.xml
45+
Export-Package: io.modelcontextprotocol.json.jackson2;version="${project.version}";-noimport:=true, \
46+
io.modelcontextprotocol.json.schema.jackson2;version="${project.version}";-noimport:=true
4547
-noimportjava: true;
4648
-nouses: true;
4749
-removeheaders: Private-Package

‎mcp-json-jackson3/pom.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
Import-Package: io.modelcontextprotocol.json,io.modelcontextprotocol.json.schema, \
4343
*;
4444
Service-Component: OSGI-INF/io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapperSupplier.xml,OSGI-INF/io.modelcontextprotocol.json.schema.jackson3.JacksonJsonSchemaValidatorSupplier.xml
45+
Export-Package: io.modelcontextprotocol.json.jackson3;version="${project.version}";-noimport:=true, \
46+
io.modelcontextprotocol.json.schema.jackson3;version="${project.version}";-noimport:=true
4547
-noimportjava: true;
4648
-nouses: true;
4749
-removeheaders: Private-Package

0 commit comments

Comments
 (0)