Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(mcp): bound request validation

justinbee5686e90b6
diff --git a/apps/api/package.json b/apps/api/package.json
index 2b58404b3..c1928be19 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -15,9 +15,9 @@
"build": "vp run compile",
"lint": "vp check .",
"typecheck": "vp run check:types",
- "test": "vp run test:run",
+ "test": "vp run test:run && node --import tsx scripts/mcp-tool-input-bounds.test.ts",
"test:coverage": "vp test run --config vitest.config.ts --coverage",
- "test:unit": "vp run test:run",
+ "test:unit": "vp run test:run && node --import tsx scripts/mcp-tool-input-bounds.test.ts",
"test:integration": "vp run test:integration:run",
"test:watch": "vp test --config vitest.config.ts",
"db:generate": "drizzle-kit generate",
@@ -37,8 +37,8 @@
"@kaneo/importers": "workspace:*",
"@kaneo/mcp": "workspace:*",
"@kaneo/permissions": "workspace:*",
- "@modelcontextprotocol/sdk": "^1.31.0",
- "@modelcontextprotocol/server": "2.2.0",
+ "@modelcontextprotocol/sdk": "1.32.0",
+ "@modelcontextprotocol/server": "2.3.0",
"@octokit/webhooks": "^14.2.0",
"@oslojs/crypto": "^1.0.1",
"@oslojs/encoding": "^1.1.0",
diff --git a/apps/api/scripts/mcp-tool-input-bounds.test.ts b/apps/api/scripts/mcp-tool-input-bounds.test.ts
new file mode 100644
index 000000000..e2058d2d5
--- /dev/null
+++ b/apps/api/scripts/mcp-tool-input-bounds.test.ts
@@ -0,0 +1,161 @@
+import assert from "node:assert/strict";
+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
+import { createMcpServerForUser } from "../src/mcp/legacy-server.ts";
+import { createModernMcpHandler } from "../src/mcp/modern.ts";
+import {
+ MCP_BODY_BYTES,
+ MCP_MAX_TOOL_INPUT_ELEMENTS,
+} from "../src/mcp/request-bounds.ts";
+
+const toolName = "set_task_custom_field_value";
+const protocolVersion = "2026-07-28";
+const normal = { taskId: "task", fieldId: "field", value: ["one"] };
+const cases = [
+ { name: "normal", args: normal, reject: false },
+ {
+ name: "larger multiselect",
+ args: { ...normal, value: Array.from({ length: 101 }, (_, i) => `v${i}`) },
+ reject: false,
+ },
+ {
+ name: "excess array elements",
+ args: {
+ ...normal,
+ value: Array.from(
+ { length: MCP_MAX_TOOL_INPUT_ELEMENTS + 1 },
+ (_, i) => `v${i}`,
+ ),
+ },
+ reject: true,
+ },
+ {
+ name: "excess nested object keys",
+ args: {
+ ...normal,
+ extra: Object.fromEntries(
+ Array.from({ length: MCP_MAX_TOOL_INPUT_ELEMENTS + 1 }, (_, i) => [
+ `key${i}`,
+ i,
+ ]),
+ ),
+ },
+ reject: true,
+ },
+];
+
+function toolRequest(
+ args: Record<string, unknown>,
+ id: number,
+ modern: boolean,
+): Request {
+ return new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: {
+ accept: "application/json, text/event-stream",
+ "content-type": "application/json",
+ ...(modern
+ ? {
+ "mcp-method": "tools/call",
+ "mcp-name": toolName,
+ "mcp-protocol-version": protocolVersion,
+ }
+ : {}),
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id,
+ method: "tools/call",
+ params: {
+ name: toolName,
+ arguments: args,
+ ...(modern
+ ? {
+ _meta: {
+ "io.modelcontextprotocol/protocolVersion": protocolVersion,
+ "io.modelcontextprotocol/clientInfo": {
+ name: "bounds-test",
+ version: "1",
+ },
+ "io.modelcontextprotocol/clientCapabilities": {},
+ },
+ }
+ : {}),
+ },
+ }),
+ });
+}
+
+async function assertToolResult(
+ response: Response,
+ shouldReject: boolean,
+): Promise<void> {
+ assert.equal(response.status, 200);
+ const text = await response.text();
+ const data =
+ text
+ .split("\n")
+ .find((line) => line.startsWith("data: "))
+ ?.slice(6) ?? text;
+ const body = JSON.parse(data) as {
+ result?: { isError?: boolean; content?: Array<{ text?: string }> };
+ };
+ assert.equal(body.result?.isError, shouldReject);
+ if (shouldReject) {
+ assert.ok(
+ body.result?.content?.[0]?.text?.includes(
+ `maximum of ${MCP_MAX_TOOL_INPUT_ELEMENTS} elements`,
+ ),
+ );
+ }
+}
+
+const originalFetch = globalThis.fetch;
+let apiCalls = 0;
+globalThis.fetch = async (input, init) => {
+ assert.equal(new URL(String(input)).pathname, "/api/custom-field/value");
+ assert.equal(init?.method, "PUT");
+ assert.equal(
+ new Headers(init?.headers).get("authorization"),
+ "Bearer test-token",
+ );
+ apiCalls++;
+ return Response.json({});
+};
+
+try {
+ for (const [index, testCase] of cases.entries()) {
+ apiCalls = 0;
+ const modern = createModernMcpHandler("test-token", "http://api.test");
+ await assertToolResult(
+ await modern.fetch(toolRequest(testCase.args, index + 1, true)),
+ testCase.reject,
+ );
+ assert.equal(apiCalls, testCase.reject ? 0 : 1, `modern: ${testCase.name}`);
+
+ apiCalls = 0;
+ const legacy = createMcpServerForUser("test-token", "http://api.test");
+ const transport = new WebStandardStreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ maxRequestBodySize: MCP_BODY_BYTES,
+ });
+ try {
+ await legacy.connect(transport);
+ await assertToolResult(
+ await transport.handleRequest(
+ toolRequest(testCase.args, index + 1, false),
+ ),
+ testCase.reject,
+ );
+ assert.equal(
+ apiCalls,
+ testCase.reject ? 0 : 1,
+ `legacy: ${testCase.name}`,
+ );
+ } finally {
+ await legacy.close();
+ }
+ }
+ console.log("MCP native bounds: 8 protocol/input cases passed");
+} finally {
+ globalThis.fetch = originalFetch;
+}
diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.ts
index 435044ce8..c48eb057e 100644
--- a/apps/api/src/mcp/index.ts
+++ b/apps/api/src/mcp/index.ts
@@ -1,4 +1,3 @@
-import { McpServer as LegacyMcpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import {
isJsonContentType,
@@ -17,7 +16,11 @@ import {
} from "./controllers/oauth-consent";
import { createModernMcpHandler } from "./modern";
import { exchangeCode } from "./oauth";
-import { oauthRequestBounds } from "./request-bounds";
+import {
+ MCP_BODY_BYTES,
+ mcpRequestBounds,
+ oauthRequestBounds,
+} from "./request-bounds";
import {
authorizationDecisionResponseSchema,
authorizationDecisionSchema,
@@ -28,7 +31,7 @@ import {
clientRegistrationSchema,
oauthErrorSchema,
} from "./schemas";
-import { registerMcpTools, toMcpToolRegistrar } from "./tools";
+import { createMcpServerForUser } from "./legacy-server";
const publicApiUrl = (process.env.KANEO_API_URL || "http://localhost:1337")
.replace(/\/api\/?$/, "")
@@ -39,15 +42,6 @@ const internalApiUrl = (
.replace(/\/api\/?$/, "")
.replace(/\/+$/, "");
-function createMcpServerForUser(token: string): LegacyMcpServer {
- const server = new LegacyMcpServer({
- name: "kaneo-mcp",
- version: "1.0.0",
- });
- registerMcpTools(toMcpToolRegistrar(server), internalApiUrl, token);
- return server;
-}
-
async function validateBearerToken(
req: Request,
): Promise<{ userId: string; token: string } | null> {
@@ -329,7 +323,13 @@ mcp.all("/mcp", async (c) => {
return c.json({ error: "Unsupported Media Type" }, 415);
}
- if (!(await isLegacyRequest(c.req.raw.clone()))) {
+ await mcpRequestBounds(c, async () => {});
+
+ if (
+ !(await isLegacyRequest(c.req.raw.clone(), undefined, {
+ maxRequestBodySize: MCP_BODY_BYTES,
+ }))
+ ) {
const modern = createModernMcpHandler(authResult.token, internalApiUrl);
return modern.fetch(c.req.raw);
}
@@ -338,8 +338,9 @@ mcp.all("/mcp", async (c) => {
// accepts session IDs issued before this change after their owner is gone.
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
+ maxRequestBodySize: MCP_BODY_BYTES,
});
- const server = createMcpServerForUser(authResult.token);
+ const server = createMcpServerForUser(authResult.token, internalApiUrl);
await server.connect(transport);
return transport.handleRequest(c.req.raw);
});
diff --git a/apps/api/src/mcp/legacy-server.ts b/apps/api/src/mcp/legacy-server.ts
new file mode 100644
index 000000000..cbf0df065
--- /dev/null
+++ b/apps/api/src/mcp/legacy-server.ts
@@ -0,0 +1,15 @@
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { registerMcpTools, toMcpToolRegistrar } from "./tools";
+import { MCP_MAX_TOOL_INPUT_ELEMENTS } from "./request-bounds";
+
+export function createMcpServerForUser(
+ token: string,
+ internalApiUrl: string,
+): McpServer {
+ const server = new McpServer(
+ { name: "kaneo-mcp", version: "1.0.0" },
+ { maxToolInputElements: MCP_MAX_TOOL_INPUT_ELEMENTS },
+ );
+ registerMcpTools(toMcpToolRegistrar(server), internalApiUrl, token);
+ return server;
+}
diff --git a/apps/api/src/mcp/modern.ts b/apps/api/src/mcp/modern.ts
index 6de701209..aea557b8c 100644
--- a/apps/api/src/mcp/modern.ts
+++ b/apps/api/src/mcp/modern.ts
@@ -1,17 +1,29 @@
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import { registerMcpTools, toMcpToolRegistrar } from "./tools";
+import { MCP_BODY_BYTES, MCP_MAX_TOOL_INPUT_ELEMENTS } from "./request-bounds";
/** Create a stateless MCP 2026 handler with a fresh server per request. */
-export function createModernMcpHandler(token: string, apiUrl: string) {
+export function createModernMcpHandler(
+ token: string,
+ apiUrl: string,
+): ReturnType<typeof createMcpHandler> {
return createMcpHandler(
() => {
- const server = new McpServer({
- name: "kaneo-mcp",
- version: "1.0.0",
- });
+ const server = new McpServer(
+ {
+ name: "kaneo-mcp",
+ version: "1.0.0",
+ },
+ {
+ maxToolInputElements: MCP_MAX_TOOL_INPUT_ELEMENTS,
+ },
+ );
registerMcpTools(toMcpToolRegistrar(server), apiUrl, token);
return server;
},
- { legacy: "reject" },
+ {
+ legacy: "reject",
+ maxRequestBodySize: MCP_BODY_BYTES,
+ },
);
}
diff --git a/apps/api/src/mcp/request-bounds.ts b/apps/api/src/mcp/request-bounds.ts
index e9703fea3..6af0851ff 100644
--- a/apps/api/src/mcp/request-bounds.ts
+++ b/apps/api/src/mcp/request-bounds.ts
@@ -3,6 +3,11 @@ import { HTTPException } from "hono/http-exception";
import { boundedRequestBody } from "../utils/bounded-request-body";
+export const MCP_BODY_BYTES = 1024 * 1024;
+// Keep large multiselects usable while bounding recursive SDK validation.
+export const MCP_MAX_TOOL_INPUT_ELEMENTS = 10_000;
+export const mcpRequestBounds = boundedRequestBody(MCP_BODY_BYTES);
+
export const OAUTH_BODY_BYTES = 32 * 1024;
export const OAUTH_URL_BYTES = 8 * 1024;
const checkBody = boundedRequestBody(OAUTH_BODY_BYTES);
diff --git a/apps/docs/core/integrations/mcp-stateless.mdx b/apps/docs/core/integrations/mcp-stateless.mdx
index f3ce06c33..be80d4d02 100644
--- a/apps/docs/core/integrations/mcp-stateless.mdx
+++ b/apps/docs/core/integrations/mcp-stateless.mdx
@@ -46,11 +46,21 @@ HTTP MCP tools reach Kaneo’s API through `KANEO_INTERNAL_API_URL`, which defau
| --- | --- |
| 401 | Complete OAuth sign-in again and check that the proxy forwards the bearer token. |
| 405 | The HTTP MCP endpoint accepts POST requests; standalone GET streams and DELETE requests are unsupported. |
+| 408 | Send the complete request body within five seconds. |
+| 413 | Reduce the request body. MCP HTTP accepts at most 1 MiB. |
| 415 | Send JSON with the correct content type. |
| 429 | Wait for `Retry-After` before retrying. |
A tool can also fail because the user lacks permission or its arguments do not match the project. Call `list_project_columns` before assigning a status and `list_workspace_members` before assigning a user.
+### MCP request limits
+
+Both HTTP protocol flows accept request bodies up to 1 MiB (1,048,576 bytes), measured from the received bytes rather than trusting `Content-Length`.
+The body must arrive within five seconds.
+Each tool call accepts up to 10,000 combined object keys and array elements across its arguments, including nested values.
+Calls above that budget return a tool result with `isError: true` without calling the Kaneo API.
+These limits apply to the HTTP endpoint, not the separate stdio package.
+
### OAuth request limits
The HTTP OAuth endpoints accept bodies up to 32 KiB and URLs up to 8 KiB.
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 0c4af0190..ebfcc9efb 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -64,7 +64,7 @@
"test:watch": "vp test --config vitest.config.ts"
},
"dependencies": {
- "@modelcontextprotocol/sdk": "^1.31.0",
+ "@modelcontextprotocol/sdk": "1.32.0",
"open": "^11.0.4",
"prompts": "^2.4.2",
"zod": "^4.6.5"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 25ea1e47a..b0da00029 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -145,11 +145,11 @@ importers:
specifier: workspace:*
version: link:../../packages/permissions
'@modelcontextprotocol/sdk':
- specifier: ^1.31.0
- version: 1.31.0([email protected])
+ specifier: 1.32.0
+ version: 1.32.0([email protected])
'@modelcontextprotocol/server':
- specifier: 2.2.0
- version: 2.2.0
+ specifier: 2.3.0
+ version: 2.3.0
'@octokit/webhooks':
specifier: ^14.2.0
version: 14.2.0
@@ -907,8 +907,8 @@ importers:
packages/mcp:
dependencies:
'@modelcontextprotocol/sdk':
- specifier: ^1.31.0
- version: 1.31.0([email protected])
+ specifier: 1.32.0
+ version: 1.32.0([email protected])
open:
specifier: ^11.0.4
version: 11.0.4
@@ -2293,12 +2293,6 @@ packages:
peerDependencies:
hono: '>=4.13.5'
- resolution: {integrity: sha512-TA//nWMqPhbfdfneACk6t5a9eqbS9lABEPyKn0/xZTah3H3U2XaVg85rJFl0/Fyit0I552YDHgXGVSf3GwqbUw==}
- engines: {node: '>=20'}
- peerDependencies:
- hono: '>=4.13.5'
-
resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==}
engines: {node: '>=20'}
@@ -2659,12 +2653,12 @@ packages:
'@mixmark-io/[email protected]':
resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==}
- '@modelcontextprotocol/[email protected]':
- resolution: {integrity: sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-09BHFaNVBe5pB2AhzCfLj0cqmsKLERvZQ4FblzP90UMGLaXVqdZPByFjURwsUYCmxonUW2yAwgTTvle+8O2/8w==}
engines: {node: '>=20'}
- '@modelcontextprotocol/[email protected]':
- resolution: {integrity: sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-8BviX/hK4Gd2eL1KdTwm0gfl4d3wdoErW0Jd00h6nomUAtk6IJk5vwQJc6kfWtJTzN5OEV/lgIiJKI8fiDGAlA==}
engines: {node: '>=18'}
peerDependencies:
'@cfworker/json-schema': ^4.1.1
@@ -2673,8 +2667,8 @@ packages:
'@cfworker/json-schema':
optional: true
- '@modelcontextprotocol/[email protected]':
- resolution: {integrity: sha512-qFnltjus6Gk8Lx6J1w2RXmr3YPN22MNT6qD6zjAkaiWIlFIFxWClz0rXHNuJF/KSUyn5YGhkSvXkWDbQHVLFEQ==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-+6b0LdsQLmHsvS7J6sQJ4weTpzUn61fU1JKS+321/+IyDYoHW5CR2Tgqcs6GgAAQvlesCo6yX3xttgmx+XGtJw==}
engines: {node: '>=20'}
'@mongodb-js/[email protected]':
@@ -8323,10 +8317,6 @@ packages:
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
- resolution: {integrity: sha512-6E2QDAc9Ick9Sq77ZrGS/dk2WUYni91aufTw6LJKpV7w8kW5/GxVUc650FOADOmlwg3K+f7Pun6XlV+pYmW6gw==}
- engines: {node: '>=16.9.0'}
-
resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}
engines: {node: '>=16.9.0'}
@@ -13567,14 +13557,9 @@ snapshots:
dependencies:
hono: 4.13.8
- dependencies:
- hono: 4.13.12
-
dependencies:
hono: 4.13.13
- optional: true
dependencies:
@@ -13831,13 +13816,13 @@ snapshots:
'@mixmark-io/[email protected]': {}
- '@modelcontextprotocol/[email protected]':
+ '@modelcontextprotocol/[email protected]':
dependencies:
zod: 4.6.5
- '@modelcontextprotocol/[email protected]([email protected])':
+ '@modelcontextprotocol/[email protected]([email protected])':
dependencies:
- '@hono/node-server': 2.1.3([email protected])
+ '@hono/node-server': 2.1.5([email protected])
ajv: 8.18.0
ajv-formats: 3.0.1([email protected])
content-type: 1.0.5
@@ -13847,7 +13832,7 @@ snapshots:
eventsource-parser: 3.1.0
express: 5.2.1
express-rate-limit: 8.2.2([email protected])
- hono: 4.13.12
+ hono: 4.13.13
jose: 6.2.8
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
@@ -13857,9 +13842,9 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@modelcontextprotocol/[email protected]([email protected])':
+ '@modelcontextprotocol/[email protected]([email protected])':
dependencies:
- '@hono/node-server': 2.1.3([email protected])
+ '@hono/node-server': 2.1.5([email protected])
ajv: 8.18.0
ajv-formats: 3.0.1([email protected])
content-type: 1.0.5
@@ -13869,7 +13854,7 @@ snapshots:
eventsource-parser: 3.1.0
express: 5.2.1
express-rate-limit: 8.2.2([email protected])
- hono: 4.13.12
+ hono: 4.13.13
jose: 6.2.8
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
@@ -13879,9 +13864,9 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@modelcontextprotocol/[email protected]':
+ '@modelcontextprotocol/[email protected]':
dependencies:
- '@modelcontextprotocol/core': 2.2.0
+ '@modelcontextprotocol/core': 2.3.0
zod: 4.6.5
'@mongodb-js/[email protected]':
@@ -15745,9 +15730,7 @@ snapshots:
metro-runtime: 0.84.6
transitivePeerDependencies:
- '@babel/core'
- - bufferutil
- supports-color
- - utf-8-validate
'@react-native/[email protected]': {}
@@ -18255,7 +18238,7 @@ snapshots:
dependencies:
- '@modelcontextprotocol/sdk': 1.31.0([email protected])
+ '@modelcontextprotocol/sdk': 1.32.0([email protected])
jsonpath-rfc9535: 1.1.0
zod: 4.6.5
transitivePeerDependencies:
@@ -19534,10 +19517,7 @@ snapshots:
dependencies:
react-is: 16.13.1
-
- optional: true
@@ -22541,7 +22521,7 @@ snapshots:
'@babel/plugin-transform-typescript': 7.28.6(@babel/[email protected])
'@babel/preset-typescript': 7.28.5(@babel/[email protected])
'@dotenvx/dotenvx': 1.52.0
- '@modelcontextprotocol/sdk': 1.31.0([email protected])
+ '@modelcontextprotocol/sdk': 1.32.0([email protected])
'@types/validate-npm-package-name': 4.0.2
browserslist: 4.29.0
cn: 0.2.6
diff --git a/tests/api/mcp-request-bounds.test.ts b/tests/api/mcp-request-bounds.test.ts
index 3dda5026f..087b4c1df 100644
--- a/tests/api/mcp-request-bounds.test.ts
+++ b/tests/api/mcp-request-bounds.test.ts
@@ -1,6 +1,25 @@
+import { isLegacyRequest } from "@modelcontextprotocol/server";
import { Hono } from "hono";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import mcpRoutes from "../../apps/api/src/mcp/index";
+
+const authMocks = vi.hoisted(() => ({
+ getSession: vi.fn(async (): Promise<{ user: { id: string } } | null> => ({
+ user: { id: "test-user" },
+ })),
+}));
+
+vi.mock("../../apps/api/src/auth", () => ({
+ auth: { api: { getSession: authMocks.getSession } },
+}));
+vi.mock("@modelcontextprotocol/server", async (importOriginal) => {
+ const original =
+ await importOriginal<typeof import("@modelcontextprotocol/server")>();
+ return { ...original, isLegacyRequest: vi.fn(original.isLegacyRequest) };
+});
import {
+ MCP_BODY_BYTES,
+ mcpRequestBounds,
OAUTH_BODY_BYTES,
OAUTH_MAX_IN_FLIGHT,
oauthRequestBounds,
@@ -13,6 +32,147 @@ const app = new Hono().post("/register", oauthRequestBounds, async (c) =>
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
+ authMocks.getSession
+ .mockReset()
+ .mockResolvedValue({ user: { id: "test-user" } });
+});
+
+describe("MCP bounded body admission", () => {
+ const parseMcp = vi.fn(async (text: string) => text);
+ const mcpApp = new Hono().post("/mcp", mcpRequestBounds, async (c) =>
+ c.text(await parseMcp(await c.req.text())),
+ );
+
+ it.each([
+ ["missing content length", undefined],
+ ["misleading small content length", "1"],
+ ])(
+ "rejects actual oversized bytes with %s",
+ async (_label, contentLength) => {
+ const body =
+ JSON.stringify({ jsonrpc: "2.0", method: "initialize" }) +
+ " ".repeat(MCP_BODY_BYTES);
+ const response = await mcpApp.request(
+ new Request("http://localhost/mcp", {
+ method: "POST",
+ headers: contentLength ? { "content-length": contentLength } : {},
+ body,
+ }),
+ );
+ expect(response.status).toBe(413);
+ expect(parseMcp).not.toHaveBeenCalled();
+ },
+ );
+
+ it("cancels a streamed overflow before parser invocation", async () => {
+ const cancel = vi.fn();
+ const body = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array(MCP_BODY_BYTES));
+ controller.enqueue(new Uint8Array(1));
+ },
+ cancel,
+ });
+ const response = await mcpApp.request(
+ new Request("http://localhost/mcp", {
+ method: "POST",
+ body,
+ duplex: "half",
+ } as RequestInit),
+ );
+ expect(response.status).toBe(413);
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(parseMcp).not.toHaveBeenCalled();
+ });
+
+ it("rejects an oversized declared content length before reading", async () => {
+ const read = vi.fn();
+ const body = new ReadableStream({ pull: read }, { highWaterMark: 0 });
+ const response = await mcpApp.request(
+ new Request("http://localhost/mcp", {
+ method: "POST",
+ headers: { "content-length": String(MCP_BODY_BYTES + 1) },
+ body,
+ duplex: "half",
+ } as RequestInit),
+ );
+ expect(response.status).toBe(413);
+ expect(read).not.toHaveBeenCalled();
+ expect(parseMcp).not.toHaveBeenCalled();
+ });
+
+ it("uses a deadline and cancels a stream that never completes", async () => {
+ vi.useFakeTimers();
+ const cancel = vi.fn();
+ const body = new ReadableStream({ start() {}, cancel });
+ const pending = mcpApp.request(
+ new Request("http://localhost/mcp", {
+ method: "POST",
+ body,
+ duplex: "half",
+ } as RequestInit),
+ );
+ await vi.advanceTimersByTimeAsync(5_001);
+ expect((await pending).status).toBe(408);
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(parseMcp).not.toHaveBeenCalled();
+ });
+
+ it("accepts the exact byte boundary", async () => {
+ const body = "x".repeat(MCP_BODY_BYTES);
+ const response = await mcpApp.request("/mcp", { method: "POST", body });
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe(body);
+ });
+
+ it("rejects oversized authenticated route input before protocol classification", async () => {
+ const classify = vi.mocked(isLegacyRequest);
+ const api = new Hono().route("/api", mcpRoutes);
+ authMocks.getSession.mockClear();
+ const bytes = new Uint8Array(MCP_BODY_BYTES + 1);
+ const request = new Request("http://mcp.test/api/mcp", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer test-token",
+ "content-type": "application/json",
+ },
+ body: bytes,
+ });
+ const response = await api.request(request);
+ expect(response.status).toBe(413);
+ expect(authMocks.getSession).toHaveBeenCalledOnce();
+ expect(classify).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["missing Authorization", undefined, 0],
+ ["invalid Bearer token", "Bearer invalid-test-token", 1],
+ ] as const)(
+ "rejects %s before reading request bytes",
+ async (_name, authorization, lookups) => {
+ if (authorization) authMocks.getSession.mockResolvedValueOnce(null);
+ const pull = vi.fn();
+ const body = new ReadableStream({ pull }, { highWaterMark: 0 });
+ const request = new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ ...(authorization ? { authorization } : {}),
+ },
+ body,
+ duplex: "half",
+ } as RequestInit);
+ try {
+ const response = await mcpRoutes.request(request);
+ expect(response.status).toBe(401);
+ expect(authMocks.getSession).toHaveBeenCalledTimes(lookups);
+ expect(pull).not.toHaveBeenCalled();
+ expect(request.bodyUsed).toBe(false);
+ } finally {
+ await body.cancel();
+ }
+ },
+ );
});
describe("OAuth bounded body reader", () => {
diff --git a/tests/api/mcp-stateless.test.ts b/tests/api/mcp-stateless.test.ts
index 6eba64dbd..d4666234d 100644
--- a/tests/api/mcp-stateless.test.ts
+++ b/tests/api/mcp-stateless.test.ts
@@ -283,15 +283,12 @@ describe("MCP 2026-07-28 stateless HTTP", () => {
params: {},
}),
});
- const clone = vi.spyOn(request, "clone");
-
const response = await mcpRoutes.request(request);
expect(response.status).toBe(200);
expect((await rpcBody(response)).result.tools).toContainEqual(
expect.objectContaining({ name: "whoami" }),
);
- expect(clone).toHaveBeenCalledOnce();
const unauthenticated = new Request("http://mcp.test/mcp", {
method: "POST",