Skip to content

Commit 507eb28

Browse files
committed
Fix non-compliant JSON-RPC error responses in servlet transports
The servlet transports returned error bodies that did not conform to the MCP JSON-RPC response format: they omitted the required "jsonrpc" field, used "jsonRpcError" instead of "error", and did not include the request ID even where it was available. These malformed responses resulted from serializing McpError directly rather than constructing a JSONRPCResponse error envelope. Because McpError extends RuntimeException, this also caused information disclosure: Jackson included exception internals such as stack traces in the response. Before (wrong; illustrative response with an abbreviated stack trace): ```json { "jsonRpcError": { "code": -123, "message": "foo" }, "message": "foo", "localizedMessage": "foo", "cause": null, "suppressed": [], "stackTrace": [ { "className": "io.modelcontextprotocol.spec.McpError$Builder", "methodName": "build", "fileName": "McpError.java", "lineNumber": 81, "nativeMethod": false } ] } ``` After (correct; no request ID is available in this example): ```json { "jsonrpc": "2.0", "error": { "code": -123, "message": "foo" } } ``` Write typed JSONRPCResponse envelopes across the SSE, streamable, and stateless servlet transports. Allow error responses without an ID while continuing to require IDs on successful responses, and propagate request IDs where already parsed. Preserve the public McpError response writer as a wrapper that unwraps the protocol error. Add regression coverage for HTTP error envelopes, request IDs, and exclusion of exception properties, including causes and suppressed exceptions. Update tests that expected a top-level exception message.
1 parent 29a1c76 commit 507eb28

8 files changed

Lines changed: 308 additions & 125 deletions

File tree

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
package io.modelcontextprotocol.server.transport;
66

77
import java.io.IOException;
8+
import java.io.PrintWriter;
89

10+
import io.modelcontextprotocol.json.McpJsonMapper;
11+
import io.modelcontextprotocol.spec.McpSchema;
912
import jakarta.servlet.http.HttpServletResponse;
1013

