Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp): reuse the gate's validated key for every tool call

Yudhi Armyndharisf1dce65521c7
diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.ts
index c5d78a822..a000cc28b 100644
--- a/src/modules/mcp/mcp.server.spec.ts
+++ b/src/modules/mcp/mcp.server.spec.ts
@@ -609,6 +609,39 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {
else expect(h.authService.validateApiKey).toHaveBeenCalledWith(expected, undefined, 's1');
});
+ // Node keeps only the first of two Authorization headers, while the SDK's web Request joins them,
+ // so the tool call must reuse the key the gate validated rather than parse its own header copy.
+ it('uses the key the gate validated when the SDK headers carry a joined Authorization', async () => {
+ const h = mount();
+ h.authService.validateApiKey.mockResolvedValue({ id: 'k1' });
+ const gate = (h.adapter.post.mock.calls[0] as unknown[])[3] as (
+ req: Request,
+ res: Response,
+ next: () => void,
+ ) => Promise<void>;
+ const req = {
+ method: 'POST',
+ path: '/mcp',
+ headers: { authorization: 'Bearer good-key' },
+ body: { jsonrpc: '2.0', id: 1 },
+ socket: { remoteAddress: '203.0.113.7' },
+ } as unknown as Request & { auth?: unknown };
+ const next = jest.fn();
+ await gate(req, makeRes() as unknown as Response, next);
+ expect(next).toHaveBeenCalledTimes(1);
+ await h.routeHandler(req, makeRes() as unknown as Response);
+
+ const result = (await toolCallback()(
+ { sessionId: 's1', to: '123', text: 'hi' },
+ { authInfo: req.auth, requestInfo: { headers: { authorization: 'Bearer good-key, Bearer other-key' } } },
+ )) as { isError?: boolean };
+
+ expect(result.isError).toBeFalsy();
+ expect(h.authService.validateApiKey).toHaveBeenLastCalledWith('good-key', undefined, 's1');
+ expect(h.tool.handler).toHaveBeenCalledTimes(1);
+ expect(h.auditService.logWarn).not.toHaveBeenCalled();
+ });
+
it('fails closed on a session-scoped tool call without sessionId (guard fires before the auth lookup)', async () => {
const h = mount();
await post(h, { jsonrpc: '2.0', id: 1 }, { authorization: 'Bearer good-key' });
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index 1a6d654d8..cc189a011 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -4,6 +4,7 @@ import type { HttpAdapterHost } from '@nestjs/core';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { AnySchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
import express, { type Request, type RequestHandler, type Response } from 'express';
@@ -32,9 +33,9 @@ export interface McpRequestContext {
}
/**
- * Extract the raw API key from request headers. Accepts X-Api-Key or Bearer token. The one parser for
- * both the mount gate (Express headers) and the per-tool check (the SDK's request headers), so the two
- * cannot disagree on what the credential is.
+ * Extract the raw API key from request headers. Accepts X-Api-Key or Bearer token. The mount gate parses
+ * the Express headers and hands the key it validated to the per-tool check as `authInfo`, so the two
+ * cannot disagree on what the credential is (the SDK's own header copy joins duplicate headers).
*/
function extractApiKey(headers: Record<string, string | string[] | undefined> = {}): string | undefined {
const xApiKey = headers['x-api-key'];
@@ -126,7 +127,7 @@ function buildServer(
},
},
async (input: Record<string, unknown>, extra: ToolExtra) => {
- const rawKey = extractApiKey(extra.requestInfo?.headers);
+ const rawKey = extra.authInfo?.token ?? extractApiKey(extra.requestInfo?.headers);
try {
const result = await invokeTool(
tool,
@@ -215,6 +216,8 @@ export function createKeyGate(
const rawKey = extractApiKey(req.headers);
if (!rawKey) throw new UnresolvedApiKeyException('Missing API key');
await authService.validateApiKey(rawKey, undefined, undefined, { recordUsage: false });
+ // The transport forwards req.auth to every tool call as extra.authInfo.
+ (req as Request & { auth?: AuthInfo }).auth = { token: rawKey, clientId: 'api-key', scopes: [] };
} catch (err) {
if (err instanceof HttpException) {
auditMcpAuthFailure(auditService, err, resolveReqContext(req));