Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp): cap the chat ids a tool takes at 255 characters

Yudhi Armyndharise9258d6ae3c3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 498c40074..0bd809932 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,6 +46,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Bound each webhook and ingress queue command at 2 s once Redis has connected, so a Redis that stops answering falls back to direct delivery and inline dispatch instead of holding every dispatch and ingress request.
- Answer `400` for a send route's `chatId` or a bulk `batchId` over 255 characters, where PostgreSQL answered `500` once the value passed its index entry limit.
+- MCP tools refuse a `chatId`, `fromChatId` or `toChatId` over 255 characters, as the send routes do, where PostgreSQL answered an internal tool error.
- Index ingress dead letters by delivery id, so the reconciler's per-delivery checks stop scanning every dead letter of an instance; the first boot builds the index.
- Replay stranded ingress events past one whose stored payload is not valid JSON, instead of failing every sweep on it.
- Hand a chat back to the bot when the plugin instance that took it over is deleted, instead of silencing every other plugin on it.
diff --git a/src/core/agent-tools/chat-id-schema.ts b/src/core/agent-tools/chat-id-schema.ts
new file mode 100644
index 000000000..1c1e80a36
--- /dev/null
+++ b/src/core/agent-tools/chat-id-schema.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+import { CHAT_ID_MAX_LENGTH } from '../../modules/message/dto/send-message.dto';
+
+/**
+ * A chat id taken by a tool, bounded as the REST bodies bound it: the id is stored under a btree index,
+ * and PostgreSQL answers a value past about 2.7 KB with a 500 that the MCP client reads as an internal
+ * tool error.
+ */
+export const chatIdSchema = z.string().min(1).max(CHAT_ID_MAX_LENGTH);
diff --git a/src/core/agent-tools/tools/label.tools.ts b/src/core/agent-tools/tools/label.tools.ts
index de1ed7279..f55e50168 100644
--- a/src/core/agent-tools/tools/label.tools.ts
+++ b/src/core/agent-tools/tools/label.tools.ts
@@ -1,11 +1,12 @@
import { z } from 'zod';
import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';
import type { LabelService } from '../../../modules/label/label.service';
+import { chatIdSchema } from '../chat-id-schema';
import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';
const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');
const labelId = z.string().min(1).describe('Label id');
-const chatId = z.string().min(1).describe('Chat JID, e.g. [email protected] or <id>@g.us');
+const chatId = chatIdSchema.describe('Chat JID, e.g. [email protected] or <id>@g.us');
/**
* Labels are a WhatsApp Business feature, and the two engines split them almost exactly down the
diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.ts
index 123bed98d..f20ffb034 100644
--- a/src/core/agent-tools/tools/message.tools.ts
+++ b/src/core/agent-tools/tools/message.tools.ts
@@ -3,6 +3,7 @@ import { isMediaUrl, MEDIA_URL_MESSAGE } from '../../../common/media/media-url';
import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';
import type { MessageService } from '../../../modules/message/message.service';
import {
+ CHAT_ID_MAX_LENGTH,
CUSTOM_PREVIEW_DESCRIPTION_MAX_LENGTH,
CUSTOM_PREVIEW_TITLE_MAX_LENGTH,
CUSTOM_PREVIEW_URL_MAX_LENGTH,
@@ -17,6 +18,7 @@ import {
LOCATION_TEXT_MAX_LENGTH,
REACTION_EMOJI_MAX_LENGTH,
} from '../../../modules/message/dto/message-actions.dto';
+import { chatIdSchema } from '../chat-id-schema';
import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';
const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');
@@ -91,7 +93,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().optional().describe('Filter to a specific chat JID'),
+ chatId: z.string().max(CHAT_ID_MAX_LENGTH).optional().describe('Filter to a specific chat JID'),
from: z.string().optional().describe('Filter by sender phone or JID'),
limit: z.number().int().min(1).max(100).optional(),
offset: z.number().int().min(0).optional(),
@@ -113,7 +115,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected] or [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected] or [email protected])'),
limit: z
.number()
.int()
@@ -135,7 +137,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID containing the message'),
+ chatId: chatIdSchema.describe('Chat JID containing the message'),
messageId: z.string().min(1).describe('Message ID to get reactions for'),
}),
handler: input => message.getMessageReactions(input.sessionId, input.chatId, input.messageId),
@@ -149,7 +151,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected] or [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected] or [email protected])'),
text: z.string().min(1).max(MESSAGE_TEXT_MAX_LENGTH).describe('Text message content'),
linkPreview: z
.boolean()
@@ -181,7 +183,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
url: mediaUrl('Image'),
base64: z.string().optional().describe('Base64-encoded image data'),
mimetype: z.string().optional().describe('MIME type (required when using base64)'),
@@ -211,7 +213,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
url: mediaUrl('Video'),
base64: z.string().optional().describe('Base64-encoded video data'),
mimetype: z.string().optional().describe('MIME type (required when using base64)'),
@@ -241,7 +243,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
url: mediaUrl('Audio'),
base64: z.string().optional().describe('Base64-encoded audio data'),
mimetype: z.string().optional().describe('MIME type (required when using base64)'),
@@ -273,7 +275,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
url: mediaUrl('Document'),
base64: z.string().optional().describe('Base64-encoded document data'),
mimetype: z.string().optional().describe('MIME type (required when using base64)'),
@@ -303,7 +305,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.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().max(LOCATION_TEXT_MAX_LENGTH).optional().describe('Location label/description'),
@@ -329,7 +331,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
contactName: z.string().min(1).max(CONTACT_NAME_MAX_LENGTH).describe('Display name of the contact to share'),
contactNumber: z
.string()
@@ -355,7 +357,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
url: mediaUrl('Sticker'),
base64: z.string().optional().describe('Base64-encoded sticker data'),
mimetype: z.string().optional().describe('MIME type (required when using base64)'),
@@ -386,7 +388,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
templateId: z.string().optional().describe('Template UUID'),
templateName: z.string().optional().describe('Template name slug'),
vars: z
@@ -414,7 +416,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID'),
+ chatId: chatIdSchema.describe('Chat JID'),
quotedMessageId: z.string().min(1).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,
@@ -436,8 +438,8 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- fromChatId: z.string().min(1).describe('Source chat JID'),
- toChatId: z.string().min(1).describe('Destination chat JID'),
+ fromChatId: chatIdSchema.describe('Source chat JID'),
+ toChatId: chatIdSchema.describe('Destination chat JID'),
messageId: z.string().min(1).describe('ID of the message to forward'),
}),
handler: input =>
@@ -457,7 +459,7 @@ export function messageTools(message: MessageService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID containing the message'),
+ chatId: chatIdSchema.describe('Chat JID containing the message'),
messageId: z.string().min(1).describe('ID of the message to react to'),
emoji: z
.string()
diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.ts
index 108ded23b..18652a09f 100644
--- a/src/core/agent-tools/tools/session.tools.ts
+++ b/src/core/agent-tools/tools/session.tools.ts
@@ -7,6 +7,7 @@ import {
MARK_READ_MESSAGE_ID_MESSAGE,
MARK_READ_MESSAGE_ID_PATTERN,
} from '../../../modules/session/dto/mark-chat-read.dto';
+import { chatIdSchema } from '../chat-id-schema';
import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';
import { paginate } from '../../../common/utils/paginate';
@@ -78,7 +79,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),
}),
handler: input => session.subscribeToPresence(input.sessionId, input.chatId).then(() => ({ success: true })),
}),
@@ -93,7 +94,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),
}),
handler: input => session.getPresence(input.sessionId, input.chatId),
}),
@@ -106,7 +107,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),
messageIds: z
// The element rule comes from the DTO rather than being restated here: the REST body
// rejects a whitespace-only id, and this path reaches the engine without the DTO at all.
@@ -131,7 +132,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),
}),
handler: input => session.markUnread(input.sessionId, input.chatId).then(success => ({ success })),
}),
@@ -144,7 +145,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
sessionScoped: true,
inputSchema: z.object({
sessionId,
- chatId: z.string().min(1).describe('Chat JID (e.g. [email protected])'),
+ chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),
state: z
.enum(['typing', 'recording', 'paused'])
.describe("'typing' or 'recording' shows the indicator; 'paused' clears it"),
diff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.ts
index 8a82bf079..1bbe977fe 100644
--- a/src/core/agent-tools/tools/tool-input-caps.spec.ts
+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts
@@ -3,6 +3,7 @@ import { validate } from 'class-validator';
import type { MessageService } from '../../../modules/message/message.service';
import type { GroupService } from '../../../modules/group/group.service';
import {
+ CHAT_ID_MAX_LENGTH,
MENTIONS_MAX,
MESSAGE_TEXT_MAX_LENGTH,
SendTextMessageDto,
@@ -240,3 +241,31 @@ describe('agent-tool identifiers reject an empty string', () => {
expect(schema.safeParse('').success).toBe(false);
});
});
+
+/**
+ * A chat id is stored under a btree index, which PostgreSQL cannot hold past about 2.7 KB, and the tool
+ * path calls the service directly. The REST bodies cap it; so does every tool field that names a chat.
+ */
+describe('agent-tool chat ids are capped as the REST bodies cap them', () => {
+ const chatFields = allAgentTools({} as never).flatMap(t =>
+ Object.entries((t.inputSchema as unknown as z.ZodObject<Record<string, z.ZodType>>).shape)
+ .filter(([key]) => /^(chatId|fromChatId|toChatId)$/.test(key))
+ .map(([key, schema]) => [`${t.name}.${key}`, schema] as const),
+ );
+
+ it('finds the chat id fields to check', () => {
+ expect(chatFields.map(([label]) => label)).toEqual(
+ expect.arrayContaining([
+ 'MessageSendText.chatId',
+ 'MessageForward.fromChatId',
+ 'MessageForward.toChatId',
+ 'SessionMarkChatRead.chatId',
+ ]),
+ );
+ });
+
+ it.each(chatFields)('%s accepts an id at the cap and rejects one past it', (_label, schema) => {
+ expect(schema.safeParse('x'.repeat(CHAT_ID_MAX_LENGTH)).success).toBe(true);
+ expect(schema.safeParse('x'.repeat(CHAT_ID_MAX_LENGTH + 1)).success).toBe(false);
+ });
+});