erp-mcp-server
Provides tools to read recent WhatsApp conversations (including the conversation ID needed to reply) and to send text messages in existing conversations, enabling the assistant to triage and respond to customer chats handled through the ERP.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@erp-mcp-server How much is in the pipeline, and how much is in Proposal?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
erp-mcp-server
English · Português
An MCP 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.
Related MCP server: Odoo MCP Server
Tools
Tool | Kind | What it does |
| read | Leads and total value per stage for a pipeline, ordered by the company's own stage configuration |
| read | Filter leads by pipeline, stage, owner, overdue flag or free-text search; keyset pagination by |
| read | One lead with its activity history and payment installments |
| read | Per seller: won this month vs monthly target, % reached, open pipeline |
| read | Month's income, expenses, balance, breakdown by category, overdue customers |
| read | Connected ad accounts and last-30-day campaign KPIs (spend, conversions, CTR, CPL) |
| read | Latest WhatsApp conversations, with the id needed to reply |
| write | Creates a lead; company and owner are filled from the logged-in identity |
| write | Adds a note to a lead's activity history |
| 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
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 summaryThe 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, 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:
Logs in once with the configured user (
POSTto the login route), keeps the session cookie in memory and reuses it.On a
401, drops the cookie and logs in again exactly once.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.
For inserts, resolves the identity (the
meroute + the users table) and stampscompany_id/owner_idfrom 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 carryreadOnlyHint: false, so MCP clients ask for confirmation before running them.whatsapp_sendsays in its description that it messages a real customer.No default endpoint.
ERP_BASE_URLhas no fallback; the server refuses to start a session againsthttp://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 intoilike/orgroups, so the model cannot rewrite the filter.Secrets stay out of the MCP config. The server reads
.envfrom its own folder; the Claude config only contains the command..envis 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+.
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
claude mcp add erp -- node /absolute/path/to/erp-mcp-server/dist/index.jsClaude Desktop (claude_desktop_config.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 messageTool names, descriptions and output are in Portuguese because the users are Brazilian; the model handles either language.
License
MIT — see LICENSE.
Português
Servidor MCP (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 |
| leitura | Leads e valor por fase de um pipeline, na ordem configurada pela empresa |
| leitura | Filtra leads por pipeline, fase, dono, inadimplência ou busca; paginação por cursor em |
| leitura | Um lead com histórico de atividades e parcelas |
| leitura | Por vendedor: fechado no mês vs meta, % atingido, pipeline aberto |
| leitura | Entradas, saídas, saldo, quebra por categoria e inadimplentes do mês |
| leitura | Contas de anúncio e KPIs dos últimos 30 dias (gasto, conversões, CTR, CPL) |
| leitura | Últimas conversas de WhatsApp, com o id para responder |
| escrita | Cria lead; empresa e dono vêm da identidade logada |
| escrita | Registra nota no histórico do lead |
| 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:
Faz login uma vez com o usuário configurado, guarda o cookie em memória e reusa.
No
401, descarta o cookie e refaz o login uma única vez.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.
Em inserts, resolve a identidade (rota
me+ tabela de usuários) e carimbacompany_id/owner_ida partir dela — o modelo não escolhe o tenant.
Nomes de rotas e tabelas ficam num lugar só, 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 levamreadOnlyHint: false— o cliente MCP pede confirmação antes de executar.Sem endpoint padrão.
ERP_BASE_URLnão tem fallback, e o servidor recusahttp://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
.envda própria pasta; a config do Claude só tem o comando..envno.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+.
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.
Available Tools
7 toolscrm_lead_detailsDetalhes do lead (CRM)BRead-onlyIdempotent
Todos os campos de um lead + histórico de atividades + parcelas de pagamento.
Inputs: lead_id (required), format.
crm_list_leadsListar leads (CRM)ARead-onlyIdempotent
Lista leads com filtros (pipeline, fase, dono, inadimplência, busca por nome/empresa). Ordenado do mais recente. Paginação por cursor: passe before_created_at com o valor do próximo cursor.
Inputs: limit, stage, format, search, +4 more.
crm_pipeline_overviewVisão do funil (CRM)ARead-onlyIdempotent
Resumo do funil de um pipeline: número de leads e valor total por fase, mais o total geral. Pipelines: comercial (padrão), marketing, cs, financeiro.
Inputs: format, pipeline.
financial_summaryResumo financeiro do mêsARead-onlyIdempotent
Entradas, saídas e saldo do mês, com quebra por categoria, mais a lista de clientes inadimplentes. Padrão: mês atual.
Inputs: year, month, format.
marketing_overviewVisão de marketing (Ads)BRead-onlyIdempotent
Contas de anúncio conectadas, campanhas e KPIs agregados dos últimos 30 dias (gasto, impressões, cliques, conversões, CTR, CPL). Puxa do endpoint de marketing do ERP (Meta/Google Ads).
Inputs: format.
sales_performanceDesempenho comercial por vendedorARead-onlyIdempotent
Por vendedor no pipeline comercial: leads ativos e valor em aberto, vendas fechadas no mês e valor, meta de faturamento (se cadastrada) e % atingido. Padrão: mês atual.
Inputs: year, month, format.
whatsapp_recentConversas recentes (WhatsApp)ARead-onlyIdempotent
Últimas conversas de WhatsApp da empresa, mais recentes primeiro. Devolve o id de cada conversa, necessário para responder com whatsapp_send.
Inputs: limit, format, search.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
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.
Maintenance
Related MCP Connectors
Read-only access to a company's ERP for Claude, ChatGPT and Gemini, with OAuth and an audit trail.
Solk CRM for Claude: accounts, pipeline, visits, quotes, orders and tickets with your permissions.
Create contacts, move deals, send proposals and invoices, read your inbox, from Claude or ChatGPT.
Connect Claude to Dutch accounting software: e-Boekhouden invoices, contacts and ledgers.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables interaction with Odoo ERP systems through 17+ business tools covering sales, purchasing, inventory, and accounting operations. Supports both Claude Desktop integration and web deployment with dual transport modes.MIT
- FlicenseNot gradedqualityDmaintenanceEnables Claude AI to analyze and access Odoo business data in real-time, including sales metrics, customer segmentation (RFM analysis), CRM pipeline, product performance, team analytics, and territorial analysis by geographic location.-
- AlicenseNot gradedqualityBmaintenanceEnables Claude to interact with Acumatica ERP through a remote MCP server with per-user OAuth, role-based access, and 44 tools for querying and managing ERP data.21Apache 2.0
- AlicenseNot gradedqualityCmaintenanceEnables Claude to connect securely to Acumatica ERP through per-user OAuth, exposing lookups, schema and documentation utilities, and an optional customer create/update tool while enforcing role-based access, consent, redaction, rate limiting, and audit logging.Apache 2.0