Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(mcp): tighten tool input schemas to match the REST DTO caps (#959)
Yudhi Armyndharisd9eec1cf6409
diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex 0ec9d9d58..83f415642 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -1,6 +1,7 @@import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { GroupService } from '../../../modules/group/group.service';+import { GROUP_DESCRIPTION_MAX_LENGTH, GROUP_NAME_MAX_LENGTH } from '../../../modules/group/dto/group.dto';import type { ToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -53,7 +54,7 @@ export function groupTools(group: GroupService): ToolDescriptor[] {sessionScoped: true,inputSchema: z.object({sessionId,- name: z.string().min(1).describe('Group subject/name'),+ name: z.string().min(1).max(GROUP_NAME_MAX_LENGTH).describe('Group subject/name'),participants: z.array(z.string()).min(1).describe('Participant WhatsApp JIDs (e.g. [email protected])'),}),handler: (input: { sessionId: string; name: string; participants: string[] }) =>@@ -85,7 +86,7 @@ export function groupTools(group: GroupService): ToolDescriptor[] {inputSchema: z.object({sessionId,groupId: z.string().describe('Group JID (e.g. [email protected])'),- subject: z.string().min(1).describe('New group subject/name'),+ subject: z.string().min(1).max(GROUP_NAME_MAX_LENGTH).describe('New group subject/name'),}),handler: async (input: { sessionId: string; groupId: string; subject: string }) => {await group.setGroupSubject(input.sessionId, input.groupId, input.subject);@@ -102,7 +103,10 @@ export function groupTools(group: GroupService): ToolDescriptor[] {inputSchema: z.object({sessionId,groupId: z.string().describe('Group JID (e.g. [email protected])'),- description: z.string().describe('New group description (may be empty to clear)'),+ description: z+ .string()+ .max(GROUP_DESCRIPTION_MAX_LENGTH)+ .describe('New group description (may be empty to clear)'),}),handler: async (input: { sessionId: string; groupId: string; description: string }) => {await group.setGroupDescription(input.sessionId, input.groupId, input.description);diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.tsindex 37282f731..271830a01 100644--- a/src/core/agent-tools/tools/message.tools.ts+++ b/src/core/agent-tools/tools/message.tools.ts@@ -1,6 +1,13 @@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 {+ CONTACT_NAME_MAX_LENGTH,+ CONTACT_NUMBER_MAX_LENGTH,+ LOCATION_TEXT_MAX_LENGTH,+ REACTION_EMOJI_MAX_LENGTH,+} from '../../../modules/message/dto/message-actions.dto';import type { ToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -223,8 +230,8 @@ export function messageTools(message: MessageService): ToolDescriptor[] {chatId: z.string().describe('Chat JID'),latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),- description: z.string().optional().describe('Location label/description'),- address: z.string().optional().describe('Street address'),+ description: z.string().max(LOCATION_TEXT_MAX_LENGTH).optional().describe('Location label/description'),+ address: z.string().max(LOCATION_TEXT_MAX_LENGTH).optional().describe('Street address'),}),handler: (input: {sessionId: string;@@ -251,8 +258,12 @@ export function messageTools(message: MessageService): ToolDescriptor[] {inputSchema: z.object({sessionId,chatId: z.string().describe('Chat JID'),- contactName: z.string().min(1).describe('Display name of the contact to share'),- contactNumber: z.string().min(1).describe('Phone number of the contact to share'),+ contactName: z.string().min(1).max(CONTACT_NAME_MAX_LENGTH).describe('Display name of the contact to share'),+ contactNumber: z+ .string()+ .min(1)+ .max(CONTACT_NUMBER_MAX_LENGTH)+ .describe('Phone number of the contact to share'),}),handler: (input: { sessionId: string; chatId: string; contactName: string; contactNumber: string }) =>message.sendContact(input.sessionId, {@@ -335,7 +346,7 @@ export function messageTools(message: MessageService): ToolDescriptor[] {sessionId,chatId: z.string().describe('Chat JID'),quotedMessageId: z.string().describe('ID of the message to quote/reply to'),- text: z.string().min(1).describe('Reply text content'),+ text: z.string().min(1).max(MESSAGE_TEXT_MAX_LENGTH).describe('Reply text content'),}),handler: (input: { sessionId: string; chatId: string; quotedMessageId: string; text: string }) =>message.reply(input.sessionId, {@@ -374,7 +385,10 @@ export function messageTools(message: MessageService): ToolDescriptor[] {sessionId,chatId: z.string().describe('Chat JID containing the message'),messageId: z.string().describe('ID of the message to react to'),- emoji: z.string().describe('Emoji to react with. Empty string removes the reaction.'),+ emoji: z+ .string()+ .max(REACTION_EMOJI_MAX_LENGTH)+ .describe('Emoji to react with. Empty string removes the reaction.'),}),handler: (input: { sessionId: string; chatId: string; messageId: string; emoji: string }) =>messagediff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.tsnew file mode 100644index 000000000..52e480896--- /dev/null+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts@@ -0,0 +1,159 @@+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 {+ CONTACT_NAME_MAX_LENGTH,+ CONTACT_NUMBER_MAX_LENGTH,+ LOCATION_TEXT_MAX_LENGTH,+ REACTION_EMOJI_MAX_LENGTH,+ ReactMessageDto,+ ReplyMessageDto,+ SendContactDto,+ SendLocationDto,+} from '../../../modules/message/dto/message-actions.dto';+import {+ CreateGroupDto,+ GROUP_DESCRIPTION_MAX_LENGTH,+ GROUP_NAME_MAX_LENGTH,+ GroupDescriptionDto,+ GroupSubjectDto,+} from '../../../modules/group/dto/group.dto';+import type { ToolDescriptor } from '../tool-descriptor';+import { messageTools } from './message.tools';+import { groupTools } from './group.tools';++// Matches src/config/app-validation.ts (see message-actions.dto.spec.ts) so the DTO side of the+// parity check runs the same validator semantics as the production pipe.+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };++const messages = messageTools({} as unknown as MessageService);+const groups = groupTools({} as unknown as GroupService);++function tool(name: string): ToolDescriptor {+ const found = [...messages, ...groups].find(t => t.name === name);+ if (!found) throw new Error(`tool not registered: ${name}`);+ return found;+}++interface CapCase {+ label: string;+ toolName: string;+ field: string;+ cap: number;+ toolInput: Record<string, unknown>;+ dtoClass: new () => object;+ dtoPayload: Record<string, unknown>;+}++// Every string field whose Zod schema previously had no max while the equivalent REST DTO+// enforces one via class-validator. Both sides now read the same exported constant.+const CASES: CapCase[] = [+ {+ label: 'MessageSendLocation.description ↔ SendLocationDto.description',+ toolName: 'MessageSendLocation',+ field: 'description',+ cap: LOCATION_TEXT_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', latitude: -6.2, longitude: 106.8 },+ dtoClass: SendLocationDto,+ dtoPayload: { chatId: '[email protected]', latitude: -6.2, longitude: 106.8 },+ },+ {+ label: 'MessageSendLocation.address ↔ SendLocationDto.address',+ toolName: 'MessageSendLocation',+ field: 'address',+ cap: LOCATION_TEXT_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', latitude: -6.2, longitude: 106.8 },+ dtoClass: SendLocationDto,+ dtoPayload: { chatId: '[email protected]', latitude: -6.2, longitude: 106.8 },+ },+ {+ label: 'MessageSendContact.contactName ↔ SendContactDto.contactName',+ toolName: 'MessageSendContact',+ field: 'contactName',+ cap: CONTACT_NAME_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', contactName: 'Alice', contactNumber: '628123456789' },+ dtoClass: SendContactDto,+ dtoPayload: { chatId: '[email protected]', contactName: 'Alice', contactNumber: '628123456789' },+ },+ {+ label: 'MessageSendContact.contactNumber ↔ SendContactDto.contactNumber',+ toolName: 'MessageSendContact',+ field: 'contactNumber',+ cap: CONTACT_NUMBER_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', contactName: 'Alice', contactNumber: '628123456789' },+ dtoClass: SendContactDto,+ dtoPayload: { chatId: '[email protected]', contactName: 'Alice', contactNumber: '628123456789' },+ },+ {+ label: 'MessageReply.text ↔ ReplyMessageDto.text',+ toolName: 'MessageReply',+ field: 'text',+ cap: MESSAGE_TEXT_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', quotedMessageId: 'm1', text: 'hi' },+ dtoClass: ReplyMessageDto,+ dtoPayload: { chatId: '[email protected]', quotedMessageId: 'm1', text: 'hi' },+ },+ {+ label: 'MessageReact.emoji ↔ ReactMessageDto.emoji',+ toolName: 'MessageReact',+ field: 'emoji',+ cap: REACTION_EMOJI_MAX_LENGTH,+ toolInput: { sessionId: 's1', chatId: '[email protected]', messageId: 'm1', emoji: '👍' },+ dtoClass: ReactMessageDto,+ dtoPayload: { chatId: '[email protected]', messageId: 'm1', emoji: '👍' },+ },+ {+ label: 'GroupCreate.name ↔ CreateGroupDto.name',+ toolName: 'GroupCreate',+ field: 'name',+ cap: GROUP_NAME_MAX_LENGTH,+ toolInput: { sessionId: 's1', name: 'weekend', participants: ['[email protected]'] },+ dtoClass: CreateGroupDto,+ dtoPayload: { name: 'weekend', participants: ['[email protected]'] },+ },+ {+ label: 'GroupSetSubject.subject ↔ GroupSubjectDto.subject',+ toolName: 'GroupSetSubject',+ field: 'subject',+ cap: GROUP_NAME_MAX_LENGTH,+ toolInput: { sessionId: 's1', groupId: '[email protected]', subject: 'new subject' },+ dtoClass: GroupSubjectDto,+ dtoPayload: { subject: 'new subject' },+ },+ {+ label: 'GroupSetDescription.description ↔ GroupDescriptionDto.description',+ toolName: 'GroupSetDescription',+ field: 'description',+ cap: GROUP_DESCRIPTION_MAX_LENGTH,+ toolInput: { sessionId: 's1', groupId: '[email protected]', description: 'rules' },+ dtoClass: GroupDescriptionDto,+ dtoPayload: { description: 'rules' },+ },+];++async function dtoFieldErrors(c: CapCase, value: string): Promise<boolean> {+ const instance = plainToInstance(c.dtoClass, { ...c.dtoPayload, [c.field]: value }, PIPE_TRANSFORM_OPTS);+ const errors = await validate(instance);+ return errors.some(e => e.property === c.field);+}++describe('agent-tool input caps (parity with the REST DTOs)', () => {+ it.each(CASES)('$label: accepts a value at the cap in both MCP and REST', async c => {+ const atCap = 'x'.repeat(c.cap);+ const parsed = tool(c.toolName).inputSchema.safeParse({ ...c.toolInput, [c.field]: atCap });+ expect(parsed.success).toBe(true);+ expect(await dtoFieldErrors(c, atCap)).toBe(false);+ });++ it.each(CASES)('$label: rejects a value above the cap in both MCP and REST', async c => {+ const overCap = 'x'.repeat(c.cap + 1);+ const parsed = tool(c.toolName).inputSchema.safeParse({ ...c.toolInput, [c.field]: overCap });+ expect(parsed.success).toBe(false);+ if (!parsed.success) {+ expect(parsed.error.issues.some(i => i.path.includes(c.field) && i.code === 'too_big')).toBe(true);+ }+ expect(await dtoFieldErrors(c, overCap)).toBe(true);+ });+});diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex 5e2a8f76a..e7730efd0 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -12,11 +12,16 @@ import {} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';+// Field caps shared with the agent-tool input schemas (src/core/agent-tools/tools/group.tools.ts)+// so MCP and REST enforce the same limits on the equivalent operations.+export const GROUP_NAME_MAX_LENGTH = 100;+export const GROUP_DESCRIPTION_MAX_LENGTH = 1024;+export class CreateGroupDto {- @ApiProperty({ description: 'Group subject/name', maxLength: 100 })+ @ApiProperty({ description: 'Group subject/name', maxLength: GROUP_NAME_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(100)+ @MaxLength(GROUP_NAME_MAX_LENGTH)name: string;@ApiProperty({ description: 'Participant WhatsApp IDs (e.g. [email protected])', type: [String] })@@ -35,17 +40,20 @@ export class ParticipantsDto {}export class GroupSubjectDto {- @ApiProperty({ description: 'New group subject/name', maxLength: 100 })+ @ApiProperty({ description: 'New group subject/name', maxLength: GROUP_NAME_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(100)+ @MaxLength(GROUP_NAME_MAX_LENGTH)subject: string;}export class GroupDescriptionDto {- @ApiProperty({ description: 'New group description (may be empty to clear it)', maxLength: 1024 })+ @ApiProperty({+ description: 'New group description (may be empty to clear it)',+ maxLength: GROUP_DESCRIPTION_MAX_LENGTH,+ })@IsString()- @MaxLength(1024)+ @MaxLength(GROUP_DESCRIPTION_MAX_LENGTH)description: string;}diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex 5c6fcc435..6a4aed8c7 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -12,6 +12,7 @@ import {MaxLength,} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';+import { MESSAGE_TEXT_MAX_LENGTH } from './send-message.dto';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -19,6 +20,13 @@ import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-bo* no metadata to validate or whitelist against.*/+// Field caps shared with the agent-tool input schemas (src/core/agent-tools/tools/message.tools.ts)+// so MCP and REST enforce the same limits on the equivalent operations.+export const LOCATION_TEXT_MAX_LENGTH = 1024;+export const CONTACT_NAME_MAX_LENGTH = 255;+export const CONTACT_NUMBER_MAX_LENGTH = 30;+export const REACTION_EMOJI_MAX_LENGTH = 32;+export class SendLocationDto {@ApiProperty({ description: 'Chat ID (e.g. [email protected])' })@IsString()@@ -35,16 +43,16 @@ export class SendLocationDto {@IsLongitude()longitude: number;- @ApiPropertyOptional({ maxLength: 1024 })+ @ApiPropertyOptional({ maxLength: LOCATION_TEXT_MAX_LENGTH })@IsOptional()@IsString()- @MaxLength(1024)+ @MaxLength(LOCATION_TEXT_MAX_LENGTH)description?: string;- @ApiPropertyOptional({ maxLength: 1024 })+ @ApiPropertyOptional({ maxLength: LOCATION_TEXT_MAX_LENGTH })@IsOptional()@IsString()- @MaxLength(1024)+ @MaxLength(LOCATION_TEXT_MAX_LENGTH)address?: string;}@@ -54,16 +62,16 @@ export class SendContactDto {@IsNotEmpty()chatId: string;- @ApiProperty({ maxLength: 255 })+ @ApiProperty({ maxLength: CONTACT_NAME_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(255)+ @MaxLength(CONTACT_NAME_MAX_LENGTH)contactName: string;- @ApiProperty({ maxLength: 30 })+ @ApiProperty({ maxLength: CONTACT_NUMBER_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(30)+ @MaxLength(CONTACT_NUMBER_MAX_LENGTH)contactNumber: string;}@@ -115,10 +123,11 @@ export class ReplyMessageDto {@IsNotEmpty()quotedMessageId: string;- @ApiProperty({ maxLength: 4096 })+ // Same body cap as SendTextMessageDto.text — a reply cannot exceed what a send allows.+ @ApiProperty({ maxLength: MESSAGE_TEXT_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(4096)+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)text: string;}@@ -151,9 +160,12 @@ export class ReactMessageDto {messageId: string;// Empty string is VALID — it removes the reaction (endpoint contract). So @IsString, not @IsNotEmpty.- @ApiProperty({ description: 'Emoji to react with. Send an empty string to remove the reaction.', maxLength: 32 })+ @ApiProperty({+ description: 'Emoji to react with. Send an empty string to remove the reaction.',+ maxLength: REACTION_EMOJI_MAX_LENGTH,+ })@IsString()- @MaxLength(32)+ @MaxLength(REACTION_EMOJI_MAX_LENGTH)emoji: string;}diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 64240d9ff..bd89b8ff7 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -15,6 +15,10 @@ import { ToStrictBoolean } from '../../../common/utils/strict-boolean';const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';+// Single source of truth for the text-body cap, shared with the agent-tool input schemas+// (src/core/agent-tools/tools/message.tools.ts) so MCP and REST enforce the same limit.+export const MESSAGE_TEXT_MAX_LENGTH = 4096;+export class SendTextMessageDto {@ApiProperty({description: 'WhatsApp chat ID ([email protected] for individual, [email protected] for groups)',@@ -27,11 +31,11 @@ export class SendTextMessageDto {@ApiProperty({description: 'Text message content',example: 'Hello from OpenWA!',- maxLength: 4096,+ maxLength: MESSAGE_TEXT_MAX_LENGTH,})@IsString()@IsNotEmpty()- @MaxLength(4096)+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)text: string;@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })