55package io .modelcontextprotocol .server .transport ;
66
77import java .io .IOException ;
8- import java .io .PrintWriter ;
98import java .util .List ;
109
1110import org .slf4j .Logger ;
1716import io .modelcontextprotocol .common .McpTransportContext ;
1817import io .modelcontextprotocol .server .McpStatelessServerHandler ;
1918import io .modelcontextprotocol .server .McpTransportContextExtractor ;
20- import io .modelcontextprotocol .spec .McpError ;
2119import io .modelcontextprotocol .spec .McpSchema ;
20+ import io .modelcontextprotocol .spec .McpSchema .JSONRPCResponse .JSONRPCError ;
2221import io .modelcontextprotocol .spec .McpStatelessServerTransport ;
2322import io .modelcontextprotocol .util .Assert ;
2423import jakarta .servlet .ServletException ;
3332 *
3433 * @author Christian Tzolov
3534 * @author Dariusz Jędrzejczyk
35+ * @author Taewoong Kim
3636 */
3737@ WebServlet (asyncSupported = true )
3838public 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