erp-mcp-server
# erp-mcp-server
**English** · [Português](#português)
An [MCP](https://modelcontextprotocol.io) server (TypeScript, stdio) that lets Claude read and act on a multi-tenant ERP — CRM pipeline, sales performance, monthly finance, ad campaigns and WhatsApp conversations — by wrapping the ERP's own HTTP API. It runs as the logged-in user, so **the server can never see or do more than that user can in the web panel**.
It was built for the ERP I develop and run in production for small and mid-sized Brazilian companies, and was tested live against production from Claude Code, answering questions like *"how much is in the pipeline and how much of it is in Proposal?"*, *"who is overdue?"*, *"how did each seller do against target this month?"* and to act: *"create a lead for X"*, *"log a note on this lead"*, *"reply to this WhatsApp conversation"*.
## What is MCP?
The Model Context Protocol is an open protocol that lets an AI client (Claude Desktop, Claude Code, other agents) discover and call **tools** exposed by a local or remote server. The client launches this server as a subprocess and talks JSON-RPC over stdin/stdout; the model sees each tool's name, description and input schema (Zod → JSON Schema) and decides when to call it. The server is the only component that holds credentials or talks to the ERP.
## Tools
| Tool | Kind | What it does |
|------|------|--------------|
| `crm_pipeline_overview` | read | Leads and total value per stage for a pipeline, ordered by the company's own stage configuration |
| `crm_list_leads` | read | Filter leads by pipeline, stage, owner, overdue flag or free-text search; keyset pagination by `created_at` |
| `crm_lead_details` | read | One lead with its activity history and payment installments |
| `sales_performance` | read | Per seller: won this month vs monthly target, % reached, open pipeline |
| `financial_summary` | read | Month's income, expenses, balance, breakdown by category, overdue customers |
| `marketing_overview` | read | Connected ad accounts and last-30-day campaign KPIs (spend, conversions, CTR, CPL) |
| `whatsapp_recent` | read | Latest WhatsApp conversations, with the id needed to reply |
| `crm_create_lead` | **write** | Creates a lead; company and owner are filled from the logged-in identity |
| `crm_add_note` | **write** | Adds a note to a lead's activity history |
| `whatsapp_send` | **write** | Sends a text message in an existing WhatsApp conversation |
Every list/summary tool accepts `format: "markdown" | "json"`. Markdown is the default because it is what the model reads best; JSON is there for chaining. Responses are summaries, not raw dumps, and are capped at 25,000 characters with a clear truncation notice.
## How authorization is inherited
```mermaid
sequenceDiagram
participant C as Claude (MCP client)
participant S as erp-mcp-server
participant A as ERP HTTP API
participant DB as Postgres (RLS)
C->>S: tools/call crm_list_leads {stage: "Proposta"}
S->>A: POST /auth/login (first call only)
A-->>S: Set-Cookie: session (JWT)
S->>A: POST /query {table:"crm_leads", filters:[...]} + cookie
A->>DB: query executed as that user (company_id, role)
DB-->>A: only rows the user is allowed to see
A-->>S: rows
S-->>C: markdown summary
```
The ERP has no classic REST API. Its core is a single query route (`/query` by default), a small PostgREST-like endpoint that takes a serializable `QuerySpec` (`table`, `action`, `columns`, `filters`, `orGroups`, `order`, `limit`, …), authenticates by session cookie and runs the query in Postgres **with row-level security applied** for that user's company and role. A few aggregation routes (marketing overview, pipeline stages, sales targets, WhatsApp send) use the same cookie.
Route and table names live in one place, [`src/schema.ts`](src/schema.ts), with generic defaults. To point the server at a real ERP, set `ERP_SCHEMA_FILE` to a JSON that overrides only what differs, e.g. `{ "routes": { "query": "/api/v2/data" }, "tables": { "leads": "deals" } }`. The tools never hard-code a path or a table.
So the server:
1. Logs in once with the configured user (`POST` to the login route), keeps the session cookie in memory and reuses it.
2. On a `401`, drops the cookie and logs in again exactly once.
3. Never connects to the database directly and never holds a service key. There is no code path that bypasses the API, so multi-tenant isolation and role permissions come for free and cannot drift from what the panel enforces.
4. For inserts, resolves the identity (the `me` route + the users table) and stamps `company_id` / `owner_id` from it — the model cannot choose the tenant.
If you want an agent with fewer permissions, create a user with a narrower role in the ERP. The server inherits it.
## Security decisions
- **Inherit, don't grant.** The server is a client of the public API, not a privileged backend. Worst case for a prompt injection is "whatever this user could already click in the panel".
- **Writes are opt-in.** The three write tools are only registered when `ERP_ENABLE_WRITES=true`. They also carry `readOnlyHint: false`, so MCP clients ask for confirmation before running them. `whatsapp_send` says in its description that it messages a real customer.
- **No default endpoint.** `ERP_BASE_URL` has no fallback; the server refuses to start a session against `http://` unless the host is localhost, so credentials never travel in clear text.
- **Model input is sanitized before it reaches the filter grammar.** Free-text search is stripped of `, ( ) . % _ *` before being interpolated into `ilike`/`or` groups, so the model cannot rewrite the filter.
- **Secrets stay out of the MCP config.** The server reads `.env` from its own folder; the Claude config only contains the command. `.env` is git-ignored.
- **Errors are actionable, not leaky.** Failures are translated into short messages (bad credentials, missing config, MFA required) instead of stack traces.
- **Bounded output.** Character cap and server-side aggregation keep the model's context clean and avoid pulling whole tables into the conversation.
## Running it
Requires Node.js 20+.
```bash
npm install
npm run build # if the path has spaces/accents and npm scripts fail: node node_modules/typescript/bin/tsc
cp .env.example .env # fill ERP_BASE_URL, ERP_EMAIL, ERP_PASSWORD (optional: ERP_SCHEMA_FILE, ERP_ENABLE_WRITES=true)
```
**Claude Code**
```bash
claude mcp add erp -- node /absolute/path/to/erp-mcp-server/dist/index.js
```
**Claude Desktop** (`claude_desktop_config.json`)
```json
{
"mcpServers": {
"erp": {
"command": "node",
"args": ["/absolute/path/to/erp-mcp-server/dist/index.js"]
}
}
}
```
The process reads `.env` and `dist/` at startup: after changing either, restart the client so it respawns the server. If the client only says "connection closed", run the same command by hand — the real error is on stderr.
## Project layout
```
src/
index.ts entry point: loads .env, builds the client, registers tools, stdio transport
schema.ts route and table names (generic defaults, overridable via ERP_SCHEMA_FILE)
client.ts HTTP client: login, cookie reuse, 401 retry, QuerySpec runner, identity
format.ts BRL/date formatting, truncation, tool result envelope
tools/_shared.ts error translation, annotations, input sanitizing
tools/crm.ts pipeline, list, details, create lead, add note
tools/sales.ts per-seller performance vs target
tools/financial.ts monthly income/expense/balance + overdue
tools/marketing.ts ad campaigns overview
tools/whatsapp.ts recent conversations, send message
```
Tool names, descriptions and output are in Portuguese because the users are Brazilian; the model handles either language.
## License
MIT — see [LICENSE](LICENSE).
---
## Português
Servidor [MCP](https://modelcontextprotocol.io) (TypeScript, stdio) que deixa o Claude consultar e agir num ERP multiempresa — funil do CRM, desempenho comercial, financeiro do mês, campanhas de anúncio e conversas de WhatsApp — envelopando a própria API HTTP do ERP. Ele roda como o usuário logado, então **o servidor nunca enxerga nem faz mais do que esse usuário faria no painel**.
Foi construído para o ERP que eu desenvolvo e opero em produção para pequenas e médias empresas brasileiras, e foi testado ao vivo contra a produção pelo Claude Code, respondendo *"quanto tenho no funil e quanto está em Proposta?"*, *"quem está inadimplente?"*, *"como cada vendedor está contra a meta?"* e para agir: *"cria um lead pro fulano"*, *"registra uma nota nesse lead"*, *"responde essa conversa no WhatsApp"*.
### O que é MCP
O Model Context Protocol é um protocolo aberto para um cliente de IA (Claude Desktop, Claude Code, outros agentes) descobrir e chamar **tools** expostas por um servidor. O cliente sobe este servidor como subprocesso e conversa em JSON-RPC por stdin/stdout; o modelo vê nome, descrição e schema de entrada de cada tool e decide quando chamar. Só o servidor guarda credencial e fala com o ERP.
### Tools
| Tool | Tipo | O que faz |
|------|------|-----------|
| `crm_pipeline_overview` | leitura | Leads e valor por fase de um pipeline, na ordem configurada pela empresa |
| `crm_list_leads` | leitura | Filtra leads por pipeline, fase, dono, inadimplência ou busca; paginação por cursor em `created_at` |
| `crm_lead_details` | leitura | Um lead com histórico de atividades e parcelas |
| `sales_performance` | leitura | Por vendedor: fechado no mês vs meta, % atingido, pipeline aberto |
| `financial_summary` | leitura | Entradas, saídas, saldo, quebra por categoria e inadimplentes do mês |
| `marketing_overview` | leitura | Contas de anúncio e KPIs dos últimos 30 dias (gasto, conversões, CTR, CPL) |
| `whatsapp_recent` | leitura | Últimas conversas de WhatsApp, com o id para responder |
| `crm_create_lead` | **escrita** | Cria lead; empresa e dono vêm da identidade logada |
| `crm_add_note` | **escrita** | Registra nota no histórico do lead |
| `whatsapp_send` | **escrita** | Envia mensagem de texto numa conversa existente |
### Como a autorização é herdada
O ERP não tem REST tradicional: o núcleo é uma rota de consulta (`/query` por padrão), um mini-PostgREST que recebe um `QuerySpec` serializável, autentica pelo cookie de sessão e executa no Postgres **com RLS aplicado** para a empresa e o papel do usuário. O servidor:
1. Faz login uma vez com o usuário configurado, guarda o cookie em memória e reusa.
2. No `401`, descarta o cookie e refaz o login uma única vez.
3. Nunca conecta direto no banco nem tem chave de serviço. Não existe caminho que pule a API, então isolamento por empresa e permissão por papel vêm de graça e não divergem do que o painel aplica.
4. Em inserts, resolve a identidade (rota `me` + tabela de usuários) e carimba `company_id` / `owner_id` a partir dela — o modelo não escolhe o tenant.
Nomes de rotas e tabelas ficam num lugar só, [`src/schema.ts`](src/schema.ts), com padrões genéricos. Para apontar para um ERP real, use `ERP_SCHEMA_FILE` com um JSON que sobrescreve só o que for diferente.
Quer um agente com menos permissão? Crie no ERP um usuário com papel mais restrito. O servidor herda.
### Decisões de segurança
- **Herdar, não conceder.** O servidor é cliente da API pública, não um backend privilegiado. O pior caso de uma prompt injection é "o que esse usuário já conseguiria clicar no painel".
- **Escrita é opt-in.** As 3 tools de escrita só são registradas com `ERP_ENABLE_WRITES=true`, e levam `readOnlyHint: false` — o cliente MCP pede confirmação antes de executar.
- **Sem endpoint padrão.** `ERP_BASE_URL` não tem fallback, e o servidor recusa `http://` fora de localhost.
- **Entrada do modelo é sanitizada** antes de entrar na gramática de filtro (`, ( ) . % _ *` removidos da busca livre).
- **Segredo fora da config do MCP.** O servidor lê o `.env` da própria pasta; a config do Claude só tem o comando. `.env` no `.gitignore`.
- **Erros acionáveis**, sem stack trace, e **saída limitada** (agregação no servidor + teto de 25 mil caracteres).
### Como rodar
Node.js 20+.
```bash
npm install
npm run build
cp .env.example .env # preencha ERP_BASE_URL, ERP_EMAIL, ERP_PASSWORD (e ERP_ENABLE_WRITES=true para escrita)
```
Claude Code: `claude mcp add erp -- node /caminho/absoluto/erp-mcp-server/dist/index.js`
Claude Desktop: mesmo bloco `mcpServers` mostrado acima em inglês.
O processo lê `.env` e `dist/` no arranque — depois de mudar qualquer um, reinicie o cliente. Se o cliente só mostrar "connection closed", rode o mesmo comando na mão: o erro real sai no stderr.
### Licença
MIT — veja [LICENSE](LICENSE).
TDQS
Scored across 7 tools
The tools mostly target distinct resources: lead details, lead listing, pipeline overview, sales performance, finance, marketing, and WhatsApp. There is some potential overlap between sales_performance and crm_pipeline_overview, but the descriptions clarify that one is seller-level performance and the other is pipeline-stage aggregation.
All tool names use snake_case and generally follow a module_topic pattern. Minor inconsistencies exist: crm_list_leads uses a verb within the CRM prefix, while most others use noun-style module names, and some domains omit a shared prefix.
Seven tools is a well-scoped set for an ERP-style analytics and CRM overview server. Each tool appears to cover a distinct domain area and none feel redundant or excessive.
The surface is almost entirely read-only summaries and lists, with no create/update/delete operations for CRM leads or other ERP entities. The whatsapp_recent description references whatsapp_send, which is not present, creating an obvious dead end and significant gap for agent workflows.