Kommo MCP Server
README.md
# Kommo MCP Server
<p align="center">
<img src="docs/assets/banner.png" alt="Kommo MCP Server — open-source MCP server for Kommo" width="100%">
</p>
<p align="center">
<img src="https://img.shields.io/badge/version-0.3.0-7c3aed?style=flat-square" alt="version 0.3.0">
<img src="https://img.shields.io/badge/MCP-Streamable%20HTTP%20%7C%20stdio-a78bfa?style=flat-square" alt="MCP Streamable HTTP | stdio">
<img src="https://img.shields.io/badge/Kommo-API%20v4-6d28d9?style=flat-square" alt="Kommo API v4">
<img src="https://img.shields.io/badge/node-%3E%3D20.12-339933?style=flat-square&logo=nodedotjs&logoColor=white" alt="node >=20.12">
<img src="https://img.shields.io/badge/TypeScript-5.9-3178c6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript 5.9">
<img src="https://img.shields.io/badge/tests-130%20passing-2ea44f?style=flat-square&logo=vitest&logoColor=white" alt="tests 130 passing">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-a78bfa?style=flat-square" alt="license MIT"></a>
</p>
<p align="center">
<img src="https://img.shields.io/badge/n8n-compatible-ea4b71?style=flat-square&logo=n8n&logoColor=white" alt="n8n">
<img src="https://img.shields.io/badge/Claude%20Code-compatible-d97757?style=flat-square&logo=anthropic&logoColor=white" alt="Claude Code">
<img src="https://img.shields.io/badge/Codex-compatible-111111?style=flat-square" alt="Codex">
<img src="https://img.shields.io/badge/Antigravity-compatible-4285f4?style=flat-square&logo=google&logoColor=white" alt="Antigravity">
</p>
**Kommo MCP Server** connects AI agents to [Kommo CRM](https://www.kommo.com). Your agent (Claude, Codex, an n8n agent, your own code…) gets a set of safe, ready-made tools to read leads, move them through the pipeline, update fields, tag, assign, add notes and tasks, launch salesbots and send WhatsApp/Instagram messages with buttons and files.
It is built for **Kommo partners and agencies** who run AI agents for many clients: **one server serves any number of Kommo accounts**, and it **stores no Kommo credentials**. Each agent sends its own account's subdomain and token with its requests.
> **The server runs no AI.** The AI is the client: it reads your business rules and decides which tool to call. The server checks every request against the real Kommo account, protects it, and executes it.
---
## Contents
1. [What it is for](#what-it-is-for)
2. [How it works](#how-it-works)
3. [Installation](#installation)
4. [Usage](#usage)
5. [Configuration](#configuration)
- [Environment variables (`.env`)](#environment-variables-env)
- [Connection settings](#connection-settings)
- [Stored accounts (optional)](#stored-accounts-optional)
- [Account policy](#account-policy)
6. [Authentication and access](#authentication-and-access)
7. [Connecting MCP clients](#connecting-mcp-clients)
8. [Tool reference](#tool-reference)
9. [Incoming message webhook](#incoming-message-webhook)
10. [Responses and errors](#responses-and-errors)
11. [Sending messages (template + salesbot)](#sending-messages-template--salesbot)
12. [Attachments: URL, base64 or binary](#attachments-url-base64-or-binary)
13. [Strict validation](#strict-validation)
14. [Security](#security)
15. [Rate limits towards Kommo](#rate-limits-towards-kommo)
16. [Audit log and logs](#audit-log-and-logs)
17. [HTTP endpoints](#http-endpoints)
18. [npm scripts](#npm-scripts)
19. [Production deployment](#production-deployment)
20. [Development and tests](#development-and-tests)
21. [Troubleshooting](#troubleshooting)
22. [Known limitations](#known-limitations)
---
## What it is for
**Typical uses:**
- **A sales or support agent on WhatsApp/Instagram** that talks to the customer and keeps Kommo up to date by itself: it moves the lead to "Interested", saves the budget in a field, tags it, hands it to a human, and replies with buttons or a PDF.
- **An internal assistant** (Claude, Codex, Cursor…) that answers questions about the CRM: "how many leads did we win this week?", "find the contact with this phone", "which leads are stuck in Negotiation?".
- **Automations without AI** (n8n, Make, Zapier, a backend, a cron job) that call the same tools over plain REST instead of rebuilding the Kommo logic in every workflow.
**What it replaces:**
| Before (logic copied into every automation) | With kommo-mcp |
|---|---|
| 5-10 sub-workflows copied into every client's instance | One server for every client and every agent |
| The agent prompt explains how to use each tool | The tools describe themselves; the prompt carries **only business rules** |
| A misspelled stage name moves the lead anywhere or fails silently | Exact match; if it does not exist, the error lists the valid options |
| Sending messages with a field + salesbot (no emojis, size limits) | Template + salesbot with a **queue**: emojis, line breaks, buttons and files |
| A separate flow to upload files to the Kommo Drive | `attachment` on any message: URL, base64 or binary, detected automatically |
| Request bursts → 429 → IP block (403) | Global and per-account limiter, automatic brake on 429/403 |
| A malicious message can ask for another lead's data | Sessions **bound to a lead**: only that lead can be touched |
| Tokens copied into every workflow and every server | The token lives only in the agent's connection settings; the server keeps nothing |
| No record of who changed what | Audit log of every write (before/after) |
**Works with any client:**
- **AI agents over MCP:** Claude (Code, Desktop, claude.ai, API), Codex, Antigravity, Cursor, VS Code, n8n's *MCP Client Tool*, LangChain, the OpenAI Agents SDK, your own agent…
- **Automations over REST:** n8n *HTTP Request*, Make, Zapier, any backend, `curl`.
---
## How it works
```
AI agents (MCP) ────┐ POST /mcp?subdomain=…[&lead_id=123]
Claude · Codex · │
Cursor · n8n agent ·├──────────────────────► kommo-mcp ──► Kommo API v4
your own agent │ │
Automations (REST) ──┘ POST /api/v1/tools/:name ├─ Access key check (who may use this server)
+ subdomain & token ├─ Credentials from the request (subdomain + token)
in each request ├─ Policy (allowlists) and toolsets
├─ Schema cache (pipelines, fields, users, bots, tags)
├─ Strict validation + per-lead lock
├─ Message queue (template + salesbot slots)
├─ Attachments (URL / base64 / binary → Kommo Drive)
├─ Global + per-account limiter, 403 brake
└─ JSONL audit log
```
What happens on each request:
1. **The agent connects** to `https://YOUR-SERVER/mcp` with its Kommo **subdomain** and **long-lived token**, plus a **server access key** if you created any.
2. **The server checks who is calling.** The access key says the agent may use *your server*; the Kommo token decides *which account* it works on. The first request with a token checks it against Kommo and reads the account's time zone.
3. **The agent sees the tools** it is allowed to use (`toolsets`, and only one lead if the session is bound with `lead_id`).
4. **The AI calls a tool** with human values: `update_lead { stage: "Interested", fields: { "Budget": 1500 } }`. No IDs needed.
5. **The server validates everything against the real account** (stage exists, field type, allowed by the policy, lead belongs to the session), then writes to Kommo, respecting the rate limits, and records the change in the audit log.
6. **The answer is short and clear**, either the result or an error that says exactly what to fix (for example, the list of valid stages).
Technical details:
- **Transport:** **stateless** MCP Streamable HTTP (each POST is independent; JSON responses), REST, and stdio for local use.
- **Multi-tenant without storage:** the account comes with each request. While an account is in use, its cache, locks and message queue stay **in memory**; idle accounts are dropped after 30 minutes.
- **On disk** the server only keeps the hashes of its access keys and, if enabled, the audit log.
- **Optional stored accounts:** a `tenants.json` with server API keys is still supported, for operators who prefer the server to hold the tokens (see [Stored accounts](#stored-accounts-optional)).
- **Stack:** Node.js ≥ 20.12, TypeScript, `@modelcontextprotocol/sdk`, Express 5, Zod 4, busboy, Vitest.
---
## Installation
**You need:**
- For each Kommo account: a **long-lived token**. A Kommo administrator creates it in *Settings → Integrations → Create integration → private → Keys and scopes → Generate long-lived token*. The agent sends it; the server does not store it.
- To send messages (optional): a connected chat channel (WhatsApp, Instagram…) and a salesbot (see [Usage → step 5](#5-optional-enable-messaging)).
Choose one way to run the server:
### Option A: Docker panel (Easypanel, Coolify, Dokploy…) — recommended for production
1. Create an app from this repository with the **Dockerfile** build.
2. Set the domain with HTTPS and the container port **3000**.
3. Mount a **volume at `/app/data`** (keeps the access keys and the audit log).
4. Set the environment variable `ADMIN_TOKEN` to 24+ random characters (the password of the admin page). For claude.ai / Claude Desktop, also set `PUBLIC_URL` and `OAUTH_SECRET`.
5. Deploy and open `https://YOUR-SERVER/health`: it answers `{ "ok": true, … }`.
6. Keep **1 replica**.
Step-by-step guides for each panel and plain Docker: **[docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)**.
### Option B: Node.js on your machine or a server
Requires Node.js **20.12 or later**.
```powershell
git clone <this repository> kommo-mcp
cd kommo-mcp
npm install
npm run build
npm start
```
No configuration is needed. The server listens on `http://localhost:3000/mcp`; check it with `http://localhost:3000/health`. To change anything, copy [.env.example](.env.example) to `.env` (every line is optional). In production, put it behind an HTTPS proxy and set `TRUST_PROXY=1`.
### Option C: local only (stdio), without a server
For Claude Desktop or Claude Code on your own machine, with a single account:
```powershell
npm install
npm run build
$env:KOMMO_SUBDOMAIN = "yourcompany"; $env:KOMMO_TOKEN = "YOUR_KOMMO_TOKEN"; node dist/index.js --stdio
```
⚠️ stdio has no access control and exposes every tool. Use it only on your own machine.
---
## Usage
### 1. Create an access key (who may use your server)
Until the first access key exists, **any valid Kommo token** can use your server (the logs warn about it). Create one key per agent or workflow:
- **Admin page:** open `https://YOUR-SERVER/admin`, log in with `ADMIN_TOKEN`, write a name (for example "n8n production") and click *Create*.
- **Or the server console** (Easypanel *Console*, Coolify *Terminal*, `docker exec`): `node dist/cli.js keys create "n8n production"`. Locally: `npm run keys -- create "my laptop"`.
The key (`kmcp_…`) is shown **only once**: copy it. You can revoke it at any time from the same page or with `node dist/cli.js keys revoke <id>`. More in [Who can use the server](#who-can-use-the-server).
### 2. Connect your agent
Every client uses the same three values:
| Setting | Value |
|---|---|
| URL | `https://YOUR-SERVER/mcp?subdomain=yourcompany` (the part before `.kommo.com`) |
| Header | `Authorization: Bearer <Kommo long-lived token>` (or `X-Kommo-Token`) |
| Header | `x-api-key: <access key>` |
For example, Claude Code:
```powershell
claude mcp add --transport http kommo "https://YOUR-SERVER/mcp?subdomain=yourcompany" --header "Authorization: Bearer YOUR_KOMMO_TOKEN" --header "x-api-key: YOUR_ACCESS_KEY"
```
In n8n: an *MCP Client Tool* node attached to the AI Agent, transport *HTTP Streamable*, and a *Multiple Headers* credential with both headers. For claude.ai, Claude Desktop, Codex, Cursor and others see [Connecting MCP clients](#connecting-mcp-clients).
### 3. Bind customer-facing agents to their lead
If the agent talks to an end customer (WhatsApp, Instagram…), add the lead to the URL: `…/mcp?subdomain=yourcompany&lead_id=123` (in n8n: `&lead_id={{ $json.LeadID }}`). The session can then only read and change **that** lead, so a message like "give me the previous customer's phone number" cannot work. See [Sessions bound to a lead](#sessions-bound-to-a-lead).
### 4. Write the agent's prompt with business rules only
The tools describe themselves, so the prompt needs no tool names or IDs:
```text
- When the customer wants to book: move them to the "Interested" stage.
- When they pay: set the price to the amount paid.
- If they have doubts about financing: move them to "Urgent attention",
add the note "Personal follow-up" and hand them to another agent.
```
The agent turns it into, for example,
`update_lead { stage: "Urgent attention", note: "Personal follow-up", responsible: "next" }`.
More examples and recommended prompts in [docs/AGENT_GUIDE.md](docs/AGENT_GUIDE.md).
### 5. (Optional) Enable messaging
To let the agent send messages with emojis, buttons and files:
1. Create the MCP template in the account: `$env:KOMMO_SUBDOMAIN="yourcompany"; $env:KOMMO_TOKEN="…"; npm run setup:templates`.
2. In Kommo, create a salesbot whose only step is *Send message → that template*. Note its ID (`data-id` in the bot list).
3. Add `&template_id=…&bot_id=…` to the agent's URL (or the `X-Kommo-Template-Id` / `X-Kommo-Bot-Id` headers). The `send_message` tool appears only when they are set.
Details in [Sending messages](#sending-messages-template--salesbot).
### 6. (Optional) Adjust what the agent may do
By default the agent may edit lead and contact fields, the lead's name and price, move leads between open stages, assign users, use existing tags and launch bots. Closing leads (Won/Lost), creating tags and clearing fields are **off**. Change it per connection with the `policy` setting, and limit the tool groups with `toolsets` (for example `toolsets=read` for a read-only assistant). See [Connection settings](#connection-settings) and [Account policy](#account-policy).
### Using it without AI (REST)
Every tool is also a plain HTTP endpoint, useful from n8n *HTTP Request*, Make or a backend:
```http
POST https://YOUR-SERVER/api/v1/tools/update_lead
X-Kommo-Subdomain: yourcompany
X-Kommo-Token: <Kommo token>
x-api-key: <access key>
Content-Type: application/json
{ "lead_id": 123, "stage": "Interested", "tags_add": ["web"] }
```
`GET /api/v1/tools` lists the tools available to that connection. The full list is in the [Tool reference](#tool-reference).
**Nothing to restart:** a new Kommo account works on its first request.
---
## Configuration
### Environment variables (`.env`)
| Variable | Default | Description |
|---|---|---|
| `PORT` | `3000` | HTTP port |
| `HOST` | `0.0.0.0` | Listen interface |
| `ALLOW_REQUEST_CREDENTIALS` | `true` | Accept the Kommo subdomain + token sent with each request |
| `ADMIN_TOKEN` | — | Password (24+ characters) of the admin page `/admin` and the admin API, where **server access keys** are created and revoked. Unset = both disabled. See [Who can use the server](#who-can-use-the-server) |
| `ACCESS_KEYS_FILE` | `./data/access-keys.json` | Where the server keeps its access keys (hashes only). In Docker: `/app/data/access-keys.json`, keep it on a volume |
| `ACCESS_KEYS` | *(empty)* | *Optional, legacy:* extra access keys as sha256 hashes (comma-separated). They work like server-created keys but cannot be revoked from the server |
| `AUDIT_LOG_FILE` | `./data/audit.log` | Audit log (JSONL). `off` = the server writes nothing to disk |
| `TENANTS_FILE` | `./tenants.json` | *Optional* stored accounts file. Ignored if it does not exist |
| `TENANTS_JSON` | — | *Optional* stored accounts as content (JSON or base64; `npm run tenants:env`). Wins over `TENANTS_FILE` |
| `LOG_LEVEL` | `info` | `debug` · `info` · `warn` · `error` |
| `KOMMO_GLOBAL_RPS` | `7` | Requests/s to Kommo across **all** accounts (they share the server's IP) |
| `KOMMO_ACCOUNT_RPS` | `6` | Requests/s per account (can be lowered per account with `rps`) |
| `KOMMO_BLOCK_COOLDOWN_MS` | `120000` | Global pause when Kommo answers a blocking 403 |
| `KOMMO_MAX_RETRY_WAIT_MS` | `5000` | Longest wait on a 429 before retrying; if Kommo asks for more, fail fast |
| `KOMMO_TIMEOUT_MS` | `15000` | Timeout per Kommo request |
| `SCHEMA_CACHE_TTL_MS` | `300000` | Lifetime of the pipelines, fields, users, bots and tags cache |
| `INBOUND_RPM_PER_KEY` | `120` | Inbound requests per API key per minute (`0` = unlimited) |
| `AUTH_FAILS_PER_MIN` | `20` | Invalid-key attempts per IP per minute before answering 429 |
| `ALLOWED_ORIGINS` | *(empty)* | Allowed browser origins, comma-separated (see [Security](#security)) |
| `MAX_BODY_MB` | `140` | Maximum request body (JSON or multipart). 140 MB fits a 100 MB file in base64. Read only after authentication |
| `TRUST_PROXY` | `0` | Number of proxies in front (Easypanel, Traefik, Nginx = `1`) |
| `PUBLIC_URL` | — | Public HTTPS URL of the server (e.g. `https://mcp.example.com`). **Turns on OAuth** for clients that cannot send a header (claude.ai, Claude Desktop, `codex mcp login`…) |
| `OAUTH_SECRET` | — | Secret (32+ characters, keep it stable) that **seals** OAuth tokens and client registrations, so the server stores nothing. Without it, OAuth connections stop working on restart |
| `OAUTH_ACCESS_TTL_MIN` | `60` | Lifetime of an OAuth access token (renewed automatically with the refresh token) |
| `OAUTH_REFRESH_TTL_DAYS` | `90` | Lifetime of an OAuth refresh token; after that the user connects again |
| `KOMMO_SUBDOMAIN` / `KOMMO_TOKEN` | — | stdio mode and scripts only: the account to use (plus optional `KOMMO_TEMPLATE_ID`, `KOMMO_BOT_ID`, `KOMMO_POLICY`, `KOMMO_TIMEZONE`, `KOMMO_TOOLSETS`) |
| `STDIO_TENANT_ID` | — | stdio mode with stored accounts: account id, or `*` for all |
| `KOMMO_TOKEN_*` | — | Stored accounts only: tokens referenced from `tenants.json` as `${KOMMO_TOKEN_...}` |
### Connection settings
Sent by the client with each request, as a URL query parameter or a header. They are set by whoever configures the agent (the n8n credential, the MCP config of Claude or Codex…), **never by the model**.
| Query | Header | Default | Description |
|---|---|---|---|
| `subdomain` | `X-Kommo-Subdomain` | **required** | `yourcompany`, `yourcompany.kommo.com` or the full URL |
| — | `X-Kommo-Token` or `Authorization: Bearer` | **required** | The account's long-lived token. Never in the URL |
| `lead_id` | `X-Kommo-Lead-Id` | — | Binds the session to one lead (conversation agents) |
| `toolsets` | `X-Kommo-Toolsets` | `read,write,messaging,bots` | Tool groups the agent sees |
| `template_id` / `bot_id` | `X-Kommo-Template-Id` / `X-Kommo-Bot-Id` | — | MCP template and its salesbot (comma-separated for several pairs). Enables `send_message` |
| `messaging` | `X-Kommo-Messaging` | — | Full messaging options as JSON or base64 (see the table below) |
| `policy` | `X-Kommo-Policy` | see below | Policy overrides as JSON or base64, e.g. `{"allowCloseLeads":true}` |
| `timezone` | `X-Kommo-Timezone` | the account's | IANA name, e.g. `America/Bogota` |
| `agent` | `X-Kommo-Agent` | `agent` | Label for the audit log |
Default policy with request credentials: all lead and contact fields, `name` and `price`, every pipeline, every bot and every user are allowed; closing leads, creating tags and clearing fields are not. Any field of [Account policy](#account-policy) can be overridden.
### Stored accounts (optional)
If you prefer the server to hold the tokens (for example, to hand clients a server key instead of their Kommo token), accounts can still be defined in `tenants.json` (or `TENANTS_JSON`). Clients then authenticate with a server API key (`kmcp_…`) instead of sending Kommo credentials. Both modes work at the same time.
A full example is in [tenants.example.json](tenants.example.json). It holds key **hashes** and `${VAR}` references to tokens in the environment. Still, never commit it to a public repository.
```jsonc
{
"tenants": [
{
"id": "demo_client", // identifier (letters, digits, - and _)
"name": "Demo Client Inc.",
"subdomain": "democlient", // democlient.kommo.com
"token": "${KOMMO_TOKEN_DEMO_CLIENT}",
"timezone": "America/Mexico_City", // for dates and reports
"rps": 5, // optional, max 7
"salesbotApi": "v4", // "v4" or "v2" (legacy)
"apiKeys": [ { "label": "n8n-agent", "sha256": "…", "toolsets": ["read","write","messaging","bots"] } ],
"messaging": { // optional; without it there is no send_message
"slots": [ { "templateId": 11111, "botId": 22222, "kind": "any" } ],
"maxAttachmentMB": 100,
"confirm": { "mode": "auto", "minHoldMs": 2500, "timeoutMs": 30000, "pollIntervalMs": 2500 }
},
"policy": { /* see below */ }
}
],
"partners": [
{ "label": "partner-claude-code", "sha256": "…", "toolsets": ["read"], "tenants": ["*"] }
]
}
```
Stored accounts get their keys with `npm run keygen -- <label>` (account key) or `npm run keygen -- <label> partner` (partner key, several accounts). Restart the server after changing `tenants.json`.
### Messaging options
The same options apply to request credentials (`messaging` setting, JSON) and to stored accounts (`messaging` in `tenants.json`):
| Field | Default | Description |
|---|---|---|
| `slots[].templateId` / `botId` | — | The MCP template and the salesbot that sends it |
| `slots[].kind` | `any` | `any`: one template for everything (recommended). `text` / `buttons`: separate templates |
| `maxLength` | `4096` | Maximum characters per message (an emoji counts as 1) |
| `maxButtons` | `3` | Maximum buttons per message |
| `maxButtonTextLength` | `20` | Maximum characters per button |
| `buttonlessOrigins` | `["com.amocrm.amocrmwa"]` | Channels that show no buttons (WhatsApp Lite via QR) |
| `buttonsFallback` | `text` | On those channels: `text` = buttons go as a numbered list in the message · `error` = not sent |
| `maxAttachmentMB` | `100` | Maximum size of one attachment (the Kommo Drive accepts up to 300 MB) |
| `allowAttachmentUrls` | `true` | Accept attachments by https URL (private IPs are always blocked). `false` = base64/binary only |
| `webPageUrls` | `link` | When an attachment URL is a web page: `link` = nothing is downloaded or uploaded, the URL goes in the text · `error` = reject |
| `channelMediaLimits` | WhatsApp: picture 5 MB, video 16 MB, file 100 MB | Media limits per channel (matched against the conversation `origin`) |
| `oversizeMedia` | `link` | A file above the channel limit: `link` = send it and flag `channel_link: true` (the customer gets a `kommo.cc` link) · `error` = reject it |
| `verifyTemplate` | `true` | Read the template back before launching the bot |
| `confirm.mode` | `auto` | `auto`: reads the lead's conversation and looks for the outgoing message with the same text (returns `delivery_status`); if the token cannot read messages, uses events. `messages`: conversation only. `events`: `outgoing_chat_message` event. `delay`: just waits `minHoldMs` |
| `confirm.minHoldMs` | `2500` | Minimum time the template stays locked after launching the bot |
| `confirm.timeoutMs` | `20000` | Longest wait for confirmation; after that the answer is `unconfirmed` |
| `confirm.pollIntervalMs` | `2000` | How often it polls |
### Account policy
The policy is what the AI **can** do, whatever the prompt or the end user asks. Names are compared ignoring case and accents; IDs and field codes are accepted too.
| Field | Default | Description |
|---|---|---|
| `writableLeadFields` | `[]` | Lead fields that may be written. `["*"]` = all (not recommended) |
| `writableContactFields` | `[]` | Contact fields (`PHONE`, `EMAIL`, `POSITION`, names…) |
| `writableLeadProps` | `[]` | Writable native properties: `"price"`, `"name"` |
| `allowedPipelines` | `["*"]` | Pipelines a lead may be moved to |
| `allowCloseLeads` | `false` | Allow moving to Won (142) / Lost (143) |
| `allowCreateTags` | `false` | Allow creating tags that do not exist |
| `allowClearFields` | `false` | Allow clearing fields |
| `allowedBots` | `[]` | Salesbots that may be launched or stopped |
| `assignableUsers` | `["*"]` | Assignable agents. Also the rotation for `responsible: "next"` |
---
## Authentication and access
### How a client authenticates
| Method | For | How |
|---|---|---|
| **Kommo credentials** (default) | n8n, Claude Code, Codex, Cursor, agent frameworks, REST | `?subdomain=yourcompany` (or `X-Kommo-Subdomain`) + the long-lived token as `Authorization: Bearer …` or `X-Kommo-Token` |
| **OAuth 2.1** (needs `PUBLIC_URL`) | Clients that only take a URL: claude.ai and Claude Desktop connectors, `codex mcp login`, MCP Inspector… | The client opens a page of this server where you enter the subdomain and token once; the client receives its own tokens |
| **Server API key** (stored accounts only) | Clients of accounts kept in `tenants.json` | `Authorization: Bearer kmcp_…` or `x-api-key: kmcp_…` |
The token always travels in a header, never in the URL (URLs end up in logs).
### What the server keeps
- **On disk:** nothing about accounts or tokens. Only the access key hashes (`ACCESS_KEYS_FILE`) and the audit log, if enabled (`AUDIT_LOG_FILE=off` disables it).
- **In memory:** while an account is in use, its schema cache, locks, message queue and the token itself (needed to call Kommo). Idle accounts are dropped after 30 minutes. A restart forgets everything.
- **OAuth:** client registrations and tokens are **sealed** with AES-256-GCM using `OAUTH_SECRET`: they carry their own data, so there is no OAuth database. Changing `OAUTH_SECRET` disconnects every OAuth client.
### Who can use the server
By default any request with a **valid** Kommo token is accepted. The first request with a token checks it against Kommo, so a made-up token gets nothing. But the server would still work for anyone who has a token of *some* Kommo account, sharing your server's rate limit and IP.
To restrict it to your agents, create **server access keys on the server**. As soon as one exists, every request with Kommo credentials must also send a key as `x-api-key` (on the OAuth page it is asked for as "Server access key"). Give each agent or workflow its own key, so you can cut one off without touching the others.
- **Admin page:** set `ADMIN_TOKEN`, open `https://YOUR-SERVER/admin`, log in with it, and create, view or revoke keys.
- **Server console** (Easypanel *Console*, Coolify *Terminal*, `docker exec`): `node dist/cli.js keys create "n8n production"`, `keys list`, `keys revoke <id>`. Locally: `npm run keys -- create "my laptop"`.
- **Admin API:** `GET` / `POST {"label": "…"}` `/admin/api/keys` and `DELETE /admin/api/keys/<id>`, with `Authorization: Bearer <ADMIN_TOKEN>`.
The full key is shown once, at creation; the server stores only its SHA-256 (in `ACCESS_KEYS_FILE`). Revoking a key applies within seconds, without a restart, and also cuts off the OAuth connections made with it. Revoking the last key opens the server again. See [Deployment → Access keys](docs/DEPLOYMENT.md#access-keys).
`ALLOW_REQUEST_CREDENTIALS=false` turns request credentials off entirely (stored accounts only).
### OAuth details
- The server is its own authorization server: discovery (`/.well-known/oauth-protected-resource/mcp`, `/.well-known/oauth-authorization-server`), dynamic client registration, authorization code with **PKCE (S256)** and refresh tokens.
- The consent page checks the Kommo token against Kommo before issuing anything. With stored accounts it also accepts a server API key.
- Access tokens last `OAUTH_ACCESS_TTL_MIN`, refresh tokens `OAUTH_REFRESH_TTL_DAYS`. Being stateless, a refresh token can be used again until it expires, and tokens cannot be revoked one by one. Revoke the Kommo token in Kommo, revoke the access key at `/admin`, or change `OAUTH_SECRET`.
- Failed attempts on the consent page count towards `AUTH_FAILS_PER_MIN`.
- `401` answers carry `WWW-Authenticate: Bearer resource_metadata="…"`, so MCP clients discover the flow by themselves.
### Toolsets
Which groups of tools a connection sees (`toolsets` setting, or the key's `toolsets` for stored accounts):
| Toolset | Tools |
|---|---|
| `read` | `get_lead_context`, `get_account_schema`, `get_incoming_message_context`, `search_leads`, `find_contact`, `sales_report`, `pipeline_summary` |
| `write` | `update_lead`, `move_lead`, `update_lead_fields`, `update_contact_fields`, `update_lead_tags`, `assign_responsible`, `add_lead_note`, `create_task` |
| `messaging` | `send_message` (only when a template and bot are configured) |
| `bots` | `run_salesbot`, `stop_salesbot` |
### Sessions bound to a lead
Add `?lead_id=123` (or the `X-Kommo-Lead-Id` header) and the session is **bound to that lead**: `lead_id` is injected, any other lead is rejected, and account-scope tools are hidden (`get_incoming_message_context`, `search_leads`, `find_contact`, `sales_report`, `pipeline_summary`).
**Always** use a bound session for agents that talk to end customers. That way a message like "give me the previous customer's phone number" cannot work.
With stored partner keys, `?account=id` picks one account; without it, the session is multi-account (`list_accounts` appears and every tool asks for `account`).
---
## Connecting MCP clients
Any MCP client works the same way:
| Setting | Value |
|---|---|
| URL | `https://YOUR-SERVER/mcp?subdomain=yourcompany` (add `&lead_id=123` to bind to a lead, `&template_id=…&bot_id=…` for messaging) |
| Transport | Streamable HTTP |
| Auth header | `Authorization: Bearer <Kommo token>` (or `X-Kommo-Token`). Plus `x-api-key: <access key>` once the server has access keys |
A detailed guide with prompt examples is in [docs/AGENT_GUIDE.md](docs/AGENT_GUIDE.md). Examples per client:
**n8n**
- *MCP Client Tool* node (conversation agent): Endpoint `https://YOUR-SERVER/mcp?subdomain=yourcompany&lead_id={{ $json.LeadID }}`, transport HTTP Streamable, **Bearer Auth** credential with the Kommo token. If the server has access keys, use a *Multiple Headers* credential instead: `Authorization: Bearer <token>` and `x-api-key: <access key>`.
- *HTTP Request* node (REST): headers `X-Kommo-Subdomain`, `X-Kommo-Token` (and `x-api-key` if required).
- One n8n credential per Kommo account; the workflow stays the same for every client.
**Claude Code**
```powershell
claude mcp add --transport http kommo "https://YOUR-SERVER/mcp?subdomain=yourcompany" --header "Authorization: Bearer YOUR_KOMMO_TOKEN"
```
Add `--header "x-api-key: YOUR_ACCESS_KEY"` if the server requires it. Or add it without headers and run `/mcp` → *Authenticate* inside Claude Code (OAuth).
**Codex** (`~/.codex/config.toml`)
```toml
[mcp_servers.kommo]
url = "https://YOUR-SERVER/mcp?subdomain=yourcompany"
bearer_token_env_var = "KOMMO_TOKEN" # the Kommo token, from an environment variable
# env_http_headers = { "x-api-key" = "KOMMO_MCP_ACCESS_KEY" } # if the server requires an access key
```
Or with OAuth: leave out `bearer_token_env_var` and run `codex mcp login kommo`.
**claude.ai / Claude Desktop** (OAuth, needs `PUBLIC_URL` and `OAUTH_SECRET`)
1. *Settings → Connectors → Add custom connector*, URL `https://YOUR-SERVER/mcp`.
2. Click *Connect*: a page of your server opens. Enter the Kommo subdomain and token (and template/bot IDs for messaging) and click *Connect*.
3. Claude keeps and renews its own sealed token.
**Antigravity, Cursor, VS Code and others:** a remote HTTP MCP server with the URL and the headers. If the client only accepts a URL, it uses OAuth.
**Agent frameworks** (Claude Agent SDK, OpenAI Agents SDK, LangChain…): a remote Streamable HTTP MCP server with the URL and the headers.
**Without AI, over REST** (n8n *HTTP Request*, Make, a backend, `curl`…):
```http
POST https://YOUR-SERVER/api/v1/tools/send_message
X-Kommo-Subdomain: yourcompany
X-Kommo-Token: <Kommo token>
X-Kommo-Template-Id: 11111
X-Kommo-Bot-Id: 22222
Content-Type: application/json
{ "lead_id": 123, "messages": [ { "text": "Hi 👋" }, { "text": "Shall we book?", "buttons": [ { "type": "inline", "text": "Yes" } ] } ] }
```
**Local (stdio), without deploying:**
```powershell
npm run build
$env:KOMMO_SUBDOMAIN = "yourcompany"; $env:KOMMO_TOKEN = "YOUR_KOMMO_TOKEN"; node dist/index.js --stdio
```
⚠️ stdio has no access control: the process gets **every toolset**. Use it only on your own machine.
---
## Tool reference
Scope: **lead** = acts on one lead (allowed in a bound session) · **account** = the whole account (hidden in a bound session) · **meta** = the account schema.
Write tools also accept:
- `dry_run: true`: validates and returns what would change, without writing.
- `expected_pipeline` / `expected_stage` (guards): if the lead is not there, nothing happens (`GUARD_FAILED`).
### Read (`read`)
| Tool | Scope | Parameters | Returns |
|---|---|---|---|
| `get_lead_context` | lead | `lead_id` | The lead with `state` (`open`, `incoming`, `won`, `lost`), pipeline/stage, owner, tags, fields; the main contact with `phones` / `emails`; `warnings` if something is missing (no contact, deleted contact, archived pipeline…) |
| `get_incoming_message_context` | account | `payload` (Kommo webhook), `verify_talk`, `skip_closed` | Normalized message + lead context + `should_process` / `skip_reason`. See [Incoming message webhook](#incoming-message-webhook) |
| `get_account_schema` | meta | `refresh?` | Pipelines/stages, fields with options, tags, users, bots and the account policy |
| `search_leads` | account | `query?`, `pipeline?`, `stage?`, `limit` (≤50) | Matching leads, **including "Incoming leads"** (`state: "incoming"`): Kommo does not return them from `/api/v4/leads`, so they are queried separately and matched by contact name |
| `find_contact` | account | `phone?`, `email?`, `query?`, `limit` (≤25) | Contacts with a **verified** phone/email match |
| `sales_report` | account | `period` (`today`, `yesterday`, `this_week`, `last_week`, `this_month`, `last_month`, `last_7_days`, `last_30_days`, `custom`), `from?`, `to?`, `pipeline?`, `top` | Created, won, revenue, average ticket, per agent and pipeline, lost by reason, close rate, top sales |
| `pipeline_summary` | account | `pipeline?` | Open leads and value per stage |
### Write (`write`)
| Tool | Main parameters | Notes |
|---|---|---|
| **`update_lead`** | `stage?`, `pipeline?`, `price?`, `name?`, `fields?`, `tags_add?`, `tags_remove?`, `responsible?` (name/email/ID or `"next"`), `note?`, `overwrite` | **Main tool.** Everything in one PATCH, **all or nothing** |
| `move_lead` | `stage`, `pipeline?` | If it is already in that stage, nothing happens |
| `update_lead_fields` | `fields: { "Field": value }`, `overwrite` | Allowlisted fields only |
| `update_contact_fields` | `fields`, `overwrite`, `multitext_mode` (`add` / `replace`) | Phones/emails are **appended** without deleting existing ones |
| `update_lead_tags` | `add`, `remove` | Keeps the other tags |
| `assign_responsible` | `user` | Active `assignableUsers` only |
| `add_lead_note` | `text` | Internal note (never reaches the customer) |
| `create_task` | `text`, `due` (`YYYY-MM-DD[THH:mm]`), `responsible?` | A task for the team |
### Bots and messaging
| Tool | Toolset | Parameters | Notes |
|---|---|---|---|
| `run_salesbot` | bots | `bot` | `allowedBots` only |
| `stop_salesbot` | bots | `bot` | `allowedBots` only |
| `send_message` | messaging | `messages: [{ text, buttons?, attachment? }]` (1-5) | In order, via template + salesbot, queued. Button: `{ type: "inline" \| "url", text, url? }`. Attachment: a URL, base64 or binary (see [Attachments](#attachments-url-base64-or-binary)) |
| `list_accounts` | — | — | Multi-account partner keys only |
---
## Incoming message webhook
`get_incoming_message_context` replaces the first chain of a *Message Catcher*-style flow:
> Get Lead → Lead Exist → Get Contact → Contact Exist → Get Pipeline → Pipeline Exist → Search Stage in Pipeline → Stage Exist → Search Contact Data → is Attachment / is Text
It is **one** call from your automation and **3 requests** to Kommo: lead with contacts, main contact and conversation. The pipeline and stage come from the cache.
```http
POST https://YOUR-SERVER/api/v1/tools/get_incoming_message_context
x-api-key: <key>
Content-Type: application/json
{ "payload": {{ $json.body }} }
```
With a **partner key** no `account` is needed: the account is taken from the webhook's own `account[subdomain]`. One flow serves all your clients without looking tokens up in another database.
**Validation order.** Checks that cost no Kommo requests go first:
| Step | On failure → `skip_reason` |
|---|---|
| The webhook belongs to the key's account | `POLICY` error (not processed) |
| Incoming message (`type = incoming`) | `not_incoming` |
| External author (the customer, not an agent or a bot) | `author_not_external` |
| Linked to a lead | `not_a_lead` |
| Non-empty text message | `empty_message` |
| The lead exists and is not deleted | `lead_not_found` |
| The conversation (`talk_id`) belongs to that lead | `talk_mismatch` |
| The lead is not Won/Lost (`skip_closed`) | `lead_closed` |
What does **not** stop processing is reported in `context.warnings`: lead without a contact, deleted contact, archived pipeline, unknown stage.
**Message kind** (`message.kind`): `text`, `voice`, `picture`, `video`, `file`, `sticker`, `location`, `contact`, `unsupported_media` or `other`. Any attachment comes in `message.attachment.link`, ready for your flow to transcribe the audio or describe the image.
`unsupported_media` is Kommo's "You received a multimedia message" placeholder that arrives without a link.
**What stays in your automation:**
- The message buffer (Redis) that groups several consecutive messages before answering.
- Transcription and image description.
- Choosing the agent by pipeline and stage: use `context.lead.pipeline.name` and `context.lead.stage.name`.
---
## Responses and errors
**MCP:** `structuredContent = { ok: true, result }`. On failure, `isError: true` with the text `ERROR [CODE]: message`.
**REST:** `{ "ok": true, "result": … }` or `{ "ok": false, "error": { "code", "message", "details?" } }`.
Error messages are designed so the AI can correct itself. For example:
`NOT_FOUND: There is no stage of pipeline "Sales" "Qualifyed". Did you mean: "Qualified"? Available: …`
| Code | HTTP (REST) | Meaning |
|---|---|---|
| `VALIDATION` | 400 | Invalid value format (date, number, phone, option, attachment…) |
| `AMBIGUOUS` | 400 | Several items match; use the ID |
| `NOT_FOUND` | 404 | Stage, field, user, lead… does not exist (with suggestions) |
| `POLICY` | 403 | The account policy does not allow it, or the session is bound to another lead |
| `GUARD_FAILED` | 409 | The lead is not in the expected pipeline or stage |
| `CONFLICT` | 409 | The field already holds another value and `overwrite` was not given |
| `RATE_LIMITED` | 429 | Kommo asked to wait longer than allowed |
| `BLOCKED` | 429 | Kommo answered a blocking 403; global pause active |
| `UNAUTHORIZED` | 502 | The account's Kommo token is invalid or expired |
| `KOMMO_ERROR` / `INTERNAL` | 500 | Kommo or unexpected error |
Write responses: `status` is `changed`, `unchanged` (already like that, nothing written) or `dry_run`, with the list of `changes`.
---
## Sending messages (template + salesbot)
**Chat templates** are used instead of the *lead field + salesbot* method, because templates support emojis, long texts, line breaks, buttons and files.
Each **slot** is a *template + salesbot* pair. The salesbot only sends that template. **One template** is enough (`kind: "any"`): the MCP adds buttons when the message has them and removes them (`buttons: [null]`) when it is plain text.
Cycle of each message, with the slot locked from start to end:
1. **PATCH** the template with the text, buttons and attachment.
2. **GET** the template: if it was not saved exactly, **the bot is not launched**.
3. **Launch the salesbot** on the lead.
4. **Wait for confirmation** up to `timeoutMs`. In `auto` mode the lead's conversation is read until the outgoing message with **the same text** shows up, with its `delivery_status` and `message_id`. If the token lacks the `list_external_messages` scope, the `outgoing_chat_message` event is used.
5. **Release the slot**; the next job in the queue runs.
Guarantees:
- **No cross-talk between leads:** the template is never edited while a bot has yet to read it.
- **Strict order** for messages to the same lead.
- **Everything is validated first**, before the first message goes out (length, buttons, URLs, attachments).
- **Buttons per channel:** WhatsApp Lite (via QR) shows no buttons. If the conversation belongs to a `buttonlessOrigins` channel, buttons become a numbered list in the text (`1. Yes ✅`, `2. No ❌`) and the result carries `buttons_as_text: true`. The customer always sees the options.
- **No channel, no send:** if the lead has no chat conversation, the answer is `VALIDATION` without touching the template or launching the bot.
- With **several slots**, several leads are served in parallel.
Result per message: `sent` (confirmed) or `unconfirmed` (Kommo accepted the bot but the send was not seen). With `unconfirmed` the agent **must not resend**, because it could duplicate.
Facts verified against the real Kommo API:
- **Token scopes:** with `list_external_messages` the MCP confirms each send by reading the conversation, the most reliable method. Without it, `/api/v4/talks/{id}/messages` answers `403 Invalid scope` and events are used.
- Only templates **created with the same token** can be edited through the API. Use `npm run setup:templates`. Templates created by hand return "Template not found".
- `buttons: []` is an error, and omitting `buttons` keeps the old ones. To remove them, send `[null]`.
- Omitting `attachment` **keeps the previous file**; to remove it, send `attachment: null`. The MCP always sends the field.
- The bot launch answers 202 **even if nothing is sent afterwards**: no channel connected, WhatsApp 24 h window closed, bot error…
---
## Attachments: URL, base64 or binary
Any message can carry a file (image, video, audio, PDF, document…), with the text as its caption. This replaces a separate *Upload Media* step with one call. **The server works out what it received** and takes the right path:
| You send | Detected as | What happens |
|---|---|---|
| `"attachment": "https://site.com/photo.jpg"` or `{ "url": … }` | URL → **file** | Downloaded safely, uploaded to the Kommo Drive and sent with its real format |
| `"attachment": "https://site.com/"` (a web page) | URL → **web page** | **Nothing is downloaded or uploaded**: the link goes in the message text (`attachment.link`) |
| `{ "base64": "…", "file_name": "catalog.pdf" }`, a `data:` URI or a bare base64 string | base64 | Decoded, validated and uploaded |
| A multipart/form-data file (REST) referenced with `{ "file": "<field>" }` | binary | Uploaded as-is, keeping its original name |
| `{ "data": …, "mimeType": …, "fileName": … }` (e.g. an n8n binary object) | auto | `data` is classified (URL, base64 or Buffer JSON) |
Misplaced values are routed correctly (a URL inside `base64`, a `data:` URI inside `url`). A string that is none of these is rejected with a clear message, and so is an on-disk reference such as n8n's `filesystem-v2:…`, with instructions on how to send the binary.
### Which source to use, by client
| Client | Recommended source |
|---|---|
| AI agent over MCP (Claude, Codex, Cursor, n8n agent…) | **URL** of the file. MCP messages are JSON, so raw binary cannot travel; base64 works too but costs the model many tokens |
| Automation over REST (n8n, Make, a backend, `curl`) | **Binary** (multipart), **base64** or **URL**, whichever the flow already has |
### Sending binary files (multipart, REST)
`POST /api/v1/tools/send_message` accepts `multipart/form-data`. No base64 conversion and no size overhead.
Simple form, with one file attached to one message:
```powershell
curl.exe -X POST https://YOUR-SERVER/api/v1/tools/send_message -H "x-api-key: YOUR_KEY" -F lead_id=123 -F "text=Here is the raffle photo 🎉" -F "photo=@photo.png"
```
In n8n: *HTTP Request* → **Body → Form-Data**, with `lead_id` and `text` as fields and the file as an **n8n Binary File** parameter. In Make or Zapier, use their multipart/file options the same way.
Several messages: send `messages` as JSON and reference each file by its field name:
```text
lead_id = 123
messages = [{"text":"The video 🎬","attachment":{"file":"video"}},{"text":"And the PDF 📄","attachment":{"file":"doc"}}]
video = (binary)
doc = (binary)
```
Only `send_message` accepts multipart. Uploaded files that no message references are rejected, so nothing is sent by mistake.
### How a URL is classified
1. Share links are turned into direct downloads (Google Drive `/file/d/…`, Dropbox `?dl=0`).
2. The URL is requested and **only the headers are read** first:
- `Content-Disposition: attachment` → file.
- `Content-Type: text/html` → **web page**: the body is never downloaded.
- An unclear type (`octet-stream`, `text/plain`, none): the first chunk is checked; if it is HTML, it is a web page and the rest is not downloaded.
3. Otherwise it is downloaded, with size and time limits.
With `webPageUrls: "error"`, a web page is rejected instead of being sent as a link.
### Upload and delivery
1. **Validate everything first.** Every attachment is classified, fetched and checked before the first message goes out: size, real type detected from the bytes, and name.
2. **Real format.** The type comes from the bytes, not from the name: a PNG named `photo.jpg` is sent as `photo.png`, and a `.mp4` is sent as a video.
3. **Upload to the Kommo Drive.** `GET /api/v4/account?with=drive_url` → `POST {drive}/v1.0/sessions` → parts of `max_part_size` following `next_url` → `uuid`.
4. **Attach to the template.** `attachment: { id: uuid, name, type }`, with `type` `picture`, `video` or `file`.
5. **Clear it afterwards.** Messages without an attachment send `attachment: null`; otherwise they would go out with the previous file.
6. **Reuse.** The same file sent to another lead reuses the uploaded `uuid` (12 h cache).
Result per message: `attachment: { source: "url" | "base64" | "binary", name, type, mime, size, reused }`, or `attachment: { link, reason: "web_page" }`.
### Channel limits (WhatsApp)
WhatsApp delivers images up to 5 MB, video and audio up to 16 MB and documents up to 100 MB. **Above that, Kommo sends a `kommo.cc` link instead of the media.**
Verified against the real API: the Kommo Drive classifies files by their **content** (an MP4 is a video even when named `.bin`), so an oversize video cannot be forced to go as a document. That is why the MCP:
- marks the result with `channel_link: true` (default `oversizeMedia: "link"`), so the agent knows the customer will get a link, or
- rejects it before sending anything (`oversizeMedia: "error"`), so a compressed file can be sent instead.
The limits are set per channel in `channelMediaLimits` (matched against the conversation `origin`: `amocrmwa`, `waba`, `whatsapp`…).
### URL security (SSRF)
- `https` only, without user or password in the URL.
- Private, local and metadata IPs (`169.254.169.254`) are blocked, also after every redirect (max 5).
- Size limit (`maxAttachmentMB`, streamed) and a 30 s timeout.
- The Kommo token is **never** sent to the source URL or to the upload URLs (they are already signed).
---
## Strict validation
- **Exact names** (stages, fields, options, users, bots, tags), ignoring case, accents and surrounding spaces. "The closest one" is never picked: the error suggests and lists the valid options.
- **Allowlist** of fields. Complex types (legal entity, files…) and tracking types (UTM, Meta Ads) are blocked.
- **No overwrite** of price or fields that hold a value unless `overwrite: true`. If the value is already the same, nothing is written (`unchanged`).
- **All or nothing** in `update_lead`: everything is validated, then a single PATCH is sent.
- **Types:**
- Numbers without commas or text.
- Integer price.
- Checkbox only with clear values (`yes`/`no`, `true`/`false`).
- Select and multiselect only with existing options.
- Valid URLs.
- **Dates:**
- Only `YYYY-MM-DD` or `YYYY-MM-DDTHH:mm`, in the account's time zone.
- Ambiguous formats (`05/06/2026`) and impossible dates (`2026-02-30`) are rejected.
- **Phones and emails:** normalized, validated and appended without deleting existing ones or duplicating.
- **Closing leads** (Won/Lost): only with `allowCloseLeads`.
- **Attachments:** source, size, real type and channel limits, all checked before the first message.
- **Concurrency:** per-lead lock and a fresh read of the lead before every write.
---
## Security
**Access**
- **No Kommo credentials at rest.** The token arrives with each request (in a header, never in the URL) and only lives in memory while the account is in use. Logs hide it (`[REDACTED]`).
- Each new token is checked against Kommo before anything runs; a rejected token answers 401.
- Accounts are isolated by token: a connection only reuses the in-memory cache of the **same** subdomain and token. Different tokens of one account still share its lead locks, template locks and rate limit, so they never collide.
- Server access keys: 256-bit keys created on the server (admin page behind `ADMIN_TOKEN`, or the console), only their SHA-256 is stored. The admin page uses a sealed, HttpOnly, SameSite=Strict cookie and only accepts form posts from its own host.
- OAuth (optional): PKCE S256 required, single-use codes valid for 5 minutes, tokens sealed with AES-256-GCM (`OAUTH_SECRET`), no database. The consent page cannot be framed (CSP `frame-ancestors 'none'`).
- Least privilege per connection: `toolsets` and `policy`.
- A lead-bound session protects against instructions injected in end customers' messages. Connection settings come from the client's configuration, never from the model.
**HTTP server**
- The body is read **after** authentication (max `MAX_BODY_MB`, JSON or multipart).
- Inbound limit per key (`INBOUND_RPM_PER_KEY`) and per IP for invalid keys (`AUTH_FAILS_PER_MIN`). Both answer 429 with `Retry-After`.
- **`Origin` validation** (DNS rebinding / CSRF, as the MCP spec requires): browser requests whose origin is not in `ALLOWED_ORIGINS` are rejected. Server-side clients (Claude Code, Codex, n8n, backends) send no `Origin`.
- Errors are always JSON, without stack traces or HTML. Headers: `X-Content-Type-Options: nosniff`, `Cache-Control: no-store`, `X-Frame-Options: DENY` and `Referrer-Policy: no-referrer`.
- `/health` is public and exposes no client data. `/api/v1/status` only shows the caller's own account(s).
- Attachment URLs are protected against SSRF (see [URL security](#url-security-ssrf)).
**What the MCP deliberately does not do:**
- It does not delete leads or contacts.
- It does not create or delete webhooks.
- It does not export data in bulk.
- It does not send emails.
**Operating recommendations**
- Expose the server **over HTTPS only**.
- Create at least one access key on any server reachable from the internet, and keep `/app/data` on a volume.
- Keep Kommo tokens in the clients' credential stores (n8n credentials, environment variables), not in prompts or workflow nodes.
- Revoke and regenerate a Kommo token if it was ever shared over chat or email.
- Give `toolsets=read` to anyone who only reads (dashboards, reports).
- Never commit `.env`, `tenants.json` or `data/` (they are already in `.gitignore`).
---
## Rate limits towards Kommo
Kommo allows about 7 requests/s per integration. After repeated 429s it blocks the IP with a 403.
- **Two limiters:** global (all accounts, since they share the IP) and per account.
- **429:** honors `retry_after` in the body or the `Retry-After` header. If the wait exceeds `KOMMO_MAX_RETRY_WAIT_MS`, it fails fast with `RATE_LIMITED`.
- **Blocking 403:** a **global pause** of `KOMMO_BLOCK_COOLDOWN_MS` with nothing else sent to Kommo, to avoid extending the block.
- **Permission or private-endpoint 403** (a JSON body from Kommo, e.g. `Invalid scope`) → `POLICY`, without pausing the other accounts. Only a 403 without a JSON body (IP block) triggers the global pause.
- **Retries** for GET/PATCH on 5xx or network errors. POSTs are not retried, to avoid duplicates.
- **Schema cache** so pipelines and fields are not queried on every call. If a stage, field, user or bot is missing (e.g. just created), the cache is **reloaded once** before failing, at most every 15 s.
- Drive upload parts go through the same limiter.
Live status: `GET /api/v1/status`.
---
## Audit log and logs
**Audit log** (`AUDIT_LOG_FILE`, JSONL): one line per write or send:
```json
{"ts":"2026-12-02T18:00:00.000Z","tenant":"demo_client","actor":"n8n-agent","action":"update_lead","entity":"lead","entityId":123,
"before":{"status":"New"},"after":{"status":"Interested"},"result":"ok"}
```
`result` is `ok`, `noop`, `error` or `unconfirmed`. `actor` is the `agent` setting plus the subdomain (or the key's label for stored accounts). It never contains tokens. Set `AUDIT_LOG_FILE=off` to write nothing to disk. Sends record the template attachment (`uuid`, name, type), never the file content.
**Server logs:** JSON on **stderr** (stdout stays free for the protocol in stdio mode). Sensitive keys are hidden.
---
## HTTP endpoints
| Route | Auth | Use |
|---|---|---|
| `POST /mcp` | Kommo credentials, OAuth token or API key | MCP Streamable HTTP. Query: the [connection settings](#connection-settings) |
| `GET` / `DELETE /mcp` | — | 405 (stateless server) |
| `POST /api/v1/tools/:name` | same | The same tool over REST (JSON). `send_message` also accepts `multipart/form-data`. Multi-account partner key: include `account` in the body |
| `GET /api/v1/tools` | same | Tools enabled for the connection |
| `GET /api/v1/status` | same | Queues, limiters and send counters for the caller's account(s) |
| `GET /health` | public | `{ ok, name, version }` |
| `GET /.well-known/oauth-protected-resource/mcp`, `GET /.well-known/oauth-authorization-server` | public | OAuth discovery (only with `PUBLIC_URL`) |
| `POST /register`, `GET /authorize`, `POST /oauth/approve`, `POST /token` | public | OAuth registration, consent page and tokens (only with `PUBLIC_URL`) |
| `GET /admin` (+ `POST /admin/login`, `/admin/keys`, `/admin/keys/:id/revoke`, `/admin/logout`) | `ADMIN_TOKEN` (login, session cookie) | Admin page: create, view and revoke access keys (only with `ADMIN_TOKEN`) |
| `GET` / `POST /admin/api/keys`, `DELETE /admin/api/keys/:id` | `Bearer <ADMIN_TOKEN>` | Admin API for access keys (JSON) |
Authentication: see [How a client authenticates](#how-a-client-authenticates).
---
## npm scripts
| Script | What it does |
|---|---|
| `npm run dev` | HTTP server with reload (tsx watch) |
| `npm run build` | Compiles to `dist/` |
| `npm start` | Runs `dist/` (reads `.env`) |
| `npm run stdio` | stdio mode from source |
| `npm test` | Tests (Vitest, with an in-memory simulated Kommo) |
| `npm run typecheck` | Type checking |
| `npm run keys -- create <label>` · `list` · `revoke <id>` | Manages the server access keys (in production: `node dist/cli.js keys …`) |
| `npm run keygen -- <label> [partner]` | Generates a stored-account key and its hash (for `tenants.json`) |
| `npm run tenants:env [-- file]` | Stored accounts: validates `tenants.json` and prints it as a `TENANTS_JSON=<base64>` line |
| `npm run docker:build` | Builds the Docker image (`kommo-mcp`) |
| `npm run smoke` | **Read-only** test against a real account (`KOMMO_SUBDOMAIN` + `KOMMO_TOKEN`, or a stored account id as argument) |
| `npm run setup:templates -- [n]` | Creates `n` MCP templates (default 1) with the account's token (same variables, or `-- <account id> [n]`) |
| `npm run inspector` | Opens MCP Inspector (needs `ALLOWED_ORIGINS`, see [Troubleshooting](#troubleshooting)) |
`scripts/live-test.ts` runs a real **write** test (moves a lead, sends messages, then restores). Use it only with a test lead.
---
## Production deployment
Ready for **Docker**: a production `Dockerfile` and `docker-compose.yml` are included. Step-by-step guides for **Easypanel**, **Coolify**, Dokploy and plain Docker are in **[docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)**.
In short:
- **Build** from the `Dockerfile`. **Port** `3000` behind HTTPS.
- **No account configuration**: agents send their Kommo credentials.
- **Recommended**: `ADMIN_TOKEN` plus a volume at `/app/data`, then create access keys at `/admin` (only your agents); `PUBLIC_URL` + `OAUTH_SECRET` for claude.ai / Claude Desktop.
- **Volume** at `/app/data`: keeps the access keys and the audit log (`AUDIT_LOG_FILE=off` disables the log).
- **A single instance.** The message queue, locks and limiters live in memory.
- The image runs as a non-root user, has a `HEALTHCHECK` on `/health` and contains no secrets.
Without Docker: `npm ci && npm run build && npm start` behind an HTTPS proxy with `TRUST_PROXY=1`.
---
## Development and tests
```powershell
npm run dev
npm test
npm run typecheck
```
The tests (`tests/`) use a **simulated Kommo** (`tests/fakeKommo.ts`) that reproduces verified real behavior: `buttons: []` rejected, asynchronous bots, events, 429/403, Drive multi-part uploads, attachment keep/clear semantics. They cover:
- validation,
- limiters and locks,
- the message queue (no cross-talk, order, single template),
- attachments (source detection, web pages, SSRF, channel limits, multipart),
- combined `update_lead`,
- request credentials (headers, query, access keys, rejected tokens, shared locks),
- access keys created on the server (store, admin page and API, live revocation),
- stateless OAuth (sealed tokens and clients, PKCE, consent page),
- stored-account keys, toolsets and bound sessions,
- HTTP hardening.
Layout:
```
src/
index.ts startup (HTTP or --stdio)
http.ts Express: auth, limits, Origin, MCP and REST routes, multipart
config.ts environment variables (Zod)
mcp/server.ts MCP server, instructions, sessions, tool execution
mcp/tools.ts tool definitions (descriptions, schemas, annotations)
services/leads.ts lead and contact reads/writes, bots, tasks
services/incoming.ts incoming message webhook (normalization + validation chain)
services/messaging.ts template + salesbot queue
services/attachments.ts source detection, safe downloads, Kommo Drive uploads
services/reports.ts sales and pipeline reports
services/runtime.ts per-account runtime (Kommo client, cache, locks)
services/policy.ts policy rules
services/audit.ts JSONL audit log
kommo/client.ts Kommo HTTP client (retries, 429/403)
kommo/rateLimiter.ts per-second limiter
kommo/schemaCache.ts cache and strict name resolution
validation/ fields and dates
auth/oauth.ts stateless OAuth 2.1 provider and consent page
auth/crypto.ts AES-256-GCM sealing for OAuth tokens and clients
tenants/dynamic.ts Kommo credentials and settings from the request
tenants/ account schema, optional tenants.json loading
util/ keyed lock, sliding window, text, multipart
scripts/ keygen, tenants-env, smoke, setup-templates, live-test
docs/AGENT_GUIDE.md how to write prompts and connect agents
docs/DEPLOYMENT.md Docker, Easypanel, Coolify and other panels
Dockerfile production image (multi-stage, non-root, healthcheck)
docker-compose.yml Compose for Coolify, Dokploy or a plain server
```
---
## Troubleshooting
| Symptom | Likely cause / fix |
|---|---|
| `401 Kommo rejected the token for "…"` | The token is wrong, expired or revoked, or belongs to another account. Generate a new long-lived token |
| `401 That looks like a Kommo token: also send the account subdomain` | Add `?subdomain=…` to the URL or the `X-Kommo-Subdomain` header |
| `401 Invalid or missing server access key` | The server has access keys: send yours as `x-api-key`, and check it was not revoked at `/admin` |
| `401 Invalid or missing credentials` | No subdomain + token were sent (or a stored-account key is wrong) |
| `400 Invalid connection settings` | A setting is malformed: subdomain, time zone, `template_id`/`bot_id` (same count), `policy`/`messaging` JSON |
| `send_message` does not appear | No `template_id` + `bot_id` in the connection, or `toolsets` excludes `messaging` |
| claude.ai says it cannot connect / no login page appears | `PUBLIC_URL` is not set, or it does not match the HTTPS address clients use |
| `401 Invalid or expired access token` | The OAuth token expired, `OAUTH_SECRET` changed (or is unset and the server restarted), or the access key was revoked (or the first access key was created). Connect again |
| `403 Origin not allowed` | The request comes from a browser (e.g. MCP Inspector at `http://localhost:6274`). Add that origin to `ALLOWED_ORIGINS` |
| `429 Too many requests with this API key` | The agent is looping or the limit is low. Check the flow or raise `INBOUND_RPM_PER_KEY` |
| `413 Body too large` | The file exceeds `MAX_BODY_MB` (or the proxy's limit). Send it as multipart or by URL |
| `UNAUTHORIZED` (502) | The Kommo token stopped working while connected. Generate a new one |
| `BLOCKED` | Kommo blocked the IP. The server pauses by itself. Lower `KOMMO_GLOBAL_RPS` if it happens again |
| `NOT_FOUND` with suggestions | The prompt uses a name that does not exist in the account. Fix the prompt or the account |
| `POLICY` | The field, bot, pipeline or agent is missing from the account policy |
| A change in Kommo is not reflected | Schema cache: wait `SCHEMA_CACHE_TTL_MS` or call `get_account_schema { refresh: true }` |
| `Template with id X not found` | The template was not created with this integration's token. Use `npm run setup:templates` |
| `send_message` answers `unconfirmed` | The channel is not connected, the WhatsApp 24 h window is closed or the bot failed. Check the lead's history in Kommo |
| The customer got a `kommo.cc` link instead of the file | The file exceeds the channel limit (WhatsApp video: 16 MB). The result says `channel_link: true`. Compress it, or set `oversizeMedia: "error"` |
| Files or links arrive as `kommo.cc/k/…` links even when they are small | Kommo's **link tracking** is on for the channel: it rewrites links and media into tracked short links. Turn it off in the Kommo channel settings |
| An attachment URL arrived as a link in the text | The URL is a web page, not a file (`attachment.link`). Use a direct file URL |
---
## Known limitations
- The queue and locks live in memory: **a single instance**. Several replicas would need them in Redis or Postgres.
- Confirmation by `outgoing_chat_message` could match a message an agent sends by hand at the same instant.
- Kommo accepts the salesbot launch (202) even if it sends nothing afterwards. In that case the MCP answers `unconfirmed`.
- Kommo accepted 5000-character contents, 4 buttons and 25-character buttons. The server's limits follow WhatsApp by default and can be changed per account.
- Media above the channel limit arrive as a `kommo.cc` link; the MCP flags it but does not compress files.
- Long-lived Kommo tokens only: Kommo's own OAuth refresh flow is not implemented.
- Stored accounts (`tenants.json`) are read at startup: changes need a restart. Request credentials need nothing.
- OAuth tokens are stateless: they cannot be revoked one by one (see [OAuth details](#oauth-details)).
---
## Contributing and license
- Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
- Vulnerabilities (private report): [SECURITY.md](SECURITY.md)
- License: [MIT](LICENSE)
Kommo is a trademark of its respective owner. This project is independent and is not affiliated with or endorsed by Kommo.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues