Context7 Platform -- Up-to-date docs for AI agents
ctx7-2586 sanitize error responses for rejected request bodies (#3142)
Ramazan Onur Acar80e681a507c5
diff --git a/.changeset/sanitize-mcp-body-errors.md b/.changeset/sanitize-mcp-body-errors.mdnew file mode 100644index 00000000..502b24a5--- /dev/null+++ b/.changeset/sanitize-mcp-body-errors.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Return sanitized JSON-RPC errors for rejected MCP request bodies.diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 9b197846..cbd2ad7d 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -25,6 +25,7 @@ import {} from "./lib/constants.js";import { maybeElicitAuthSignIn } from "./lib/auth/auth-prompt.js";import { getMaxSubscriptions } from "./lib/subscriptions.js";+import { mcpBodyErrorHandler } from "./lib/mcp-body-error-handler.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -35,7 +36,8 @@ function getPluginFromRequest(req: express.Request): typeof CLAUDE_CODE_PLUGIN |}function requiresAuthentication(req: express.Request, plugin?: typeof CLAUDE_CODE_PLUGIN): boolean {- return req.path === "/mcp/oauth" || Boolean(plugin);+ // The MCP routes live on a router mounted at /mcp, so req.path is relative to it.+ return `${req.baseUrl}${req.path}` === "/mcp/oauth" || Boolean(plugin);}// Parse CLI arguments using commander@@ -328,8 +330,10 @@ async function main() {// Only private/local infrastructure may supply forwarding headers. Express// then walks the chain right-to-left and ignores attacker-added prefixes.app.set("trust proxy", ["loopback", "linklocal", "uniquelocal", "100.64.0.0/10"]);- app.use(express.json());+ // Registered ahead of the MCP router so its error responses carry the CORS+ // headers too; browser clients would otherwise see a CORS failure instead+ // of the status.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {res.setHeader("Access-Control-Allow-Origin", "*");res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");@@ -465,14 +469,16 @@ async function main() {}};- app.all("/mcp", async (req, res) => {- await handleMcpRequest(req, res);- });-+ // JSON bodies and JSON-RPC error envelopes are the MCP contract only, so the+ // parser and its error boundary live on the MCP router: every other route+ // stays out of the parser and keeps its own response shape.+ const mcpRouter = express.Router();+ mcpRouter.use(express.json());+ mcpRouter.use(mcpBodyErrorHandler);+ mcpRouter.all("/", (req, res) => handleMcpRequest(req, res));// OAuth-protected endpoint - requires authentication- app.all("/mcp/oauth", async (req, res) => {- await handleMcpRequest(req, res);- });+ mcpRouter.all("/oauth", (req, res) => handleMcpRequest(req, res));+ app.use("/mcp", mcpRouter);app.get("/ping", (_req: express.Request, res: express.Response) => {res.json({ status: "ok", message: "pong" });diff --git a/packages/mcp/src/lib/mcp-body-error-handler.ts b/packages/mcp/src/lib/mcp-body-error-handler.tsnew file mode 100644index 00000000..481070fd--- /dev/null+++ b/packages/mcp/src/lib/mcp-body-error-handler.ts@@ -0,0 +1,30 @@+import type { ErrorRequestHandler } from "express";++// Error boundary for the MCP router's JSON body parser. express.json() reports+// a body it will not accept via next(err); left unhandled, Express answers with+// an HTML stack trace naming dependency versions and absolute paths.+export const mcpBodyErrorHandler: ErrorRequestHandler = (err, req, res, next) => {+ const { status, type } = err as { status?: unknown; type?: unknown };++ // body-parser tags every rejection with a 4xx; anything else is not a body+ // problem. Once a response has started, only Express can wind it down.+ if (typeof status !== "number" || status < 400 || status >= 500 || res.headersSent) {+ return next(err);+ }++ // Method, path and size only: the body is the rejected input, and the+ // headers carry the API key.+ console.error(+ `Rejected request body (${status}, ${String(type ?? "unknown")}): ${req.method} ${req.baseUrl}${req.path} bytes=${req.headers["content-length"] ?? "unknown"}`+ );++ // Fixed messages: body-parser's own quote offsets into the body.+ const parseFailure = err instanceof SyntaxError && type === "entity.parse.failed";+ res.status(status).json({+ jsonrpc: "2.0",+ error: parseFailure+ ? { code: -32700, message: "Parse error" }+ : { code: -32600, message: "Invalid Request" },+ id: null,+ });+};diff --git a/packages/mcp/test/integration.test.ts b/packages/mcp/test/integration.test.tsindex 269c6773..f591edc2 100644--- a/packages/mcp/test/integration.test.ts+++ b/packages/mcp/test/integration.test.ts@@ -162,6 +162,117 @@ describe("OAuth discovery", () => {});});+// A malformed body fails inside express.json(), which calls next(err). That+// jumps past every 3-arg middleware — CORS, both /mcp routes (so neither the+// auth check nor handleMcpRequest's catch runs) and the catch-all 404 — and+// used to land in Express's default handler and its HTML stack trace.+describe.each(["/mcp", "/mcp/oauth"])("malformed JSON body on %s", (endpoint) => {+ test("answers with a sanitized JSON-RPC parse error", async () => {+ const response = await fetch(new URL(endpoint, httpUrl), {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json, text/event-stream",+ // Credentials ride along on real traffic, so assert they are not echoed.+ Authorization: "Bearer ctx7sk-parse-error-canary",+ },+ body: '{"jsonrpc":"2.0","method":"tools/list","params":{"leak-canary":',+ });++ expect(response.status).toBe(400);+ expect(response.headers.get("content-type")).toMatch(/^application\/json/);+ // The throw happens upstream of the CORS middleware, so browser clients see+ // a CORS failure instead of the 400 unless the headers are restored.+ expect(response.headers.get("access-control-allow-origin")).toBe("*");++ const raw = await response.text();+ for (const leak of [+ "node_modules",+ "body-parser",+ "raw-body",+ "SyntaxError",+ "<html",+ "<pre",+ "at JSON.parse",+ PKG_ROOT,+ "leak-canary",+ "ctx7sk-parse-error-canary",+ ]) {+ expect(raw).not.toContain(leak);+ }++ expect(JSON.parse(raw)).toEqual({+ jsonrpc: "2.0",+ error: { code: -32700, message: "Parse error" },+ id: null,+ });+ });+});++// body-parser refuses some bodies before JSON.parse is reached. Those are still+// client mistakes, so they keep the status it assigned instead of being+// reported as a server fault that invites the client to retry forever.+test("keeps an oversized body a sanitized 413 rather than a 500", async () => {+ const response = await fetch(new URL("/mcp", httpUrl), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ // Comfortably past express.json()'s 100kb default limit.+ body: JSON.stringify({ jsonrpc: "2.0", padding: "A".repeat(200_000) }),+ });++ expect(response.status).toBe(413);+ expect(response.headers.get("content-type")).toMatch(/^application\/json/);++ const raw = await response.text();+ for (const leak of ["node_modules", "PayloadTooLargeError", "<html", "<pre", PKG_ROOT]) {+ expect(raw).not.toContain(leak);+ }+ expect(JSON.parse(raw)).toEqual({+ jsonrpc: "2.0",+ error: { code: -32600, message: "Invalid Request" },+ id: null,+ });+});++// The parser is mounted on the MCP router only. A malformed body sent anywhere+// else never reaches it, so the route answers on its own terms: /ping is+// GET-only and an unknown path is unknown, and both land on the catch-all 404+// exactly as they would with a well-formed body.+describe.each(["/ping", "/does-not-exist"])("malformed JSON body on %s", (path) => {+ test("follows that route's own contract rather than JSON-RPC", async () => {+ const response = await fetch(new URL(path, httpUrl), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: "{",+ });++ expect(response.status).toBe(404);+ expect(await response.json()).toEqual({+ error: "not_found",+ message: "Endpoint not found. Use /mcp for MCP protocol communication.",+ });+ });+});++// Guard against over-classifying: only body-parser's entity.parse.failed is a+// parse error. These bodies parse fine and must keep their existing SDK-issued+// codes rather than collapsing into -32700.+describe.each([+ ["a non-JSON-RPC object", '{"hello":"world"}', 400, -32600],+ ["an empty body", "", 400, -32600],+])("valid JSON: %s", (_label, body, status, code) => {+ test("is not reported as a parse error", async () => {+ const response = await fetch(new URL("/mcp", httpUrl), {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json" },+ body,+ });++ expect(response.status).toBe(status);+ expect(await response.json()).toMatchObject({ error: { code } });+ });+});+describe("HTTP API key headers", () => {test("accepts the advertised X-Context7-API-Key header", async () => {const apiKey = "ctx7sk-advertised-header-test";