Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp): stop a chat history read when the client leaves

Yudhi Armyndharis1c6742361944
diff --git a/src/core/agent-tools/tool-descriptor.ts b/src/core/agent-tools/tool-descriptor.ts
index 5cbe3b136..100dc4f21 100644
--- a/src/core/agent-tools/tool-descriptor.ts
+++ b/src/core/agent-tools/tool-descriptor.ts
@@ -25,7 +25,7 @@ export interface ToolDescriptor<I = unknown> {
/** The quote resolves within the authorized chat, as it does on the REST reply route. */
chatQuotedAllowed?: boolean;
/** Calls the service. Receives validated input + the resolved, scoped key. */
- handler: (input: I, apiKey: ApiKey, chatScope?: ChatScopeService) => Promise<unknown>;
+ handler: (input: I, apiKey: ApiKey, chatScope?: ChatScopeService, signal?: AbortSignal) => Promise<unknown>;
}
/**
@@ -42,7 +42,7 @@ export interface ToolDescriptor<I = unknown> {
*/
export type AnyToolDescriptor = Omit<ToolDescriptor, 'inputSchema' | 'handler'> & {
inputSchema: z.ZodType;
- handler: (input: never, apiKey: ApiKey, chatScope?: ChatScopeService) => Promise<unknown>;
+ handler: (input: never, apiKey: ApiKey, chatScope?: ChatScopeService, signal?: AbortSignal) => Promise<unknown>;
};
/**
diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.ts
index fd1a4460f..1c956543d 100644
--- a/src/core/agent-tools/tool-invoker.spec.ts
+++ b/src/core/agent-tools/tool-invoker.spec.ts
@@ -34,6 +34,23 @@ describe('invokeTool', () => {
expect(out).toEqual({ got: 5 });
});
+ it('hands the cancellation signal to the handler', async () => {
+ const handler = jest.fn().mockResolvedValue('ok');
+ const tool: ToolDescriptor = { ...readTool, handler };
+ const controller = new AbortController();
+ await invokeTool(
+ tool,
+ { n: 1 },
+ 'rawkey',
+ auth() as unknown as AuthService,
+ undefined,
+ undefined,
+ undefined,
+ controller.signal,
+ );
+ expect(handler).toHaveBeenCalledWith({ n: 1 }, expect.objectContaining({ id: 'k1' }), undefined, controller.signal);
+ });
+
it('refuses a chat-restricted key on a tool that declares no chat scope', async () => {
const a = auth({ allowedChats: ['[email protected]'] });
await expect(invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService)).rejects.toBeInstanceOf(
diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.ts
index 7ba77a462..ae9072bd9 100644
--- a/src/core/agent-tools/tool-invoker.ts
+++ b/src/core/agent-tools/tool-invoker.ts
@@ -24,6 +24,8 @@ import type { AnyToolDescriptor } from './tool-descriptor';
* allowed, a tool the chat-restricted key may not run, or a chat argument outside
* its allowlist). Schema validation errors and handler errors do not reach this
* callback. Re-thrown after it.
+ * @param signal Optional cancellation signal (the MCP client went away or cancelled the request), handed
+ * to the handler so a long call can stop.
*/
export async function invokeTool(
tool: AnyToolDescriptor,
@@ -33,6 +35,7 @@ export async function invokeTool(
onAuthenticated?: (apiKeyId: string) => void,
onAuthFailure?: (error: unknown) => void,
chatScope?: ChatScopeService,
+ signal?: AbortSignal,
): Promise<unknown> {
// AUTH PHASE β€” every rejection here is an authentication/authorization failure (the MCP analog of the
// REST ApiKeyGuard's authorize()). Wrapped so onAuthFailure can record the audit trail at the boundary.
@@ -112,5 +115,5 @@ export async function invokeTool(
}
// The single cast the erasure needs, placed next to the parse that justifies it: `input` is
// whatever this tool's own `inputSchema` just accepted, which is exactly what its handler declares.
- return tool.handler(input as never, apiKey, chatScope);
+ return tool.handler(input as never, apiKey, chatScope, signal);
}
diff --git a/src/core/agent-tools/tools/message.tools.spec.ts b/src/core/agent-tools/tools/message.tools.spec.ts
index c37efc30e..ecf11064f 100644
--- a/src/core/agent-tools/tools/message.tools.spec.ts
+++ b/src/core/agent-tools/tools/message.tools.spec.ts
@@ -51,10 +51,27 @@ describe('messageTools', () => {
includeMedia: true,
deep: true,
});
- expect(getChatHistory).toHaveBeenCalledWith('s1', '[email protected]', 50, true, true);
+ expect(getChatHistory).toHaveBeenCalledWith('s1', '[email protected]', 50, true, true, undefined);
expect(out).toEqual([{ id: 'm1' }]);
});
+ it('MessageHistory hands the request cancellation signal to getChatHistory', async () => {
+ const getChatHistory = jest.fn().mockResolvedValue([]);
+ const tools = makeTools({ getChatHistory } as unknown as MessageService);
+ const controller = new AbortController();
+ await invokeTool(
+ tools.get('MessageHistory')!,
+ { sessionId: 's1', chatId: '[email protected]' },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ undefined,
+ undefined,
+ undefined,
+ controller.signal,
+ );
+ expect((getChatHistory.mock.calls[0] as unknown[])[5]).toBe(controller.signal);
+ });
+
it('MessageGetReactions delegates to getMessageReactions', async () => {
const getMessageReactions = jest.fn().mockResolvedValue([{ emoji: 'πŸ‘' }]);
const tools = makeTools({ getMessageReactions } as unknown as MessageService);
diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.ts
index b395448bf..bb3e013b2 100644
--- a/src/core/agent-tools/tools/message.tools.ts
+++ b/src/core/agent-tools/tools/message.tools.ts
@@ -127,8 +127,8 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
includeMedia: z.boolean().optional().describe('Download media as base64 (slower)'),
deep: z.boolean().optional().describe('Raise limit ceiling to 2000 for reaching further back in history'),
}),
- handler: input =>
- message.getChatHistory(input.sessionId, input.chatId, input.limit, input.includeMedia, input.deep),
+ handler: (input, _apiKey, _chatScope, signal) =>
+ message.getChatHistory(input.sessionId, input.chatId, input.limit, input.includeMedia, input.deep, signal),
}),
defineTool({
name: 'MessageGetReactions',
diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.ts
index a302817c7..c96774b7e 100644
--- a/src/modules/mcp/mcp.server.spec.ts
+++ b/src/modules/mcp/mcp.server.spec.ts
@@ -588,6 +588,23 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {
expect(h.auditService.logWarn).not.toHaveBeenCalled();
});
+ it('hands the SDK request cancellation signal to the tool handler', async () => {
+ const h = mount();
+ h.authService.validateApiKey.mockResolvedValue({ id: 'k1' });
+ await post(h, { jsonrpc: '2.0', id: 1 });
+ const controller = new AbortController();
+ let received: AbortSignal | undefined;
+ h.tool.handler = (_input, _key, _scope, signal) => {
+ received = signal;
+ return Promise.resolve({ ok: true });
+ };
+ await toolCallback()(
+ { sessionId: 's1', to: '123', text: 'hi' },
+ { authInfo: { token: 'good-key' }, signal: controller.signal },
+ );
+ expect(received).toBe(controller.signal);
+ });
+
// One parser for every surface that reads Authorization, so a header the REST guard accepts is
// accepted here too and one it refuses is refused here too.
it.each([
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index 01810685c..d246d05c5 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -135,6 +135,7 @@ function buildServer(
// as auth failures. Best-effort; success and non-auth errors skip this.
error => auditMcpAuthFailure(auditService, error, reqContext),
chatScope,
+ extra.signal,
);
return smartToolResult(result as object);
} catch (error) {