Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(agent-tools): expose labels, and compose the tool surface once
Yudhi Armyndharis6195c41042b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c8f926e58..7ba07c751 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Labels are reachable from an agent.** They had five REST endpoints and no tools at all, so an+ agent could read and write contacts, groups, messages and webhooks but could not see a label, let+ alone tag a chat with one. Eight tools close that.++ Each description states which engine supports it, because labels split almost exactly down the+ middle: every read needs whatsapp-web.js, since Baileys exposes no label query; editing a label+ needs Baileys, since whatsapp-web.js cannot change one; only tagging and untagging a chat works on+ both. Left unsaid, an agent reads the `501` as a transient failure and retries a call that cannot+ succeed on that engine.++- **Sessions record which process owns them.** A session's WhatsApp engine runs in exactly oneprocess, but nothing recorded which, so a booting process reset every active-looking session onthe assumption they were all its own leftovers. With one process that is correct. With two it isdiff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex bd21920a7..dc397e2c3 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -14,7 +14,7 @@| **Tool registry (`ToolDescriptor`)** | ✅ Implemented | `src/core/agent-tools/tool-descriptor.ts` || **Tool invoker (auth → validate → service)** | ✅ Implemented | `src/core/agent-tools/tool-invoker.ts` || **Registry service** | ✅ Implemented | `src/core/agent-tools/tool-registry.service.ts` |-| **Curated tool tables (~39 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` |+| **Curated tool tables (49 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` || **MCP transport adapter** | ✅ Implemented | `src/modules/mcp/mcp.server.ts` || **Opt-in module gate** | ✅ Implemented | `src/modules/mcp/mcp.module.ts`, `src/app.module.ts` || **Per-key rate limiter** | ✅ Implemented | `src/modules/mcp/mcp-rate-limit.ts` |@@ -125,6 +125,14 @@ declares a `tier` (`read` | `write`) and, for writes, a required role.| **Contact** | list, get, check-number, resolve-phone, profile-picture | block, unblock || **Group** | list, get, invite-code | create, add participants, set subject, set description || **Webhook** | list, get (read-only) | — |+| **Label** | list, get, chats for a label, labels on a chat | upsert, delete, add to chat, remove from chat |++> **Labels split across the engines**, and each tool's description says which way. Every label+> *read* needs whatsapp-web.js — Baileys exposes no label query at all. Editing a label (upsert,+> delete) needs Baileys — whatsapp-web.js cannot change a label. Only tagging and untagging a chat+> works on both. An agent told this can pick the right call; one that is not will read the `501` as+> a transient failure and retry something that cannot succeed on that engine. Labels are a WhatsApp+> Business feature throughout.**Deliberately excluded from the surface** (not exposed as tools): session lifecycle(create/delete/start/stop/logout/force-kill), chat delete, bulk send, message delete, message edit,diff --git a/src/core/agent-tools/agent-tools.module.ts b/src/core/agent-tools/agent-tools.module.tsindex 73e93c2d4..86f0e8967 100644--- a/src/core/agent-tools/agent-tools.module.ts+++ b/src/core/agent-tools/agent-tools.module.ts@@ -5,38 +5,30 @@ import { MessageModule } from '../../modules/message/message.module';import { ContactModule } from '../../modules/contact/contact.module';import { GroupModule } from '../../modules/group/group.module';import { WebhookModule } from '../../modules/webhook/webhook.module';+import { LabelModule } from '../../modules/label/label.module';import { SessionService } from '../../modules/session/session.service';import { MessageService } from '../../modules/message/message.service';import { ContactService } from '../../modules/contact/contact.service';import { GroupService } from '../../modules/group/group.service';import { WebhookService } from '../../modules/webhook/webhook.service';-import { sessionTools } from './tools/session.tools';-import { messageTools } from './tools/message.tools';-import { contactTools } from './tools/contact.tools';-import { groupTools } from './tools/group.tools';-import { webhookTools } from './tools/webhook.tools';+import { LabelService } from '../../modules/label/label.service';+import { allAgentTools } from './tools';@Global()@Module({- imports: [SessionModule, MessageModule, ContactModule, GroupModule, WebhookModule],+ imports: [SessionModule, MessageModule, ContactModule, GroupModule, WebhookModule, LabelModule],providers: [{provide: ToolRegistryService,- inject: [SessionService, MessageService, ContactService, GroupService, WebhookService],+ inject: [SessionService, MessageService, ContactService, GroupService, WebhookService, LabelService],useFactory: (session: SessionService,message: MessageService,contact: ContactService,group: GroupService,webhook: WebhookService,- ) =>- new ToolRegistryService([- ...sessionTools(session),- ...messageTools(message),- ...contactTools(contact),- ...groupTools(group),- ...webhookTools(webhook),- ]),+ labels: LabelService,+ ) => new ToolRegistryService(allAgentTools({ session, message, contact, group, webhook, labels })),},],exports: [ToolRegistryService],diff --git a/src/core/agent-tools/session-scope-invariant.spec.ts b/src/core/agent-tools/session-scope-invariant.spec.tsindex 3744a470d..fa2a7ac40 100644--- a/src/core/agent-tools/session-scope-invariant.spec.ts+++ b/src/core/agent-tools/session-scope-invariant.spec.ts@@ -1,9 +1,5 @@+import { allAgentTools } from './tools';import { z } from 'zod';-import { sessionTools } from './tools/session.tools';-import { messageTools } from './tools/message.tools';-import { contactTools } from './tools/contact.tools';-import { groupTools } from './tools/group.tools';-import { webhookTools } from './tools/webhook.tools';import type { AnyToolDescriptor } from './tool-descriptor';// Registry-level invariant (not a per-tool enumeration): EVERY sessionScoped tool must require a@@ -13,13 +9,7 @@ import type { AnyToolDescriptor } from './tool-descriptor';// This catches a FUTURE tool authored with z.string().optional() — no test edit needed when one is added.describe('agent-tool registry: every sessionScoped tool requires a non-empty sessionId', () => {// Handlers are never invoked here; stub services are fine — we only inspect the schema/flags.- const allTools: AnyToolDescriptor[] = [- ...sessionTools({} as never),- ...messageTools({} as never),- ...contactTools({} as never),- ...groupTools({} as never),- ...webhookTools({} as never),- ];+ const allTools: AnyToolDescriptor[] = [...allAgentTools({} as never)];const sessionScoped = allTools.filter(t => t.sessionScoped === true);@@ -27,6 +17,23 @@ describe('agent-tool registry: every sessionScoped tool requires a non-empty sesexpect(sessionScoped.length).toBeGreaterThan(0);});+ /**+ * The other direction, and the one that actually leaks. `tool-invoker` only applies the+ * allowedSessions fence to a tool marked sessionScoped, so a tool that takes a sessionId and+ * forgets the flag lets a session-restricted key act on any session at all. Nothing else notices:+ * the tool works, the schema is valid, and only the fence is missing.+ */+ it('marks every tool that takes a sessionId as sessionScoped', () => {+ const takesSessionId = allTools.filter(tool => {+ const shape = (tool.inputSchema as unknown as z.ZodObject<Record<string, z.ZodType>>).shape;+ return shape != null && 'sessionId' in shape;+ });++ // Guard the guard: a shape probe that silently matched nothing would make this vacuous.+ expect(takesSessionId.length).toBeGreaterThan(0);+ expect(takesSessionId.filter(tool => tool.sessionScoped !== true).map(tool => tool.name)).toEqual([]);+ });+it.each(sessionScoped.map(t => [t.name, t] as const))('%s rejects a missing and an empty sessionId',(_name, tool) => {diff --git a/src/core/agent-tools/tool-registry.spec.ts b/src/core/agent-tools/tool-registry.spec.tsindex e20ae95a8..8e5d2ec99 100644--- a/src/core/agent-tools/tool-registry.spec.ts+++ b/src/core/agent-tools/tool-registry.spec.ts@@ -1,16 +1,7 @@+import { allAgentTools } from './tools';import { ToolRegistryService } from './tool-registry.service';import type { ToolDescriptor } from './tool-descriptor';-import type { SessionService } from '../../modules/session/session.service';-import type { MessageService } from '../../modules/message/message.service';-import type { ContactService } from '../../modules/contact/contact.service';-import type { GroupService } from '../../modules/group/group.service';-import type { WebhookService } from '../../modules/webhook/webhook.service';import { z } from 'zod';-import { sessionTools } from './tools/session.tools';-import { messageTools } from './tools/message.tools';-import { contactTools } from './tools/contact.tools';-import { groupTools } from './tools/group.tools';-import { webhookTools } from './tools/webhook.tools';const r: ToolDescriptor = {name: 'R',@@ -90,19 +81,19 @@ describe('v1 tool surface snapshot', () => {'WebhooksList','WebhookFindBySession','WebhookFindOne',+ 'LabelFindAll',+ 'LabelFindOne',+ 'LabelListChats',+ 'LabelListForChat',+ 'LabelUpsert',+ 'LabelDelete',+ 'LabelAddToChat',+ 'LabelRemoveFromChat',].sort();- const actualNames = [- ...sessionTools({} as unknown as SessionService),- ...messageTools({} as unknown as MessageService),- ...contactTools({} as unknown as ContactService),- ...groupTools({} as unknown as GroupService),- ...webhookTools({} as unknown as WebhookService),- ]- .map(t => t.name)- .sort();+ const actualNames = [...allAgentTools({} as never)].map(t => t.name).sort();expect(actualNames).toEqual(expected);- expect(expected).toHaveLength(41);+ expect(expected).toHaveLength(49);});});diff --git a/src/core/agent-tools/tools/index.ts b/src/core/agent-tools/tools/index.tsnew file mode 100644index 000000000..f2a1c85fa--- /dev/null+++ b/src/core/agent-tools/tools/index.ts@@ -0,0 +1,42 @@+import type { SessionService } from '../../../modules/session/session.service';+import type { MessageService } from '../../../modules/message/message.service';+import type { ContactService } from '../../../modules/contact/contact.service';+import type { GroupService } from '../../../modules/group/group.service';+import type { WebhookService } from '../../../modules/webhook/webhook.service';+import type { LabelService } from '../../../modules/label/label.service';+import type { AnyToolDescriptor } from '../tool-descriptor';+import { sessionTools } from './session.tools';+import { messageTools } from './message.tools';+import { contactTools } from './contact.tools';+import { groupTools } from './group.tools';+import { webhookTools } from './webhook.tools';+import { labelTools } from './label.tools';++/** The services each tool family needs. Stubs suffice where a spec only inspects declarations. */+export interface AgentToolDeps {+ session: SessionService;+ message: MessageService;+ contact: ContactService;+ group: GroupService;+ webhook: WebhookService;+ labels: LabelService;+}++/**+ * The complete tool surface, in one place.+ *+ * The module used to assemble this inline while the specs assembled their own copies, so a family+ * added to the module was invisible to the checks meant to police it — the published name list and+ * the session-scope invariant both silently kept passing. Composing once means a new family is+ * covered by construction rather than by remembering to list it three times.+ */+export function allAgentTools(deps: AgentToolDeps): AnyToolDescriptor[] {+ return [+ ...sessionTools(deps.session),+ ...messageTools(deps.message),+ ...contactTools(deps.contact),+ ...groupTools(deps.group),+ ...webhookTools(deps.webhook),+ ...labelTools(deps.labels),+ ];+}diff --git a/src/core/agent-tools/tools/label.tools.ts b/src/core/agent-tools/tools/label.tools.tsnew file mode 100644index 000000000..a21856cb6--- /dev/null+++ b/src/core/agent-tools/tools/label.tools.ts@@ -0,0 +1,114 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { LabelService } from '../../../modules/label/label.service';+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');++/**+ * Labels are a WhatsApp Business feature, and the two engines split them almost exactly down the+ * middle: whatsapp-web.js can read labels but not edit them, Baileys can edit them but cannot read+ * them back. Each description says which, because an agent that does not know will read a `501` as+ * a transient failure and retry — and the retry cannot succeed on that engine.+ */+export function labelTools(labels: LabelService): AnyToolDescriptor[] {+ return [+ defineTool({+ name: 'LabelFindAll',+ description:+ 'List every label on the account. WhatsApp Business only. Requires the whatsapp-web.js engine — ' ++ 'Baileys exposes no label query at all and answers 501.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({ sessionId }),+ handler: input => labels.getLabels(input.sessionId),+ }),+ defineTool({+ name: 'LabelFindOne',+ description:+ 'Get one label by id. Answers 404 when no label carries that id. WhatsApp Business only, and ' ++ 'whatsapp-web.js only — Baileys answers 501.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({ sessionId, labelId }),+ handler: input => labels.getLabelById(input.sessionId, input.labelId),+ }),+ defineTool({+ name: 'LabelListChats',+ 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),+ }),+ defineTool({+ name: 'LabelListForChat',+ description:+ 'List the labels on one chat. WhatsApp Business only, and whatsapp-web.js only — Baileys answers 501.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({ sessionId, chatId }),+ handler: input => labels.getChatLabels(input.sessionId, input.chatId),+ }),+ defineTool({+ name: 'LabelUpsert',+ description:+ 'Create or update a label. One operation on purpose: WhatsApp carries a single write keyed by the ' ++ 'label id, so whether this creates or updates depends only on whether that id already exists — ' ++ 'which is why the caller chooses the id. Requires the Baileys engine; whatsapp-web.js cannot edit ' ++ 'labels and answers 501.',+ tier: 'write',+ sessionScoped: true,+ requiredRole: ApiKeyRole.OPERATOR,+ inputSchema: z.object({+ sessionId,+ labelId,+ name: z.string().min(1).max(100).optional().describe('Label text; left unchanged when omitted'),+ color: z+ .number()+ .int()+ .min(0)+ .max(19)+ .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 }),+ }),+ defineTool({+ name: 'LabelDelete',+ description:+ 'Delete a label from the account. This removes the label itself, not its use on one chat — use ' ++ 'LabelRemoveFromChat for that. Requires the Baileys engine; whatsapp-web.js answers 501.',+ tier: 'write',+ sessionScoped: true,+ destructive: true,+ requiredRole: ApiKeyRole.OPERATOR,+ inputSchema: z.object({ sessionId, labelId }),+ handler: input => labels.deleteLabel(input.sessionId, input.labelId),+ }),+ defineTool({+ name: 'LabelAddToChat',+ description: 'Tag a chat with an existing label. Works on both engines. WhatsApp Business only.',+ tier: 'write',+ sessionScoped: true,+ requiredRole: ApiKeyRole.OPERATOR,+ inputSchema: z.object({ sessionId, chatId, labelId }),+ handler: input => labels.addLabelToChat(input.sessionId, input.chatId, input.labelId),+ }),+ defineTool({+ name: 'LabelRemoveFromChat',+ description:+ 'Remove a label from a chat, leaving the label itself in place. Works on both engines. ' ++ 'WhatsApp Business only.',+ tier: 'write',+ sessionScoped: true,+ requiredRole: ApiKeyRole.OPERATOR,+ inputSchema: z.object({ sessionId, chatId, labelId }),+ handler: input => labels.removeLabelFromChat(input.sessionId, input.chatId, input.labelId),+ }),+ ];+}diff --git a/src/modules/label/label.module.ts b/src/modules/label/label.module.tsindex 9ad339e0a..a68210e99 100644--- a/src/modules/label/label.module.ts+++ b/src/modules/label/label.module.ts@@ -5,5 +5,6 @@ import { LabelService } from './label.service';@Module({controllers: [LabelController],providers: [LabelService],+ exports: [LabelService],})export class LabelModule {}