Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp): report label write results instead of an internal error after the write ran

Yudhi Armyndharise3333a963b81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 44e7f2070..c9bea8599 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The webhook producer enqueues idempotently, and the bundled Redis is pinned `--maxmemory-policy noeviction` so queued jobs are not silently dropped.
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
+- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
- Corrected column names in `docs/05-database-design.md`.
### Security
diff --git a/src/core/agent-tools/tools/label.tools.spec.ts b/src/core/agent-tools/tools/label.tools.spec.ts
new file mode 100644
index 000000000..19901f821
--- /dev/null
+++ b/src/core/agent-tools/tools/label.tools.spec.ts
@@ -0,0 +1,52 @@
+import { invokeTool } from '../tool-invoker';
+import { labelTools } from './label.tools';
+import { smartToolResult } from '../../../modules/mcp/tool-result';
+import type { LabelService } from '../../../modules/label/label.service';
+import type { AuthService } from '../../../modules/auth/auth.service';
+
+function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {
+ return {
+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', role: 'operator', allowedSessions: null }),
+ hasPermission: jest.fn().mockReturnValue(true),
+ };
+}
+
+// The engine's four label writes resolve void. Every write tool must map that to an object result:
+// the MCP mount formats results with smartToolResult, and an undefined result used to throw there —
+// reported to the agent as `Internal error` AFTER the write had already executed on WhatsApp, so
+// the agent retried an operation that had succeeded.
+describe('label write tools', () => {
+ const writes = [
+ ['LabelUpsert', 'upsertLabel', { sessionId: 's1', labelId: '7', name: 'VIP' }],
+ ['LabelDelete', 'deleteLabel', { sessionId: 's1', labelId: '7' }],
+ ['LabelAddToChat', 'addLabelToChat', { sessionId: 's1', chatId: '[email protected]', labelId: '7' }],
+ ['LabelRemoveFromChat', 'removeLabelFromChat', { sessionId: 's1', chatId: '[email protected]', labelId: '7' }],
+ ] as const;
+
+ it.each(writes)('%s resolves an object result the MCP mount can format', async (toolName, method, input) => {
+ const svc = { [method]: jest.fn().mockResolvedValue(undefined) } as unknown as LabelService;
+
+ const tool = labelTools(svc).find(t => t.name === toolName)!;
+ const out = await invokeTool(tool, input, 'key', makeAuth() as unknown as AuthService);
+
+ expect(out).toEqual({ success: true });
+ // The exact formatting step the MCP server runs on the result (mcp.server.ts).
+ const formatted = smartToolResult(out as object);
+ expect(formatted.content[0]).toEqual({ type: 'text', text: '{"success":true}' });
+ });
+
+ it('LabelUpsert forwards only name/color to the service', async () => {
+ const upsertLabel = jest.fn().mockResolvedValue(undefined);
+ const svc = { upsertLabel } as unknown as LabelService;
+
+ const tool = labelTools(svc).find(t => t.name === 'LabelUpsert')!;
+ await invokeTool(
+ tool,
+ { sessionId: 's1', labelId: '7', name: 'VIP', color: 3 },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+
+ expect(upsertLabel).toHaveBeenCalledWith('s1', '7', { name: 'VIP', color: 3 });
+ });
+});
diff --git a/src/core/agent-tools/tools/label.tools.ts b/src/core/agent-tools/tools/label.tools.ts
index a21856cb6..8bf6ca30f 100644
--- a/src/core/agent-tools/tools/label.tools.ts
+++ b/src/core/agent-tools/tools/label.tools.ts
@@ -76,7 +76,10 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {
.optional()
.describe('WhatsApp colour index 0-19; left unchanged when omitted'),
}),
- handler: input => labels.upsertLabel(input.sessionId, input.labelId, { name: input.name, color: input.color }),
+ handler: input =>
+ labels
+ .upsertLabel(input.sessionId, input.labelId, { name: input.name, color: input.color })
+ .then(() => ({ success: true })),
}),
defineTool({
name: 'LabelDelete',
@@ -88,7 +91,7 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {
destructive: true,
requiredRole: ApiKeyRole.OPERATOR,
inputSchema: z.object({ sessionId, labelId }),
- handler: input => labels.deleteLabel(input.sessionId, input.labelId),
+ handler: input => labels.deleteLabel(input.sessionId, input.labelId).then(() => ({ success: true })),
}),
defineTool({
name: 'LabelAddToChat',
@@ -97,7 +100,8 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {
sessionScoped: true,
requiredRole: ApiKeyRole.OPERATOR,
inputSchema: z.object({ sessionId, chatId, labelId }),
- handler: input => labels.addLabelToChat(input.sessionId, input.chatId, input.labelId),
+ handler: input =>
+ labels.addLabelToChat(input.sessionId, input.chatId, input.labelId).then(() => ({ success: true })),
}),
defineTool({
name: 'LabelRemoveFromChat',
@@ -108,7 +112,8 @@ export function labelTools(labels: LabelService): AnyToolDescriptor[] {
sessionScoped: true,
requiredRole: ApiKeyRole.OPERATOR,
inputSchema: z.object({ sessionId, chatId, labelId }),
- handler: input => labels.removeLabelFromChat(input.sessionId, input.chatId, input.labelId),
+ handler: input =>
+ labels.removeLabelFromChat(input.sessionId, input.chatId, input.labelId).then(() => ({ success: true })),
}),
];
}
diff --git a/src/modules/mcp/tool-result.spec.ts b/src/modules/mcp/tool-result.spec.ts
new file mode 100644
index 000000000..41274ee94
--- /dev/null
+++ b/src/modules/mcp/tool-result.spec.ts
@@ -0,0 +1,26 @@
+import { smartToolResult } from './tool-result';
+
+describe('smartToolResult', () => {
+ it('inlines a small object as JSON text', () => {
+ expect(smartToolResult({ id: 1 }).content).toEqual([{ type: 'text', text: '{"id":1}' }]);
+ });
+
+ it('passes a string payload through as plain text', () => {
+ expect(smartToolResult('done').content).toEqual([{ type: 'text', text: 'done' }]);
+ });
+
+ it('survives an undefined handler result instead of throwing after the write ran', () => {
+ // JSON.stringify(undefined) is undefined; reading .length off it threw a TypeError that
+ // handleToolError then reported as `Internal error` for an operation that had succeeded.
+ const result = smartToolResult(undefined as unknown as object);
+ expect(result.content).toEqual([{ type: 'text', text: 'null' }]);
+ });
+
+ it('offloads a payload over 4 KB to an embedded resource', () => {
+ const big = { blob: 'x'.repeat(5000) };
+ const result = smartToolResult(big);
+ expect(result.content).toHaveLength(2);
+ expect(result.content[0].type).toBe('text');
+ expect(result.content[1]).toMatchObject({ type: 'resource', resource: { mimeType: 'application/json' } });
+ });
+});
diff --git a/src/modules/mcp/tool-result.ts b/src/modules/mcp/tool-result.ts
index 43c910310..3fa60d54b 100644
--- a/src/modules/mcp/tool-result.ts
+++ b/src/modules/mcp/tool-result.ts
@@ -9,7 +9,9 @@ const logger = new Logger('Mcp');
* ones (> 4 KB) to an embedded base64 resource so the response stays compact.
*/
export function smartToolResult(data: string | object | object[]): CallToolResult {
- const text = typeof data === 'string' ? data : JSON.stringify(data);
+ // JSON.stringify(undefined) is undefined, not a string — a handler that resolves void would turn
+ // a completed write into a thrown TypeError here, reported to the agent as a failure it retries.
+ const text = typeof data === 'string' ? data : (JSON.stringify(data) ?? 'null');
const mimeType = typeof data === 'string' ? 'text/plain' : 'application/json';
const ext = typeof data === 'string' ? 'txt' : 'json';
if (text.length > 4096) {