1114
/**
@@ -20,6 +23,20 @@ final class HttpServletResponseUtils {
2023
private HttpServletResponseUtils() {
2124
}
2225

26+
/**
27+
* Writes a protocol response rather than serializing an exception as a Java bean.
28+
*/
29+
static void writeJsonResponse(HttpServletResponse response, int httpCode, McpJsonMapper jsonMapper,
30+
McpSchema.JSONRPCResponse message) throws IOException {
31+
String json = jsonMapper.writeValueAsString(message);
32+
response.setContentType("application/json");
33+
response.setCharacterEncoding("UTF-8");
34+
response.setStatus(httpCode);
35+
PrintWriter writer = response.getWriter();
36+
writer.write(json);
37+
writer.flush();
38+
}
39+
2340
/**
2441
* Prepares the response for streaming Server-Sent Events: sets the content type and
2542
* the headers that keep intermediaries from caching, transforming or buffering the

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

Lines changed: 18 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
import io.modelcontextprotocol.json.McpJsonMapper;
1919
import io.modelcontextprotocol.json.TypeRef;
2020
import io.modelcontextprotocol.server.McpTransportContextExtractor;
21-
import io.modelcontextprotocol.spec.McpError;
2221
import io.modelcontextprotocol.spec.McpSchema;
22+
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
2323
import io.modelcontextprotocol.spec.McpServerSession;
2424
import io.modelcontextprotocol.spec.McpServerTransport;
2525
import io.modelcontextprotocol.spec.McpServerTransportProvider;
@@ -375,48 +375,37 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
375375
}
376376

377377
if (!HttpServletRequestUtils.isJsonContentType(request.getContentType())) {
378-
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
379-
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
380-
.message("Unsupported Media Type: Content-Type must be application/json")
381-
.build());
378+
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, null,
379+
new JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST,
380+
"Unsupported Media Type: Content-Type must be application/json"));
382381
return;
383382
}
384383

385384
// Get the session ID from the request parameter
386385
String sessionId = request.getParameter("sessionId");
387386
if (sessionId == null) {
388-
response.setContentType(APPLICATION_JSON);
389-
response.setCharacterEncoding(UTF_8);
390-
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
391-
String jsonError = jsonMapper.writeValueAsString(McpError.builder(McpSchema.ErrorCodes.METHOD_NOT_FOUND)
392-
.message("Session ID missing in message endpoint")
393-
.build());
394-
PrintWriter writer = response.getWriter();
395-
writer.write(jsonError);
396-
writer.flush();
387+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, null,
388+
new JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND, "Session ID missing in message endpoint"));
397389
return;
398390
}
399391

400392
// Get the session from the sessions map
401393
McpServerSession session = sessions.get(sessionId);
402394
if (session == null) {
403-
response.setContentType(APPLICATION_JSON);
404-
response.setCharacterEncoding(UTF_8);
405-
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
406-
String jsonError = jsonMapper.writeValueAsString(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
407-
.message("Session not found: " + sessionId)
408-
.build());
409-
PrintWriter writer = response.getWriter();
410-
writer.write(jsonError);
411-
writer.flush();
395+
this.responseError(response, HttpServletResponse.SC_NOT_FOUND, null,
396+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, "Session not found: " + sessionId));
412397
return;
413398
}
414399

400+
Object requestId = null;
415401
try {
416402
String body = HttpServletRequestUtils.readBody(request, this.requestMaxSize);
417403

418404
final McpTransportContext transportContext = this.contextExtractor.extract(request);
419405
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
406+
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest) {
407+
requestId = jsonrpcRequest.id();
408+
}
420409

421410
// Process the message through the session's handle method
422411
// Block for Servlet compatibility
@@ -430,16 +419,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
430419
catch (Exception e) {
431420
logger.error("Error processing message: {}", e.getMessage());
432421
try {
433-
McpError mcpError = McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
434-
.message(e.getMessage())
435-
.build();
436-
response.setContentType(APPLICATION_JSON);
437-
response.setCharacterEncoding(UTF_8);
438-
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
439-
String jsonError = jsonMapper.writeValueAsString(mcpError);
440-
PrintWriter writer = response.getWriter();
441-
writer.write(jsonError);
442-
writer.flush();
422+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId,
423+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, e.getMessage()));
443424
}
444425
catch (IOException ex) {
445426
logger.error(FAILED_TO_SEND_ERROR_RESPONSE, ex.getMessage());
@@ -486,14 +467,10 @@ private void sendEvent(PrintWriter writer, String eventType, String data) throws
486467
}
487468
}
488469

489-
private void responseError(HttpServletResponse response, int httpCode, McpError mcpError) throws IOException {
490-
response.setContentType(APPLICATION_JSON);
491-
response.setCharacterEncoding(UTF_8);
492-
response.setStatus(httpCode);
493-
String jsonError = jsonMapper.writeValueAsString(mcpError);
494-
PrintWriter writer = response.getWriter();
495-
writer.write(jsonError);
496-
writer.flush();
470+
private void responseError(HttpServletResponse response, int httpCode, Object requestId, JSONRPCError error)
471+
throws IOException {
472+
HttpServletResponseUtils.writeJsonResponse(response, httpCode, this.jsonMapper,
473+
McpSchema.JSONRPCResponse.error(requestId, error));
497474
}
498475

499476
/**

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

Lines changed: 26 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
import io.modelcontextprotocol.common.McpTransportContext;
1818
import io.modelcontextprotocol.server.McpStatelessServerHandler;
1919
import io.modelcontextprotocol.server.McpTransportContextExtractor;
20-
import io.modelcontextprotocol.spec.McpError;
2120
import io.modelcontextprotocol.spec.McpSchema;
21+
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
2222
import io.modelcontextprotocol.spec.McpStatelessServerTransport;
2323
import io.modelcontextprotocol.util.Assert;
2424
import jakarta.servlet.ServletException;
@@ -169,30 +169,30 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
169169
}
170170

171171
if (!HttpServletRequestUtils.isJsonContentType(request.getContentType())) {
172-
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
173-
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
174-
.message("Unsupported Media Type: Content-Type must be application/json")
175-
.build());
172+
this.responseError(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, null,
173+
new JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST,
174+
"Unsupported Media Type: Content-Type must be application/json"));
176175
return;
177176
}
178177

179178
String accept = request.getHeader(ACCEPT);
180179
if (accept == null || !(accept.contains(APPLICATION_JSON) && accept.contains(TEXT_EVENT_STREAM))) {
181-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
182-
McpError.builder(McpSchema.ErrorCodes.METHOD_NOT_FOUND)
183-
.message("Both application/json and text/event-stream required in Accept header")
184-
.build());
180+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, null,
181+
new JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND,
182+
"Both application/json and text/event-stream required in Accept header"));
185183
return;
186184
}
187185

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

188+
Object requestId = null;
190189
try {
191190
String body = HttpServletRequestUtils.readBody(request, this.requestMaxSize);
192191

193192
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
194193

195194
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest) {
195+
requestId = jsonrpcRequest.id();
196196
try {
197197
McpSchema.JSONRPCResponse jsonrpcResponse = this.mcpHandler
198198
.handleRequest(transportContext, jsonrpcRequest)
@@ -210,10 +210,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
210210
}
211211
catch (Exception e) {
212212
logger.error("Failed to handle request: {}", e.getMessage());
213-
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
214-
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
215-
.message("Failed to handle request: " + e.getMessage())
216-
.build());
213+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId,
214+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
215+
"Failed to handle request: " + e.getMessage()));
217216
}
218217
}
219218
else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
@@ -225,51 +224,42 @@ else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
225224
}
226225
catch (Exception e) {
227226
logger.error("Failed to handle notification: {}", e.getMessage());
228-
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
229-
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
230-
.message("Failed to handle notification: " + e.getMessage())
231-
.build());
227+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, new JSONRPCError(
228+
McpSchema.ErrorCodes.INTERNAL_ERROR, "Failed to handle notification: " + e.getMessage()));
232229
}
233230
}
234231
else {
235-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
236-
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST)
237-
.message("The server accepts either requests or notifications")
238-
.build());
232+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, null, new JSONRPCError(
233+
McpSchema.ErrorCodes.INVALID_REQUEST, "The server accepts either requests or notifications"));
239234
}
240235
}
241236
catch (MaxSizeExceededException e) {
242237
response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
243238
}
244239
catch (IllegalArgumentException | IOException e) {
245240
logger.error("Failed to deserialize message: {}", e.getMessage());
246-
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST,
247-
McpError.builder(McpSchema.ErrorCodes.INVALID_REQUEST).message("Invalid message format").build());
241+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, requestId,
242+
new JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST, "Invalid message format"));
248243
}
249244
catch (Exception e) {
250245
logger.error("Unexpected error handling message: {}", e.getMessage());
251-
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
252-
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
253-
.message("Unexpected error: " + e.getMessage())
254-
.build());
246+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId,
247+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, "Unexpected error: " + e.getMessage()));
255248
}
256249
}
257250

258251
/**
259252
* Sends an error response to the client.
260253
* @param response The HTTP servlet response
261254
* @param httpCode The HTTP status code
262-
* @param mcpError The MCP error to send
255+
* @param requestId The request ID, if available
256+
* @param error The protocol error to send
263257
* @throws IOException If an I/O error occurs
264258
*/
265-
private void responseError(HttpServletResponse response, int httpCode, McpError mcpError) throws IOException {
266-
response.setContentType(APPLICATION_JSON);
267-
response.setCharacterEncoding(UTF_8);
268-
response.setStatus(httpCode);
269-
String jsonError = jsonMapper.writeValueAsString(mcpError);
270-
PrintWriter writer = response.getWriter();
271-
writer.write(jsonError);
272-
writer.flush();
259+
private void responseError(HttpServletResponse response, int httpCode, Object requestId, JSONRPCError error)
260+
throws IOException {
261+
HttpServletResponseUtils.writeJsonResponse(response, httpCode, this.jsonMapper,
262+
McpSchema.JSONRPCResponse.error(requestId, error));
273263
}
274264

275265
/**

0 commit comments

Comments
 (0)