Skip to content

Commit 7f67c85

Browse files
mcp: enforce body size limit in Stremable connection (#1055)
This PR enforces a body size limit on Streamable connection to prevent OOM attacks
1 parent 4c2aece commit 7f67c85

2 files changed

Lines changed: 140 additions & 1 deletion

File tree

‎mcp/streamable.go‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,25 @@ type StreamableHTTPOptions struct {
194194
// protection := http.NewCrossOriginProtection()
195195
// protectedHandler := protection.Handler(handler)
196196
CrossOriginProtection *http.CrossOriginProtection
197+
198+
// MaxRequestBodyBytes limits the number of bytes read from any incoming
199+
// HTTP request body. Requests that exceed this limit are rejected with
200+
// 413 Request Entity Too Large.
201+
//
202+
// The limit is enforced during the read, so it applies uniformly to
203+
// requests using Content-Length, Transfer-Encoding: chunked, or HTTP/2
204+
// (which has no Content-Length).
205+
//
206+
// If zero, [DefaultMaxRequestBodyBytes] is used.
207+
// A negative value disables the limit entirely; do not use this on
208+
// servers exposed to untrusted clients.
209+
MaxRequestBodyBytes int64
197210
}
198211

212+
// DefaultMaxRequestBodyBytes is the default value used for
213+
// [StreamableHTTPOptions.MaxRequestBodyBytes] when it is left at zero.
214+
const DefaultMaxRequestBodyBytes = 4 << 20 // 4 MiB
215+
199216
// NewStreamableHTTPHandler returns a new [StreamableHTTPHandler].
200217
//
201218
// The getServer function is used to create or look up servers for new
@@ -216,6 +233,10 @@ func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *Strea
216233
h.opts.CrossOriginProtection = &http.CrossOriginProtection{}
217234
}
218235

236+
if h.opts.MaxRequestBodyBytes == 0 {
237+
h.opts.MaxRequestBodyBytes = DefaultMaxRequestBodyBytes
238+
}
239+
219240
return h
220241
}
221242

@@ -308,6 +329,11 @@ func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Reque
308329
}
309330
}
310331

