Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

mcp: reject bodies that are not a JSON-RPC request before dispatch

Carl-Gerhard Lindesvärdc894c04b45d3
diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.ts
index efb5b0c73..2be373d23 100644
--- a/packages/core/src/modules/mcp/mcp.service.test.ts
+++ b/packages/core/src/modules/mcp/mcp.service.test.ts
@@ -163,6 +163,51 @@ describe('handleStatelessMcpRequest — auth', () => {
});
describe('handleStatelessMcpRequest — protocol', () => {
+ const INVALID_BODIES: Array<[string, unknown]> = [
+ ['id without method', { jsonrpc: '2.0', id: 9 }],
+ ['a response message', { jsonrpc: '2.0', id: 9, result: {} }],
+ ['missing jsonrpc', { id: 9, method: 'ping' }],
+ ['null id', { jsonrpc: '2.0', id: null, method: 'ping' }],
+ ['non-string method', { jsonrpc: '2.0', id: 9, method: 5 }],
+ ['jsonrpc 1.0', { jsonrpc: '1.0', id: 9, method: 'ping' }],
+ ];
+
+ for (const [label, body] of INVALID_BODIES) {
+ it(`400s ${label} with -32600 instead of hanging`, async () => {
+ const res = await Promise.race([
+ post(VALID_TOKEN, body),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error('request hung')), 2000)
+ ),
+ ]);
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({
+ jsonrpc: '2.0',
+ error: { code: -32_600 },
+ });
+ });
+ }
+
+ it('echoes a legal id on an invalid request and nulls an illegal one', async () => {
+ const legal = await post(VALID_TOKEN, { jsonrpc: '2.0', id: 9 });
+ expect(legal.body).toMatchObject({ id: 9 });
+ const illegal = await post(VALID_TOKEN, { jsonrpc: '2.0', id: { a: 1 } });
+ expect(illegal.body).toMatchObject({ id: null });
+ });
+
+ for (const [label, body] of [
+ ['an empty string', ''],
+ ['a string', 'hello'],
+ ['null', null],
+ ['an array', [1, 2]],
+ ] as Array<[string, unknown]>) {
+ it(`400s ${label} body instead of throwing`, async () => {
+ const res = await post(VALID_TOKEN, body);
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({ error: { code: -32_600 } });
+ });
+ }
+
it('202s a notification and never runs it through the MCP server', async () => {
const res = await post(VALID_TOKEN, {
jsonrpc: '2.0',
diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.ts
index d0c829cec..dfbff85af 100644
--- a/packages/core/src/modules/mcp/mcp.service.ts
+++ b/packages/core/src/modules/mcp/mcp.service.ts
@@ -19,7 +19,13 @@
// server where `deps` is in hand — not a context problem.
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
-import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
+import {
+ ErrorCode,
+ isJSONRPCNotification,
+ isJSONRPCRequest,
+ type JSONRPCMessage,
+ RequestIdSchema,
+} from '@modelcontextprotocol/sdk/types.js';
import type { ServiceDeps, Services } from '../../services';
import {
authenticateToken,
@@ -50,6 +56,26 @@ export interface McpHttpResult {
body: unknown;
}
+const INVALID_REQUEST_STATUS = 400;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/** JSON-RPC `-32600`, echoing the caller's id when it is a legal one. */
+function invalidRequest(body: unknown, message: string): McpHttpResult {
+ const rawId = isRecord(body) ? body.id : undefined;
+ const id = RequestIdSchema.safeParse(rawId).success ? rawId : null;
+ return {
+ status: INVALID_REQUEST_STATUS,
+ body: {
+ jsonrpc: '2.0',
+ id,
+ error: { code: ErrorCode.InvalidRequest, message },
+ },
+ };
+}
+
/**
* Handle one stateless MCP POST request end-to-end.
*
@@ -76,13 +102,24 @@ export async function handleStatelessMcpRequest(
throw err;
}
- const message = body as JSONRPCMessage;
+ // The SDK drops anything that is not a request or notification on the
+ // floor via `Protocol.onerror` and never replies — a well-formed *response*
+ // message included — so an unvalidated body left the HTTP request pending
+ // forever. The gate has to sit here, before dispatch.
+ if (!isRecord(body)) {
+ return invalidRequest(body, 'Invalid Request: body must be a JSON object');
+ }
// Notifications carry no `id` and expect no response.
- if (!('id' in message)) {
+ if (isJSONRPCNotification(body)) {
return { status: 202, body: null };
}
+ if (!isJSONRPCRequest(body)) {
+ return invalidRequest(body, 'Invalid Request: not a JSON-RPC 2.0 request');
+ }
+ const message: JSONRPCMessage = body;
+
logToolCall(deps, message, context);
const isInitializeRequest =
'method' in message && message.method === 'initialize';
@@ -122,6 +159,10 @@ async function runOnEphemeralServer(
return await new Promise<JSONRPCMessage>((resolve, reject) => {
clientTransport.onmessage = resolve;
+ // The SDK reports an undispatchable message here and nowhere else, so a
+ // message that slips past the gate rejects instead of leaking a pending
+ // HTTP request.
+ server.server.onerror = reject;
clientTransport.send(message).catch(reject);
});
} finally {