Skip to main content
Glama
Analytics MCP Server

Analytics MCP Server

by piyusht007
README.md
# Analytics MCP Server

[![CI](https://github.com/piyusht007/analytics-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/piyusht007/analytics-mcp-server/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.10%20%7C%203.12-blue)
![MCP](https://img.shields.io/badge/MCP-python--sdk%202.x-8250df)
![DuckDB](https://img.shields.io/badge/engine-DuckDB-fff000)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

**Let an AI agent answer "*why did this metric change?*" with real numbers instead of guesses.**

> Everything here is synthetic and vendor-neutral. The KPIs reflect general
> contact-center domain knowledge (queues, abandon rate, handle time, service level).
> There is no proprietary code, schema, endpoint or customer data.

## What is this?

Every Monday someone asks an analytics team: *"Abandon rate jumped last month. Why?"*
Answering well takes three things:

1. the **right definition** of the KPI (is abandon rate divided by offered contacts or by
   queued ones?),
2. a **correct comparison** of two periods, and
3. a **breakdown** that tells a *rate* problem (the billing queue got worse) apart from a
   *mix* problem (more contacts came through a channel that is naturally different).

AI chat assistants are good at the conversation but unreliable at step 1, and letting
them write raw SQL is risky. This project is a small **MCP server**, a plug-in that any
[Model Context Protocol](https://modelcontextprotocol.io) client (Claude Desktop, VS Code,
GitHub Copilot CLI, …) can connect to. It gives the agent five **read-only tools** over a
**governed KPI catalog**:

| Tool | In plain words |
|---|---|
| `list_kpis` | "What can I measure, and for which dates?" |
| `describe_kpi` | "How exactly is this KPI defined, and what's related to it?" |
| `query_kpi` | "Give me this KPI for these dates, sliced and filtered like this." |
| `compare_periods` | "Did it get better or worse between these two periods?" |
| `explain_change` | "Which segments caused the change, and was it rate or mix?" |

The agent picks a KPI **by name**. The server owns the SQL, the maths and the safety
checks, and runs everything on [DuckDB](https://duckdb.org) over
[Delta Lake](https://delta.io) tables. The data is a seeded, synthetic **contact center**
(queues, channels, abandon rate, handle time, service level, CSAT, staffing) with three
problems hidden in it on purpose, so you can check that the agent finds them.

## The big picture

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/big-picture-dark.svg">
  <img src="docs/diagrams/big-picture.svg" alt="An analyst asks an AI agent; the agent calls MCP tools; the MCP server validates the call, the semantic layer compiles safe SQL from a YAML catalog, DuckDB runs it over Arrow tables loaded from Delta Lake by delta-rs, and JSON with the numbers and the SQL goes back to the agent" width="100%">
</picture>

- **Analyst:** asks a question in plain words in any MCP-capable chat app.
- **AI agent** (an LLM inside an MCP client): plans the investigation and calls tools.
  It never writes SQL.
- **MCP server** (Python, MCP SDK): exposes the tools and checks every argument.
- **Semantic layer** (a YAML catalog + Python): defines each KPI once and turns a tool
  call into safe, parameterised SQL.
- **Query engine** (DuckDB): runs the SQL in a locked-down, in-memory sandbox over
  Arrow tables that delta-rs loaded from Delta Lake.

## How it works, step by step

Here is what happens for a single tool call:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/one-tool-call-dark.svg">
  <img src="docs/diagrams/one-tool-call.svg" alt="Five steps: the agent calls query_kpi over JSON-RPC/stdio; the server checks it against the catalog; Python compiles SQL with every value bound as a parameter; DuckDB runs it in a sandbox over Arrow data loaded from Delta by delta-rs; the result returns as JSON with the SQL" width="100%">
</picture>

1. **The agent calls a tool**, for example
   `query_kpi(kpi="abandon_rate", start="2026-03-01", end="2026-03-31", group_by=["week"], filters={"queue": ["billing"]})`.
   The MCP client sends it to the server as JSON-RPC over stdio.
2. **The server checks it against the catalog.** The KPI, `group_by` and filter keys must
   exactly match catalog entries, and dates must be ISO dates. If not, the agent gets a
   readable error listing the allowed values, and it can fix its call.
3. **The semantic layer compiles SQL.** Formulas come from the catalog, never from the
   caller. Every caller value (dates, filter values) is bound as a `?` parameter.
4. **DuckDB runs it in a sandbox:** in memory, no file or network access, settings locked.
5. **JSON comes back** with `value`, `numerator` and `denominator` per row, **plus the SQL
   and its parameters**, so every number can be traced back to how it was computed.

## A worked example

The repo includes a demo agent that you can run with no API key:
`python examples/demo_agent.py`. It is a **scripted, deterministic policy** standing in
for an LLM, so every run is the same. It talks to the real server, launched as a stdio
subprocess exactly as Claude Desktop or VS Code would launch it.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/worked-example-dark.svg">
  <img src="docs/diagrams/worked-example.svg" alt="The question 'Why did abandon rate get worse in March?' answered in seven tool calls: abandon rate went from 3.7% to 7.2%, the top driver is the billing queue (rate effect), billing's weekly abandon rate hit 16.8%, billing's scheduled agent hours fell from 7,936 to 5,272 and its speed of answer slowed from 21 s to 95 s" width="100%">
</picture>

The final answer, as printed by the demo:

```text
AGENT Abandon rate worsened from 3.7% to 7.2% (+3.5 pp). Largest driver: queue=billing (+3.6 pp,
      104% of the change; mainly rate effect - segment value 3.6% -> 17.1%, share of volume 27% -> 27%).
      Within queue=billing, the weekly series peaks at 18.4% (2026-03-16). Related KPIs for billing
      moved materially: Scheduled agent hours decreased: 7,936h -> 5,272h (-2,664); Average speed of
      answer (ASA) worsened: 21s -> 95s (+73s). The next-largest driver in another dimension
      (channel=voice) overlaps with this one - contributions are computed per dimension, so they are
      alternative views of the same change, not extra causes. Suggested next step: review billing
      queue operations for 2026-03-01..2026-03-31.
```

"104% of the change" is not a typo: the other queues improved slightly, which offset
part of the billing increase.

### Rate or mix?

`explain_change` splits every segment's contribution into a **rate effect** (the segment
itself got better or worse) and a **mix effect** (its share of volume moved). The two
hidden stories below look very different:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/rate-vs-mix-dark.svg">
  <img src="docs/diagrams/rate-vs-mix.svg" alt="Left: abandon rate Feb to Mar by queue, +3.46 pp, almost all of it a billing rate effect. Right: average handle time Jan to Feb by channel, -8.13 s, mostly mix effect because chat's share grew" width="100%">
</picture>

Within one dimension, the effects add up exactly to the total change. The maths is in
[docs/architecture.md](docs/architecture.md#how-explain_change-works).

## Why it's safe to give this to an agent

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/diagrams/safety-layers-dark.svg">
  <img src="docs/diagrams/safety-layers.svg" alt="Four layers of safety: the catalog is validated at load time, caller input is never pasted into SQL, DuckDB is sandboxed, and all tools are read-only" width="100%">
</picture>

## Quickstart

```bash
git clone https://github.com/piyusht007/analytics-mcp-server.git
cd analytics-mcp-server
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e ".[dev]"

analytics-mcp-generate --out data  # seeded synthetic dataset as Delta tables (~5 s)
pytest -q                          # 76 tests
python examples/demo_agent.py      # scripted agent over a real stdio MCP connection
analytics-mcp --data-dir data      # run the server (stdio) for an MCP client
```

If the data directory doesn't exist when the server starts, the server generates it.
Logs go to stderr, because stdout carries the MCP protocol.

### Connect a client

Ready-to-edit snippets are in [`examples/`](examples). Replace the paths with absolute
ones. On Windows, use `.venv\Scripts\analytics-mcp.exe` (escape the backslashes in JSON).

**VS Code (GitHub Copilot agent mode)**: `.vscode/mcp.json`
([`examples/vscode.mcp.json`](examples/vscode.mcp.json)):

```json
{
  "servers": {
    "analytics": {
      "type": "stdio",
      "command": "${workspaceFolder}/.venv/bin/analytics-mcp",
      "args": ["--data-dir", "${workspaceFolder}/data"]
    }
  }
}
```

**Claude Desktop**: `claude_desktop_config.json`
([`examples/claude_desktop_config.json`](examples/claude_desktop_config.json)):

```json
{
  "mcpServers": {
    "analytics": {
      "command": "/absolute/path/to/analytics-mcp-server/.venv/bin/analytics-mcp",
      "args": ["--data-dir", "/absolute/path/to/analytics-mcp-server/data"]
    }
  }
}
```

**GitHub Copilot CLI**: `~/.copilot/mcp-config.json`
([`examples/copilot-cli.mcp-config.json`](examples/copilot-cli.mcp-config.json)).

The server can also be configured with environment variables: `ANALYTICS_MCP_DATA_DIR`,
and `ANALYTICS_MCP_CATALOG` to point at your own KPI catalog.

Then ask your agent something like *"Why did average handle time jump in the week of
March 10?"* and watch it call the tools.

## Deeper docs

| Doc | What's in it |
|---|---|
| [docs/architecture.md](docs/architecture.md) | Full MCP surface, the KPI catalog format, generated SQL, the `explain_change` maths, safety layers and design decisions |
| [docs/dataset.md](docs/dataset.md) | The synthetic tables and the three injected stories with their expected answers |
| [docs/diagrams/build_svgs.py](docs/diagrams/build_svgs.py) | Generates every diagram in this README (light and dark): `python docs/diagrams/build_svgs.py` |

## Testing

`pytest` runs 76 tests in a few seconds:

| File | What it checks |
|---|---|
| `test_catalog.py` | The bundled catalog is valid. Every KPI compiles for every dimension and grain. 14 kinds of invalid catalog and 11 unsafe expressions are rejected |
| `test_sql_safety.py` | Injection attempts in `group_by`, filter keys, filter values and dates. Values are bound parameters. DuckDB lockdown (no `read_csv`, settings can't be changed) |
| `test_kpi_correctness.py` | All 9 KPIs match **hand-computed** values on a 6-row fixture. Full-dataset values match an independent PyArrow computation. Delta and Parquet results are identical |
| `test_explain.py` | `explain_change` recovers all three injected stories. Contributions reconcile exactly. A hand-worked pure-mix example (−18.75 / −31.25) |
| `test_server.py` | End to end over MCP (in-process client): tools, annotations, resource, prompt, structured output, errors returned to the agent |
| `test_demo.py` | The scripted agent reaches the right conclusions using only tool calls |

CI ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)) runs `ruff check`,
`ruff format --check` and `pytest` on Ubuntu (Python 3.10 and 3.12) and Windows
(Python 3.12), runs the demo over a real stdio connection, and checks that the diagrams
are up to date with their generator.

## Project layout

```text
analytics-mcp-server/
├── src/analytics_mcp/
│   ├── catalog/kpis.yaml      # the semantic layer (KPI definitions)
│   ├── semantic.py            # catalog loading/validation + safe SQL compiler
│   ├── engine.py              # DuckDB execution, compare_periods, explain_change
│   ├── periods.py             # period parsing + formatting
│   ├── server.py              # MCP server: tools, resource, prompt (stdio)
│   └── data/generate.py       # seeded synthetic Delta dataset with injected anomalies
├── examples/                  # demo agent + client config snippets
├── docs/                      # architecture, dataset, diagrams (+ generator)
├── tests/                     # pytest suite (76 tests)
└── .github/workflows/ci.yml   # ruff + pytest + demo + diagram check
```

## Roadmap

- [ ] **Streamable HTTP transport** with OAuth, for a shared, multi-user deployment
- [ ] **Row-level security**: per-caller mandatory filters (for example, a team lead sees only their queues), enforced in the compiler
- [ ] **Multi-dimension drill-down** (`queue × channel`) and automatic "drill into the top segment" recursion in `explain_change`
- [ ] **Statistical guardrails**: confidence intervals and minimum-volume thresholds so small segments don't produce noisy "drivers"
- [ ] **Anomaly scan tool**: sweep all KPIs × segments for changes outside expected ranges
- [ ] **Import from dbt / Cube / MetricFlow** semantic models, plus a BI measure exporter that keeps definitions in sync
- [ ] Optional LLM-backed demo (via MCP sampling) next to the deterministic one

## License

[MIT](LICENSE) © 2026 Piyush Tiwari. All data in this repository is synthetic.

TDQS

A3.9/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct role in the KPI workflow: discovery (list_kpis), definition (describe_kpi), computation (query_kpi), period comparison (compare_periods), and causal explanation (explain_change). The descriptions explicitly differentiate compare_periods from explain_change, and query_kpi is clearly the raw data tool.

Naming Consistency5/5

All tool names follow a consistent verb_noun snake_case pattern: list_kpis, describe_kpi, query_kpi, compare_periods, explain_change. The convention is predictable and readable throughout.

Tool Count5/5

Five tools is well-scoped for an analytics KPI server, covering discovery, definition, querying, comparison, and explanation without redundancy. Each tool earns its place in the workflow.

Completeness4/5

The surface covers the core KPI lifecycle: catalog listing, definitions, computation, period comparison, and change explanation. Minor gaps exist, such as no dedicated tool to list all dimensions across KPIs or export results, but agents can work around these via list_kpis and describe_kpi.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues