Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(mcp): accept mentions on the agent tools
Yudhi Armyndharisb722a3770cd2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a4c2532be..e7bf96302 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed+- The agent tools accept `mentions` on the text, media, template and reply sends, matching the REST routes. A tool schema is not strict, so an agent that passed the field before had it dropped without an error and the message went out untagged. Not offered on the sticker tool, whose adapters build no tag list.- `mentions` reaches every route whose engine can carry it: `reply`, `edit`, `send-template` and each `send-bulk` item, alongside the send routes that already had it. `send-template` also gained `linkPreview`. On `edit` the tags are re-applied rather than preserved, because an edit replaces the message content. Thanks @Magnarks for the report.- `POST /sessions/{sessionId}/chats/unread` publishes its own `MarkChatUnreadDto` rather than sharing `MarkChatReadDto`. The body is unchanged (`chatId` alone), but a generated client sees the schema under a new name.- ⚠️ **Breaking (Go, Java and typed Python callers).** `markRead` and `subscribePresence` each take their own request type rather than the shared `MarkChatRequest`, which now serves `markUnread` alone. Swap the type at both call sites; the wire body is unchanged and the JavaScript and PHP clients are unaffected. `SubscribePresenceDto` had no contract-gate coverage while one type stood for two routes.diff --git a/src/core/agent-tools/tools/message.tools.spec.ts b/src/core/agent-tools/tools/message.tools.spec.tsindex 03f05a149..03088480a 100644--- a/src/core/agent-tools/tools/message.tools.spec.ts+++ b/src/core/agent-tools/tools/message.tools.spec.ts@@ -267,6 +267,69 @@ describe('messageTools', () => {expect(out).toEqual({ id: 'm2' });});+ it('forwards a tag list on the text and reply tools', async () => {+ const sendText = jest.fn().mockResolvedValue({ id: 'm1' });+ const reply = jest.fn().mockResolvedValue({ id: 'm2' });+ const tools = makeTools({ sendText, reply } as unknown as MessageService);++ await run(tools.get('MessageSendText')!, {+ sessionId: 's1',+ chatId: '[email protected]',+ text: 'hi @62811',+ mentions: ['[email protected]'],+ });+ expect(sendText).toHaveBeenCalledWith('s1', expect.objectContaining({ mentions: ['[email protected]'] }));++ await run(tools.get('MessageReply')!, {+ sessionId: 's1',+ chatId: '[email protected]',+ quotedMessageId: 'm1',+ text: 'hi @62811',+ mentions: ['[email protected]'],+ });+ expect(reply).toHaveBeenCalledWith('s1', expect.objectContaining({ mentions: ['[email protected]'] }));+ });++ it('refuses a tag that is not an individual WID, instead of dropping it', async () => {+ // The whole point of declaring the field here. A tool schema is a plain z.object, so before it was+ // declared an agent's `mentions` was stripped silently and the send reported success; and this path+ // calls the service directly, so no ValidationPipe ever sees the value.+ const sendText = jest.fn().mockResolvedValue({ id: 'm1' });+ const tools = makeTools({ sendText } as unknown as MessageService);++ // The detail lives on the response, not on .message, which reads "Bad Request Exception".+ await expect(+ run(tools.get('MessageSendText')!, {+ sessionId: 's1',+ chatId: '[email protected]',+ text: 'hi',+ mentions: ['[email protected]'],+ }),+ ).rejects.toMatchObject({+ response: { message: [expect.stringContaining('individual WID') as unknown as string] },+ });+ expect(sendText).not.toHaveBeenCalled();+ });++ it('does not offer mentions on the sticker tool, whose adapters build no tag list', async () => {+ // Control for the additions above: the field is added where the layer behind it carries the value,+ // not everywhere. Both adapters build the sticker content without mentions, so declaring it here+ // would accept the field and drop it.+ const sendSticker = jest.fn().mockResolvedValue({ id: 'm1' });+ const tools = makeTools({ sendSticker } as unknown as MessageService);++ await run(tools.get('MessageSendSticker')!, {+ sessionId: 's1',+ chatId: '[email protected]',+ url: 'https://example.test/s.webp',+ mentions: ['[email protected]'],+ });+ // The KEY must be absent, not merely undefined: a schema that declared the field and forwarded it+ // would pass an `undefined` value here and satisfy a looser assertion.+ const [, forwarded] = sendSticker.mock.calls[0] as [string, Record<string, unknown>];+ expect(Object.keys(forwarded)).not.toContain('mentions');+ });+it('MessageForward delegates to forward', async () => {const forward = jest.fn().mockResolvedValue({ id: 'm2' });const tools = makeTools({ forward } as unknown as MessageService);diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.tsindex 59d76c0f4..024b218ec 100644--- a/src/core/agent-tools/tools/message.tools.ts+++ b/src/core/agent-tools/tools/message.tools.ts@@ -1,7 +1,12 @@import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { MessageService } from '../../../modules/message/message.service';-import { MESSAGE_TEXT_MAX_LENGTH } from '../../../modules/message/dto/send-message.dto';+import {+ MENTIONS_MAX,+ MENTION_WID_MAX_LENGTH,+ MESSAGE_TEXT_MAX_LENGTH,+} from '../../../modules/message/dto/send-message.dto';+import { isMentionWid } from '../../../modules/message/dto/is-mention-wid.validator';import {CONTACT_NAME_MAX_LENGTH,CONTACT_NUMBER_MAX_LENGTH,@@ -25,6 +30,23 @@ const quotedMessageIdSchema = z'the serialized message id, Baileys the raw key id of a message it has already stored.',);+/**+ * Mirrors the REST `mentions` field. The element rule and both caps come from the DTO rather than+ * being restated here: a tool handler calls the service directly, so the ValidationPipe never runs+ * and this schema is the only thing standing between an agent and the engine.+ *+ * Not offered on the sticker tool: both adapters build the sticker content without a mention list,+ * so declaring it there would accept the field and drop it.+ */+const mentionsSchema = z+ .array(z.string().max(MENTION_WID_MAX_LENGTH).refine(isMentionWid, 'must be an individual WID, e.g. [email protected]'))+ .max(MENTIONS_MAX)+ .optional()+ .describe(+ 'WIDs to @mention (e.g. ["[email protected]"]). The text or caption must also carry the matching ' ++ '@<number> token for WhatsApp to render the tag.',+ );+export function messageTools(message: MessageService): AnyToolDescriptor[] {return [defineTool({@@ -91,7 +113,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {inputSchema: z.object({sessionId,chatId: z.string().describe('Chat JID (e.g. [email protected] or [email protected])'),- text: z.string().min(1).max(4096).describe('Text message content'),+ text: z.string().min(1).max(MESSAGE_TEXT_MAX_LENGTH).describe('Text message content'),linkPreview: z.boolean().optional()@@ -100,6 +122,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {'unset means the engine default, and the engines differ.',),quotedMessageId: quotedMessageIdSchema,+ mentions: mentionsSchema,}),handler: input =>message.sendText(input.sessionId, {@@ -107,6 +130,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {text: input.text,...(input.linkPreview === undefined ? {} : { linkPreview: input.linkPreview }),quotedMessageId: input.quotedMessageId,+ mentions: input.mentions,}),}),defineTool({@@ -124,6 +148,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: z.string().max(255).optional(),caption: z.string().max(1024).optional(),quotedMessageId: quotedMessageIdSchema,+ mentions: mentionsSchema,}),handler: input =>message.sendImage(input.sessionId, {@@ -134,6 +159,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: input.filename,caption: input.caption,quotedMessageId: input.quotedMessageId,+ mentions: input.mentions,}),}),defineTool({@@ -151,6 +177,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: z.string().max(255).optional(),caption: z.string().max(1024).optional(),quotedMessageId: quotedMessageIdSchema,+ mentions: mentionsSchema,}),handler: input =>message.sendVideo(input.sessionId, {@@ -161,6 +188,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: input.filename,caption: input.caption,quotedMessageId: input.quotedMessageId,+ mentions: input.mentions,}),}),defineTool({@@ -179,6 +207,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {caption: z.string().max(1024).optional(),ptt: z.boolean().optional().describe('Send as a WhatsApp voice note (PTT)'),quotedMessageId: quotedMessageIdSchema,+ mentions: mentionsSchema,}),handler: input =>message.sendAudio(input.sessionId, {@@ -190,6 +219,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {caption: input.caption,ptt: input.ptt,quotedMessageId: input.quotedMessageId,+ mentions: input.mentions,}),}),defineTool({@@ -207,6 +237,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: z.string().max(255).optional(),caption: z.string().max(1024).optional(),quotedMessageId: quotedMessageIdSchema,+ mentions: mentionsSchema,}),handler: input =>message.sendDocument(input.sessionId, {@@ -217,6 +248,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {filename: input.filename,caption: input.caption,quotedMessageId: input.quotedMessageId,+ mentions: input.mentions,}),}),defineTool({@@ -312,6 +344,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {.record(z.string(), z.string()).optional().describe('Variables to substitute into {{placeholder}} tokens'),+ mentions: mentionsSchema,}),handler: input =>message.sendTemplate(input.sessionId, {@@ -319,6 +352,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {templateId: input.templateId,templateName: input.templateName,vars: input.vars,+ mentions: input.mentions,}),}),defineTool({@@ -332,12 +366,14 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {chatId: z.string().describe('Chat JID'),quotedMessageId: z.string().describe('ID of the message to quote/reply to'),text: z.string().min(1).max(MESSAGE_TEXT_MAX_LENGTH).describe('Reply text content'),+ mentions: mentionsSchema,}),handler: input =>message.reply(input.sessionId, {chatId: input.chatId,quotedMessageId: input.quotedMessageId,text: input.text,+ mentions: input.mentions,}),}),defineTool({diff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.tsindex 024e856fd..7dcddc4c5 100644--- a/src/core/agent-tools/tools/tool-input-caps.spec.ts+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts@@ -2,7 +2,11 @@ import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';import type { MessageService } from '../../../modules/message/message.service';import type { GroupService } from '../../../modules/group/group.service';-import { MESSAGE_TEXT_MAX_LENGTH } from '../../../modules/message/dto/send-message.dto';+import {+ MENTIONS_MAX,+ MESSAGE_TEXT_MAX_LENGTH,+ SendTextMessageDto,+} from '../../../modules/message/dto/send-message.dto';import {CONTACT_NAME_MAX_LENGTH,CONTACT_NUMBER_MAX_LENGTH,@@ -156,6 +160,17 @@ const PARTICIPANT_CASES: CapCase[] = [dtoClass: ParticipantsDto,dtoPayload: {},},+ {+ // The tool path calls the service directly, so the ValidationPipe never runs and the zod schema+ // is the only cap between an agent and the engine. This case fails if either side moves.+ label: 'MessageSendText.mentions ↔ SendTextMessageDto.mentions',+ toolName: 'MessageSendText',+ field: 'mentions',+ cap: MENTIONS_MAX,+ toolInput: { sessionId: 's1', chatId: '[email protected]', text: 'hi' },+ dtoClass: SendTextMessageDto,+ dtoPayload: { chatId: '[email protected]', text: 'hi' },+ },];async function dtoFieldErrors(c: CapCase, value: unknown): Promise<boolean> {diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 4b90cd43c..72cd89350 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -20,10 +20,11 @@ export const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';/**- * Caps for a `mentions` array, exported because the field now appears on every REST route whose- * engine can carry it: send, reply, edit, template and bulk. Inline literals repeated per site is- * how the two numbers would drift apart between endpoints that share one documented contract. The- * agent-tool schemas do NOT declare mentions on any tool yet, so nothing there reads these.+ * Caps for a `mentions` array, exported because the field appears on every REST route whose engine+ * can carry it (send, reply, edit, template, bulk) and on the matching agent-tool schemas. Inline+ * literals repeated per site is how the two numbers would drift apart between endpoints that share+ * one documented contract, and the tool path needs them most: it calls the service directly, so the+ * ValidationPipe never runs and the zod schema is the only cap there is.*/export const MENTIONS_MAX = 1024;export const MENTION_WID_MAX_LENGTH = 64;