Skip to main content
Glama
README.md
# ERP Copilot MCP

[![CI](https://github.com/salomaonunnegasilva-web/erp-copilot-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/salomaonunnegasilva-web/erp-copilot-mcp/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.11%2B-blue)
![MCP SDK](https://img.shields.io/badge/MCP%20SDK-2.x-6f42c1)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

**A read-only [Model Context Protocol](https://modelcontextprotocol.io) server that lets Claude, ChatGPT or any MCP client answer operations questions from an ERP database *and* the company's SOPs, with page-level citations, over a connection that cannot change data.**

> *"Which orders are late, and what does our SOP say we must do about them?"*
> The assistant calls `get_open_orders(overdue_only=true)` and `search_documents(...)`, then answers with the 10 late orders and cites *[Order Fulfillment & Shipping SOP, p. 2]*: review them in the 9:00 am ops meeting and notify each customer within 24 hours.

It is built the way production integrations need to be built: a read-only database role, an AST-based SQL guard, an audit log of every tool call, OAuth-ready remote transport, and an eval suite that runs in CI.

<!-- Record a 2-minute screen capture and save it as docs/demo.gif, then uncomment: -->
<!-- ![Demo](docs/demo.gif) -->

## What it demonstrates

| Capability | How |
|---|---|
| Connect an AI assistant to a business system safely | MCP tools over Postgres through a read-only role, plus a SQL guard and per-call audit log |
| RAG you can trust | Hybrid retrieval (pgvector + Postgres full-text, fused with RRF) with `[Document, p. N]` citations |
| Measurable quality | 46-case deterministic eval suite (retrieval, tool correctness vs oracle SQL, guard) in GitHub Actions, plus an optional agent eval with Claude |
| Local and remote | stdio for Claude Desktop; streamable HTTP with OAuth 2.1 resource-server auth for remote connectors |

## Architecture

```mermaid
flowchart LR
    client["Claude Desktop · ChatGPT · any MCP client"]
    subgraph server["ERP Copilot MCP server (Python, MCP SDK 2.x)"]
        biz["Business tools<br/>open orders · low stock · customer summary"]
        sqlt["Schema tools + run_readonly_query"]
        guard["SQL guard<br/>(sqlglot AST checks + row cap)"]
        rag["search_documents<br/>hybrid retrieval + citations"]
    end
    subgraph pg["PostgreSQL 16 + pgvector"]
        erp[("erp schema<br/>orders · inventory · invoices · POs")]
        docs[("docs.chunks<br/>embeddings + tsvector")]
    end
    pdfs["SOP / policy PDFs"] -->|"erp-copilot ingest"| docs
    client -->|"stdio, or HTTPS + OAuth bearer token"| server
    sqlt --> guard
    biz -->|"read-only role"| erp
    guard -->|"read-only role"| erp
    rag -->|"read-only role"| docs
    server -.->|"one JSON line per call"| audit[("audit.jsonl")]
```

The sample data is a fictional industrial distributor, **Serra Industrial Supply** (warehouses BHZ, SAO and HOU): 24 customers, 48 products, ~190 orders, invoices, purchase orders, and four 3-page SOP/policy PDFs. Everything is synthetic and regenerated deterministically by `scripts/`.

## Tools

| Tool | Answers questions like |
|---|---|
| `get_open_orders` | "Which orders are late?" · "What's open for Atacama Solar Builders in Houston?" |
| `get_low_stock` | "What's below reorder point in São Paulo, and does it already have a PO?" |
| `get_customer_summary` | "Why are Gulf Coast Fabrication's orders not being picked?" (credit hold, overdue invoices, exposure) |
| `search_documents` | "What's the restocking fee?" · "Who approves releasing a credit hold?" (with citations) |
| `list_tables` / `describe_table` | Schema discovery with column descriptions and sample rows |
| `run_readonly_query` | Ad-hoc analysis: "Top 5 products by units sold in October" (guarded SELECT only) |

There is also a `daily_ops_briefing` prompt that walks the model through late orders, low stock and credit risks.

## Quickstart

### Option A: everything in Docker

```bash
git clone https://github.com/salomaonunnegasilva-web/erp-copilot-mcp && cd erp-copilot-mcp
cp .env.example .env              # set MCP_DEV_TOKEN to a long random string
docker compose up -d --build      # Postgres + sample data + MCP server on :8000
curl http://localhost:8000/healthz
```

Connect with the MCP Inspector (`npx @modelcontextprotocol/inspector`): transport **Streamable HTTP**, URL `http://localhost:8000/mcp`, header `Authorization: Bearer <MCP_DEV_TOKEN>`.

### Option B: local Python + Claude Desktop (stdio)

```bash
cp .env.example .env
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
docker compose up -d db           # or load db/init/*.sql into your own Postgres: make db-init
erp-copilot ingest                # chunk + embed the PDFs into docs.chunks
erp-copilot check                 # proves the connection is read-only and the index exists
```

Then add the server to Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS). See [`docs/claude_desktop_config.example.json`](docs/claude_desktop_config.example.json):

```json
{
  "mcpServers": {
    "erp-copilot": {
      "command": "/ABSOLUTE/PATH/TO/erp-copilot-mcp/.venv/bin/erp-copilot",
      "args": ["serve", "--transport", "stdio"],
      "env": { "DATABASE_URL": "postgresql://copilot_ro:copilot_ro@localhost:5432/erp" }
    }
  }
}
```

### Try these

- *Which orders are past their required date, and who should we call first?*
- *Why are Gulf Coast Fabrication's orders stuck, and what has to happen to release them?* (ERP + credit policy, cited)
- *What's low in São Paulo, and what does the SOP say about expediting?*
- *Top 5 products by revenue in the last 90 days* (the model writes SQL; the guard checks it)
- *Delete the cancelled orders* (refused: the connection is read-only)

## Safety model

Defense in depth. Any single layer can fail without data being changed.

1. **Read-only database role.** `copilot_ro` has `default_transaction_read_only = on`, a 5 s `statement_timeout`, and only `SELECT` on the `erp` and `docs` schemas. The server enforces the same settings per connection.
2. **SQL guard** (`src/erp_copilot/sql_guard.py`). Parses model-written SQL with sqlglot and allows exactly one `SELECT`. It rejects DML/DDL anywhere in the tree (including data-modifying CTEs), `SELECT INTO`, `FOR UPDATE`, system catalogs and other schemas, and functions such as `pg_sleep`, `pg_read_file`, `dblink` and `set_config`. Every query is wrapped with a row cap and returns a `truncated` flag. Errors are written for the model to act on.
3. **Tool annotations.** Every tool is declared `readOnlyHint: true, destructiveHint: false`.
4. **Audit log.** One JSON line per call: principal (token subject), tool, arguments, status (`ok` / `denied` / `error`), rows and duration.
5. **Remote transport.** It refuses to start without auth. In OAuth mode the server is an OAuth 2.1 *resource server*: it publishes Protected Resource Metadata at `/.well-known/oauth-protected-resource` and validates JWT access tokens from your IdP (Auth0, Okta, Entra ID, Keycloak…) via JWKS. It checks issuer, audience, expiry and scopes. DNS-rebinding protection is on via allowed hosts.

## Evals

```bash
erp-copilot eval                       # deterministic, no API key, runs in CI on every push
erp-copilot agent-eval                 # optional: Claude answers 6 questions end to end (needs ANTHROPIC_API_KEY)
```

Every eval case goes through the real MCP server in-process, so it exercises tool registration, argument validation, serialization, the guard and the database. It does not call the Python functions directly.

| Suite | Cases | What passes | Current result (`hash` embeddings) |
|---|---|---|---|
| Retrieval | 16 | the right document **and page** is in the top 3 | 16/16 · hit@1 81% · MRR 0.90 |
| Tool correctness | 13 | tool output equals an independently written oracle SQL query | 13/13 |
| Guard | 17 | 13 attacks refused, 4 legitimate analytical queries still run | 17/17 |

The default `hash` embeddings are deterministic and offline, so CI is reproducible, but their semantics are weak. That is why hit@1 is 81%. Switch to real embeddings and the eval shows you the gain:

```bash
pip install -e ".[openai]"   # or ".[local]" for sentence-transformers
EMBEDDING_PROVIDER=openai erp-copilot ingest --rebuild && EMBEDDING_PROVIDER=openai erp-copilot eval
```

The agent eval scores three things: whether Claude **chose the right tools**, whether its answer contains the facts an oracle query says it must, and whether it **cites the right page**. Add cases to `evals/*.jsonl` as you find failures.

## Configuration

All settings are environment variables (a `.env` in the working directory is loaded automatically). See [`.env.example`](.env.example).

| Variable | Default | Purpose |
|---|---|---|
| `DATABASE_URL` | `postgresql://copilot_ro:…@localhost:5432/erp` | Read-only connection used by every tool |
| `ADMIN_DATABASE_URL` | `postgresql://erp_admin:…@localhost:5432/erp` | Ingestion and eval oracles only |
| `EMBEDDING_PROVIDER` / `EMBEDDING_DIM` | `hash` / `384` | `hash`, `openai` or `local` (re-ingest with `--rebuild` after changing) |
| `MCP_DEV_TOKEN` | – | Static bearer token for local HTTP testing |
| `OAUTH_ISSUER` / `OAUTH_AUDIENCE` / `OAUTH_JWKS_URL` / `OAUTH_REQUIRED_SCOPES` | – | OAuth 2.1 resource-server mode |
| `MCP_PUBLIC_URL` / `MCP_ALLOWED_HOSTS` | `http://localhost:8000` / `localhost:*,127.0.0.1:*` | Resource identifier and DNS-rebinding protection |
| `MAX_ROWS` / `STATEMENT_TIMEOUT_MS` | `200` / `5000` | Guard row cap and per-statement timeout |
| `AUDIT_LOG_PATH` | `logs/audit.jsonl` | Audit log location |

## Project layout

```
src/erp_copilot/
  server.py       MCP server: tools, prompt, health route, transports
  erp_tools.py    business logic shared by the server, the evals and the tests
  sql_guard.py    AST checks for model-written SQL
  search.py       hybrid retrieval (pgvector + full-text, RRF) with citations
  ingest.py       PDF/Markdown → page-aware chunks → embeddings
  embeddings.py   hash / OpenAI / sentence-transformers providers
  auth.py         dev token + JWT (JWKS) verifiers, OAuth resource-server settings
  audit.py        JSONL audit decorator
  evals.py        deterministic eval suite      agent_eval.py  Claude end-to-end eval
db/init/          read-only role, schema (with column comments), generated seed data
docs/sources/     SOP Markdown sources → docs/sample/*.pdf (scripts/build_sample_pdfs.py)
evals/            golden cases: retrieval, tools, guard, agent
tests/            unit + integration tests (incl. a real stdio client session)
```

## Roadmap

- [ ] Record the demo GIF (Claude Desktop answering the questions above)
- [ ] Publish the eval delta for real embeddings in this README
- [ ] OAuth with a hosted IdP and a public HTTPS deployment, used as a remote connector
- [ ] SQL Server adapter for on-premises ERPs
- [ ] TypeScript port of the server
- [ ] Listing in MCP server registries

## License

MIT. The data, company and documents are fictional.

---

Built by **Gabriel da Silva Salomão**, AI automation engineer (RAG, MCP, enterprise workflow and ERP integration) · [LinkedIn](https://www.linkedin.com/in/gabriel-949ab9161/) · [boostsolutions.ai](https://boostsolutions.ai/)