44
55package io .modelcontextprotocol .server .transport ;
66
7- import java .io .BufferedReader ;
87import java .io .IOException ;
98import java .io .PrintWriter ;
109import java .time .Duration ;
7069@ WebServlet (asyncSupported = true )
7170public class HttpServletSseServerTransportProvider extends HttpServlet implements McpServerTransportProvider {
7271
72+ /**
73+ * Default maximum size of a single request body: 16 MiB (16 * 1024 * 1024 bytes).
74+ */
75+ private static final int DEFAULT_REQUEST_MAX_SIZE = 16 * 1024 * 1024 ;
76+
7377 /**
7478 * Logger for this class
7579 */
@@ -105,6 +109,11 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement
105109 */
106110 private final McpJsonMapper jsonMapper ;
107111
112+ /**
113+ * Maximum size, in bytes, of a single request body accepted by this transport.
114+ */
115+ private final int requestMaxSize ;
116+
108117 /**
109118 * Base URL for the server transport
110119 */
@@ -160,24 +169,28 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement
160169 * keep-alive functionality
161170 * @param contextExtractor The extractor for transport context from the request.
162171 * @param securityValidator The security validator for validating HTTP requests.
172+ * @param requestMaxSize The maximum size, in bytes, of a single request body. Must be
173+ * positive.
163174 */
164175 private HttpServletSseServerTransportProvider (McpJsonMapper jsonMapper , String baseUrl , String messageEndpoint ,
165176 String sseEndpoint , Duration keepAliveInterval ,
166177 McpTransportContextExtractor <HttpServletRequest > contextExtractor ,
167- ServerTransportSecurityValidator securityValidator ) {
178+ ServerTransportSecurityValidator securityValidator , int requestMaxSize ) {
168179
169180 Assert .notNull (jsonMapper , "JsonMapper must not be null" );
170181 Assert .notNull (messageEndpoint , "messageEndpoint must not be null" );
171182 Assert .notNull (sseEndpoint , "sseEndpoint must not be null" );
172183 Assert .notNull (contextExtractor , "Context extractor must not be null" );
173184 Assert .notNull (securityValidator , "Security validator must not be null" );
185+ Assert .isTrue (requestMaxSize > 0 , "requestMaxSize must be positive" );
174186
175187 this .jsonMapper = jsonMapper ;
176188 this .baseUrl = baseUrl ;
177189 this .messageEndpoint = messageEndpoint ;
178190 this .sseEndpoint = sseEndpoint ;
179191 this .contextExtractor = contextExtractor ;
180192 this .securityValidator = securityValidator ;
193+ this .requestMaxSize = requestMaxSize ;
181194
182195 if (keepAliveInterval != null ) {
183196
@@ -340,6 +353,11 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
340353 return ;
341354 }
342355
356+ if (request .getContentLengthLong () > this .requestMaxSize ) {
357+ response .sendError (HttpServletResponse .SC_REQUEST_ENTITY_TOO_LARGE );
358+ return ;
359+ }
360+
343361 String requestURI = request .getRequestURI ();
344362 if (!requestURI .endsWith (messageEndpoint )) {
345363 response .sendError (HttpServletResponse .SC_NOT_FOUND );
@@ -386,22 +404,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
386404 }
387405
388406 try {
389- BufferedReader reader = request .getReader ();
390- StringBuilder body = new StringBuilder ();
391- String line ;
392- while ((line = reader .readLine ()) != null ) {
393- body .append (line );
394- }
407+ String body = HttpServletRequestUtils .readBody (request , this .requestMaxSize );
395408
396409 final McpTransportContext transportContext = this .contextExtractor .extract (request );
397- McpSchema .JSONRPCMessage message = McpSchema .deserializeJsonRpcMessage (jsonMapper , body . toString () );
410+ McpSchema .JSONRPCMessage message = McpSchema .deserializeJsonRpcMessage (jsonMapper , body );
398411
399412 // Process the message through the session's handle method
400413 // Block for Servlet compatibility
401414 session .handle (message ).contextWrite (ctx -> ctx .put (McpTransportContext .KEY , transportContext )).block ();
402415
403416 response .setStatus (HttpServletResponse .SC_OK );
404417 }
418+ catch (MaxSizeExceededException e ) {
419+ response .sendError (HttpServletResponse .SC_REQUEST_ENTITY_TOO_LARGE );
420+ }
405421 catch (Exception e ) {
406422 logger .error ("Error processing message: {}" , e .getMessage ());
407423 try {
@@ -599,6 +615,8 @@ public static class Builder {
599615
600616 private ServerTransportSecurityValidator securityValidator = ServerTransportSecurityValidator .NOOP ;
601617
618+ private int requestMaxSize = DEFAULT_REQUEST_MAX_SIZE ;
619+
602620 /**
603621 * Sets the JsonMapper implementation to use for serialization/deserialization. If
604622 * not specified, a JacksonJsonMapper will be created from the configured
@@ -685,6 +703,19 @@ public Builder securityValidator(ServerTransportSecurityValidator securityValida
685703 return this ;
686704 }
687705
706+ /**
707+ * Sets the maximum size, in bytes, of a single request body accepted by this
708+ * transport. Requests whose body exceeds this size are rejected with a 413
709+ * (Payload Too Large) response. Defaults to 16 MiB if not set.
710+ * @param requestMaxSize The maximum request body size, in bytes. Must be
711+ * positive.
712+ * @return This builder instance
713+ */
714+ public Builder maxRequestSize (int requestMaxSize ) {
715+ this .requestMaxSize = requestMaxSize ;
716+ return this ;
717+ }
718+
688719 /**
689720 * Builds a new instance of HttpServletSseServerTransportProvider with the
690721 * configured settings.
@@ -697,7 +728,7 @@ public HttpServletSseServerTransportProvider build() {
697728 }
698729 return new HttpServletSseServerTransportProvider (
699730 jsonMapper == null ? McpJsonDefaults .getMapper () : jsonMapper , baseUrl , messageEndpoint ,
700- sseEndpoint , keepAliveInterval , contextExtractor , securityValidator );
731+ sseEndpoint , keepAliveInterval , contextExtractor , securityValidator , requestMaxSize );
701732 }
702733
703734 }
0 commit comments