88 "bytes"
99 "context"
1010 "crypto/rand"
11+ "errors"
1112 "fmt"
1213 "io"
1314 "mime"
@@ -65,6 +66,12 @@ type SSEOptions struct {
6566 // Only disable this if you understand the security implications.
6667 // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
6768 DisableLocalhostProtection bool
69+
70+ // MaxRequestBodyBytes limits the number of bytes read from an incoming
71+ // POST body before the server responds with 413 Request Entity Too Large.
72+ // It matches [StreamableHTTPOptions.MaxRequestBodyBytes]: if zero,
73+ // [DefaultMaxRequestBodyBytes] is used; a negative value disables the limit.
74+ MaxRequestBodyBytes int64
6875}
6976
7077// NewSSEHandler returns a new [SSEHandler] that creates and manages MCP
@@ -122,6 +129,12 @@ type SSEServerTransport struct {
122129 // Response is the hanging response body to the incoming GET request.
123130 Response http.ResponseWriter
124131
132+ // MaxRequestBodyBytes limits the number of bytes read from a POSTed
133+ // message body before [SSEServerTransport.ServeHTTP] responds with 413
134+ // Request Entity Too Large. If zero, [DefaultMaxRequestBodyBytes] is used;
135+ // a negative value disables the limit. See [SSEOptions.MaxRequestBodyBytes].
136+ MaxRequestBodyBytes int64
137+
125138 // incoming is the queue of incoming messages.
126139 // It is never closed, and by convention, incoming is non-nil if and only if
127140 // the transport is connected.
@@ -143,9 +156,22 @@ func (t *SSEServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request)
143156 return
144157 }
145158
159+ limit := t .MaxRequestBodyBytes
160+ if limit == 0 {
161+ limit = DefaultMaxRequestBodyBytes
162+ }
163+ if limit > 0 && req .Body != nil {
164+ req .Body = http .MaxBytesReader (w , req .Body , limit )
165+ }
166+
146167 // Read and parse the message.
147168 data , err := io .ReadAll (req .Body )
148169 if err != nil {
170+ var mbe * http.MaxBytesError
171+ if errors .As (err , & mbe ) {
172+ http .Error (w , fmt .Sprintf ("request body exceeds %d bytes" , mbe .Limit ), http .StatusRequestEntityTooLarge )
173+ return
174+ }
149175 http .Error (w , "failed to read body" , http .StatusBadRequest )
150176 return
151177 }
@@ -260,7 +286,11 @@ func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
260286 return
261287 }
262288
263- transport := & SSEServerTransport {Endpoint : endpoint .RequestURI (), Response : w }
289+ transport := & SSEServerTransport {
290+ Endpoint : endpoint .RequestURI (),
291+ Response : w ,
292+ MaxRequestBodyBytes : h .opts .MaxRequestBodyBytes ,
293+ }
264294
265295 // The session is terminated when the request exits.
266296 h .mu .Lock ()
0 commit comments