Skip to content
Merged
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
5 changes: 4 additions & 1 deletion src/server/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): E
const { host = '127.0.0.1', allowedHosts } = options;

const app = express();
app.use(express.json());

// If allowedHosts is explicitly provided, use that for validation
if (allowedHosts) {
Expand All @@ -70,5 +69,9 @@ export function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): E
}
}

// The JSON body parser runs after the Host header validation, so a request
// with a disallowed Host is answered 403 without its body being read.
app.use(express.json());

return app;
}
63 changes: 63 additions & 0 deletions src/server/requestBody.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/** Default upper bound, in bytes, on a request body read by the HTTP entry points (4 MiB). */
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 4 * 1024 * 1024;

/** Upper bound on the number of messages accepted in one JSON-RPC batch array. */
export const MAX_BATCH_SIZE = 100;

/** The message answered with 413 for a request body over `maxBytes`. */
export function requestBodyTooLargeMessage(maxBytes: number): string {
return `Payload Too Large: Request body must not exceed ${maxBytes} bytes`;
}

/**
* Resolves a `maxRequestBodySize` option to the bound to apply: the default when
* omitted, otherwise the value itself, which must be a positive finite number of
* bytes (a `RangeError` is thrown at configuration time for anything else).
*/
export function resolveMaxRequestBodySize(value: number | undefined): number {
if (value === undefined) {
return DEFAULT_MAX_REQUEST_BODY_SIZE;
}
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(value)}`);
}
return value;
}

/**
* Reads a request body as text, up to `maxBytes` (default
* {@linkcode DEFAULT_MAX_REQUEST_BODY_SIZE}). A declared `Content-Length` over the
* limit is refused without reading anything; otherwise the read stops as soon as
* more than the limit has arrived. Stream failures propagate.
*/
export async function readRequestBody(
request: Request,
maxBytes: number = DEFAULT_MAX_REQUEST_BODY_SIZE
): Promise<{ tooLarge: true } | { tooLarge: false; text: string }> {
if (Number(request.headers.get('content-length')) > maxBytes) {
return { tooLarge: true };
}
if (request.body === null) {
return { tooLarge: false, text: '' };
}
const reader = request.body.getReader();
const decoder = new TextDecoder();
let received = 0;
let text = '';
try {
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
received += value.byteLength;
if (received > maxBytes) {
return { tooLarge: true };
}
text += decoder.decode(value, { stream: true });
}
} finally {
reader.releaseLock();
}
return { tooLarge: false, text: text + decoder.decode() };
}
26 changes: 24 additions & 2 deletions src/server/webStandardStreamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import { isJsonContentType } from '../shared/mediaType.js';
import { Transport } from '../shared/transport.js';
import { AuthInfo } from './auth/types.js';
import { MAX_BATCH_SIZE, readRequestBody, requestBodyTooLargeMessage, resolveMaxRequestBodySize } from './requestBody.js';
import { armSseKeepAlive, DEFAULT_SSE_KEEP_ALIVE_MS } from './sseKeepAlive.js';
import {
MessageExtraInfo,
Expand Down Expand Up @@ -159,14 +160,23 @@ export interface WebStandardStreamableHTTPServerTransportOptions {
* Defaults to `15000`; values below 1 (including `0`) disable keep-alive.
*/
keepAliveMs?: number;

/**
* Upper bound, in bytes, on a POST body the transport reads itself. A body
* over the bound (declared `Content-Length`, or observed while streaming)
* is answered `413` before anything is parsed. Not applied when the caller
* supplies `parsedBody`. Must be a positive number.
* @default 4194304 (4 MiB)
*/
maxRequestBodySize?: number;
}

/**
* Options for handling a request
*/
export interface HandleRequestOptions {
/**
* Pre-parsed request body. If provided, the transport will use this instead of parsing req.json().
* Pre-parsed request body. If provided, the transport will use this instead of reading and parsing the request body.
* Useful when using body-parser middleware that has already parsed the body.
*/
parsedBody?: unknown;
Expand Down Expand Up @@ -245,6 +255,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
private _enableDnsRebindingProtection: boolean;
private _retryInterval?: number;
private _keepAliveMs: number;
private _maxRequestBodySize: number;
private _closed = false;

sessionId?: string;
Expand All @@ -263,6 +274,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;
this._retryInterval = options.retryInterval;
this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS;
this._maxRequestBodySize = resolveMaxRequestBodySize(options.maxRequestBodySize);
}

/**
Expand Down Expand Up @@ -735,12 +747,22 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
rawMessage = options.parsedBody;
} else {
try {
rawMessage = await req.json();
const body = await readRequestBody(req, this._maxRequestBodySize);
if (body.tooLarge) {
const message = requestBodyTooLargeMessage(this._maxRequestBodySize);
this.onerror?.(new Error(message));
return this.createJsonErrorResponse(413, -32000, message);
}
rawMessage = JSON.parse(body.text);
} catch {
this.onerror?.(new Error('Parse error: Invalid JSON'));
return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON');
Comment on lines 757 to 759

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟣 Pre-existing (kept by this diff): the bare catch around the body read hard-codes 400/-32700 'Parse error: Invalid JSON' for all failures, including stream/read errors from readRequestBody, without discriminating the thrown cause — the repo review instructions (Recurring Catches: Error Handling) explicitly require flagging catch-alls that emit client-fault JSON-RPC codes for server/transport-internal failures.

Extended reasoning...

A client's connection drops (or the upstream stream errors) mid-upload of a POST body. readRequestBody propagates the stream failure, the catch at lines 757-759 swallows it, and the server answers 400 with JSON-RPC code -32700 'Parse error: Invalid JSON'. The client is told its request was malformed and may reformat/retry the same payload pointlessly, and onerror receives a fabricated parse error instead of the real network/stream error, hiding the actual cause from server operators.

Verification: pre-existing. The bare catch is real at HEAD src/server/webStandardStreamableHttp.ts:750-760: const body = await readRequestBody(req, this._maxRequestBodySize); ... rawMessage = JSON.parse(body.text); } catch { this.onerror?.(new Error('Parse error: Invalid JSON')); return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON'); }. src/server/requestBody.ts's readRequestBody expli

}
}
if (Array.isArray(rawMessage) && rawMessage.length > MAX_BATCH_SIZE) {
this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`));
return this.createJsonErrorResponse(400, -32600, `Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`);
}

