Skip to content

Commit 100f703

Browse files
committed
fix(server): use typed servlet JSON-RPC error responses
Share JSON response writing across servlet transports and preserve parsed request IDs. Allow error responses without an ID and use a fallback message for exceptions without messages. Signed-off-by: Taewoong Kim <ktw2172@gmail.com>
1 parent 01969f5 commit 100f703

12 files changed

Lines changed: 509 additions & 522 deletions

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

Lines changed: 0 additions & 61 deletions
This file was deleted.

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

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

77
import java.io.IOException;
8+
import java.io.PrintWriter;
9+
10+
import io.modelcontextprotocol.json.McpJsonMapper;
11+
import io.modelcontextprotocol.spec.McpSchema;
812

913
import jakarta.servlet.http.HttpServletResponse;
1014

1115
/**
1216
* Utility methods for working with {@link HttpServletResponse}. For internal use only.
1317
*
1418
* @author Daniel Garnier-Moiroux
19+
* @author Taewoong Kim
1520
*/
1621
final class HttpServletResponseUtils {
1722

@@ -20,6 +25,20 @@ final class HttpServletResponseUtils {
2025
private HttpServletResponseUtils() {
2126
}
2227

28+
/**
29+
* Writes a JSON-RPC response with the supplied HTTP status.
30+
*/
31+
static void writeJsonResponse(HttpServletResponse response, int httpStatus, McpJsonMapper jsonMapper,
32+
McpSchema.JSONRPCResponse jsonRpcResponse) throws IOException {
33+
String json = jsonMapper.writeValueAsString(jsonRpcResponse);
34+
response.setContentType("application/json");
35+
response.setCharacterEncoding("UTF-8");
36+
response.setStatus(httpStatus);
37+
PrintWriter writer = response.getWriter();
38+
writer.write(json);
39+
writer.flush();
40+
}
41+
2342
/**
2443
* Prepares the response for streaming Server-Sent Events: sets the content type and
2544
* the headers that keep intermediaries from caching, transforming or buffering the

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

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import java.time.Duration;
1010
import java.util.List;
1111
import java.util.Map;
12+
import java.util.Objects;
1213
import java.util.UUID;
1314
import java.util.concurrent.ConcurrentHashMap;
1415
import java.util.concurrent.atomic.AtomicBoolean;
@@ -18,8 +19,8 @@
1819
import io.modelcontextprotocol.json.McpJsonMapper;
1920
import io.modelcontextprotocol.json.TypeRef;
2021
import io.modelcontextprotocol.server.McpTransportContextExtractor;
21-
import io.modelcontextprotocol.spec.McpError;
2222
import io.modelcontextprotocol.spec.McpSchema;
23+
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
2324
import io.modelcontextprotocol.spec.McpServerSession;
2425
import io.modelcontextprotocol.spec.McpServerTransport;
2526
import io.modelcontextprotocol.spec.McpServerTransportProvider;
@@ -65,6 +66,7 @@
6566
* {@link HttpServletStreamableServerTransportProvider} or
6667
* {@link HttpServletStatelessServerTransport}.
6768
* @author Alexandros Pappas
69+
* @author Taewoong Kim
6870
* @see McpServerTransportProvider
6971
* @see HttpServlet
7072
* @see <a href=
@@ -376,29 +378,24 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
376378

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

385386
// Get the session ID from the request parameter
386387
String sessionId = request.getParameter("sessionId");
387388
if (sessionId == null) {
388389
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, null,
389-
McpError.builder(McpSchema.ErrorCodes.METHOD_NOT_FOUND)
390-
.message("Session ID missing in message endpoint")
391-
.build());
390+
new JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND, "Session ID missing in message endpoint"));
392391
return;
393392
}
394393

395394
// Get the session from the sessions map
396395
McpServerSession session = sessions.get(sessionId);
397396
if (session == null) {
398397
this.responseError(response, HttpServletResponse.SC_NOT_FOUND, null,
399-
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
400-
.message("Session not found: " + sessionId)
401-
.build());
398+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, "Session not found: " + sessionId));
402399
return;
403400
}
404401

@@ -408,7 +405,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
408405

409406
final McpTransportContext transportContext = this.contextExtractor.extract(request);
410407
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
411-
requestId = requestId(message);
408+
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest) {
409+
requestId = jsonrpcRequest.id();
410+
}
412411

413412
// Process the message through the session's handle method
414413
// Block for Servlet compatibility
@@ -422,10 +421,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
422421
catch (Exception e) {
423422
logger.error("Error processing message: {}", e.getMessage());
424423
try {
425-
McpError mcpError = McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
426-
.message(e.getMessage())
427-
.build();
428-
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId, mcpError);
424+
JSONRPCError error = new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
425+
Objects.requireNonNullElse(e.getMessage(), "Internal error"));
426+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId, error);
429427
}
430428
catch (IOException ex) {
431429
logger.error(FAILED_TO_SEND_ERROR_RESPONSE, ex.getMessage());
@@ -472,13 +470,10 @@ private void sendEvent(PrintWriter writer, String eventType, String data) throws
472470
}
473471
}
474472

475-
private void responseError(HttpServletResponse response, int httpCode, Object requestId, McpError mcpError)
473+
private void responseError(HttpServletResponse response, int httpCode, Object requestId, JSONRPCError error)
476474
throws IOException {
477-
HttpServletJsonRpcErrorWriter.writeError(this.jsonMapper, response, httpCode, requestId, mcpError);
478-
}
479-
480-
private static Object requestId(McpSchema.JSONRPCMessage message) {
481-
return (message instanceof McpSchema.JSONRPCRequest request) ? request.id() : null;
475+
McpSchema.JSONRPCResponse errorResponse = McpSchema.JSONRPCResponse.error(requestId, error);
476+
HttpServletResponseUtils.writeJsonResponse(response, httpCode, this.jsonMapper, errorResponse);
482477
}
483478

484479
/**

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

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

77
import java.io.IOException;
8-
import java.io.PrintWriter;
98
import java.util.List;
109

1110
import org.slf4j.Logger;
@@ -17,8 +16,8 @@
1716
import io.modelcontextprotocol.common.McpTransportContext;
1817
import io.modelcontextprotocol.server.McpStatelessServerHandler;
1918
import io.modelcontextprotocol.server.McpTransportContextExtractor;
20-
import io.modelcontextprotocol.spec.McpError;
2119
import io.modelcontextprotocol.spec.McpSchema;
20+
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
2221
import io.modelcontextprotocol.spec.McpStatelessServerTransport;
2322
import io.modelcontextprotocol.util.Assert;
2423
import jakarta.servlet.ServletException;
@@ -33,6 +32,7 @@
3332
*
3433
* @author Christian Tzolov
3534
* @author Dariusz Jędrzejczyk
35+
* @author Taewoong Kim
3636
*/
3737
@WebServlet(asyncSupported = true)
3838
public class HttpServletStatelessServerTransport extends HttpServlet implements McpStatelessServerTransport {
@@ -169,51 +169,44 @@ 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)
199199
.contextWrite(ctx -> ctx.put(McpTransportContext.KEY, transportContext))
200200
.block();
201201

202-
response.setContentType(APPLICATION_JSON);
203-
response.setCharacterEncoding(UTF_8);
204-
response.setStatus(HttpServletResponse.SC_OK);
205-
206-
String jsonResponseText = jsonMapper.writeValueAsString(jsonrpcResponse);
207-
PrintWriter writer = response.getWriter();
208-
writer.write(jsonResponseText);
209-
writer.flush();
202+
HttpServletResponseUtils.writeJsonResponse(response, HttpServletResponse.SC_OK, this.jsonMapper,
203+
jsonrpcResponse);
210204
}
211205
catch (Exception e) {
212206
logger.error("Failed to handle request: {}", e.getMessage());
213207
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, jsonrpcRequest.id(),
214-
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
215-
.message("Failed to handle request: " + e.getMessage())
216-
.build());
208+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
209+
"Failed to handle request: " + e.getMessage()));
217210
}
218211
}
219212
else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
@@ -225,50 +218,42 @@ else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
225218
}
226219
catch (Exception e) {
227220
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());
221+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, new JSONRPCError(
222+
McpSchema.ErrorCodes.INTERNAL_ERROR, "Failed to handle notification: " + e.getMessage()));
232223
}
233224
}
234225
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());
226+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, null, new JSONRPCError(
227+
McpSchema.ErrorCodes.INVALID_REQUEST, "The server accepts either requests or notifications"));
239228
}
240229
}
241230
catch (MaxSizeExceededException e) {
242231
response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
243232
}
244233
catch (IllegalArgumentException | IOException e) {
245234
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());
235+
this.responseError(response, HttpServletResponse.SC_BAD_REQUEST, requestId,
236+
new JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST, "Invalid message format"));
248237
}
249238
catch (Exception e) {
250239
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());
240+
this.responseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, requestId,
241+
new JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, "Unexpected error: " + e.getMessage()));
255242
}
256243
}
257244

258245
/**
259246
* Sends an error response to the client.
260247
* @param response The HTTP servlet response
261248
* @param httpCode The HTTP status code
262-
* @param mcpError The MCP error to send
249+
* @param requestId The request identifier, or null when unavailable
250+
* @param error The JSON-RPC error to send
263251
* @throws IOException If an I/O error occurs
264252
*/
265-
private void responseError(HttpServletResponse response, int httpCode, McpError mcpError) throws IOException {
266-
this.responseError(response, httpCode, null, mcpError);
267-
}
268-
269-
private void responseError(HttpServletResponse response, int httpCode, Object requestId, McpError mcpError)
253+
private void responseError(HttpServletResponse response, int httpCode, Object requestId, JSONRPCError error)
270254
throws IOException {
271-
HttpServletJsonRpcErrorWriter.writeError(this.jsonMapper, response, httpCode, requestId, mcpError);
255+
McpSchema.JSONRPCResponse errorResponse = McpSchema.JSONRPCResponse.error(requestId, error);
256+
HttpServletResponseUtils.writeJsonResponse(response, httpCode, this.jsonMapper, errorResponse);
272257
}
273258

274259
/**

0 commit comments

Comments
 (0)