Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(mcp): enforce chat scopes on tools (#1776)
Yudhi Armyndharise3afa6a31b01
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex debc50ecd..8399cacc8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- Allow chat-restricted MCP keys to read and send within their chat allowlist using the REST authorization rules.- Carry `chatId` in `message.ack` and `message.failed` payloads so a webhook `chatId` filter scopes delivery events per chat.- Filter stored messages by time, direction, type or message reference, with stable message-time pagination.- Scope built-in message search and group detail/settings to a chat-restricted key's allowed chats; reject plugin search for these keys.diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 35ce8207a..497d2ac0f 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -201,10 +201,7 @@ only when an agent genuinely needs to send messages / mutate state.- **Do not expose `/mcp` to the public internet** without a fronting authentication proxy.The static API key is appropriate for a self-hosted, locally/network-reached deployment;public exposure should wait for OAuth 2.1 support (planned).-- **Chat-restricted keys are refused.** A key carrying `allowedChats` gets an `isError` tool- result naming `ForbiddenException` ("API key is restricted to selected chats") on every tool- call, the same default deny REST applies to routes with no chat dimension. Use a session-scoped- key for MCP instead.+- **Chat-restricted keys use the REST chat fence.** Message, contact, presence, label membership, and group detail/settings tools authorize their chat arguments against `allowedChats`, including persisted phone/LID aliases. Forwarding requires both chats to be allowed. Message listing requires an explicit chat; chat, contact, group, and label chat lists filter the complete result before pagination. Ordinary send quotes are refused; `MessageReply` resolves its quote inside the authorized chat. Account-wide tools without a chat fence remain refused, including session discovery/statistics, webhook management, and group creation/invites. `SessionFindOne` remains available within `allowedSessions`. Rejections return an `isError` tool result with `ForbiddenException`; role and session restrictions still apply.- **IP-restricted keys are refused.** The `/mcp` gate cannot check the client address, so a keywith `allowedIps` gets `403` on every request. Use a key without an IP allow-list for MCP.@@ -227,6 +224,7 @@ Keep the blast radius small:- Leave `MCP_READONLY` at its default unless the agent must write.- Give a read-only agent a `VIEWER` key, and scope every MCP key to the sessions it needs(`allowedSessions`).+- Set `allowedChats` when the client should read or send only selected conversations.- When write tools are on, have the MCP client ask a human to confirm each write call.## 24.6 Enabling & Client Setupdiff --git a/src/core/agent-tools/tool-chat-scope.spec.ts b/src/core/agent-tools/tool-chat-scope.spec.tsnew file mode 100644index 000000000..b5460ddce--- /dev/null+++ b/src/core/agent-tools/tool-chat-scope.spec.ts@@ -0,0 +1,161 @@+import { ForbiddenException } from '@nestjs/common';+import { z } from 'zod';+import { ChatScopeService } from '../../modules/auth/chat-scope.service';+import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import type { AuthService } from '../../modules/auth/auth.service';+import type { ContactService } from '../../modules/contact/contact.service';+import type { GroupService } from '../../modules/group/group.service';+import type { LabelService } from '../../modules/label/label.service';+import type { MessageService } from '../../modules/message/message.service';+import type { SessionService } from '../../modules/session/session.service';+import { messageTools } from './tools/message.tools';+import { sessionTools } from './tools/session.tools';+import { contactTools } from './tools/contact.tools';+import { groupTools } from './tools/group.tools';+import { labelTools } from './tools/label.tools';+import { invokeTool } from './tool-invoker';+import { defineTool, type AnyToolDescriptor } from './tool-descriptor';++const CHAT = '[email protected]';+const OTHER = '[email protected]';+const key = { id: 'scoped-key', allowedSessions: ['s1'], allowedChats: [CHAT] };+const auth = {+ validateApiKey: jest.fn().mockResolvedValue(key),+ hasPermission: jest.fn().mockReturnValue(true),+} as unknown as AuthService;++const call = (tool: AnyToolDescriptor, input: unknown, scope = new ChatScopeService()) =>+ invokeTool(tool, input, 'key', auth, undefined, undefined, scope);++describe('chat-restricted tool calls', () => {+ const sendText = jest.fn().mockResolvedValue({ messageId: 'm1' });+ const forward = jest.fn().mockResolvedValue({ messageId: 'm2' });+ const reply = jest.fn().mockResolvedValue({ messageId: 'm3' });+ const tools = messageTools({ sendText, forward, reply } as unknown as MessageService);+ const tool = (name: string) => tools.find(t => t.name === name)!;++ beforeEach(() => jest.clearAllMocks());++ it('allows a send to an allowed chat through the shared invoker', async () => {+ await expect(call(tool('MessageSendText'), { sessionId: 's1', chatId: CHAT, text: 'hello' })).resolves.toEqual({+ messageId: 'm1',+ });+ expect(sendText).toHaveBeenCalledTimes(1);+ });++ it('refuses an outside destination before sending', async () => {+ await expect(+ call(tool('MessageSendText'), { sessionId: 's1', chatId: OTHER, text: 'hello' }),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(sendText).not.toHaveBeenCalled();+ });++ it('allows phone dialects and a persisted LID twin but refuses an unmapped LID', async () => {+ const scope = new ChatScopeService({+ findPhoneForLid: jest.fn(lid => Promise.resolve(lid === '123456' ? '628111000111' : undefined)),+ findLidsForPhone: jest.fn().mockResolvedValue(['123456']),+ } as unknown as LidMappingStoreService);+ for (const chatId of ['[email protected]', '123456@lid']) {+ await call(tool('MessageSendText'), { sessionId: 's1', chatId, text: 'hello' }, scope);+ }+ await expect(+ call(tool('MessageSendText'), { sessionId: 's1', chatId: '654321@lid', text: 'hello' }, scope),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(sendText).toHaveBeenCalledTimes(2);+ });++ it('fails closed without the scope service or with an unmarked tool', async () => {+ await expect(+ invokeTool(tool('MessageSendText'), { sessionId: 's1', chatId: CHAT, text: 'hello' }, 'key', auth),+ ).rejects.toBeInstanceOf(ForbiddenException);+ const descriptor = sessionTools({} as SessionService).find(t => t.name === 'SessionGetStats')!;+ await expect(call(descriptor, {})).rejects.toBeInstanceOf(ForbiddenException);+ expect(sendText).not.toHaveBeenCalled();+ });++ it('authorizes the parsed destination and records a scope refusal before the handler', async () => {+ const handler = jest.fn();+ const rejected = jest.fn();+ const descriptor = defineTool({+ name: 'NormalizedDestination',+ description: 'Send to a normalized destination',+ tier: 'write',+ chatScope: ['chatId'],+ inputSchema: z.object({ chatId: z.string().transform(() => OTHER) }),+ handler,+ });+ await expect(+ invokeTool(descriptor, { chatId: CHAT }, 'key', auth, undefined, rejected, new ChatScopeService()),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(handler).not.toHaveBeenCalled();+ expect(rejected).toHaveBeenCalledWith(expect.any(ForbiddenException));+ });++ it.each([+ { fromChatId: OTHER, toChatId: CHAT },+ { fromChatId: CHAT, toChatId: OTHER },+ ])('fences both endpoints of a forward: %j', async endpoints => {+ await expect(+ call(tool('MessageForward'), { sessionId: 's1', messageId: 'm1', ...endpoints }),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(forward).not.toHaveBeenCalled();+ });++ it('allows forwarding when both endpoints are inside the allowlist', async () => {+ await expect(+ call(tool('MessageForward'), { sessionId: 's1', fromChatId: CHAT, toChatId: CHAT, messageId: 'm1' }),+ ).resolves.toEqual({ messageId: 'm2' });+ });++ it('refuses ordinary send quotes but permits a reply bound to its allowed chat', async () => {+ const input = { sessionId: 's1', chatId: CHAT, text: 'hello', quotedMessageId: 'quoted' };+ await expect(call(tool('MessageSendText'), input)).rejects.toBeInstanceOf(ForbiddenException);+ expect(sendText).not.toHaveBeenCalled();+ await expect(call(tool('MessageReply'), input)).resolves.toEqual({ messageId: 'm3' });+ });++ it('requires a chat for message listing even when its schema makes chatId optional', async () => {+ await expect(call(tool('MessageList'), { sessionId: 's1' })).rejects.toBeInstanceOf(ForbiddenException);+ });++ it('filters the complete chat list before applying the requested page', async () => {+ const chats = [{ id: OTHER }, { id: CHAT }];+ const listChats = jest.fn().mockResolvedValue(chats);+ const getChats = jest.fn().mockResolvedValue(chats.slice(0, 1));+ const descriptor = sessionTools({ listChats, getChats } as unknown as SessionService).find(+ t => t.name === 'SessionGetChats',+ )!;+ await expect(call(descriptor, { sessionId: 's1', limit: 1 })).resolves.toEqual([{ id: CHAT }]);+ expect(listChats).toHaveBeenCalledWith('s1');+ expect(getChats).not.toHaveBeenCalled();+ });++ it.each(['ContactFindAll', 'GroupFindAll'])(+ 'filters %s beyond the first thousand rows before pagination',+ async name => {+ const allowed = [{ id: CHAT }, { id: CHAT, name: 'second' }];+ const all = [...Array.from({ length: 1001 }, () => ({ id: OTHER })), ...allowed];+ const list = jest.fn().mockResolvedValue(all);+ const paged = jest.fn();+ const descriptors =+ name === 'ContactFindAll'+ ? contactTools({ listContacts: list, getContacts: paged } as unknown as ContactService)+ : groupTools({ listGroups: list, getGroups: paged } as unknown as GroupService);+ await expect(+ call(+ descriptors.find(t => t.name === name)!,+ { sessionId: 's1', limit: 1, offset: 1 },+ ),+ ).resolves.toEqual([allowed[1]]);+ expect(list).toHaveBeenCalledWith('s1');+ expect(paged).not.toHaveBeenCalled();+ },+ );++ it('filters label chat membership', async () => {+ const descriptor = labelTools({+ getChatsByLabel: jest.fn().mockResolvedValue([{ id: OTHER }, { id: CHAT }]),+ } as unknown as LabelService).find(t => t.name === 'LabelListChats')!;+ await expect(call(descriptor, { sessionId: 's1', labelId: '1' })).resolves.toEqual([{ id: CHAT }]);+ });+});diff --git a/src/core/agent-tools/tool-descriptor.ts b/src/core/agent-tools/tool-descriptor.tsindex 014141a70..5b77d9410 100644--- a/src/core/agent-tools/tool-descriptor.ts+++ b/src/core/agent-tools/tool-descriptor.ts@@ -1,6 +1,7 @@import type { z } from 'zod';import type { ApiKey } from '../../modules/auth/entities/api-key.entity';import type { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';+import type { ChatScopeService } from '../../modules/auth/chat-scope.service';/** A single agent-invocable capability. Protocol-neutral: no MCP types here. */export interface ToolDescriptor<I = unknown> {@@ -19,10 +20,14 @@ export interface ToolDescriptor<I = unknown> {requiredRole?: ApiKeyRole;/** If true, input MUST carry `sessionId`, checked against the key's allowedSessions. */sessionScoped?: boolean;+ /** Allowed chat input fields, a filtered list, or a chat-independent operation. Unmarked tools deny restricted keys. */+ chatScope?: readonly string[] | 'filtered' | 'agnostic';+ /** The quote resolves within the authorized chat, as it does on the REST reply route. */+ chatQuotedAllowed?: boolean;/** Result rendering hint for the MCP adapter. Default 'smart'. */resultDisposition?: 'json' | 'smart';/** Calls the service. Receives validated input + the resolved, scoped key. */- handler: (input: I, apiKey: ApiKey) => Promise<unknown>;+ handler: (input: I, apiKey: ApiKey, chatScope?: ChatScopeService) => Promise<unknown>;}/**@@ -39,7 +44,7 @@ export interface ToolDescriptor<I = unknown> {*/export type AnyToolDescriptor = Omit<ToolDescriptor, 'inputSchema' | 'handler'> & {inputSchema: z.ZodType;- handler: (input: never, apiKey: ApiKey) => Promise<unknown>;+ handler: (input: never, apiKey: ApiKey, chatScope?: ChatScopeService) => Promise<unknown>;};/**diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsindex 44de96623..7e2785149 100644--- a/src/core/agent-tools/tool-invoker.ts+++ b/src/core/agent-tools/tool-invoker.ts@@ -2,6 +2,7 @@ import { BadRequestException, ForbiddenException, UnauthorizedException } from 'import { ZodError } from 'zod';import { containsNul } from '../../common/validation/no-nul-character';import type { AuthService } from '../../modules/auth/auth.service';+import type { ChatScopeService } from '../../modules/auth/chat-scope.service';import type { AnyToolDescriptor } from './tool-descriptor';/**@@ -17,9 +18,8 @@ import type { AnyToolDescriptor } from './tool-descriptor';* string, preventing pre-auth bucket allocation by anonymous callers.* @param onAuthFailure Optional callback invoked with the error when the AUTH* phase rejects (missing/invalid/revoked/expired key, wrong role, IP/session not- * allowed). Mirrors the REST ApiKeyGuard's auth-failure hook (which records the- * audit trail). Fires BEFORE input validation and the tool handler, so a 401/403- * thrown from a handler body is NOT surfaced here. Re-thrown after the callback.+ * allowed). Chat argument checks run after parsing so normalized values remain+ * authorized. Handler errors do not reach this callback. Re-thrown after it.*/export async function invokeTool(tool: AnyToolDescriptor,@@ -28,6 +28,7 @@ export async function invokeTool(authService: AuthService,onAuthenticated?: (apiKeyId: string) => void,onAuthFailure?: (error: unknown) => void,+ chatScope?: ChatScopeService,): 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.@@ -56,10 +57,8 @@ export async function invokeTool(throw new ForbiddenException('API key lacks the required role');}- // Tools carry no chat-scope marks, so a chat-restricted key cannot be confined to its chats here:- // refuse it outright rather than let a tool act on any chat. Mirrors the REST guard's- // default-deny for routes with no chat dimension.- if ((apiKey.allowedChats?.length ?? 0) > 0) {+ // Restricted keys may reach only explicitly fenced, filtered or chat-independent tools.+ if ((apiKey.allowedChats?.length ?? 0) > 0 && (!tool.chatScope || !chatScope)) {throw new ForbiddenException('API key is restricted to selected chats');}} catch (error) {@@ -69,7 +68,7 @@ export async function invokeTool(throw error;}- // VALIDATION + HANDLER PHASE — not part of auth; their errors are not auth failures.+ // Validate before checking chat arguments; validation errors are not auth failures.let input: unknown;try {input = tool.inputSchema.parse(rawInput);@@ -81,7 +80,33 @@ export async function invokeTool(}// PostgreSQL rejects U+0000 in every text parameter; REST refuses the same input in NulBodyPipe.if (containsNul(input)) throw new BadRequestException('Tool input must not contain a NUL character');+ if (chatScope?.isRestricted(apiKey)) {+ try {+ // Inspect the parsed values, so schema normalization cannot change the authorized target.+ const values = input !== null && typeof input === 'object' ? (input as Record<string, unknown>) : {};+ if (typeof tool.chatScope !== 'string') {+ const fields = tool.chatScope ?? [];+ if (fields.length === 0) throw new ForbiddenException('API key is restricted to selected chats');+ for (const field of fields) {+ const chatId = values[field];+ if (typeof chatId !== 'string' || !chatId.trim()) {+ throw new ForbiddenException(`${field} is required for a key restricted to selected chats`);+ }+ if (!(await chatScope.allows(apiKey, chatId))) {+ throw new ForbiddenException('API key not authorized for this chat');+ }+ }+ }+ const quote = values.quotedMessageId;+ if (!tool.chatQuotedAllowed && quote !== undefined && quote !== null && quote !== '') {+ throw new ForbiddenException('API key is restricted to selected chats');+ }+ } catch (error) {+ onAuthFailure?.(error);+ throw error;+ }+ }// 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);+ return tool.handler(input as never, apiKey, chatScope);}diff --git a/src/core/agent-tools/tools/contact.tools.ts b/src/core/agent-tools/tools/contact.tools.tsindex 36ae4a334..813750ed8 100644--- a/src/core/agent-tools/tools/contact.tools.ts+++ b/src/core/agent-tools/tools/contact.tools.ts@@ -2,6 +2,7 @@ import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { ContactService } from '../../../modules/contact/contact.service';import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';+import { paginate } from '../../../common/utils/paginate';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -9,6 +10,7 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {return [defineTool({name: 'ContactFindAll',+ chatScope: 'filtered',description: 'List all contacts for a session. Use limit/offset to page through large contact lists.',tier: 'read',sessionScoped: true,@@ -17,10 +19,17 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {limit: z.number().int().min(1).max(1000).optional(),offset: z.number().int().min(0).optional(),}),- handler: input => contact.getContacts(input.sessionId, { limit: input.limit, offset: input.offset }),+ handler: async (input, apiKey, chatScope) => {+ if (!chatScope?.isRestricted(apiKey)) {+ return contact.getContacts(input.sessionId, { limit: input.limit, offset: input.offset });+ }+ const visible = await chatScope.filter(apiKey, await contact.listContacts(input.sessionId), item => item.id);+ return paginate(visible, input.limit, input.offset);+ },}),defineTool({name: 'ContactFindOne',+ chatScope: ['contactId'],description: 'Get details for a specific contact by JID (e.g. [email protected]).',tier: 'read',sessionScoped: true,@@ -48,6 +57,7 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {}),defineTool({name: 'ContactResolvePhone',+ chatScope: ['contactId'],description:'Resolve a contact JID (e.g. an @lid) to a phone number. Best-effort — returns null when the engine cannot map it.',tier: 'read',@@ -63,6 +73,7 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {}),defineTool({name: 'ContactGetProfilePicture',+ chatScope: ['contactId'],description: 'Get the profile picture URL for a contact.',tier: 'read',sessionScoped: true,@@ -77,6 +88,7 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {}),defineTool({name: 'ContactBlock',+ chatScope: ['contactId'],description: 'Block a contact. The contact will no longer be able to send messages. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -92,6 +104,7 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {}),defineTool({name: 'ContactUnblock',+ chatScope: ['contactId'],description: 'Unblock a previously blocked contact. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex c1f9f65ab..4aa67217c 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -7,6 +7,7 @@ import {GROUP_PARTICIPANTS_MAX,} from '../../../modules/group/dto/group.dto';import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';+import { paginate } from '../../../common/utils/paginate';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -14,6 +15,7 @@ export function groupTools(group: GroupService): AnyToolDescriptor[] {return [defineTool({name: 'GroupFindAll',+ chatScope: 'filtered',description: 'List all groups the session is a member of. Use limit/offset to page.',tier: 'read',sessionScoped: true,@@ -22,10 +24,17 @@ export function groupTools(group: GroupService): AnyToolDescriptor[] {limit: z.number().int().min(1).max(1000).optional(),offset: z.number().int().min(0).optional(),}),- handler: input => group.getGroups(input.sessionId, { limit: input.limit, offset: input.offset }),+ handler: async (input, apiKey, chatScope) => {+ if (!chatScope?.isRestricted(apiKey)) {+ return group.getGroups(input.sessionId, { limit: input.limit, offset: input.offset });+ }+ const visible = await chatScope.filter(apiKey, await group.listGroups(input.sessionId), item => item.id);+ return paginate(visible, input.limit, input.offset);+ },}),defineTool({name: 'GroupFindOne',+ chatScope: ['groupId'],description: 'Get detailed info for a specific group including participants list.',tier: 'read',sessionScoped: true,@@ -103,6 +112,7 @@ export function groupTools(group: GroupService): AnyToolDescriptor[] {}),defineTool({name: 'GroupSetSubject',+ chatScope: ['groupId'],description: 'Change the group name/subject. Requires OPERATOR role.',tier: 'write',destructive: true,@@ -120,6 +130,7 @@ export function groupTools(group: GroupService): AnyToolDescriptor[] {}),defineTool({name: 'GroupSetDescription',+ chatScope: ['groupId'],description: 'Change the group description. Pass empty string to clear it. Requires OPERATOR role.',tier: 'write',destructive: true,diff --git a/src/core/agent-tools/tools/label.tools.ts b/src/core/agent-tools/tools/label.tools.tsindex a0aa4c5bc..de1ed7279 100644--- a/src/core/agent-tools/tools/label.tools.ts+++ b/src/core/agent-tools/tools/label.tools.ts@@ -37,16 +37,21 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {}),defineTool({name: 'LabelListChats',+ chatScope: 'filtered',description:'List the chats carrying a label. Use it to answer "which conversations are tagged X". ' +'WhatsApp Business only, and whatsapp-web.js only — Baileys answers 501.',tier: 'read',sessionScoped: true,inputSchema: z.object({ sessionId, labelId }),- handler: input => labels.getChatsByLabel(input.sessionId, input.labelId),+ handler: async (input, apiKey, chatScope) => {+ const chats = await labels.getChatsByLabel(input.sessionId, input.labelId);+ return chatScope ? chatScope.filter(apiKey, chats, chat => chat.id) : chats;+ },}),defineTool({name: 'LabelListForChat',+ chatScope: ['chatId'],description:'List the labels on one chat. WhatsApp Business only, and whatsapp-web.js only — Baileys answers 501.',tier: 'read',@@ -96,6 +101,7 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {}),defineTool({name: 'LabelAddToChat',+ chatScope: ['chatId'],description: 'Tag a chat with an existing label. Works on both engines. WhatsApp Business only.',tier: 'write',sessionScoped: true,@@ -106,6 +112,7 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {}),defineTool({name: 'LabelRemoveFromChat',+ chatScope: ['chatId'],description:'Remove a label from a chat, leaving the label itself in place. Works on both engines. ' +'WhatsApp Business only.',diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.tsindex 991b2cf85..123bed98d 100644--- a/src/core/agent-tools/tools/message.tools.ts+++ b/src/core/agent-tools/tools/message.tools.ts@@ -84,6 +84,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {return [defineTool({name: 'MessageList',+ chatScope: ['chatId'],description:'List persisted messages for a session, optionally filtered by chatId or sender. Reads from the local DB.',tier: 'read',@@ -105,6 +106,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageHistory',+ chatScope: ['chatId'],description:'Fetch live chat history from WhatsApp for a specific chat. Bypasses the local DB — useful for messages that arrived before the gateway started.',tier: 'read',@@ -127,6 +129,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageGetReactions',+ chatScope: ['chatId'],description: 'Get reactions for a specific message, including which contacts sent which emoji.',tier: 'read',sessionScoped: true,@@ -139,6 +142,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendText',+ chatScope: ['chatId'],description: 'Send a plain text message to a chat or group. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -170,6 +174,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendImage',+ chatScope: ['chatId'],description: 'Send an image message via URL or base64. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -199,6 +204,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendVideo',+ chatScope: ['chatId'],description: 'Send a video message via URL or base64. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -228,6 +234,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendAudio',+ chatScope: ['chatId'],description: 'Send an audio/voice message via URL or base64. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -259,6 +266,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendDocument',+ chatScope: ['chatId'],description: 'Send a document/file message via URL or base64. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -288,6 +296,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendLocation',+ chatScope: ['chatId'],description: 'Send a location pin message. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -313,6 +322,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendContact',+ chatScope: ['chatId'],description: 'Send a contact card message. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -338,6 +348,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendSticker',+ chatScope: ['chatId'],description: 'Send a sticker message via URL or base64. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -367,6 +378,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageSendTemplate',+ chatScope: ['chatId'],description:'Render a stored text template and send it as a text message. Provide either templateId or templateName. Requires OPERATOR role.',tier: 'write',@@ -394,6 +406,8 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageReply',+ chatQuotedAllowed: true,+ chatScope: ['chatId'],description: 'Reply to a specific message (quoted reply). Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -415,6 +429,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageForward',+ chatScope: ['fromChatId', 'toChatId'],description: 'Forward a message from one chat to another. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -434,6 +449,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {}),defineTool({name: 'MessageReact',+ chatScope: ['chatId'],description:'Add or remove a reaction emoji on a message. Send empty string emoji to remove. Requires OPERATOR role.',tier: 'write',diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex d3a9bf4f8..108ded23b 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -8,6 +8,7 @@ import {MARK_READ_MESSAGE_ID_PATTERN,} from '../../../modules/session/dto/mark-chat-read.dto';import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';+import { paginate } from '../../../common/utils/paginate';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -30,6 +31,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionFindOne',+ chatScope: 'agnostic',description: 'Get one session by its UUID, including connection status and phone number.',tier: 'read',sessionScoped: true,@@ -39,6 +41,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionGetChats',+ chatScope: 'filtered',description: 'List recent chats for a session (most recent first). Use limit/offset to page through large lists.',tier: 'read',sessionScoped: true,@@ -47,7 +50,13 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {limit: z.number().int().min(1).max(1000).optional(),offset: z.number().int().min(0).optional(),}),- handler: input => session.getChats(input.sessionId, { limit: input.limit, offset: input.offset }),+ handler: async (input, apiKey, chatScope) => {+ if (!chatScope?.isRestricted(apiKey)) {+ return session.getChats(input.sessionId, { limit: input.limit, offset: input.offset });+ }+ const visible = await chatScope.filter(apiKey, await session.listChats(input.sessionId), chat => chat.id);+ return paginate(visible, input.limit, input.offset);+ },}),defineTool({name: 'SessionGetStats',@@ -58,6 +67,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionSubscribePresence',+ chatScope: ['chatId'],description:"Subscribe to a chat's presence (online / typing / recording). Updates then arrive as " +'presence.update events; read the latest with SessionGetPresence. The subscription is lost on ' +@@ -74,6 +84,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionGetPresence',+ chatScope: ['chatId'],description:'The last presence reported for a chat, or null when none has been — the chat was never ' +'subscribed, or nothing has changed since. Subscribe first with SessionSubscribePresence.',@@ -88,6 +99,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionMarkChatRead',+ chatScope: ['chatId'],description: 'Mark a chat as read (clears unread count). Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -112,6 +124,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionMarkChatUnread',+ chatScope: ['chatId'],description: 'Mark a chat as unread. Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,@@ -124,6 +137,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {}),defineTool({name: 'SessionSendChatState',+ chatScope: ['chatId'],description: "Show a typing/recording indicator in a chat, or clear it with 'paused'. Requires OPERATOR role.",tier: 'write',requiredRole: ApiKeyRole.OPERATOR,diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex e83d0abab..54d36b7b7 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -65,12 +65,15 @@ export class GroupService {}}+ /** Every group before a caller applies authorization and pagination. */+ listGroups(sessionId: string) {+ return this.getEngine(sessionId).getGroups();+ }+getGroups(sessionId: string, opts: ListOptions = {}) {// getEngine throws synchronously (sync 400 guard); the engine returns the full set and we// bound the HTTP response window via paginate().- return this.getEngine(sessionId)- .getGroups()- .then(groups => paginate(groups, opts.limit, opts.offset));+ return this.listGroups(sessionId).then(groups => paginate(groups, opts.limit, opts.offset));}async getGroupInfo(sessionId: string, groupId: string) {diff --git a/src/modules/mcp/mcp.module.ts b/src/modules/mcp/mcp.module.tsindex 973df62d4..e4979cb40 100644--- a/src/modules/mcp/mcp.module.ts+++ b/src/modules/mcp/mcp.module.ts@@ -3,6 +3,7 @@ import { HttpAdapterHost } from '@nestjs/core';import { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';import { AuthService } from '../auth/auth.service';import { AuditService } from '../audit/audit.service';+import { ChatScopeService } from '../auth/chat-scope.service';import { KeyRateLimiter, readRateLimitConfig, readIpRateLimitConfig } from './mcp-rate-limit';import { mountMcpServer } from './mcp.server';@@ -23,6 +24,7 @@ export class McpModule implements NestModule {private readonly httpAdapterHost: HttpAdapterHost,// AuditModule is @Global(), so AuditService is injectable here without an explicit import.private readonly auditService: AuditService,+ private readonly chatScope: ChatScopeService,) {}static forRoot(options: McpModuleOptions = {}): DynamicModule {@@ -54,6 +56,7 @@ export class McpModule implements NestModule {ipRateLimiter,{ basePath, serverInfo },this.auditService,+ this.chatScope,);}}diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex f8dfe215a..c1d52e679 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -5,6 +5,7 @@ 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 { ChatScopeService } from '../auth/chat-scope.service';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';@@ -104,6 +105,7 @@ function buildServer(serverInfo: { name: string; version: string },auditService: AuditService | undefined,reqContext: McpRequestContext,+ chatScope?: ChatScopeService,): McpServer {const server = new McpServer({ name: serverInfo.name, version: serverInfo.version },@@ -137,9 +139,10 @@ function buildServer(id => rateLimiter.check(id),// onAuthFailure: mirror the REST ApiKeyGuard — record rejected/denied auth attempts (401/403// only) at the auth boundary so the audit trail covers MCP credential probing. Fires inside- // invokeTool's auth phase (before the tool handler), so handler-thrown 403s are NOT mislabeled+ // invokeTool's authorization checks (before the tool handler), so handler-thrown 403s are NOT mislabeled// as auth failures. Best-effort; success and non-auth errors skip this.error => auditMcpAuthFailure(auditService, error, reqContext),+ chatScope,);return tool.resultDisposition === 'json'? jsonToolResult(result as object)@@ -252,6 +255,7 @@ export function mountMcpServer(ipRateLimiter: KeyRateLimiter,options: MountMcpServerOptions = {},auditService?: AuditService,+ chatScope?: ChatScopeService,): void {const basePath = (options.basePath ?? '/mcp').replace(/\/$/, '') || '/mcp';const serverInfo = options.serverInfo ?? { name: 'openwa', version: '0.0.0' };@@ -272,6 +276,7 @@ export function mountMcpServer(serverInfo,auditService,resolveReqContext(req),+ chatScope,);const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });try {diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.tsindex 5f72d174b..4f3f181b0 100644--- a/test/mcp-auth.e2e-spec.ts+++ b/test/mcp-auth.e2e-spec.ts@@ -12,6 +12,7 @@ import { AppModule } from '../src/app.module';import { applyGlobalValidation } from '../src/config/app-validation';import { AuthService } from '../src/modules/auth/auth.service';import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';+import { SessionService } from '../src/modules/session/session.service';// --- MCP protocol helpers ---@@ -57,6 +58,7 @@ describe('MCP server (e2e)', () => {let viewerKey: string;let chatKey: string;let ipKey: string;+ const scopedSession = '11111111-1111-4111-8111-111111111111';const initialize = () =>jsonRpcRequest('initialize', {protocolVersion: '2025-11-25',@@ -76,7 +78,12 @@ describe('MCP server (e2e)', () => {const authService = app.get(AuthService);viewerKey = (await authService.createApiKey({ name: 'e2e-mcp-viewer', role: ApiKeyRole.VIEWER })).rawKey;chatKey = (- await authService.createApiKey({ name: 'e2e-mcp-chat', role: ApiKeyRole.VIEWER, allowedChats: ['[email protected]'] })+ await authService.createApiKey({+ name: 'e2e-mcp-chat',+ role: ApiKeyRole.VIEWER,+ allowedSessions: [scopedSession],+ allowedChats: ['[email protected]'],+ })).rawKey;ipKey = (await authService.createApiKey({ name: 'e2e-mcp-ip', role: ApiKeyRole.VIEWER, allowedIps: ['127.0.0.1'] })).rawKey;@@ -183,6 +190,69 @@ describe('MCP server (e2e)', () => {expect(content?.find(c => c.type === 'text')?.text ?? '').toMatch(/restricted to selected chats/i);});+ it('a chat-restricted key receives only allowed chats before pagination', async () => {+ const list = jest+ .spyOn(app.get(SessionService), 'listChats')+ .mockResolvedValue([{ id: '[email protected]' }, { id: '[email protected]' }] as Awaited<+ ReturnType<SessionService['listChats']>+ >);+ try {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set(MCP_HEADERS)+ .set('X-API-Key', chatKey)+ .send(+ jsonRpcRequest('tools/call', { name: 'SessionGetChats', arguments: { sessionId: scopedSession, limit: 1 } }),+ );+ expect(res.status).toBe(200);+ const result = parseMcpResponse(res).result as { isError?: boolean; content: Array<{ text: string }> };+ expect(result.isError).not.toBe(true);+ expect(JSON.parse(result.content[0].text)).toEqual([{ id: '[email protected]' }]);+ expect(list).toHaveBeenCalledWith(scopedSession);+ } finally {+ list.mockRestore();+ }+ });++ it('a chat-restricted key cannot read history from another chat', async () => {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set(MCP_HEADERS)+ .set('X-API-Key', chatKey)+ .send(+ jsonRpcRequest('tools/call', {+ name: 'MessageHistory',+ arguments: { sessionId: scopedSession, chatId: '[email protected]' },+ }),+ );+ expect(res.status).toBe(200);+ const result = parseMcpResponse(res).result as { isError?: boolean; content: Array<{ text: string }> };+ expect(result.isError).toBe(true);+ expect(result.content[0].text).toContain('API key not authorized for this chat');+ });++ it('chat filtering retains the session fence', async () => {+ const list = jest.spyOn(app.get(SessionService), 'listChats');+ try {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set(MCP_HEADERS)+ .set('X-API-Key', chatKey)+ .send(+ jsonRpcRequest('tools/call', {+ name: 'SessionGetChats',+ arguments: { sessionId: '22222222-2222-4222-8222-222222222222' },+ }),+ );+ expect(res.status).toBe(200);+ const result = parseMcpResponse(res).result as { isError?: boolean };+ expect(result.isError).toBe(true);+ expect(list).not.toHaveBeenCalled();+ } finally {+ list.mockRestore();+ }+ });+// ---------------------------------------------------------------------------// 4. Unsupported Content-Type → 415// ---------------------------------------------------------------------------