let messages: JSONRPCMessage[];

Expand Down
29 changes: 29 additions & 0 deletions test/server/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2062,6 +2062,35 @@ describe('createMcpExpressApp', () => {
expect(app).toBeDefined();
});

test('validates the Host header before the JSON body parser runs', async () => {
const app = createMcpExpressApp();
app.post('/mcp', (req, res) => {
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 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 parse JSON bodies', async () => {
const app = createMcpExpressApp({ host: '0.0.0.0' }); // Disable host validation for this test
app.post('/test', (req, res) => {
Expand Down
109 changes: 109 additions & 0 deletions test/server/streamableHttp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4324,3 +4324,112 @@ describe('WebStandardStreamableHTTPServerTransport SSE keep-alive lifecycle', ()
expect(oncloseCalls).toBe(1);
});
});

describe('WebStandardStreamableHTTPServerTransport request body limits', () => {
/** A fresh stateless transport per request (a stateless transport serves one request). */
function stateless(maxRequestBodySize?: number): WebStandardStreamableHTTPServerTransport {
return new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, maxRequestBodySize });
}

function post(body: unknown, headers: Record<string, string> = {}): Request {
return new Request('http://localhost/mcp', {
method: 'POST',
headers: { Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body)
});
}

/** A POST whose body yields up to `chunks` 1 MiB chunks on demand, counting pulls. */
function streamedPost(chunks: number, headers: Record<string, string> = {}): { request: Request; 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(32));
}
},
{ highWaterMark: 0 }
);
const request = new Request('http://localhost/mcp', {
method: 'POST',
headers: { Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', ...headers },
body,
duplex: 'half'
} as RequestInit);
return { request, pulls: () => pulled };
}

it('answers 413 when Content-Length exceeds the body size limit without reading the body', async () => {
const { request, pulls } = streamedPost(1, { 'Content-Length': String(4 * 1024 * 1024 + 1) });
const response = await stateless().handleRequest(request);
expect(response.status).toBe(413);
expectErrorResponse(await response.json(), -32000, /Payload Too Large/);
expect(pulls()).toBe(0);
});

it('answers 413 once a streamed body without Content-Length exceeds the limit', async () => {
const { request, pulls } = streamedPost(8);
const response = await stateless().handleRequest(request);
expect(response.status).toBe(413);
expect(pulls()).toBeLessThan(8);
});

it('maxRequestBodySize sets the bound on both read paths and is validated at construction', async () => {
const declared = await stateless(1024).handleRequest(streamedPost(1, { 'Content-Length': '1025' }).request);
expect(declared.status).toBe(413);
expectErrorResponse(await declared.json(), -32000, /must not exceed 1024 bytes/);
const streamed = streamedPost(2);
const overLimit = await stateless(1024).handleRequest(streamed.request);
expect(overLimit.status).toBe(413);
expect(streamed.pulls()).toBe(1);

const roomy = stateless(8 * 1024 * 1024);
const onmessage = vi.fn();
roomy.onmessage = onmessage;
const padded: JSONRPCMessage = {
jsonrpc: '2.0',
method: 'notifications/initialized',
params: { pad: 'x'.repeat(5 * 1024 * 1024) }
};
const accepted = await roomy.handleRequest(post(padded));
expect(accepted.status).toBe(202);
expect(onmessage).toHaveBeenCalledTimes(1);

for (const invalid of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
expect(() => stateless(invalid)).toThrow(RangeError);
}
});

it('answers 400 for a JSON-RPC batch longer than 100 messages and dispatches none of it', async () => {
const batch = Array.from({ length: 101 }, (_, i): JSONRPCMessage => ({ jsonrpc: '2.0', method: 'ping', id: i }));
const onmessage = vi.fn();
const [reading, preParsing] = [stateless(), stateless()];
reading.onmessage = preParsing.onmessage = onmessage;
const read = await reading.handleRequest(post(batch));
const preParsed = await preParsing.handleRequest(post(batch), { parsedBody: batch });
for (const response of [read, preParsed]) {
expect(response.status).toBe(400);
expectErrorResponse(await response.json(), -32600, /Batch must not exceed 100 messages/);
}
expect(onmessage).not.toHaveBeenCalled();
});

it('StreamableHTTPServerTransport applies maxRequestBodySize to the Node request body', async () => {
const nodeTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, maxRequestBodySize: 1024 });
const server = createServer((req, res) => void nodeTransport.handleRequest(req, res));
const baseUrl = await listenOnRandomPort(server);
try {
const padded = { jsonrpc: '2.0', method: 'notifications/initialized', params: { pad: 'x'.repeat(2048) } } as JSONRPCMessage;
const response = await sendPostRequest(baseUrl, padded);
expect(response.status).toBe(413);
expectErrorResponse(await response.json(), -32000, /must not exceed 1024 bytes/);
} finally {
await nodeTransport.close();
server.close();
}
});
});
Loading