Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(mcp): answer GET and DELETE /mcp with 405
Yudhi Armyndharis0d567daa56dc
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e740b9630..7ad089cb5 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6207,7 +6207,7 @@ Key facts:- **Path is exactly `POST /mcp` — no `/api` prefix.** The global `api` prefix applies only to Nest controllers; this route is mounted straight on Express.- Gated by **`MCP_ENABLED=true`**. When off, the module/route is never mounted and `POST /mcp` returns `404`.- MCP is **read-only by default**: only read-tier tools are registered unless you set `MCP_READONLY=false` to expose write tools. Per-key sliding-window rate limit: `MCP_RATE_LIMIT_MAX` (default 60) per `MCP_RATE_LIMIT_WINDOW_MS` (default 60000).-- Stateless transport (no SSE/session id for normal calls).+- Stateless transport (no SSE/session id for normal calls). `GET /mcp` and `DELETE /mcp` answer `405` with `Allow: POST` and a JSON-RPC error body.- Pre-auth per-IP throttle: `MCP_IP_RATE_LIMIT_MAX` (default 120) JSON-RPC messages per `MCP_IP_RATE_LIMIT_WINDOW_MS` (default 60000). Each element of a batch counts; an over-budget request gets HTTP `429` with a JSON-RPC error body and runs none of its messages, but still spends whatever budget the IP had left.**Request body** — JSON-RPC 2.0 envelope (validated by the MCP SDK, **not** the Nest ValidationPipe)diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 92b0280ee..5197ab0b0 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -39,8 +39,10 @@ group management — so an agent can drive WhatsApp through the same business loREST API uses.Set `MCP_ENABLED=true` to mount a stateless Streamable-HTTP transport at **`POST /mcp`**-on the existing server (same port, no extra process). When `MCP_ENABLED` is unset, the-MCP module and the `@modelcontextprotocol/sdk` package are never loaded.+on the existing server (same port, no extra process). The transport offers no SSE stream+and no sessions, so `GET /mcp` and `DELETE /mcp` answer `405` with `Allow: POST`. When+`MCP_ENABLED` is unset, the MCP module and the `@modelcontextprotocol/sdk` package are+never loaded.## 24.2 Design Goalsdiff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.tsindex c52a0f922..d84d4cf8e 100644--- a/src/modules/mcp/mcp.server.spec.ts+++ b/src/modules/mcp/mcp.server.spec.ts@@ -241,7 +241,7 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {tool: AnyToolDescriptor;authService: { validateApiKey: jest.Mock; hasPermission: jest.Mock };auditService: { logWarn: jest.Mock };- adapter: { post: jest.Mock };+ adapter: { post: jest.Mock; get: jest.Mock; delete: jest.Mock };}const mount = (): Harness => {@@ -261,6 +261,8 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {post: jest.fn((_path: string, ...handlers: unknown[]) => {routeHandlers = handlers;}),+ get: jest.fn(),+ delete: jest.fn(),};mountMcpServer(adapter as unknown as Parameters<typeof mountMcpServer>[0],@@ -308,6 +310,25 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {return mockRegisteredTools[0].callback;};+ it('answers GET and DELETE with a JSON-RPC 405 carrying Allow: POST (stateless, no SSE stream)', () => {+ const h = mount();+ for (const verb of ['get', 'delete'] as const) {+ expect(h.adapter[verb]).toHaveBeenCalledWith('/mcp', expect.any(Function));+ const refuse = (h.adapter[verb].mock.calls[0] as unknown[])[1] as (req: Request, res: Response) => void;+ const res = { status: jest.fn(), set: jest.fn(), json: jest.fn() };+ res.status.mockReturnValue(res);+ res.set.mockReturnValue(res);+ refuse({} as Request, res as unknown as Response);+ expect(res.status).toHaveBeenCalledWith(405);+ expect(res.set).toHaveBeenCalledWith('Allow', 'POST');+ expect(res.json).toHaveBeenCalledWith({+ jsonrpc: '2.0',+ error: { code: -32000, message: 'Method not allowed.' },+ id: null,+ });+ }+ });+it('parses the body before the per-IP throttle so a batch is charged per message', () => {const h = mount();const [path, parser] = h.adapter.post.mock.calls[0] as unknown[];diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex cb8a47ba0..01a224536 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -159,7 +159,7 @@ export interface MountMcpServerOptions {** Tool handlers are built ONCE at mount time (closure over registry/authService/rateLimiter).* Per-request: mint a fresh McpServer + StreamableHTTPServerTransport, handle, tear down.- * Stateless (sessionIdGenerator: undefined) — no session map, no GET/DELETE reconnect.+ * Stateless (sessionIdGenerator: undefined): no session map; GET/DELETE answer 405.* Creating a new McpServer per request is safe and avoids the single-transport constraint;* tool registration is O(n) pure function calls with no I/O overhead.*/@@ -246,7 +246,8 @@ export function mountMcpServer(}};- const adapter = httpAdapter as unknown as { post: (path: string, ...handlers: RequestHandler[]) => unknown };+ type Mount = (path: string, ...handlers: RequestHandler[]) => unknown;+ const adapter = httpAdapter as unknown as { post: Mount; get: Mount; delete: Mount };// The route throttle gates the auth DB lookup and per-request MCP server/transport construction. The// process-wide capped json() in main.ts runs first for all routes; this route-level parser is a// defensive fallback and no-ops once the global parser has consumed the body. It sits before the@@ -258,4 +259,16 @@ export function mountMcpServer(// silently leave this mount uncapped.const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);adapter.post(basePath, express.json({ limit: bodyLimit, inflate: false }), createIpThrottle(ipRateLimiter), handler);+ // Stateless transport: no standalone SSE stream and no session to delete. The Streamable HTTP spec+ // requires a GET to be answered with a stream or 405, and SDK clients treat anything but 405 as an+ // error on every connect. Routing these to the transport would open a stream (GET) or answer 200+ // (DELETE), so they are refused here without touching auth or the DB.+ const methodNotAllowed: RequestHandler = (_req, res) => {+ res+ .status(405)+ .set('Allow', 'POST')+ .json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed.' }, id: null });+ };+ adapter.get(basePath, methodNotAllowed);+ adapter.delete(basePath, methodNotAllowed);}diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.tsindex 1798c79fa..ad20318ef 100644--- a/test/mcp-auth.e2e-spec.ts+++ b/test/mcp-auth.e2e-spec.ts@@ -146,6 +146,22 @@ describe('MCP server (e2e)', () => {expect(res.status).toBe(415);});+ // ---------------------------------------------------------------------------+ // 4b. GET / DELETE: the stateless transport offers no SSE stream and no session,+ // so both answer 405 (an SDK client treats anything else as an error)+ // ---------------------------------------------------------------------------+ it('GET and DELETE /mcp answer 405 with Allow: POST', async () => {+ const server = app.getHttpServer();+ const get = await request(server).get('/mcp').set('Accept', 'text/event-stream');+ expect(get.status).toBe(405);+ expect(get.headers['allow']).toBe('POST');+ expect(get.body).toEqual({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed.' }, id: null });++ const del = await request(server).delete('/mcp');+ expect(del.status).toBe(405);+ expect(del.headers['allow']).toBe('POST');+ });+// ---------------------------------------------------------------------------// 5. MCP_READONLY mode — write tools hidden from catalogue// Tested at integration level: the `readOnly` flag path in mcp.server.ts