Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .changeset/request-body-size-limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
'@modelcontextprotocol/server': patch
'@modelcontextprotocol/node': patch
'@modelcontextprotocol/hono': patch
'@modelcontextprotocol/express': patch
---

Read Streamable HTTP request bodies with a size limit. Every SDK-owned body read —
`WebStandardStreamableHTTPServerTransport` (and the Node transport built on it),
`createMcpHandler`, `toNodeHandler`, and `createMcpHonoApp`'s JSON pre-parse — now stops at
4 MiB by default (the limit the legacy SSE transport already uses; the Express adapter and stdio
bound their reads too) and answers `413 Payload Too Large` before anything is parsed.
`toWebRequest` (when it reads the Node stream itself) now rejects once the body exceeds the
limit with an error whose `name` is `'RequestBodyTooLargeError'` and `status` is `413`, and
`toNodeHandler` answers that with `413`; hand-wired callers of `toWebRequest` should handle the
rejection or pass a pre-parsed body, and `isLegacyRequest` reports such a request as non-legacy
so the modern handler answers it. JSON-RPC batch arrays are limited to 100 messages; a longer
batch is answered `400` / `-32600` and none of it is dispatched.

The limit is configurable with a new `maxRequestBodySize` option (bytes, default

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 nit: new user-facing behavior (default 4 MiB body cap answering 413, 100-message batch cap answering 400) and the new maxRequestBodySize option on four public surfaces are documented only in this changeset and JSDoc — no docs/ guide page is updated. REVIEW.md's checklist explicitly requires prose documentation (not just JSDoc) for new features and a check that existing docs don't omit new behavior; the serving guides are exactly where the sibling knobs already live: docs/serving/legacy-clients.md:96 tells users to raise jsonLimit to '4mb' because "the SSE transport itself accepts messages up to 4mb", and docs/serving/express.md… [also at: packages/server/src/index.ts:78 - nit: new public feature ships with zero prose documentation under docs/ — the maxRequestBodySize option (added to…]

Extended reasoning...

An operator whose MCP server accepts large tool arguments (e.g. base64 images) follows docs/serving/express.md or docs/serving/http.md to deploy after upgrading; clients start receiving 413 for >4 MiB POSTs. The guides they were told to follow never mention the limit, the maxRequestBodySize option, or that on the toNodeHandler path both the adapter's and the handler's bound must be raised in step, so they either misdiagnose the 413 as a proxy problem or raise only CreateMcpHandlerOptions.maxRequestBodySize and still get 413 from the adapter's default bound. The only discoverable documentation is a CHANGELOG entry and per-symbol JSDoc.

Verification: nit. The omission is real. The diff stat shows no docs/** file is touched (13 changed files, all under .changeset/ and packages/), yet the change introduces user-facing behavior and a new public option on four surfaces: .changeset/request-body-size-limit.md states "now stops at 4 MiB by default ... and answers 413 Payload Too Large", "JSON-RPC batch arrays are limited to 100 messages;

`DEFAULT_MAX_REQUEST_BODY_SIZE` = 4 MiB, exported from `@modelcontextprotocol/server`) on
`WebStandardStreamableHTTPServerTransportOptions`, `CreateMcpHandlerOptions` (forwarded to its
stateless legacy leg; `isLegacyRequest` and `legacyStatelessFallback` take the same option),
`CreateMcpHonoAppOptions`, and `ToNodeHandlerOptions` / `ToWebRequestOptions` (the adapter's
bound applies before the handler's, so raise both). The bounded reader is exported as
`readRequestBody` for adapter authors. Hosts that pre-parse the body and pass it as
`parsedBody` skip the SDK's read and its size limit entirely; the batch bound applies either way.

`createMcpHonoApp` and `createMcpExpressApp` now run their Host/Origin validation before the
JSON body parser, so a request from a disallowed Host or Origin with an invalid JSON body is
answered `403` rather than `400`, and its body is not read.
5 changes: 4 additions & 1 deletion packages/middleware/express/src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): E
const { host = '127.0.0.1', allowedHosts, allowedOrigins, jsonLimit } = options;

const app = express();
app.use(express.json(jsonLimit ? { limit: jsonLimit } : undefined));

// If allowedHosts is explicitly provided, use that for validation
if (allowedHosts) {
Expand Down Expand Up @@ -106,5 +105,9 @@ export function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): E
app.use(localhostOriginValidation());
}

// The JSON body parser runs after the Host/Origin validation, so a request
// from a disallowed origin is answered 403 without its body being read.
app.use(express.json(jsonLimit ? { limit: jsonLimit } : undefined));

return app;
}
38 changes: 38 additions & 0 deletions packages/middleware/express/test/express.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { NextFunction, Request, Response } from 'express';
import supertest from 'supertest';
import { vi } from 'vitest';

import { createMcpExpressApp } from '../src/express';
Expand Down Expand Up @@ -107,6 +108,43 @@ describe('@modelcontextprotocol/express', () => {
});

describe('createMcpExpressApp', () => {
test('validates Host/Origin before the JSON body parser runs', async () => {
const app = createMcpExpressApp();
app.post('/mcp', (req: Request, res: Response) => {
res.json({ parsed: req.body });
});

const disallowedHost = await supertest(app)
.post('/mcp')
.set('Host', 'evil.example.com')
.set('Content-Type', 'application/json')
.send('{not json');
expect(disallowedHost.status).toBe(403);

const disallowedOrigin = await supertest(app)
.post('/mcp')
.set('Host', 'localhost:3000')
.set('Origin', 'http://evil.example.com')
.set('Content-Type', 'application/json')
.send('{not json');
expect(disallowedOrigin.status).toBe(403);

const invalidJson = await supertest(app)
.post('/mcp')
.set('Host', 'localhost:3000')
.set('Content-Type', 'application/json')
.send('{not json');
expect(invalidJson.status).toBe(400);

const allowed = await supertest(app)
.post('/mcp')
.set('Host', 'localhost:3000')
.set('Content-Type', 'application/json')
.send({ ok: true });
expect(allowed.status).toBe(200);
expect(allowed.body).toEqual({ parsed: { ok: true } });
});

test('should enable localhost DNS rebinding protection by default', () => {
const app = createMcpExpressApp();

Expand Down
94 changes: 66 additions & 28 deletions packages/middleware/hono/src/hono.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isJsonContentType } from '@modelcontextprotocol/server';
import { DEFAULT_MAX_REQUEST_BODY_SIZE, isJsonContentType, readRequestBody } from '@modelcontextprotocol/server';
import type { Context } from 'hono';
import { Hono } from 'hono';

Expand Down Expand Up @@ -36,6 +36,28 @@ export interface CreateMcpHonoAppOptions {
* is rejected with `403`.
*/
allowedOrigins?: string[];

/**
* Upper bound, in bytes, on a JSON request body the app's body-parsing
* middleware reads. A larger body is answered `413` before being parsed.
* Must be a positive number. The counterpart of `createMcpExpressApp`'s
* `jsonLimit`.
* @default 4194304 (4 MiB)
*/
maxRequestBodySize?: number;
}

/**
* Reads (bounded, via the transport's own reader) and parses a JSON body from a
* clone of the request, so the original stream stays readable. Returning only the
* parsed value keeps the decoded text from outliving the parse.
*/
async function parseJsonBody(request: Request, maxBytes: number): Promise<{ tooLarge: true } | { tooLarge: false; value: unknown }> {
const body = await readRequestBody(request, maxBytes);
if (body.tooLarge) {
return { tooLarge: true };
}
return { tooLarge: false, value: JSON.parse(body.text) };
}

/**
Expand All @@ -47,42 +69,21 @@ export interface CreateMcpHonoAppOptions {
*
* This also installs a small JSON body parsing middleware (similar to `express.json()`)
* that stashes the parsed body into `c.set('parsedBody', ...)` when the `Content-Type`
* media type is `application/json`.
* media type is `application/json`. It runs after the Host/Origin validation, and JSON
* bodies over `maxRequestBodySize` (4 MiB by default) are answered `413` before being parsed.
*
* @param options - Configuration options
* @returns A configured Hono application
*/
export function createMcpHonoApp(options: CreateMcpHonoAppOptions = {}): Hono {
const { host = '127.0.0.1', allowedHosts, allowedOrigins } = options;
const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE;
if (typeof maxRequestBodySize !== 'number' || !Number.isFinite(maxRequestBodySize) || maxRequestBodySize <= 0) {
throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(maxRequestBodySize)}`);
}

const app = new Hono();

// Similar to `express.json()`: parse JSON bodies and make them available to MCP adapters via `parsedBody`.
app.use('*', async (c: Context, next) => {
// If an upstream middleware already set parsedBody, keep it.
if (c.get('parsedBody') !== undefined) {
return await next();
}

// Parsed media type, never a substring match — see isJsonContentType.
// A body left unparsed here is answered 415 by the transport's own
// Content-Type check downstream.
if (!isJsonContentType(c.req.header('content-type'))) {
return await next();
}

try {
// Parse from a clone so we don't consume the original request stream.
const parsed = await c.req.raw.clone().json();
c.set('parsedBody', parsed);
} catch {
// Mirror express.json() behavior loosely: reject invalid JSON.
return c.text('Invalid JSON', 400);
}

return await next();
});

// If allowedHosts is explicitly provided, use that for validation.
if (allowedHosts) {
app.use('*', hostHeaderValidation(allowedHosts));
Expand Down Expand Up @@ -111,5 +112,42 @@ export function createMcpHonoApp(options: CreateMcpHonoAppOptions = {}): Hono {
app.use('*', localhostOriginValidation());
}

// Similar to `express.json()`: parse JSON bodies (up to maxRequestBodySize; larger ones are
// answered 413) and make them available to MCP adapters via `parsedBody`.
app.use('*', async (c: Context, next) => {
// If an upstream middleware already set parsedBody, keep it.
if (c.get('parsedBody') !== undefined) {
return await next();
}

// Parsed media type, never a substring match — see isJsonContentType.
// A body left unparsed here is answered 415 by the transport's own
// Content-Type check downstream.
if (!isJsonContentType(c.req.header('content-type'))) {
return await next();
}

try {
// Parse from a clone so we don't consume the original request stream.
const parsed = await parseJsonBody(c.req.raw.clone(), maxRequestBodySize);
if (parsed.tooLarge) {
return c.json(
{
jsonrpc: '2.0',
error: { code: -32_000, message: `Payload Too Large: Request body must not exceed ${maxRequestBodySize} bytes` },
id: null
},
413
);
}
c.set('parsedBody', parsed.value);
} catch {
// Mirror express.json() behavior loosely: reject invalid JSON.
return c.text('Invalid JSON', 400);
}

return await next();
});

return app;
}
85 changes: 85 additions & 0 deletions packages/middleware/hono/test/hono.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,89 @@ describe('@modelcontextprotocol/hono', () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ preset: true });
});

/** A body that yields up to `chunks` 1 MiB chunks on demand (no Content-Length), counting pulls. */
function streamedBody(chunks: number): { body: ReadableStream<Uint8Array>; pulls: () => number } {
let pulled = 0;
const body = new ReadableStream<Uint8Array>(
{
pull(controller) {
if (pulled >= chunks) {
return controller.close();
}
pulled++;
controller.enqueue(new Uint8Array(1024 * 1024).fill(0x20));
}
},
{ highWaterMark: 0 }
);
return { body, pulls: () => pulled };
}
const jsonHeaders = { Host: 'localhost:3000', 'content-type': 'application/json' };

test('createMcpHonoApp rejects a disallowed Host before reading the body', async () => {
const app = createMcpHonoApp();
app.post('/echo', (c: Context) => c.text('ok'));

const { body, pulls } = streamedBody(1);
const init = { method: 'POST', headers: { ...jsonHeaders, Host: 'example.com:3000' }, body, duplex: 'half' };
const res = await app.request('http://localhost/echo', init as RequestInit);
expect(res.status).toBe(403);
expect(pulls()).toBe(0);
});

test('createMcpHonoApp answers 413 for a JSON body over the size limit', async () => {
const app = createMcpHonoApp();
app.post('/echo', (c: Context) => c.text('ok'));

const declared = streamedBody(5);
const declaredOverLimit = { ...jsonHeaders, 'content-length': String(4 * 1024 * 1024 + 1) };
const res = await app.request('http://localhost/echo', {
method: 'POST',
headers: declaredOverLimit,
body: declared.body,
duplex: 'half'
} as RequestInit);
expect(res.status).toBe(413);
expect(await res.json()).toEqual({
jsonrpc: '2.0',
error: { code: -32_000, message: expect.stringMatching(/^Payload Too Large/) },
id: null
});
// clone() tees the body, which buffers one chunk up front; nothing past that is read.
expect(declared.pulls()).toBeLessThanOrEqual(1);

const streamed = await app.request('http://localhost/echo', {
method: 'POST',
headers: jsonHeaders,
body: streamedBody(5).body,
duplex: 'half'
} as RequestInit);
expect(streamed.status).toBe(413);
expect(((await streamed.json()) as { error: { code: number } }).error.code).toBe(-32_000);
});

test('createMcpHonoApp maxRequestBodySize moves the pre-parse bound and is validated', async () => {
const strict = createMcpHonoApp({ maxRequestBodySize: 1024 });
strict.post('/echo', (c: Context) => c.text('ok'));
const refused = await strict.request('http://localhost/echo', {
method: 'POST',
headers: jsonHeaders,
body: JSON.stringify({ pad: 'x'.repeat(2048) })
});
expect(refused.status).toBe(413);
expect(((await refused.json()) as { error: { message: string } }).error.message).toMatch(/must not exceed 1024 bytes/);

const roomy = createMcpHonoApp({ maxRequestBodySize: 8 * 1024 * 1024 });
roomy.post('/echo', (c: Context) => c.json({ keys: Object.keys(c.get('parsedBody') as object) }));
const served = await roomy.request('http://localhost/echo', {
method: 'POST',
headers: jsonHeaders,
body: JSON.stringify({ pad: 'x'.repeat(5 * 1024 * 1024) })
});
expect(served.status).toBe(200);
expect(await served.json()).toEqual({ keys: ['pad'] });

expect(() => createMcpHonoApp({ maxRequestBodySize: 0 })).toThrow(RangeError);
});
});
Loading
Loading