332+
// Bound the request body to protect against OOM attacks.
333+
if req.Body != nil && h.opts.MaxRequestBodyBytes > 0 {
334+
req.Body = http.MaxBytesReader(w, req.Body, h.opts.MaxRequestBodyBytes)
335+
}
336+
311337
// [§2.7] of the spec (2025-06-18): validate the MCP-Protocol-Version
312338
// header. If provided, it must be a supported version. If absent, the
313339
// version is unknown (the request may be an initialize for any version).
@@ -368,6 +394,11 @@ func (h *StreamableHTTPHandler) serveStateless(w http.ResponseWriter, req *http.
368394

369395
info, err := h.ephemeralConnectOpts(req)
370396
if err != nil {
397+
var mbe *http.MaxBytesError
398+
if errors.As(err, &mbe) {
399+
http.Error(w, fmt.Sprintf("request body exceeds %d bytes", mbe.Limit), http.StatusRequestEntityTooLarge)
400+
return
401+
}
371402
http.Error(w, err.Error(), http.StatusBadRequest)
372403
return
373404
}
@@ -435,7 +466,8 @@ func (h *StreamableHTTPHandler) ephemeralConnectOpts(req *http.Request) (*epheme
435466
var hasInitialize, hasInitialized, usesNewProtocol, isSubscriptionsListen bool
436467
body, err := io.ReadAll(req.Body)
437468
if err != nil {
438-
return nil, fmt.Errorf("failed to read body")
469+
// Preserve *http.MaxBytesError so serveStateless can respond with 413.
470+
return nil, fmt.Errorf("failed to read body: %w", err)
439471
}
440472
req.Body.Close()
441473
req.Body = io.NopCloser(bytes.NewBuffer(body))
@@ -1374,6 +1406,11 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques
13741406
// Read incoming messages.
13751407
body, err := io.ReadAll(req.Body)
13761408
if err != nil {
1409+
var mbe *http.MaxBytesError
1410+
if errors.As(err, &mbe) {
1411+
http.Error(w, fmt.Sprintf("request body exceeds %d bytes", mbe.Limit), http.StatusRequestEntityTooLarge)
1412+
return
1413+
}
13771414
http.Error(w, "failed to read body", http.StatusBadRequest)
13781415
return
13791416
}

‎mcp/streamable_test.go‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3802,3 +3802,105 @@ func TestStreamableServerRejectsDuplicateInFlightRequestID(t *testing.T) {
38023802
default:
38033803
}
38043804
}
3805+
3806+
// TestStreamableMaxRequestBodyBytes verifies that the streamable HTTP handler
3807+
// enforces StreamableHTTPOptions.MaxRequestBodyBytes on incoming request
3808+
// bodies. The limit must apply uniformly regardless of transfer encoding:
3809+
// Content-Length, Transfer-Encoding: chunked, or HTTP/2 (which has no
3810+
// Content-Length).
3811+
func TestStreamableMaxRequestBodyBytes(t *testing.T) {
3812+
// A minimally-valid JSON-RPC initialize request. The body-size check runs
3813+
// before parsing, so exact contents don't matter for the reject cases,
3814+
// but we use a real one for the "under limit" success case.
3815+
validInit := []byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"v1"}}}`)
3816+
3817+
// Build a payload of the requested size by padding a JSON object. The
3818+
// server doesn't need to parse it; the MaxBytesReader trips first.
3819+
oversizedBody := func(n int) []byte {
3820+
b := make([]byte, n)
3821+
b[0] = '{'
3822+
for i := 1; i < n-1; i++ {
3823+
b[i] = ' '
3824+
}
3825+
b[n-1] = '}'
3826+
return b
3827+
}
3828+
3829+
tests := []struct {
3830+
name string
3831+
limit int64 // value assigned to MaxRequestBodyBytes
3832+
body []byte
3833+
wantStatus int
3834+
wantStatusDesc string
3835+
}{
3836+
{
3837+
name: "default limit rejects oversized",
3838+
limit: 0, // triggers DefaultMaxRequestBodyBytes (4 MiB)
3839+
body: oversizedBody(DefaultMaxRequestBodyBytes + 1),
3840+
wantStatus: http.StatusRequestEntityTooLarge,
3841+
wantStatusDesc: "413 for body > 4MiB default",
3842+
},
3843+
{
3844+
name: "custom limit rejects oversized",
3845+
limit: 1024,
3846+
body: oversizedBody(2048),
3847+
wantStatus: http.StatusRequestEntityTooLarge,
3848+
wantStatusDesc: "413 for body > custom 1KiB limit",
3849+
},
3850+
{
3851+
name: "chunked encoding does not bypass limit",
3852+
limit: 1024,
3853+
body: oversizedBody(4096),
3854+
wantStatus: http.StatusRequestEntityTooLarge,
3855+
wantStatusDesc: "413 for chunked body > limit (regression: Content-Length-only checks are bypassable)",
3856+
},
3857+
{
3858+
name: "negative limit disables the check",
3859+
limit: -1,
3860+
body: oversizedBody(2 * DefaultMaxRequestBodyBytes),
3861+
wantStatus: http.StatusBadRequest, // body is not valid JSON-RPC; but the size check must not fire
3862+
wantStatusDesc: "not 413 when limit is disabled",
3863+
},
3864+
{
3865+
name: "under limit succeeds",
3866+
limit: 64 * 1024,
3867+
body: validInit,
3868+
wantStatus: http.StatusOK,
3869+
wantStatusDesc: "200 for a valid initialize under the limit",
3870+
},
3871+
}
3872+
3873+
for _, tc := range tests {
3874+
t.Run(tc.name, func(t *testing.T) {
3875+
server := NewServer(testImpl, nil)
3876+
handler := NewStreamableHTTPHandler(
3877+
func(*http.Request) *Server { return server },
3878+
&StreamableHTTPOptions{
3879+
Stateless: true,
3880+
MaxRequestBodyBytes: tc.limit,
3881+
},
3882+
)
3883+
ts := httptest.NewServer(handler)
3884+
defer ts.Close()
3885+
3886+
req, err := http.NewRequest(http.MethodPost, ts.URL, bytes.NewReader(tc.body))
3887+
if err != nil {
3888+
t.Fatalf("NewRequest: %v", err)
3889+
}
3890+
req.Header.Set("Content-Type", "application/json")
3891+
req.Header.Set("Accept", "application/json, text/event-stream")
3892+
3893+
resp, err := ts.Client().Do(req)
3894+
if err != nil {
3895+
t.Fatalf("Do: %v", err)
3896+
}
3897+
defer resp.Body.Close()
3898+
body, _ := io.ReadAll(resp.Body)
3899+
3900+
if resp.StatusCode != tc.wantStatus {
3901+
t.Fatalf("%s: status = %d, want %d (body=%q)",
3902+
tc.wantStatusDesc, resp.StatusCode, tc.wantStatus, string(body))
3903+
}
3904+
})
3905+
}
3906+
}

0 commit comments

Comments
 (0)