Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(mcp): add opt-in MCP server exposing a curated agent-tool surface
Yudhi Armyndharis643e76b2e0af
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57b9c66a0..962ae526b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- MCP server (opt-in, `MCP_ENABLED=true`): exposes a curated ~39-tool agent surface (sessions, messaging, contacts, basic group ops, webhook reads) over the Model Context Protocol at `POST /mcp`, on the existing single port. Off by default — the MCP SDK is not loaded unless enabled, and every REST route is unchanged. Tools call the existing services and reuse the same API-key auth, role, and per-session scoping as REST; reads vs writes are tiered and `MCP_READONLY=true` mounts read tools only. Destructive/privileged operations are deliberately excluded from the surface. (relates to #256; salvages result-shaping from #461 — thanks @tobiasstrebitzer)+## [0.7.2] - 2026-06-24### Addeddiff --git a/README.md b/README.mdindex a0134fcf0..493628a1a 100644--- a/README.md+++ b/README.md@@ -275,6 +275,39 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/webhooks \> Fields: `sender` / `recipient` / `body` / `type` / `mentions` / `fromMe` / `hasMedia` / `isGroup`. A> webhook with no filters behaves exactly as before. See the API specification for the full schema.+## 🤖 MCP Server (AI Agents)++OpenWA can expose a **curated set of tools over the [Model Context Protocol](https://modelcontextprotocol.io)** so AI agents (Claude, Cursor, …) can drive WhatsApp. It is **off by default** and **additive** — every REST route keeps working unchanged.++Set `MCP_ENABLED=true` to mount a stateless Streamable-HTTP transport at **`POST /mcp`** on the existing server (same port, no extra process). It exposes ~39 curated tools (sessions, messaging, contacts, basic group ops, webhook reads) — a focused surface rather than the full API, so agents aren't overwhelmed and destructive operations stay off the agent path.++```bash+MCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / compose+```++Point an MCP client at it (e.g. for Claude Code, a `.mcp.json` at your project root):++```json+{+ "mcpServers": {+ "openwa": {+ "type": "http",+ "url": "http://localhost:2785/mcp",+ "headers": { "Authorization": "Bearer YOUR_API_KEY" }+ }+ }+}+```++The key can be passed as `Authorization: Bearer …` or `X-API-Key: …`. Every tool call goes through the **same API-key auth, role, and per-session scoping** as REST.++**Security guidance:**++- **Mint a dedicated, least-privilege key** for the agent — a non-admin, **session-scoped** key (`OPERATOR` role at most). The plaintext key is shown only once on creation; to rotate, create a new key and delete the old one.+- The key **must not** carry an IP allow-list (`allowedIps`) — there is no genuine client IP over MCP, so such a key is rejected.+- Set **`MCP_READONLY=true`** to mount only the read tools (no sends/writes).+- **Do not expose `/mcp` to the public internet** without a fronting auth proxy. For a self-hosted, locally-reached deployment the static API key is appropriate; public exposure should use OAuth 2.1 (not yet built).+---## 🛠 Tech Stackdiff --git a/package-lock.json b/package-lock.jsonindex abca05ce9..db1b08f9b 100644--- a/package-lock.json+++ b/package-lock.json@@ -14,6 +14,7 @@"@bull-board/api": "^8.0.1","@bull-board/express": "^8.0.1","@bull-board/nestjs": "^8.0.1",+ "@modelcontextprotocol/sdk": "^1.29.0","@nestjs-modules/ioredis": "^2.0.2","@nestjs/bullmq": "^11.0.4","@nestjs/common": "^11.1.27",@@ -44,7 +45,8 @@"typeorm": "^0.3.29","undici": "^8.5.0","uuid": "^14.0.1",- "whatsapp-web.js": "^1.34.7"+ "whatsapp-web.js": "^1.34.7",+ "zod": "^4.4.3"},"devDependencies": {"@eslint/eslintrc": "^3.2.0",@@ -1740,6 +1742,18 @@"integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==","license": "BSD-3-Clause"},+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },"node_modules/@humanfs/core": {"version": "0.19.2","resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",@@ -3390,6 +3404,68 @@"integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==","license": "MIT"},+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },"node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {"version": "3.0.4","resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz",@@ -5810,7 +5886,6 @@"version": "3.0.1","resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz","integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",- "dev": true,"license": "MIT","dependencies": {"ajv": "^8.0.0"@@ -5828,7 +5903,6 @@"version": "8.20.0","resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz","integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",- "dev": true,"license": "MIT","dependencies": {"fast-deep-equal": "^3.1.3",@@ -5845,7 +5919,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz","integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",- "dev": true,"license": "MIT"},"node_modules/ajv-keywords": {@@ -7134,6 +7207,15 @@"devtools-protocol": "*"}},+ "node_modules/chromium-bidi/node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/ci-info": {"version": "4.4.0","resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",@@ -8836,6 +8918,27 @@"bare-events": "^2.7.0"}},+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",+ "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/execa": {"version": "5.1.1","resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",@@ -8909,6 +9012,7 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -8947,6 +9051,24 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-rate-limit": {+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",+ "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },"node_modules/extract-zip": {"version": "2.0.1","resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",@@ -8986,7 +9108,6 @@"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz","integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",- "dev": true,"license": "MIT"},"node_modules/fast-diff": {@@ -9026,7 +9147,6 @@"version": "3.1.0","resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz","integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",- "dev": true,"funding": [{"type": "github",@@ -9854,6 +9974,16 @@"url": "https://github.com/sponsors/EvanHahn"}},+ "node_modules/hono": {+ "version": "4.12.27",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.27.tgz",+ "integrity": "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=16.9.0"+ }+ },"node_modules/hookified": {"version": "1.15.1","resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",@@ -11080,6 +11210,15 @@"url": "https://github.com/chalk/supports-color?sponsor=1"}},+ "node_modules/jose": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/js-tokens": {"version": "4.0.0","resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",@@ -11131,6 +11270,12 @@"dev": true,"license": "MIT"},+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },"node_modules/json-stable-stringify-without-jsonify": {"version": "1.0.1","resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",@@ -12857,6 +13002,15 @@"node": ">= 6"}},+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },"node_modules/pkg-dir": {"version": "4.2.0","resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",@@ -13768,7 +13922,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz","integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",- "dev": true,"license": "MIT","engines": {"node": ">=0.10.0"@@ -16747,13 +16900,23 @@}},"node_modules/zod": {- "version": "3.25.76",- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }}}}diff --git a/package.json b/package.jsonindex e92fa5cb1..c87bc5979 100644--- a/package.json+++ b/package.json@@ -51,6 +51,7 @@"@bull-board/api": "^8.0.1","@bull-board/express": "^8.0.1","@bull-board/nestjs": "^8.0.1",+ "@modelcontextprotocol/sdk": "^1.29.0","@nestjs-modules/ioredis": "^2.0.2","@nestjs/bullmq": "^11.0.4","@nestjs/common": "^11.1.27",@@ -81,7 +82,8 @@"typeorm": "^0.3.29","undici": "^8.5.0","uuid": "^14.0.1",- "whatsapp-web.js": "^1.34.7"+ "whatsapp-web.js": "^1.34.7",+ "zod": "^4.4.3"},"devDependencies": {"@eslint/eslintrc": "^3.2.0",diff --git a/src/app.module.ts b/src/app.module.tsindex 3aaa9ed26..e4ac8e30e 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -32,6 +32,7 @@ import { CatalogModule } from './modules/catalog/catalog.module';import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';import { PluginsApiModule } from './modules/plugins/plugins.module';+import { AgentToolsModule } from './core/agent-tools/agent-tools.module';// Only import QueueModule if explicitly enabled to avoid Redis connection errorsconst queueModules: Array<Type | DynamicModule> = [];@@ -43,6 +44,22 @@ if (process.env.QUEUE_ENABLED === 'true') {queueModules.push(queueModule.QueueModule);}+// Only mount the MCP server if explicitly enabled to avoid startup cost and+// the SDK import (which pulls in @modelcontextprotocol/sdk) in non-MCP deployments.+const mcpModules: Array<Type | DynamicModule> = [];+if (process.env.MCP_ENABLED === 'true') {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { McpModule } = require('./modules/mcp/mcp.module') as typeof import('./modules/mcp/mcp.module');+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { version } = require('../package.json') as { version: string };+ mcpModules.push(+ McpModule.forRoot({+ basePath: '/mcp',+ serverInfo: { name: 'openwa', version },+ }),+ );+}+// Serve the bundled dashboard SPA from this same NestJS process/port when a build is// present (the production image copies dashboard/dist in). In local dev the build is// absent, so this stays inert and the Vite dev server (:2886) handles the UI. Opt out@@ -216,6 +233,8 @@ if (dashboardServingEnabled && dashboardBuildPresent) {StatusModule, // Phase 3: Status/Stories APICatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins API+ AgentToolsModule, // Agent-invocable tool registry (protocol-neutral)+ ...mcpModules, // MCP Streamable-HTTP server (opt-in via MCP_ENABLED=true)...serveStaticModules, // Bundled dashboard SPA (production single-port setup)],})diff --git a/src/core/agent-tools/agent-tools.module.ts b/src/core/agent-tools/agent-tools.module.tsnew file mode 100644index 000000000..73e93c2d4--- /dev/null+++ b/src/core/agent-tools/agent-tools.module.ts@@ -0,0 +1,44 @@+import { Global, Module } from '@nestjs/common';+import { ToolRegistryService } from './tool-registry.service';+import { SessionModule } from '../../modules/session/session.module';+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 { 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';++@Global()+@Module({+ imports: [SessionModule, MessageModule, ContactModule, GroupModule, WebhookModule],+ providers: [+ {+ provide: ToolRegistryService,+ inject: [SessionService, MessageService, ContactService, GroupService, WebhookService],+ useFactory: (+ session: SessionService,+ message: MessageService,+ contact: ContactService,+ group: GroupService,+ webhook: WebhookService,+ ) =>+ new ToolRegistryService([+ ...sessionTools(session),+ ...messageTools(message),+ ...contactTools(contact),+ ...groupTools(group),+ ...webhookTools(webhook),+ ]),+ },+ ],+ exports: [ToolRegistryService],+})+export class AgentToolsModule {}diff --git a/src/core/agent-tools/tool-descriptor.ts b/src/core/agent-tools/tool-descriptor.tsnew file mode 100644index 000000000..40dd38ba3--- /dev/null+++ b/src/core/agent-tools/tool-descriptor.ts@@ -0,0 +1,26 @@+import type { z } from 'zod';+import type { ApiKey } from '../../modules/auth/entities/api-key.entity';+import type { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';++/** A single agent-invocable capability. Protocol-neutral: no MCP types here. */+export interface ToolDescriptor<I = unknown> {+ /** Explicit, stable public name, e.g. 'MessageSendText'. */+ name: string;+ /** Agent-legible description: what it does, when to use it, preconditions. */+ description: string;+ /** Input contract: validates the call AND is advertised to the agent. */+ inputSchema: z.ZodType<I>;+ tier: 'read' | 'write';+ /** True for irreversible/dangerous ops (none are exposed in v1). */+ destructive?: boolean;+ /** Safe to repeat without additional effect. Defaults to (tier === 'read'). */+ idempotent?: boolean;+ /** Minimum role; checked via AuthService.hasPermission. */+ requiredRole?: ApiKeyRole;+ /** If true, input MUST carry `sessionId`, checked against the key's allowedSessions. */+ sessionScoped?: boolean;+ /** Result rendering hint for the MCP adapter. Default 'smart'. */+ resultDisposition?: 'json' | 'smart';+ /** Calls the service. Receives validated input + the resolved, scoped key. */+ handler: (input: I, apiKey: ApiKey) => Promise<unknown>;+}diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.tsnew file mode 100644index 000000000..b1b18792d--- /dev/null+++ b/src/core/agent-tools/tool-invoker.spec.ts@@ -0,0 +1,79 @@+import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';+import { z } from 'zod';+import { invokeTool } from './tool-invoker';+import type { ToolDescriptor } from './tool-descriptor';+import type { AuthService } from '../../modules/auth/auth.service';+import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';++const readTool: ToolDescriptor = {+ name: 'T',+ description: 'd',+ tier: 'read',+ inputSchema: z.object({ n: z.number() }),+ handler: input => Promise.resolve({ got: (input as { n: number }).n }),+};++function auth(over: Partial<Record<string, unknown>> = {}): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {+ return {+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: null, ...over }),+ hasPermission: jest.fn().mockReturnValue(true),+ };+}++describe('invokeTool', () => {+ it('rejects a missing key', async () => {+ await expect(invokeTool(readTool, { n: 1 }, undefined, auth() as unknown as AuthService)).rejects.toBeInstanceOf(+ UnauthorizedException,+ );+ });++ it('validates input AFTER auth and runs the handler', async () => {+ const a = auth();+ const out = await invokeTool(readTool, { n: 5 }, 'rawkey', a as unknown as AuthService);+ expect(a.validateApiKey).toHaveBeenCalledWith('rawkey', undefined, undefined);+ expect(out).toEqual({ got: 5 });+ });++ it('maps a zod failure to BadRequestException', async () => {+ await expect(invokeTool(readTool, { n: 'x' }, 'rawkey', auth() as unknown as AuthService)).rejects.toBeInstanceOf(+ BadRequestException,+ );+ });++ it('passes sessionId from input to validateApiKey when sessionScoped', async () => {+ const a = auth();+ const scoped: ToolDescriptor = {+ ...readTool,+ sessionScoped: true,+ inputSchema: z.object({ sessionId: z.string() }),+ handler: () => Promise.resolve('ok'),+ };+ await invokeTool(scoped, { sessionId: 's1' }, 'rawkey', a as unknown as AuthService);+ expect(a.validateApiKey).toHaveBeenCalledWith('rawkey', undefined, 's1');+ });++ it('rejects when validateApiKey throws for an out-of-scope session', async () => {+ const a = auth();+ (a.validateApiKey as jest.Mock).mockRejectedValueOnce(+ new UnauthorizedException('API key not authorized for this session'),+ );+ const scoped: ToolDescriptor = {+ ...readTool,+ sessionScoped: true,+ inputSchema: z.object({ sessionId: z.string() }),+ handler: () => Promise.resolve('ok'),+ };+ await expect(+ invokeTool(scoped, { sessionId: 'other-session' }, 'rawkey', a as unknown as AuthService),+ ).rejects.toBeInstanceOf(UnauthorizedException);+ });++ it('enforces requiredRole via hasPermission', async () => {+ const a = auth();+ (a.hasPermission as jest.Mock).mockReturnValue(false);+ const writeTool: ToolDescriptor = { ...readTool, tier: 'write', requiredRole: ApiKeyRole.OPERATOR };+ await expect(invokeTool(writeTool, { n: 1 }, 'rawkey', a as unknown as AuthService)).rejects.toBeInstanceOf(+ ForbiddenException,+ );+ });+});diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsnew file mode 100644index 000000000..2b8d8ef5a--- /dev/null+++ b/src/core/agent-tools/tool-invoker.ts@@ -0,0 +1,42 @@+import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';+import { ZodError } from 'zod';+import type { AuthService } from '../../modules/auth/auth.service';+import type { ToolDescriptor } from './tool-descriptor';++/**+ * Run one tool call with REST-equivalent guarantees, reusing core's own auth:+ * auth (role + allowedSessions + IP fail-closed) → validate input → handler.+ * Mirrors the REST guard-then-pipe order (auth before validation).+ * `clientIp` is undefined over MCP — a key with allowedIps therefore fails closed+ * inside validateApiKey (documented limitation).+ */+export async function invokeTool(+ tool: ToolDescriptor,+ rawInput: unknown,+ rawKey: string | undefined,+ authService: AuthService,+): Promise<unknown> {+ if (!rawKey) {+ throw new UnauthorizedException('Missing API key');+ }+ // Pre-extract sessionId for the scope check BEFORE full validation (REST reads+ // req.params.sessionId in the guard, before the pipe).+ const probe = (rawInput ?? {}) as Record<string, unknown>;+ const sessionId = tool.sessionScoped && typeof probe.sessionId === 'string' ? probe.sessionId : undefined;++ const apiKey = await authService.validateApiKey(rawKey, undefined, sessionId);+ if (tool.requiredRole && !authService.hasPermission(apiKey, tool.requiredRole)) {+ throw new ForbiddenException('API key lacks the required role');+ }++ let input: unknown;+ try {+ input = tool.inputSchema.parse(rawInput);+ } catch (e) {+ if (e instanceof ZodError) {+ throw new BadRequestException(e.issues.map(i => `${i.path.join('.') || '(root)'}: ${i.message}`));+ }+ throw e;+ }+ return tool.handler(input, apiKey);+}diff --git a/src/core/agent-tools/tool-registry.service.ts b/src/core/agent-tools/tool-registry.service.tsnew file mode 100644index 000000000..8ee49c8c4--- /dev/null+++ b/src/core/agent-tools/tool-registry.service.ts@@ -0,0 +1,25 @@+import { Injectable } from '@nestjs/common';+import type { ToolDescriptor } from './tool-descriptor';++@Injectable()+export class ToolRegistryService {+ private readonly byName = new Map<string, ToolDescriptor>();++ constructor(tools: ToolDescriptor[]) {+ for (const t of tools) {+ if (this.byName.has(t.name)) {+ throw new Error(`Duplicate agent tool name: ${t.name}`);+ }+ this.byName.set(t.name, t);+ }+ }++ list(opts: { readOnly?: boolean } = {}): ToolDescriptor[] {+ const all = [...this.byName.values()];+ return opts.readOnly ? all.filter(t => t.tier === 'read') : all;+ }++ get(name: string): ToolDescriptor | undefined {+ return this.byName.get(name);+ }+}diff --git a/src/core/agent-tools/tool-registry.spec.ts b/src/core/agent-tools/tool-registry.spec.tsnew file mode 100644index 000000000..5f4d7cd7f--- /dev/null+++ b/src/core/agent-tools/tool-registry.spec.ts@@ -0,0 +1,106 @@+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',+ description: 'd',+ tier: 'read',+ inputSchema: z.object({}),+ handler: () => Promise.resolve(1),+};+const w: ToolDescriptor = {+ name: 'W',+ description: 'd',+ tier: 'write',+ inputSchema: z.object({}),+ handler: () => Promise.resolve(1),+};++describe('ToolRegistryService', () => {+ it('throws on duplicate tool names', () => {+ expect(() => new ToolRegistryService([r, r])).toThrow(/duplicate/i);+ });+ it('list() returns all; list({readOnly}) returns only read tools', () => {+ const reg = new ToolRegistryService([r, w]);+ expect(+ reg+ .list()+ .map(t => t.name)+ .sort(),+ ).toEqual(['R', 'W']);+ expect(reg.list({ readOnly: true }).map(t => t.name)).toEqual(['R']);+ });+ it('get() resolves by name', () => {+ expect(new ToolRegistryService([r]).get('R')).toBe(r);+ });+});++describe('v1 tool surface snapshot', () => {+ it('exposes exactly the v1 tool surface (locks the agent contract)', () => {+ const expected = [+ 'SessionFindAll',+ 'SessionFindOne',+ 'SessionGetChats',+ 'SessionGetStats',+ 'SessionMarkChatRead',+ 'SessionMarkChatUnread',+ 'SessionSendChatState',+ 'MessageList',+ 'MessageHistory',+ 'MessageGetReactions',+ 'MessageSendText',+ 'MessageSendImage',+ 'MessageSendVideo',+ 'MessageSendAudio',+ 'MessageSendDocument',+ 'MessageSendLocation',+ 'MessageSendContact',+ 'MessageSendSticker',+ 'MessageSendTemplate',+ 'MessageReply',+ 'MessageForward',+ 'MessageReact',+ 'ContactFindAll',+ 'ContactFindOne',+ 'ContactCheckNumber',+ 'ContactResolvePhone',+ 'ContactGetProfilePicture',+ 'ContactBlock',+ 'ContactUnblock',+ 'GroupFindAll',+ 'GroupFindOne',+ 'GroupGetInviteCode',+ 'GroupCreate',+ 'GroupAddParticipants',+ 'GroupSetSubject',+ 'GroupSetDescription',+ 'WebhooksList',+ 'WebhookFindBySession',+ 'WebhookFindOne',+ ].sort();++ const actualNames = [+ ...sessionTools({} as unknown as SessionService), // eslint-disable-line @typescript-eslint/no-unsafe-argument+ ...messageTools({} as unknown as MessageService), // eslint-disable-line @typescript-eslint/no-unsafe-argument+ ...contactTools({} as unknown as ContactService), // eslint-disable-line @typescript-eslint/no-unsafe-argument+ ...groupTools({} as unknown as GroupService), // eslint-disable-line @typescript-eslint/no-unsafe-argument+ ...webhookTools({} as unknown as WebhookService), // eslint-disable-line @typescript-eslint/no-unsafe-argument+ ]+ .map(t => t.name)+ .sort();++ expect(actualNames).toEqual(expected);+ expect(expected).toHaveLength(39);+ });+});diff --git a/src/core/agent-tools/tools/contact.tools.ts b/src/core/agent-tools/tools/contact.tools.tsnew file mode 100644index 000000000..67e9fb70f--- /dev/null+++ b/src/core/agent-tools/tools/contact.tools.ts@@ -0,0 +1,110 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { ContactService } from '../../../modules/contact/contact.service';+import type { ToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().describe('Session UUID (the session id, not the name)');++export function contactTools(contact: ContactService): ToolDescriptor[] {+ return [+ {+ name: 'ContactFindAll',+ description: 'List all contacts for a session. Use limit/offset to page through large contact lists.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ limit: z.number().int().min(1).max(1000).optional(),+ offset: z.number().int().min(0).optional(),+ }),+ handler: (input: { sessionId: string; limit?: number; offset?: number }) =>+ contact.getContacts(input.sessionId, { limit: input.limit, offset: input.offset }),+ },+ {+ name: 'ContactFindOne',+ description: 'Get details for a specific contact by JID (e.g. [email protected]).',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ contactId: z.string().describe('Contact JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; contactId: string }) =>+ contact.getContactById(input.sessionId, input.contactId),+ },+ {+ name: 'ContactCheckNumber',+ description:+ 'Check whether a phone number is registered on WhatsApp. Returns exists flag and the WhatsApp JID if found.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ number: z.string().describe('Phone number to check (e.g. 628123456789, digits only)'),+ }),+ handler: async (input: { sessionId: string; number: string }) => {+ const whatsappId = await contact.getNumberId(input.sessionId, input.number);+ return { number: input.number, exists: whatsappId !== null, whatsappId };+ },+ },+ {+ name: 'ContactResolvePhone',+ description:+ 'Resolve a contact JID (e.g. an @lid) to a phone number. Best-effort — returns null when the engine cannot map it.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ contactId: z.string().describe('Contact JID to resolve (e.g. an @lid)'),+ }),+ handler: async (input: { sessionId: string; contactId: string }) => {+ const phone = await contact.resolveContactPhone(input.sessionId, input.contactId);+ return { contactId: input.contactId, phone };+ },+ },+ {+ name: 'ContactGetProfilePicture',+ description: 'Get the profile picture URL for a contact.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ contactId: z.string().describe('Contact JID (e.g. [email protected])'),+ }),+ handler: async (input: { sessionId: string; contactId: string }) => {+ const url = await contact.getProfilePicture(input.sessionId, input.contactId);+ return { url };+ },+ },+ {+ name: 'ContactBlock',+ description: 'Block a contact. The contact will no longer be able to send messages. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ contactId: z.string().describe('Contact JID (e.g. [email protected])'),+ }),+ handler: async (input: { sessionId: string; contactId: string }) => {+ await contact.blockContact(input.sessionId, input.contactId);+ return { success: true, message: 'Contact blocked' };+ },+ },+ {+ name: 'ContactUnblock',+ description: 'Unblock a previously blocked contact. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ contactId: z.string().describe('Contact JID (e.g. [email protected])'),+ }),+ handler: async (input: { sessionId: string; contactId: string }) => {+ await contact.unblockContact(input.sessionId, input.contactId);+ return { success: true, message: 'Contact unblocked' };+ },+ },+ ];+}diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsnew file mode 100644index 000000000..c393b97cc--- /dev/null+++ b/src/core/agent-tools/tools/group.tools.ts@@ -0,0 +1,111 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { GroupService } from '../../../modules/group/group.service';+import type { ToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().describe('Session UUID (the session id, not the name)');++export function groupTools(group: GroupService): ToolDescriptor[] {+ return [+ {+ name: 'GroupFindAll',+ description: 'List all groups the session is a member of. Use limit/offset to page.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ limit: z.number().int().min(1).max(1000).optional(),+ offset: z.number().int().min(0).optional(),+ }),+ handler: (input: { sessionId: string; limit?: number; offset?: number }) =>+ group.getGroups(input.sessionId, { limit: input.limit, offset: input.offset }),+ },+ {+ name: 'GroupFindOne',+ description: 'Get detailed info for a specific group including participants list.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ groupId: z.string().describe('Group JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; groupId: string }) => group.getGroupInfo(input.sessionId, input.groupId),+ },+ {+ name: 'GroupGetInviteCode',+ description: 'Get the invite code and link for a group.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ groupId: z.string().describe('Group JID (e.g. [email protected])'),+ }),+ handler: async (input: { sessionId: string; groupId: string }) => {+ const inviteCode = await group.getGroupInviteCode(input.sessionId, input.groupId);+ return { inviteCode, inviteLink: `https://chat.whatsapp.com/${inviteCode}` };+ },+ },+ {+ name: 'GroupCreate',+ description: 'Create a new WhatsApp group with a name and initial participants. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ name: z.string().min(1).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[] }) =>+ group.createGroup(input.sessionId, input.name, input.participants),+ },+ {+ name: 'GroupAddParticipants',+ description: 'Add participants to an existing group. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ groupId: z.string().describe('Group JID (e.g. [email protected])'),+ participants: z.array(z.string()).min(1).describe('Participant WhatsApp JIDs to add'),+ }),+ handler: async (input: { sessionId: string; groupId: string; participants: string[] }) => {+ await group.addParticipants(input.sessionId, input.groupId, input.participants);+ return { success: true, message: 'Participants added' };+ },+ },+ {+ name: 'GroupSetSubject',+ description: 'Change the group name/subject. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ groupId: z.string().describe('Group JID (e.g. [email protected])'),+ subject: z.string().min(1).describe('New group subject/name'),+ }),+ handler: async (input: { sessionId: string; groupId: string; subject: string }) => {+ await group.setGroupSubject(input.sessionId, input.groupId, input.subject);+ return { success: true, message: 'Group subject updated' };+ },+ },+ {+ name: 'GroupSetDescription',+ description: 'Change the group description. Pass empty string to clear it. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ 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)'),+ }),+ handler: async (input: { sessionId: string; groupId: string; description: string }) => {+ await group.setGroupDescription(input.sessionId, input.groupId, input.description);+ return { success: true, message: 'Group description updated' };+ },+ },+ ];+}diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.tsnew file mode 100644index 000000000..96fef2039--- /dev/null+++ b/src/core/agent-tools/tools/message.tools.ts@@ -0,0 +1,376 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { MessageService } from '../../../modules/message/message.service';+import type { ToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().describe('Session UUID (the session id, not the name)');++export function messageTools(message: MessageService): ToolDescriptor[] {+ return [+ {+ name: 'MessageList',+ description:+ 'List persisted messages for a session, optionally filtered by chatId or sender. Reads from the local DB.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().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(500).optional(),+ offset: z.number().int().min(0).optional(),+ }),+ handler: (input: { sessionId: string; chatId?: string; from?: string; limit?: number; offset?: number }) =>+ message.getMessages(input.sessionId, {+ chatId: input.chatId,+ from: input.from,+ limit: input.limit,+ offset: input.offset,+ }),+ },+ {+ name: 'MessageHistory',+ description:+ 'Fetch live chat history from WhatsApp for a specific chat. Bypasses the local DB — useful for messages that arrived before the gateway started.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected] or [email protected])'),+ limit: z.number().int().min(1).max(2000).optional(),+ includeMedia: z.boolean().optional().describe('Download media as base64 (slower)'),+ deep: z.boolean().optional().describe('Raise limit ceiling to 2000 for reaching further back in history'),+ }),+ handler: (input: { sessionId: string; chatId: string; limit?: number; includeMedia?: boolean; deep?: boolean }) =>+ message.getChatHistory(input.sessionId, input.chatId, input.limit, input.includeMedia, input.deep),+ },+ {+ name: 'MessageGetReactions',+ description: 'Get reactions for a specific message, including which contacts sent which emoji.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID containing the message'),+ messageId: z.string().describe('Message ID to get reactions for'),+ }),+ handler: (input: { sessionId: string; chatId: string; messageId: string }) =>+ message.getMessageReactions(input.sessionId, input.chatId, input.messageId),+ },+ {+ name: 'MessageSendText',+ description: 'Send a plain text message to a chat or group. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ 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'),+ }),+ handler: (input: { sessionId: string; chatId: string; text: string }) =>+ message.sendText(input.sessionId, { chatId: input.chatId, text: input.text }),+ },+ {+ name: 'MessageSendImage',+ description: 'Send an image message via URL or base64. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ url: z.string().url().optional().describe('Image URL (http/https)'),+ base64: z.string().optional().describe('Base64-encoded image data'),+ mimetype: z.string().optional().describe('MIME type (required when using base64)'),+ filename: z.string().max(255).optional(),+ caption: z.string().max(1024).optional(),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+ }) =>+ message.sendImage(input.sessionId, {+ chatId: input.chatId,+ url: input.url,+ base64: input.base64,+ mimetype: input.mimetype,+ filename: input.filename,+ caption: input.caption,+ }),+ },+ {+ name: 'MessageSendVideo',+ description: 'Send a video message via URL or base64. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ url: z.string().url().optional().describe('Video URL (http/https)'),+ base64: z.string().optional().describe('Base64-encoded video data'),+ mimetype: z.string().optional().describe('MIME type (required when using base64)'),+ filename: z.string().max(255).optional(),+ caption: z.string().max(1024).optional(),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+ }) =>+ message.sendVideo(input.sessionId, {+ chatId: input.chatId,+ url: input.url,+ base64: input.base64,+ mimetype: input.mimetype,+ filename: input.filename,+ caption: input.caption,+ }),+ },+ {+ name: 'MessageSendAudio',+ description: 'Send an audio/voice message via URL or base64. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ url: z.string().url().optional().describe('Audio URL (http/https)'),+ base64: z.string().optional().describe('Base64-encoded audio data'),+ mimetype: z.string().optional().describe('MIME type (required when using base64)'),+ filename: z.string().max(255).optional(),+ caption: z.string().max(1024).optional(),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+ }) =>+ message.sendAudio(input.sessionId, {+ chatId: input.chatId,+ url: input.url,+ base64: input.base64,+ mimetype: input.mimetype,+ filename: input.filename,+ caption: input.caption,+ }),+ },+ {+ name: 'MessageSendDocument',+ description: 'Send a document/file message via URL or base64. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ url: z.string().url().optional().describe('Document URL (http/https)'),+ base64: z.string().optional().describe('Base64-encoded document data'),+ mimetype: z.string().optional().describe('MIME type (required when using base64)'),+ filename: z.string().max(255).optional(),+ caption: z.string().max(1024).optional(),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+ }) =>+ message.sendDocument(input.sessionId, {+ chatId: input.chatId,+ url: input.url,+ base64: input.base64,+ mimetype: input.mimetype,+ filename: input.filename,+ caption: input.caption,+ }),+ },+ {+ name: 'MessageSendLocation',+ description: 'Send a location pin message. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ 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'),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ latitude: number;+ longitude: number;+ description?: string;+ address?: string;+ }) =>+ message.sendLocation(input.sessionId, {+ chatId: input.chatId,+ latitude: input.latitude,+ longitude: input.longitude,+ description: input.description,+ address: input.address,+ }),+ },+ {+ name: 'MessageSendContact',+ description: 'Send a contact card message. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ 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'),+ }),+ handler: (input: { sessionId: string; chatId: string; contactName: string; contactNumber: string }) =>+ message.sendContact(input.sessionId, {+ chatId: input.chatId,+ contactName: input.contactName,+ contactNumber: input.contactNumber,+ }),+ },+ {+ name: 'MessageSendSticker',+ description: 'Send a sticker message via URL or base64. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ url: z.string().url().optional().describe('Sticker URL (http/https)'),+ base64: z.string().optional().describe('Base64-encoded sticker data'),+ mimetype: z.string().optional().describe('MIME type (required when using base64)'),+ filename: z.string().max(255).optional(),+ caption: z.string().max(1024).optional(),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+ }) =>+ message.sendSticker(input.sessionId, {+ chatId: input.chatId,+ url: input.url,+ base64: input.base64,+ mimetype: input.mimetype,+ filename: input.filename,+ caption: input.caption,+ }),+ },+ {+ name: 'MessageSendTemplate',+ description:+ 'Render a stored text template and send it as a text message. Provide either templateId or templateName. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID'),+ templateId: z.string().optional().describe('Template UUID'),+ templateName: z.string().optional().describe('Template name slug'),+ vars: z+ .record(z.string(), z.string())+ .optional()+ .describe('Variables to substitute into {{placeholder}} tokens'),+ }),+ handler: (input: {+ sessionId: string;+ chatId: string;+ templateId?: string;+ templateName?: string;+ vars?: Record<string, string>;+ }) =>+ message.sendTemplate(input.sessionId, {+ chatId: input.chatId,+ templateId: input.templateId,+ templateName: input.templateName,+ vars: input.vars,+ }),+ },+ {+ name: 'MessageReply',+ description: 'Reply to a specific message (quoted reply). Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ 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'),+ }),+ handler: (input: { sessionId: string; chatId: string; quotedMessageId: string; text: string }) =>+ message.reply(input.sessionId, {+ chatId: input.chatId,+ quotedMessageId: input.quotedMessageId,+ text: input.text,+ }),+ },+ {+ name: 'MessageForward',+ description: 'Forward a message from one chat to another. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ fromChatId: z.string().describe('Source chat JID'),+ toChatId: z.string().describe('Destination chat JID'),+ messageId: z.string().describe('ID of the message to forward'),+ }),+ handler: (input: { sessionId: string; fromChatId: string; toChatId: string; messageId: string }) =>+ message.forward(input.sessionId, {+ fromChatId: input.fromChatId,+ toChatId: input.toChatId,+ messageId: input.messageId,+ }),+ },+ {+ name: 'MessageReact',+ description:+ 'Add or remove a reaction emoji on a message. Send empty string emoji to remove. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ 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.'),+ }),+ handler: (input: { sessionId: string; chatId: string; messageId: string; emoji: string }) =>+ message+ .reactToMessage(input.sessionId, { chatId: input.chatId, messageId: input.messageId, emoji: input.emoji })+ .then(() => ({ success: true })),+ },+ ];+}diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsnew file mode 100644index 000000000..d53d080f8--- /dev/null+++ b/src/core/agent-tools/tools/session.tools.ts@@ -0,0 +1,90 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { ChatState } from '../../../engine/interfaces/whatsapp-engine.interface';+import type { SessionService } from '../../../modules/session/session.service';+import type { ToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().describe('Session UUID (the session id, not the name)');++export function sessionTools(session: SessionService): ToolDescriptor[] {+ return [+ {+ name: 'SessionFindAll',+ description:+ 'List the WhatsApp sessions this API key may access (id, name, status). Use to discover available sessions before calling session-scoped tools.',+ tier: 'read',+ inputSchema: z.object({}),+ handler: (_input, apiKey) => session.findAll(apiKey.allowedSessions),+ },+ {+ name: 'SessionFindOne',+ description: 'Get one session by its UUID, including connection status and phone number.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({ sessionId }),+ handler: (input: { sessionId: string }) => session.findOne(input.sessionId),+ },+ {+ name: 'SessionGetChats',+ description: 'List recent chats for a session (most recent first). Use limit/offset to page through large lists.',+ tier: 'read',+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ limit: z.number().int().min(1).max(1000).optional(),+ offset: z.number().int().min(0).optional(),+ }),+ handler: (input: { sessionId: string; limit?: number; offset?: number }) =>+ session.getChats(input.sessionId, { limit: input.limit, offset: input.offset }),+ },+ {+ name: 'SessionGetStats',+ description: 'Aggregate session counts (total, active, ready, disconnected) the key is allowed to see.',+ tier: 'read',+ inputSchema: z.object({}),+ handler: (_input, apiKey) => session.getStats(apiKey.allowedSessions),+ },+ {+ name: 'SessionMarkChatRead',+ description: 'Mark a chat as read (clears unread count). Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; chatId: string }) =>+ session.sendSeen(input.sessionId, input.chatId).then(success => ({ success })),+ },+ {+ name: 'SessionMarkChatUnread',+ description: 'Mark a chat as unread. Requires OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; chatId: string }) =>+ session.markUnread(input.sessionId, input.chatId).then(success => ({ success })),+ },+ {+ name: 'SessionSendChatState',+ description: "Show a typing/recording indicator in a chat, or clear it with 'paused'. Requires OPERATOR role.",+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ state: z+ .enum(['typing', 'recording', 'paused'])+ .describe("'typing' or 'recording' shows the indicator; 'paused' clears it"),+ }),+ handler: (input: { sessionId: string; chatId: string; state: ChatState }) =>+ session.sendChatState(input.sessionId, input.chatId, input.state).then(() => ({ success: true })),+ },+ ];+}diff --git a/src/core/agent-tools/tools/webhook.tools.ts b/src/core/agent-tools/tools/webhook.tools.tsnew file mode 100644index 000000000..4edc65ae8--- /dev/null+++ b/src/core/agent-tools/tools/webhook.tools.ts@@ -0,0 +1,40 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { WebhookService } from '../../../modules/webhook/webhook.service';+import type { ToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().describe('Session UUID (the session id, not the name)');++export function webhookTools(webhook: WebhookService): ToolDescriptor[] {+ return [+ {+ name: 'WebhooksList',+ description: 'List all webhooks the API key is allowed to see, across all its accessible sessions.',+ tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,+ inputSchema: z.object({}),+ handler: (_input, apiKey) => webhook.findAll(apiKey.allowedSessions),+ },+ {+ name: 'WebhookFindBySession',+ description: 'List all webhooks registered for a specific session.',+ tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({ sessionId }),+ handler: (input: { sessionId: string }) => webhook.findBySession(input.sessionId),+ },+ {+ name: 'WebhookFindOne',+ description: 'Get details for a specific webhook by ID within a session.',+ tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ webhookId: z.string().describe('Webhook UUID'),+ }),+ handler: (input: { sessionId: string; webhookId: string }) => webhook.findOne(input.sessionId, input.webhookId),+ },+ ];+}diff --git a/src/modules/contact/contact.module.ts b/src/modules/contact/contact.module.tsindex 5cdf56c08..cdfb0736f 100644--- a/src/modules/contact/contact.module.ts+++ b/src/modules/contact/contact.module.ts@@ -7,5 +7,6 @@ import { SessionModule } from '../session/session.module';imports: [SessionModule],controllers: [ContactController],providers: [ContactService],+ exports: [ContactService],})export class ContactModule {}diff --git a/src/modules/group/group.module.ts b/src/modules/group/group.module.tsindex c9574a2d8..feef5f9e0 100644--- a/src/modules/group/group.module.ts+++ b/src/modules/group/group.module.ts@@ -7,5 +7,6 @@ import { SessionModule } from '../session/session.module';imports: [SessionModule],controllers: [GroupController],providers: [GroupService],+ exports: [GroupService],})export class GroupModule {}diff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.tsnew file mode 100644index 000000000..2b6b33b19--- /dev/null+++ b/src/modules/mcp/mcp-rate-limit.spec.ts@@ -0,0 +1,18 @@+import { KeyRateLimiter } from './mcp-rate-limit';++describe('KeyRateLimiter', () => {+ it('allows up to max per window, then throws 429', () => {+ let now = 1_000;+ const rl = new KeyRateLimiter(2, 1000, () => now);+ rl.check('k');+ rl.check('k');+ expect(() => rl.check('k')).toThrow(/rate limit/i);+ now = 2_500; // window passed+ expect(() => rl.check('k')).not.toThrow();+ });+ it('buckets per key', () => {+ const rl = new KeyRateLimiter(1, 1000, () => 0);+ rl.check('a');+ expect(() => rl.check('b')).not.toThrow();+ });+});diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.tsnew file mode 100644index 000000000..463b43562--- /dev/null+++ b/src/modules/mcp/mcp-rate-limit.ts@@ -0,0 +1,26 @@+import { HttpException, HttpStatus } from '@nestjs/common';++/**+ * Per-API-key sliding window rate limiter.+ * The inherited IP-keyed throttler collapses all MCP calls into one 127.0.0.1 bucket,+ * so MCP needs its own per-key limiter.+ * In-memory per-process; move to Redis for multi-instance deployments.+ */+export class KeyRateLimiter {+ private readonly hits = new Map<string, number[]>();+ constructor(+ private readonly max = 60,+ private readonly windowMs = 60_000,+ private readonly now: () => number = () => Date.now(),+ ) {}++ check(key: string): void {+ const t = this.now();+ const recent = (this.hits.get(key) ?? []).filter(ts => t - ts < this.windowMs);+ if (recent.length >= this.max) {+ throw new HttpException('MCP rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);+ }+ recent.push(t);+ this.hits.set(key, recent);+ }+}diff --git a/src/modules/mcp/mcp.module.ts b/src/modules/mcp/mcp.module.tsnew file mode 100644index 000000000..3a9294282--- /dev/null+++ b/src/modules/mcp/mcp.module.ts@@ -0,0 +1,47 @@+import { type DynamicModule, Module, type MiddlewareConsumer, type NestModule } from '@nestjs/common';+import { HttpAdapterHost } from '@nestjs/core';+import { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';+import { AuthService } from '../auth/auth.service';+import { KeyRateLimiter } from './mcp-rate-limit';+import { mountMcpServer } from './mcp.server';++export interface McpModuleOptions {+ basePath?: string;+ serverInfo?: { name: string; version: string };+ rateLimitMax?: number;+ rateLimitWindowMs?: number;+}++// Module-level options store: set by forRoot(), read by configure().+// Safe because configure() runs after DI resolution (i.e., after forRoot() has been called).+let _moduleOptions: McpModuleOptions = {};++@Module({})+export class McpModule implements NestModule {+ constructor(+ private readonly registry: ToolRegistryService,+ private readonly authService: AuthService,+ private readonly httpAdapterHost: HttpAdapterHost,+ ) {}++ static forRoot(options: McpModuleOptions = {}): DynamicModule {+ _moduleOptions = options;+ return {+ module: McpModule,+ global: false,+ providers: [],+ exports: [],+ };+ }++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ configure(_consumer: MiddlewareConsumer): void {+ const httpAdapter = this.httpAdapterHost.httpAdapter;+ if (!httpAdapter) {+ throw new Error('McpModule: HttpAdapterHost.httpAdapter is not available.');+ }+ const { rateLimitMax, rateLimitWindowMs, basePath, serverInfo } = _moduleOptions;+ const rateLimiter = new KeyRateLimiter(rateLimitMax, rateLimitWindowMs);+ mountMcpServer(httpAdapter, this.registry, this.authService, rateLimiter, { basePath, serverInfo });+ }+}diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsnew file mode 100644index 000000000..1b757ce9a--- /dev/null+++ b/src/modules/mcp/mcp.server.ts@@ -0,0 +1,137 @@+import { Logger } from '@nestjs/common';+import type { HttpAdapterHost } from '@nestjs/core';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';+import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';+import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';+import express, { type Request, type RequestHandler, type Response } from 'express';+import { invokeTool } from '../../core/agent-tools/tool-invoker';+import type { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';+import type { AuthService } from '../auth/auth.service';+import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';+import type { KeyRateLimiter } from './mcp-rate-limit';++const logger = new Logger('McpServer');++type HttpAdapter = NonNullable<HttpAdapterHost['httpAdapter']>;+type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;++/** Extract the raw API key from MCP request headers. Accepts X-Api-Key or Bearer token. */+function extractApiKey(extra: ToolExtra): string | undefined {+ const headers = extra.requestInfo?.headers ?? {};+ const xApiKey = headers['x-api-key'];+ if (xApiKey) {+ return Array.isArray(xApiKey) ? xApiKey[0] : xApiKey;+ }+ const auth = headers['authorization'];+ const authStr = Array.isArray(auth) ? auth[0] : auth;+ if (authStr?.toLowerCase().startsWith('bearer ')) {+ return authStr.slice(7).trim();+ }+ return undefined;+}++/**+ * Build the MCP server ONCE and register all tools from the registry.+ * The SDK's `registerTool` accepts `AnySchema` (z4.$ZodType) directly, so we+ * pass `tool.inputSchema` verbatim — no `.shape` extraction needed.+ */+function buildServer(+ registry: ToolRegistryService,+ authService: AuthService,+ rateLimiter: KeyRateLimiter,+ readOnly: boolean,+ serverInfo: { name: string; version: string },+): McpServer {+ const server = new McpServer(+ { name: serverInfo.name, version: serverInfo.version },+ { capabilities: { tools: {}, logging: {} } },+ );++ const tools = registry.list({ readOnly });+ for (const tool of tools) {+ server.registerTool(+ tool.name,+ {+ description: tool.description,+ // inputSchema accepts AnySchema (zod v4 $ZodType is compatible)+ inputSchema: tool.inputSchema as Parameters<typeof server.registerTool>[1]['inputSchema'],+ annotations: {+ readOnlyHint: tool.tier === 'read',+ destructiveHint: tool.destructive ?? false,+ idempotentHint: tool.idempotent ?? tool.tier === 'read',+ },+ },+ async (input: Record<string, unknown>, extra: ToolExtra) => {+ const rawKey = extractApiKey(extra);+ try {+ rateLimiter.check(rawKey ?? '');+ const result = await invokeTool(tool, input, rawKey, authService);+ return tool.resultDisposition === 'json'+ ? jsonToolResult(result as object)+ : smartToolResult(result as object);+ } catch (error) {+ return handleToolError(error);+ }+ },+ );+ }++ logger.log(`MCP server built with ${tools.length} tools (readOnly=${readOnly})`);+ return server;+}++export interface MountMcpServerOptions {+ basePath?: string;+ serverInfo?: { name: string; version: string };+ readOnly?: boolean;+}++/**+ * Mount the MCP Streamable-HTTP transport on the existing Nest/Express adapter+ * at `POST {basePath}` (default `/mcp`), single-port.+ *+ * Tool handlers are built ONCE at mount time (closure over registry/authService/rateLimiter).+ * Per-request: mint a fresh McpServer + StreamableHTTPServerTransport, handle, tear down.+ * Stateless (sessionIdGenerator: undefined) — no session map, no GET/DELETE reconnect.+ * Creating a new McpServer per request is safe and avoids the single-transport constraint;+ * tool registration is O(n) pure function calls with no I/O overhead.+ */+export function mountMcpServer(+ httpAdapter: HttpAdapter,+ registry: ToolRegistryService,+ authService: AuthService,+ rateLimiter: KeyRateLimiter,+ options: MountMcpServerOptions = {},+): void {+ const basePath = (options.basePath ?? '/mcp').replace(/\/$/, '') || '/mcp';+ const serverInfo = options.serverInfo ?? { name: 'openwa', version: '0.0.0' };+ const readOnly = options.readOnly ?? process.env.MCP_READONLY === 'true';++ // Eagerly compute the tool list at mount time to validate the registry is populated+ // and to emit the log line once. The actual McpServer is re-created per request to+ // avoid the SDK's single-transport-at-a-time constraint under concurrent load.+ const tools = registry.list({ readOnly });+ logger.log(`MCP server mounted at POST ${basePath} (${tools.length} tools)`);++ const handler: RequestHandler = async (req: Request, res: Response) => {+ const server = buildServer(registry, authService, rateLimiter, readOnly, serverInfo);+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });+ try {+ res.on('close', () => {+ void transport.close();+ void server.close();+ });+ await server.connect(transport);+ await transport.handleRequest(req, res, req.body);+ } catch (error) {+ logger.error('Error handling MCP request', error instanceof Error ? error.stack : String(error));+ if (!res.headersSent) {+ res.status(500).json({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null });+ }+ }+ };++ const adapter = httpAdapter as unknown as { post: (path: string, ...handlers: RequestHandler[]) => unknown };+ adapter.post(basePath, express.json(), handler);+}diff --git a/src/modules/mcp/tool-result.ts b/src/modules/mcp/tool-result.tsnew file mode 100644index 000000000..65d6dc6ad--- /dev/null+++ b/src/modules/mcp/tool-result.ts@@ -0,0 +1,49 @@+import { randomUUID } from 'node:crypto';+import { Logger } from '@nestjs/common';+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';++const logger = new Logger('Mcp');++/**+ * Format a tool result, inlining small payloads as text and offloading large+ * 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);+ const mimeType = typeof data === 'string' ? 'text/plain' : 'application/json';+ const ext = typeof data === 'string' ? 'txt' : 'json';+ if (text.length > 4096) {+ const uri = `mcp://toolResult/${randomUUID()}.${ext}`;+ const buffer = Buffer.from(text);+ return {+ content: [+ { type: 'text', text: `Received resource ${uri} with ${buffer.byteLength} bytes` },+ { type: 'resource', resource: { uri, mimeType, blob: buffer.toString('base64') } },+ ],+ };+ }+ return { content: [{ type: 'text', text }] };+}++/** Format a tool result as compact JSON text. */+export function jsonToolResult(data: object, isError = false): CallToolResult {+ const result: CallToolResult = { content: [{ type: 'text', text: JSON.stringify(data) }] };+ if (isError) {+ result.isError = true;+ }+ return result;+}++/**+ * Map a thrown error to a tool-error result. Stack traces and raw thrown values+ * are logged server-side only - never put on the wire, where they would leak+ * server internals to the MCP client.+ */+export function handleToolError(error: unknown): CallToolResult {+ if (error instanceof Error) {+ logger.error(error.message, error.stack);+ return jsonToolResult({ success: false, name: error.name, message: error.message }, true);+ }+ logger.error('Unknown tool error', String(error));+ return jsonToolResult({ success: false, name: 'Unknown error', message: 'An unknown error occurred' }, true);+}diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.tsnew file mode 100644index 000000000..c0ea0eb5b--- /dev/null+++ b/test/mcp-auth.e2e-spec.ts@@ -0,0 +1,174 @@+// archiver v8 is ESM-only; stub it so ts-jest can load the module graph.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++// Enable the MCP server before AppModule is imported.+process.env.MCP_ENABLED = 'true';++import { Test, TestingModule } from '@nestjs/testing';+import { type INestApplication, ValidationPipe } from '@nestjs/common';+import request from 'supertest';+import type { App } from 'supertest/types';+import { AppModule } from '../src/app.module';++// --- MCP protocol helpers ---++const MCP_HEADERS = {+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+};++function jsonRpcRequest(method: string, params: Record<string, unknown> = {}, id = 1) {+ return { jsonrpc: '2.0', method, params, id };+}++/**+ * Parse the MCP response. The StreamableHTTP transport sends:+ * - `text/event-stream` SSE for normal requests (tools/list, tools/call)+ * - `application/json` directly for some responses+ *+ * Supertest parses `application/json` into `.body`. For SSE, `.body` is empty+ * and the actual content is in `.text` (raw string). We try both.+ */+function parseMcpResponse(res: { body: unknown; text: string }): Record<string, unknown> {+ // If supertest parsed JSON, body will be a non-empty object+ if (typeof res.body === 'object' && res.body !== null && Object.keys(res.body).length > 0) {+ return res.body as Record<string, unknown>;+ }+ // SSE format: "event: message\ndata: {...}\n\n" — extract the data line+ const text = res.text ?? '';+ const match = /^data:\s*(.+)$/m.exec(text);+ if (match) {+ return JSON.parse(match[1]) as Record<string, unknown>;+ }+ // Plain JSON text fallback+ if (text.trim().startsWith('{')) {+ return JSON.parse(text) as Record<string, unknown>;+ }+ return {};+}++// --- Test suite ---++describe('MCP server (e2e)', () => {+ let app: INestApplication<App>;++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ app.setGlobalPrefix('api');+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ await app.init();+ }, 30_000);++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore TypeORM multi-datasource teardown quirk */+ }+ });++ // ---------------------------------------------------------------------------+ // 1. MCP endpoint is reachable — initialize succeeds+ // ---------------------------------------------------------------------------+ it('POST /mcp with initialize request responds with 200', async () => {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set(MCP_HEADERS)+ .send(+ jsonRpcRequest('initialize', {+ protocolVersion: '2025-11-25',+ capabilities: {},+ clientInfo: { name: 'test-client', version: '0.0.1' },+ }),+ );++ expect([200, 202]).toContain(res.status);+ });++ // ---------------------------------------------------------------------------+ // 2. tools/list returns the tool catalogue with known names+ // ---------------------------------------------------------------------------+ it('tools/list returns the tool catalogue', async () => {+ const res = await request(app.getHttpServer()).post('/mcp').set(MCP_HEADERS).send(jsonRpcRequest('tools/list'));++ expect(res.status).toBe(200);+ const body = parseMcpResponse(res);+ const result = body.result as Record<string, unknown> | undefined;+ expect(result).toBeDefined();+ const tools = result?.tools as Array<{ name: string }> | undefined;+ expect(Array.isArray(tools)).toBe(true);+ expect(tools!.length).toBeGreaterThan(0);+ // Verify well-known tools are present+ const names = tools!.map(t => t.name);+ expect(names).toContain('SessionFindAll');+ });++ // ---------------------------------------------------------------------------+ // 3. tools/call without API key returns an error tool result+ // (auth is protocol-level: tool errors surface as isError=true, not HTTP 401)+ // ---------------------------------------------------------------------------+ it('tools/call without API key returns isError tool result', async () => {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set(MCP_HEADERS)+ .send(+ jsonRpcRequest('tools/call', {+ name: 'SessionFindAll',+ arguments: {},+ }),+ );++ expect(res.status).toBe(200);+ const body = parseMcpResponse(res);+ // The tool handler catches UnauthorizedException and routes through handleToolError,+ // returning a tool result with isError=true.+ const result = body.result as Record<string, unknown> | undefined;+ expect(result?.isError).toBe(true);+ const content = result?.content as Array<{ type: string; text?: string }> | undefined;+ expect(Array.isArray(content)).toBe(true);+ const text = content?.find(c => c.type === 'text')?.text ?? '';+ expect(text).toMatch(/unauthorized|missing api key/i);+ });++ // ---------------------------------------------------------------------------+ // 4. Unsupported Content-Type → 415+ // ---------------------------------------------------------------------------+ it('POST /mcp with wrong Content-Type returns 415', async () => {+ const res = await request(app.getHttpServer())+ .post('/mcp')+ .set({ 'Content-Type': 'text/plain', Accept: 'application/json, text/event-stream' })+ .send('{}');++ expect(res.status).toBe(415);+ });++ // ---------------------------------------------------------------------------+ // 5. MCP_READONLY mode — write tools hidden from catalogue+ // Tested at integration level: the `readOnly` flag path in mcp.server.ts+ // calls registry.list({ readOnly: true }), which is unit-tested in+ // tool-registry.spec.ts. A second full app boot is not cost-effective here;+ // we note the gap and mark as pending.+ // ---------------------------------------------------------------------------+ it.todo('MCP_READONLY=true hides write tools — requires second app boot');++ // ---------------------------------------------------------------------------+ // 6. Rate limiter at 429+ // The per-key limiter is fully covered by mcp-rate-limit.spec.ts.+ // Triggering it in e2e needs > 60 same-key tool calls in 60s, making the+ // suite slow. The wiring (mountMcpServer → rateLimiter.check) is 3 lines+ // with no branching. Marking as pending.+ // ---------------------------------------------------------------------------+ it.todo('rate limiter returns 429-equivalent tool error past cap — see mcp-rate-limit.spec.ts');++ // ---------------------------------------------------------------------------+ // 7. Session-scoped key scoping+ // Requires a created session + a key with allowedSessions set. The full+ // session lifecycle (QR scan, WhatsApp connect) is not automatable in e2e.+ // Covered by invokeTool unit test (tool-invoker.spec.ts).+ // ---------------------------------------------------------------------------+ it.todo('session-scoped key calling another sessions tool is rejected — see tool-invoker.spec.ts');+});