Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
*/
final class HttpServletRequestUtils {

private static final String APPLICATION_JSON = "application/json";

private HttpServletRequestUtils() {
}

Expand All @@ -41,6 +43,27 @@ static Map<String, List<String>> extractHeaders(HttpServletRequest request) {
return headers;
}

/**
* Checks whether a {@code Content-Type} header value denotes
* {@code application/json}. Only the media type is compared, case-insensitively;
* parameters such as {@code charset} are ignored. This is not a substring search, so
* a value like {@code text/plain; a=application/json} is rejected.
* <p>
* Requiring {@code application/json} prevents browsers from sending cross-origin
* JSON-RPC messages as CORS "simple requests" (e.g. with {@code text/plain}), which
* would otherwise reach the server without a preflight.
* @param contentType The {@code Content-Type} header value, may be {@code null}
* @return {@code true} if the media type is {@code application/json}
*/
static boolean isJsonContentType(String contentType) {
if (contentType == null) {
return false;
}
int parametersStart = contentType.indexOf(';');
String mediaType = parametersStart == -1 ? contentType : contentType.substring(0, parametersStart);
return APPLICATION_JSON.equalsIgnoreCase(mediaType.trim());
}

/**
* Reads the request body, decoded using the request's character encoding (or UTF-8 if
* not specified), while bounding the number of bytes read.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,14 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
return;
}

if (!HttpServletRequestUtils.isJsonContentType(request.getContentType())) {
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
return;
}

// Get the session ID from the request parameter
String sessionId = request.getParameter("sessionId");
if (sessionId == null) {
Expand Down Expand Up @@ -452,6 +460,16 @@ private void sendEvent(PrintWriter writer, String eventType, String data) throws
}
}

private void responseError(HttpServletResponse response, int httpCode, McpError mcpError) throws IOException {
response.setContentType(APPLICATION_JSON);
response.setCharacterEncoding(UTF_8);
response.setStatus(httpCode);
String jsonError = jsonMapper.writeValueAsString(mcpError);
PrintWriter writer = response.getWriter();
writer.write(jsonError);
writer.flush();
}

/**
* Cleans up resources when the servlet is being destroyed.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,13 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
return;
}

McpTransportContext transportContext = this.contextExtractor.extract(request);
if (!HttpServletRequestUtils.isJsonContentType(request.getContentType())) {
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
return;
}

String accept = request.getHeader(ACCEPT);
if (accept == null || !(accept.contains(APPLICATION_JSON) && accept.contains(TEXT_EVENT_STREAM))) {
Expand All @@ -179,6 +185,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
return;
}

McpTransportContext transportContext = this.contextExtractor.extract(request);

try {
String body = HttpServletRequestUtils.readBody(request, this.requestMaxSize);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,14 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
badRequestErrors.add("application/json required in Accept header");
}

if (!HttpServletRequestUtils.isJsonContentType(request.getContentType())) {
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
return;
}

McpTransportContext transportContext = this.contextExtractor.extract(request);

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
Expand Down Expand Up @@ -100,6 +103,22 @@ void honorsRequestCharacterEncoding() throws Exception {
assertThat(body).isEqualTo("café");
}

@ParameterizedTest
@ValueSource(strings = { "application/json", "application/json; charset=utf-8", "application/json;charset=UTF-8",
"Application/JSON", " application/json ; charset=utf-8" })
void acceptsJsonContentType(String contentType) {
assertThat(HttpServletRequestUtils.isJsonContentType(contentType)).isTrue();
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = { "text/plain", "text/plain;charset=UTF-8", "text/plain; a=application/json",
"application/x-www-form-urlencoded", "multipart/form-data", "application/json-seq", "application/jsonp",
"application/json, text/plain", "text/event-stream" })
void rejectsNonJsonContentType(String contentType) {
assertThat(HttpServletRequestUtils.isJsonContentType(contentType)).isFalse();
}

private static HttpServletRequest requestWithBody(String body, String characterEncoding) throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getInputStream()).thenReturn(servletInputStream(body.getBytes(StandardCharsets.UTF_8)));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2026-2026 the original author or authors.
*/

package io.modelcontextprotocol.server.transport;

import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;

/**
* Utility methods for working with {@link ServerRequest}. For internal use only.
*
* @author Daniel Garnier-Moiroux
*/
final class WebFluxServerRequestUtils {

private WebFluxServerRequestUtils() {
}

/**
* Checks whether the request's {@code Content-Type} header denotes
* {@code application/json}. Only the media type is compared, case-insensitively;
* parameters such as {@code charset} are ignored. A missing or malformed header is
* rejected.
* <p>
* Requiring {@code application/json} prevents browsers from sending cross-origin
* JSON-RPC messages as CORS "simple requests" (e.g. with {@code text/plain}), which
* would otherwise reach the server without a preflight.
* @param request The incoming server request
* @return {@code true} if the media type is {@code application/json}
*/
static boolean isJsonContentType(ServerRequest request) {
try {
return request.headers().contentType().map(MediaType.APPLICATION_JSON::equalsTypeAndSubtype).orElse(false);
}
catch (InvalidMediaTypeException ex) {
return false;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,13 @@ private Mono<ServerResponse> handleMessage(ServerRequest request) {
return ServerResponse.status(e.getStatusCode()).bodyValue(e.getMessage());
}

if (!WebFluxServerRequestUtils.isJsonContentType(request)) {
return ServerResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
.bodyValue(McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
}

if (request.queryParam("sessionId").isEmpty()) {
return ServerResponse.badRequest().bodyValue(new McpError("Session ID missing in message endpoint"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,13 @@ private Mono<ServerResponse> handlePost(ServerRequest request) {
return ServerResponse.status(e.getStatusCode()).bodyValue(e.getMessage());
}

if (!WebFluxServerRequestUtils.isJsonContentType(request)) {
return ServerResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
.bodyValue(McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
}

McpTransportContext transportContext = this.contextExtractor.extract(request);

List<MediaType> acceptHeaders = request.headers().asHttpHeaders().getAccept();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ private Mono<ServerResponse> handlePost(ServerRequest request) {
return ServerResponse.status(e.getStatusCode()).bodyValue(e.getMessage());
}

if (!WebFluxServerRequestUtils.isJsonContentType(request)) {
return ServerResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
.bodyValue(McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
.message("Unsupported Media Type: Content-Type must be application/json")
.build());
}

McpTransportContext transportContext = this.contextExtractor.extract(request);

List<MediaType> acceptHeaders = request.headers().asHttpHeaders().getAccept();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,25 @@
package io.modelcontextprotocol;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ValueSource;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
Expand All @@ -26,12 +35,20 @@
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServer.AsyncSpecification;
import io.modelcontextprotocol.server.McpServer.SingleSessionSyncSpecification;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.server.McpTransportContextExtractor;
import io.modelcontextprotocol.server.TestUtil;
import io.modelcontextprotocol.server.transport.WebFluxSseServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;

import static io.modelcontextprotocol.util.ToolsUtils.EMPTY_JSON_SCHEMA;
import static org.assertj.core.api.Assertions.assertThat;

@Timeout(15)
class WebFluxSseIntegrationTests extends AbstractMcpClientServerIntegrationTests {

Expand Down Expand Up @@ -103,4 +120,69 @@ public void after() {
}
}

@ParameterizedTest
@ValueSource(strings = { "text/plain;charset=UTF-8", "application/x-www-form-urlencoded", "multipart/form-data" })
void rejectsNonJsonContentType(String contentType) {
var webClient = WebClient.create("http://localhost:" + PORT);
var toolCalled = new AtomicBoolean();
prepareAsyncServerBuilder().capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.tools(McpServerFeatures.AsyncToolSpecification.builder()
.tool(McpSchema.Tool.builder().name("tool1").inputSchema(EMPTY_JSON_SCHEMA).build())
.callHandler((exchange, request) -> {
toolCalled.set(true);
return Mono.just(McpSchema.CallToolResult.builder().build());
})
.build())
.build();

// Establish an SSE session to obtain the session-scoped message endpoint. The
// SSE stream must stay open for the session to remain active.
var messageEndpoint = Sinks.<String>one();
Disposable sseSubscription = webClient.get()
.uri(CUSTOM_SSE_ENDPOINT)
.accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<ServerSentEvent<String>>() {
})
.filter(event -> WebFluxSseServerTransportProvider.ENDPOINT_EVENT_TYPE.equals(event.event()))
.subscribe(event -> messageEndpoint.tryEmitValue(event.data()));
try {
String endpoint = messageEndpoint.asMono().block(Duration.ofSeconds(5));

// Initialize the session, so that the tool call below would be handled if it
// were accepted
for (String message : List.of("""
{"jsonrpc":"2.0","id":"init","method":"initialize","params":{
"protocolVersion":"2024-11-05","capabilities":{},
"clientInfo":{"name":"test-client","version":"1.0.0"}}}""", """
{"jsonrpc":"2.0","method":"notifications/initialized"}""")) {
var initResponse = webClient.post()
.uri(endpoint)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(message)
.exchangeToMono(ClientResponse::toBodilessEntity)
.block();
assertThat(initResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
}

// CORS-safelisted content types can be sent cross-origin by a browser without
// a preflight, so they must be rejected before the message is handled
var response = webClient.post()
.uri(endpoint)
.contentType(MediaType.parseMediaType(contentType))
.bodyValue(
"""
{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"tool1","arguments":{}}}""")
.exchangeToMono(clientResponse -> clientResponse.toEntity(String.class))
.block();

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
assertThat(response.getBody()).contains("Unsupported Media Type: Content-Type must be application/json");
assertThat(toolCalled).isFalse();
}
finally {
sseSubscription.dispose();
}
}

}
Loading
Loading