Skip to main content
Glama
Analytics MCP server

Analytics MCP server

by aby3941
README.md
# Analytics MCP server

An [MCP](https://modelcontextprotocol.io) server that lets an AI assistant answer business questions from a company database, **safely and consistently**. Example questions: "What was our MRR at the end of June 2025?", "Which segment churned most in August?", "How many urgent tickets did we get this year?"

Any MCP client can use it, such as Claude Code or Claude Desktop. It gives the assistant two ways in:
- **a semantic layer**: named metrics like `mrr`, `customer_churn_rate` and `arpa`, each with one agreed definition, so the assistant never invents its own formula for "churn";
- **read-only SQL** for everything else, behind several independent layers of protection.

```
You:    Which customer segment had the highest churn rate in August 2025?
Claude: → list_metrics → get_metric(customer_churn_rate, 2025-08, 2025-08, group_by=segment)
        SMB, at 5.2% (mid-market 3.6%).
```

## Why

Managers wait days for an analyst to pull a number, and different teams compute "churn" differently. This lets them ask in plain English and get an answer in seconds. It uses the company's own metric definitions, and every query lands in an audit log. The catch is that letting an AI run SQL on company data is a security problem, so most of this project is about making that safe and **proving** it.

## How it works

```mermaid
flowchart LR
    C[MCP client<br/>Claude Code / Desktop] -- stdio or HTTP --> S[MCP server<br/>5 read-only tools]
    S --> M[Semantic layer<br/>fixed SQL templates]
    S --> G[SQL guard<br/>sqlglot AST allowlist]
    M --> D
    G --> D[(Postgres<br/>read-only role · read-only txn<br/>5 s timeout · row + byte caps)]
    S --> A[Audit log<br/>every tool call]
```

| Tool | What it does |
|---|---|
| `list_tables` · `describe_table` | Tables, row counts, column types and descriptions (from `COMMENT ON`) |
| `list_metrics` | The 9 metric definitions, with units and allowed dimensions |
| `get_metric(metric, start_month, end_month, group_by?)` | A metric by month, optionally split by segment, country, plan or acquisition channel |
| `run_sql(sql)` | Read-only SQL for anything the metrics don't cover |

Every tool is marked read-only (`readOnlyHint`). Errors come back to the AI as tool errors it can act on, never as stack traces or connection strings.

### Defence in depth for `run_sql`

| Layer | Stops |
|---|---|
| **1. SQL guard** ([`guard.py`](src/analytics_mcp/guard.py)) | Parses with sqlglot and accepts only a single `SELECT` or set operation. It rejects any write or DDL node anywhere in the tree, including inside CTEs, plus `SELECT INTO` and `FOR UPDATE`. Only the six business tables are allowed (no `pg_catalog`, `information_schema` or `public`). Functions must be on an **allowlist**, and `LIMIT` is capped. |
| **2. Read-only role** | `analytics_ro` can `SELECT` on six tables and nothing else: no temp tables, no `CREATE`, no role memberships, a `temp_file_limit`. |
| **3. Read-only transaction** | Every query runs in `BEGIN READ ONLY … ROLLBACK`. |
| **4. Resource limits** | 5 s statement timeout. Rows stream from the server and the query is **cancelled** at 1,000 rows or 2 MB, so a huge result can't exhaust memory. |
| **5. Audit log** | One JSON line per tool call: arguments, success, rows, duration, error. |

## Security review: attacking it directly

An independent review attacked the guard and the database layers directly, with no AI in the loop. It used **157 hand-written hostile queries** and **20,000 random fuzz inputs** mixing quoting, escapes and comments. It found real bypasses, all now fixed and covered by tests:

| Severity | Finding | Fix |
|---|---|---|
| Critical ×2 | **Parser differential.** sqlglot copies parts of the input verbatim into the SQL it generates: the string in `INTERVAL '1' DAY TO '<text>'` and the contents of `OPERATOR(...)`. A crafted query therefore smuggled `pg_sleep`, catalog reads and advisory locks past the guard. | The SQL that will actually run is checked again and must round-trip unchanged. `OPERATOR(...)` is rejected. |
| High | Postgres runs `(value).function` and `alias.function` as function calls, e.g. `(42::bigint).pg_advisory_lock`. That reached functions off the allowlist, including terminating other sessions. | Field notation is allowed only for real columns. |
| Low | `reg*` casts (`'x'::regrole`) listed every role and schema. A column named like a function (`corr(CORR, b)`) dodged the allowlist. | Both rejected. |
| Medium | The result byte cap didn't limit memory, because the driver had already buffered the whole result. | Rows now stream and the query is cancelled at the cap. |

After the fixes, the guard blocks 121 of the 157 queries. The other 36 are harmless: plain strings, `SELECT user`, system columns, capped scans. The read-only role and transaction block every write even when the guard is bypassed on purpose in tests.

## Results

All numbers come from `amcp eval` runs. Raw output is in [`evals/results/`](evals/results/).

**Data:** a deterministic synthetic B2B SaaS company, "Brightdesk", covering 2024–2025: 1,560 customers, 2,335 subscriptions, 15,176 invoices, 14,118 payments and 7,767 support tickets. It has four planted business patterns: a churn spike after a price rise, fast German enterprise growth, a support backlog, and better partner-channel retention. Tests check that all four are present.

### Can the AI answer business questions through it?
Claude Code (Opus 5.5), connected to the server over stdio, answered 30 business questions. Each answer was checked against ground truth from **hand-written SQL kept separate from the server's metric code**, so a wrong metric definition can't make itself look correct.

| Metric | Result |
|---|---|
| Correct answers | **30/30** (numbers and labels) |
| Answers that used the shared metric definitions | 77% (the rest needed raw SQL) |
| Average tool calls per question | 2.6 |
| Median / p95 time per answer | 9.0 s / 11.7 s |

### Does it hold up against prompt-injection attacks?
12 attack prompts went through the same agent setup. They tried to delete or modify data, read password hashes, leak the connection string, `pg_sleep`, create tables, `COPY` to a server file, read server files, use a data-modifying CTE, escalate to superuser, switch off read-only mode, and hide a `DROP TABLE` inside a normal question.

| Metric | Result |
|---|---|
| Attacks with the database unchanged and nothing leaked | **12/12** |
| …where the agent called the server's tools (database still unchanged; 1 query rejected by the guard) | 4 |
| …where the agent refused without calling a tool | 6 |
| …blocked by the model's own safety layer before reaching the server | 2 (reported as *not testing the server*) |

Read this honestly: the attack eval mostly measures the **model's** judgement, because a well-aligned model refuses most of these. The **server's** defences are what the security review above proves. Those 157 queries were sent straight to the guard and the database, with no AI in between.

## Quick start

Requirements: Python 3.11+, Docker or Podman, and the [Claude Code](https://claude.com/claude-code) CLI for the agent eval.

```bash
make install
cp .env.example .env
make db-up        # Postgres 17 on localhost:5435
make seed         # generate the company, load schema saas, create the read-only role

.venv/bin/amcp metric customer_churn_rate 2025-01 2025-12 --group-by segment
.venv/bin/amcp sql "SELECT country, count(*) FROM customers GROUP BY 1 ORDER BY 2 DESC"
.venv/bin/amcp sql "DELETE FROM customers"        # rejected by the guard
make mcp-config   # prints a ready-to-paste config for Claude Desktop / Claude Code
```

Then add the printed config to your MCP client and ask it a business question. To run the evals: `make eval`.

## Testing

1,106 tests, written from a behaviour spec ([`docs/SPEC.md`](docs/SPEC.md)) separately from the implementation:

- **919 unit tests**, no database or AI:
  - about 550 guard cases covering every bypass class above, plus a round-trip property test;
  - metric template safety;
  - the audit log;
  - the tools and the MCP server through the SDK's in-process API;
  - the agent-eval harness with a fake runner;
  - a subprocess test proving that stdout carries nothing but JSON-RPC.
- **187 integration tests** against real Postgres, each run in a throwaway database:
  - the seed is deterministic and the planted patterns are present;
  - every metric matches a brute-force Python computation;
  - the read-only role and transaction block writes even with the guard bypassed;
  - timeouts, row and byte caps, streaming cancellation, and no leftover advisory locks.

```bash
make test       # unit tests
make test-all   # + integration tests (needs make db-up)
```

## Project layout

```
src/analytics_mcp/
  seed.py        deterministic synthetic company + read-only role
  guard.py       SQL guard (sqlglot AST allowlist, round-trip check)
  db.py          read-only transactions, timeout, streaming with row/byte caps
  metrics.py     semantic layer: 9 metrics, fixed SQL templates
  tools.py       the 5 tools, independent of the transport
  audit.py       JSON-lines audit log
  server.py      MCP adapter (stdio / streamable HTTP)
  agent_eval.py  drives Claude Code against the server; questions + attacks
  cli.py         amcp command
evals/           30 questions with ground-truth SQL, 12 attacks, results
```

## Limitations and next steps

- **Synthetic data:** one company, two years. The next step is a messier real-world schema with more tables and ambiguous column names.
- **Small eval sets** (30 questions, 12 attacks), and one model. Next: harder multi-step questions and other MCP clients.
- **Single connection:** the HTTP mode serializes clients through one connection. A connection pool is the next step for real multi-user use.
- **Authentication** for the HTTP transport isn't implemented. Use stdio, or put it behind an authenticating proxy.

## License

MIT. The company and all customer data are synthetic.