The Open Framework for Building Agents
fix(eve): bound MCP request sizes (#2992)
Colton Padden2c2c552f0562
diff --git a/.changeset/mcp-request-size-limits.md b/.changeset/mcp-request-size-limits.mdnew file mode 100644index 000000000..619f5d6de--- /dev/null+++ b/.changeset/mcp-request-size-limits.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The MCP channel now bounds every request: bodies over 1 MiB receive a JSON-RPC `413` before the transport reads them, and `agent_start.message` (64 KiB), input-response `text` (16 KiB), IDs (256 chars), and responses per update (64) are validated before any session is created.diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdxindex 6cc24908a..aa8eaa922 100644--- a/docs/channels/mcp.mdx+++ b/docs/channels/mcp.mdx@@ -202,7 +202,7 @@ A tool result with `isError: true` means the call itself was rejected. A `failedCancellation is cooperative, so call `agent_get` after `agent_cancel` until the state becomes terminal.-Optional output schemas are limited to 64 KiB, 32 levels, and 2,048 nodes. External `$ref` values are rejected.+Requests are bounded: the whole MCP request body is limited to 1 MiB, `message` to 64 KiB, each input-response `text` to 16 KiB (both measured as UTF-8 bytes, not characters), and one `agent_update` to 64 responses. Optional output schemas are limited to 64 KiB, 32 levels, and 2,048 nodes, and external `$ref` values are rejected. Oversized bodies receive a JSON-RPC `413`; oversized fields fail input validation before any work starts.### Durability guaranteesdiff --git a/packages/eve/src/internal/mcp/streamable-http-server.test.ts b/packages/eve/src/internal/mcp/streamable-http-server.test.tsindex f9cac1f50..fd5e18cf9 100644--- a/packages/eve/src/internal/mcp/streamable-http-server.test.ts+++ b/packages/eve/src/internal/mcp/streamable-http-server.test.ts@@ -7,6 +7,7 @@ import {defineMcpTool,MCP_LEGACY_PROTOCOL_VERSION,MCP_PROTOCOL_VERSION,+ MCP_REQUEST_BODY_MAX_BYTES,McpToolOperationError,} from "#internal/mcp/streamable-http-server.js";@@ -440,18 +441,70 @@ describe("stateless MCP Streamable HTTP server", () => {expect(await jsonRpcResponse(response)).toMatchObject({ error: { code: -32000 } });});- it("bounds compatibility preflight parsing before the transport reads the body", async () => {+ it("bounds every POST body before the transport reads it", async () => {+ const { call, handle } = server();+ const padding = "x".repeat(MCP_REQUEST_BODY_MAX_BYTES + 1);+ const oversized = [+ // Legacy-era request without a protocol version header.+ request({ id: 1, jsonrpc: "2.0", method: "tools/list", params: { padding } }),+ // Legacy-era request that declares the 2025 header.+ request(+ { id: 2, jsonrpc: "2.0", method: "tools/list", params: { padding } },+ { "mcp-protocol-version": MCP_LEGACY_PROTOCOL_VERSION },+ ),+ // Modern-era request with a complete envelope and header.+ modernRequest({+ id: 3,+ jsonrpc: "2.0",+ method: "tools/call",+ params: { arguments: { value: 1, padding }, name: "echo" },+ }),+ ];++ for (const oversizedRequest of oversized) {+ const response = await handle(oversizedRequest);+ expect(response.status).toBe(413);+ await expect(response.json()).resolves.toMatchObject({+ error: { code: -32_000, message: "Request body too large" },+ id: null,+ jsonrpc: "2.0",+ });+ }+ expect(call).not.toHaveBeenCalled();+ });++ it("fails fast on an oversized declared content length", async () => {const { handle } = server();const response = await handle(- request({ padding: "x".repeat(4 * 1024 * 1024), method: "tools/list" }),+ new Request("https://agent.example/mcp", {+ body: JSON.stringify({ id: 1, jsonrpc: "2.0", method: "tools/list" }),+ headers: {+ accept: "application/json, text/event-stream",+ "content-length": String(MCP_REQUEST_BODY_MAX_BYTES + 1),+ "content-type": "application/json",+ "mcp-protocol-version": MCP_PROTOCOL_VERSION,+ },+ method: "POST",+ }),);-expect(response.status).toBe(413);- await expect(response.json()).resolves.toMatchObject({- error: { code: -32_000, message: "Request body too large" },- id: null,- jsonrpc: "2.0",- });+ });++ it("rejects malformed JSON on every POST path with a parse error", async () => {+ const { handle } = server();+ const response = await handle(+ new Request("https://agent.example/mcp", {+ body: "{not json",+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ "mcp-protocol-version": MCP_PROTOCOL_VERSION,+ },+ method: "POST",+ }),+ );+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toMatchObject({ error: { code: -32_700 } });});it("rejects duplicate tool names at construction", () => {diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.tsindex d42dd3ad2..1e271a0c2 100644--- a/packages/eve/src/internal/mcp/streamable-http-server.ts+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts@@ -12,7 +12,11 @@ const log = createLogger("mcp.server");export const MCP_PROTOCOL_VERSION = "2026-07-28";export const MCP_LEGACY_PROTOCOL_VERSION = "2025-11-25";-const MCP_COMPATIBILITY_INSPECTION_MAX_BYTES = 4 * 1024 * 1024;+/**+ * Upper bound for any MCP POST body. Tool arguments are small JSON; the+ * largest legitimate payload is an `outputSchema`, itself capped at 64 KiB.+ */+export const MCP_REQUEST_BODY_MAX_BYTES = 1024 * 1024;export interface McpToolDefinition<TInputSchema extends StandardSchemaWithJSON = StandardSchemaWithJSON,@@ -142,22 +146,24 @@ export function createMcpStreamableHttpServer(const auth = await options.authenticate(request);if (auth instanceof Response) return auth;- const preflight = await preflightModernRequest(request);- if (preflight.response !== undefined) return preflight.response;-const handler = createMcpHandler(() => createServer(options, tools, auth), {legacy: "stateless",});- return await handler.fetch(- request,- preflight.parsedBody === undefined ? undefined : { parsedBody: preflight.parsedBody },- );- };-}+ if (request.method.toUpperCase() !== "POST") return await handler.fetch(request);++ // Every POST body is read here, bounded, before the SDK sees it. The+ // parsed value is handed to the SDK so the body is never read twice.+ const inspected = await inspectRequestBody(request);+ if (inspected.tooLarge) return requestBodyTooLargeResponse();+ if (inspected.invalidJson) return invalidJsonResponse();+ const parsedBody = inspected.value;+ if (parsedBody === undefined) return await handler.fetch(request);-interface ModernRequestPreflight {- readonly parsedBody?: unknown;- readonly response?: Response;+ const preflightFailure = await preflightModernRequest(request, parsedBody);+ if (preflightFailure !== undefined) return preflightFailure;++ return await handler.fetch(request, { parsedBody });+ };}/**@@ -166,30 +172,15 @@ interface ModernRequestPreflight {* missing-header case here until the upstream handler does:* modelcontextprotocol/typescript-sdk#2589.*/-async function preflightModernRequest(request: Request): Promise<ModernRequestPreflight> {- if (request.method.toUpperCase() !== "POST" || request.headers.has("mcp-protocol-version")) {- return {};- }-- const inspected = await inspectRequestBody(request);- if (inspected.tooLarge) return { response: requestBodyTooLargeResponse() };- if (inspected.invalidJson) return { response: invalidJsonResponse() };- const parsedBody = inspected.value;- if (parsedBody === undefined) return {};-- if (!claimsCurrentProtocolVersion(parsedBody)) {- return { parsedBody };- }+async function preflightModernRequest(+ request: Request,+ parsedBody: unknown,+): Promise<Response | undefined> {+ if (request.headers.has("mcp-protocol-version")) return undefined;+ if (!claimsCurrentProtocolVersion(parsedBody)) return undefined;const earlierFailure = await probeEarlierValidationFailure(request, parsedBody);- if (earlierFailure !== undefined) {- return { parsedBody, response: earlierFailure };- }-- return {- parsedBody,- response: headerMismatchResponse(parsedBody),- };+ return earlierFailure ?? headerMismatchResponse(parsedBody);}async function inspectRequestBody(request: Request): Promise<{@@ -200,6 +191,13 @@ async function inspectRequestBody(request: Request): Promise<{const body = request.body;if (body === null) return { tooLarge: false };+ // Trust a declared length only to fail fast; the streamed count is the guard.+ const declaredLength = Number(request.headers.get("content-length"));+ if (Number.isFinite(declaredLength) && declaredLength > MCP_REQUEST_BODY_MAX_BYTES) {+ await body.cancel().catch(() => {});+ return { tooLarge: true };+ }+const reader = body.getReader();const chunks: Uint8Array[] = [];let size = 0;@@ -208,7 +206,7 @@ async function inspectRequestBody(request: Request): Promise<{const chunk = await reader.read();if (chunk.done) break;size += chunk.value.byteLength;- if (size > MCP_COMPATIBILITY_INSPECTION_MAX_BYTES) {+ if (size > MCP_REQUEST_BODY_MAX_BYTES) {await reader.cancel();return { tooLarge: true };}diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.tsindex 55a856b65..e6a0e8f03 100644--- a/packages/eve/src/public/channels/mcp.test.ts+++ b/packages/eve/src/public/channels/mcp.test.ts@@ -256,6 +256,53 @@ describe("mcpChannel", () => {expect(createSession).not.toHaveBeenCalled();});+ it("rejects oversized UTF-8 messages and input responses before starting work", async () => {+ const createSession = vi.fn();+ const channel = mcpChannel({ auth: none() });+ const route = channel.routes[1]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");++ const oversizedStart = await route.handler(+ mcpRequest({+ id: 1,+ jsonrpc: "2.0",+ method: "tools/call",+ params: {+ // 3 bytes per char: well under 64 Ki characters, over 64 KiB.+ arguments: { message: "日".repeat(24 * 1_024) },+ name: "agent_start",+ },+ }),+ routeArgs(createSession),+ );+ await expect(jsonRpcResponse(oversizedStart)).resolves.toMatchObject({+ result: {+ content: [{ text: expect.stringContaining("Input validation error"), type: "text" }],+ isError: true,+ },+ });++ const oversizedUpdate = await route.handler(+ mcpRequest({+ id: 2,+ jsonrpc: "2.0",+ method: "tools/call",+ params: {+ arguments: {+ invocationId: "inv",+ responses: [{ requestId: "r", text: "日".repeat(6 * 1_024) }],+ },+ name: "agent_update",+ },+ }),+ routeArgs(createSession),+ );+ await expect(jsonRpcResponse(oversizedUpdate)).resolves.toMatchObject({+ result: { isError: true },+ });+ expect(createSession).not.toHaveBeenCalled();+ });+it("mounts OAuth resource metadata and augments auth failures", async () => {const channel = mcpChannel({auth: oauthResource(diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex 651cf39ef..60f4215d6 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -420,7 +420,7 @@ function createInvocationTools(? startDescription: `${agentDescription} ${startDescription}`,inputSchema: z.strictObject({- message: z.string().min(1),+ message: utf8Bounded(MAX_MESSAGE_BYTES).min(1),outputSchema: z.looseObject({}).optional(),}),name: "agent_start",@@ -447,7 +447,7 @@ function createInvocationTools("Reads complete durable invocation state. Wait at least pollAfterMs between calls. " +"Terminal statuses are completed, failed, and cancelled. input_required needs agent_update; " +`authorization_required needs the user to follow the returned authorization.${publicHandleDescription}`,- inputSchema: z.strictObject({ invocationId: z.string().min(1) }),+ inputSchema: z.strictObject({ invocationId: z.string().min(1).max(MAX_ID_CHARS) }),name: "agent_get",outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,},@@ -475,8 +475,8 @@ function createInvocationTools("entry in inputRequests, each keyed by its requestId, in a single call; partial batches are rejected. " +"Returns the current invocation state; repeating the same accepted answers is safe.",inputSchema: z.strictObject({- invocationId: z.string().min(1),- responses: z.array(inputResponseSchema).min(1),+ invocationId: z.string().min(1).max(MAX_ID_CHARS),+ responses: z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE),}),name: "agent_update",outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,@@ -505,7 +505,7 @@ function createInvocationTools("Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and " +"can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). " +"Safe to call repeatedly.",- inputSchema: z.strictObject({ invocationId: z.string().min(1) }),+ inputSchema: z.strictObject({ invocationId: z.string().min(1).max(MAX_ID_CHARS) }),name: "agent_cancel",outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,},@@ -587,6 +587,28 @@ const AUTHORIZATION_REQUEST_SCHEMA = z.strictObject({webhookUrl: z.url().optional(),});+// Bounds on caller-supplied text. The transport already caps the whole body+// at MCP_REQUEST_BODY_MAX_BYTES; these keep individual durable fields sane.+// Text bounds are UTF-8 bytes, matching the transport cap and the docs;+// string.length undercounts multibyte input by up to 3x.+const MAX_MESSAGE_BYTES = 64 * 1_024;+const MAX_RESPONSE_TEXT_BYTES = 16 * 1_024;+const MAX_ID_CHARS = 256;+const MAX_RESPONSES_PER_UPDATE = 64;++function utf8Bounded(maxBytes: number) {+ const encoder = new TextEncoder();+ return z.string().refine((value) => encoder.encode(value).byteLength <= maxBytes, {+ message: `must be at most ${String(maxBytes)} bytes when UTF-8 encoded`,+ });+}++const MCP_INPUT_RESPONSE_SCHEMA = inputResponseSchema.safeExtend({+ optionId: z.string().max(MAX_ID_CHARS).optional(),+ requestId: z.string().min(1).max(MAX_ID_CHARS),+ text: utf8Bounded(MAX_RESPONSE_TEXT_BYTES).optional(),+});+const MCP_INPUT_REQUEST_SCHEMA = inputRequestSchema.safeExtend({action: z.strictObject({callId: z.string(),