@@ -425,14 +425,32 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
425425
426426 McpTransportContext transportContext = this .contextExtractor .extract (request );
427427
428- try {
429- HttpServletResponseUtils .prepareSseResponse (response );
428+ // Before getWriter(): the character encoding is ignored once the writer is taken
429+ HttpServletResponseUtils .prepareSseResponse (response );
430430
431- AsyncContext asyncContext = request .startAsync ();
431+ PrintWriter writer ;
432+ AsyncContext asyncContext ;
433+ try {
434+ writer = response .getWriter ();
435+ asyncContext = request .startAsync ();
432436 asyncContext .setTimeout (0 );
437+ }
438+ catch (Exception e ) {
439+ // A deployment error, such as a servlet or filter not supporting async.
440+ // Nothing has been sent and async has not started, so an error status can
441+ // still be returned
442+ logger .error ("Failed to start the GET stream for session {}: {}" , sessionId , e .getMessage ());
443+ response .sendError (HttpServletResponse .SC_INTERNAL_SERVER_ERROR );
444+ return ;
445+ }
433446
434- HttpServletStreamableMcpSessionTransport sessionTransport = new HttpServletStreamableMcpSessionTransport (
435- sessionId , asyncContext , response .getWriter ());
447+ // From here on the headers may already be sent: a failure can only end the stream
448+ HttpServletStreamableMcpSessionTransport sessionTransport = new HttpServletStreamableMcpSessionTransport (
449+ sessionId , asyncContext , writer );
450+ try {
451+ // Send the status line and headers now: the listening stream may stay idle
452+ // for a long time, and clients wait for the headers before reading events
453+ response .flushBuffer ();
436454
437455 // Replay the messages the client missed while its stream was broken
438456 String lastEventId = request .getHeader (HttpHeaders .LAST_EVENT_ID );
@@ -450,9 +468,14 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
450468
451469 registerAsyncLifecycle (asyncContext , sessionId , listeningStream ::releaseTransport );
452470 }
471+ catch (IOException e ) {
472+ // Only flushing the headers throws it: the client is gone
473+ logger .debug ("Failed to send the GET stream headers for session {}: {}" , sessionId , e .getMessage ());
474+ sessionTransport .close ();
475+ }
453476 catch (Exception e ) {
454477 logger .error ("Failed to handle GET request for session {}: {}" , sessionId , e .getMessage ());
455- response . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR );
478+ sessionTransport . close ( );
456479 }
457480 }
458481
@@ -597,28 +620,56 @@ else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
597620 response .setStatus (HttpServletResponse .SC_ACCEPTED );
598621 }
599622 else if (message instanceof McpSchema .JSONRPCRequest jsonrpcRequest ) {
600- // For streaming responses, we need to return SSE
623+ // For streaming responses, we need to return SSE. Before getWriter(): the
624+ // character encoding is ignored once the writer is taken
601625 HttpServletResponseUtils .prepareSseResponse (response );
602626
603- AsyncContext asyncContext = request .startAsync ();
604- asyncContext .setTimeout (0 );
627+ PrintWriter writer ;
628+ AsyncContext asyncContext ;
629+ try {
630+ writer = response .getWriter ();
631+ asyncContext = request .startAsync ();
632+ asyncContext .setTimeout (0 );
633+ }
634+ catch (Exception e ) {
635+ // A deployment error, such as a servlet or filter not supporting
636+ // async. Nothing has been sent and async has not started, so an error
637+ // status can still be returned
638+ logger .error ("Failed to start the request stream for session {}: {}" , sessionId , e .getMessage ());
639+ response .sendError (HttpServletResponse .SC_INTERNAL_SERVER_ERROR );
640+ return ;
641+ }
605642
643+ // From here on the headers may already be sent: a failure can only end
644+ // the stream
606645 HttpServletStreamableMcpSessionTransport sessionTransport = new HttpServletStreamableMcpSessionTransport (
607- sessionId , asyncContext , response .getWriter ());
608-
609- // The listener is given the stream rather than its transport, so that the
610- // end of the connection detaches the stream from the session instead of
611- // only dropping the socket: a stream outliving its connection keeps the
612- // session looking busy and spares it from the sweeper
613- McpStreamableServerSession .McpStreamableServerSessionStream responseStream = session
614- .responseStream (sessionTransport );
615- registerAsyncLifecycle (asyncContext , sessionId , responseStream ::releaseTransport );
616-
646+ sessionId , asyncContext , writer );
617647 try {
648+ // The listener is given the stream rather than its transport, so that
649+ // the end of the connection detaches the stream from the session
650+ // instead of only dropping the socket: a stream outliving its
651+ // connection keeps the session looking busy and spares it from the
652+ // sweeper
653+ McpStreamableServerSession .McpStreamableServerSessionStream responseStream = session
654+ .responseStream (sessionTransport );
655+ registerAsyncLifecycle (asyncContext , sessionId , responseStream ::releaseTransport );
656+
657+ // Send the status line and headers now: the request may take a long
658+ // time to answer, and clients wait for the headers before reading
659+ // events
660+ response .flushBuffer ();
661+
618662 responseStream .handle (jsonrpcRequest )
619663 .contextWrite (ctx -> ctx .put (McpTransportContext .KEY , transportContext ))
620664 .block ();
621665 }
666+ catch (IOException e ) {
667+ // Only flushing the headers throws it: the client is gone, and the
668+ // request is not handled
669+ logger .debug ("Failed to send the request stream headers for session {}: {}" , sessionId ,
670+ e .getMessage ());
671+ sessionTransport .close ();
672+ }
622673 catch (Exception e ) {
623674 logger .error ("Failed to handle request stream: {}" , e .getMessage ());
624675 // The transport may already have completed the async context, when
0 commit comments