Analytics MCP Server
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., "@Analytics MCP Server Why did abandon rate jump last month compared with the prior month?"
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.
Analytics MCP Server
**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:
the right definition of the KPI (is abandon rate divided by offered contacts or by queued ones?),
a correct comparison of two periods, and
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 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 |
| "What can I measure, and for which dates?" |
| "How exactly is this KPI defined, and what's related to it?" |
| "Give me this KPI for these dates, sliced and filtered like this." |
| "Did it get better or worse between these two periods?" |
| "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 over Delta Lake 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.
Related MCP server: MCP Analytics Server
The big 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:
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.The server checks it against the catalog. The KPI,
group_byand 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.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.DuckDB runs it in a sandbox: in memory, no file or network access, settings locked.
JSON comes back with
value,numeratoranddenominatorper 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.
The final answer, as printed by the demo:
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:
Within one dimension, the effects add up exactly to the total change. The maths is in docs/architecture.md.
Why it's safe to give this to an agent
Quickstart
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 clientIf 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/. 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):
{
"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):
{
"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).
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 |
Full MCP surface, the KPI catalog format, generated SQL, the | |
The synthetic tables and the three injected stories with their expected answers | |
Generates every diagram in this README (light and dark): |
Testing
pytest runs 76 tests in a few seconds:
File | What it checks |
| The bundled catalog is valid. Every KPI compiles for every dimension and grain. 14 kinds of invalid catalog and 11 unsafe expressions are rejected |
| Injection attempts in |
| 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 |
|
|
| End to end over MCP (in-process client): tools, annotations, resource, prompt, structured output, errors returned to the agent |
| The scripted agent reaches the right conclusions using only tool calls |
CI (.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
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 checkRoadmap
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 inexplain_changeStatistical 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 © 2026 Piyush Tiwari. All data in this repository is synthetic.
Available Tools
5 toolscompare_periodsARead-onlyIdempotent
Compare a KPI between a baseline period_a and a comparison period_b. Periods are 'YYYY-MM', 'YYYY-MM-DD/YYYY-MM-DD' or a single day. Says whether the change is an improvement given the KPI's good direction.
Inputs: kpi (required), period_a (required), period_b (required), filters. Returns: object
describe_kpiBRead-onlyIdempotent
Full definition of one KPI: business description, SQL numerator/denominator, grain, allowed dimensions and time grains, synonyms and related KPIs.
Inputs: kpi (required). Returns: object
explain_changeARead-onlyIdempotent
Explain why a KPI changed between period_a and period_b. Runs a contribution (shift-share) analysis for each dimension, splitting every segment's contribution into a rate effect (the segment got better/worse) and a mix effect (its share of volume shifted). Returns ranked top_drivers, per-dimension breakdowns and a narrative.
Inputs: kpi (required), period_a (required), period_b (required), top_n, +2 more. Returns: object
list_kpisARead-onlyIdempotent
List every KPI in the catalog with unit, good direction, dimensions and the date range the data covers. Call this first.
Inputs: no named parameters. Returns: object
query_kpiARead-onlyIdempotent
Compute a KPI for an inclusive date range (YYYY-MM-DD), optionally grouped by catalog dimensions and/or a time grain ('day', 'week', 'month') and filtered by dimension values, e.g. filters={"queue": ["billing"]}. Returns rows plus the generated SQL for transparency.
Inputs: end (required), kpi (required), start (required), filters, +1 more. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
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.
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.
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.
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
Related MCP Connectors
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
Build a semantic layer of reusable metrics and query it in plain words. Share models with your team.
AI data analyst for product analytics, billing and warehouse data. Investigations and watchers.
Read-only analytics for all your apps: users, AI traffic, revenue, with the SQL behind every number.
Related MCP Servers
- FlicenseNot gradedqualityBmaintenanceExposes a governed semantic layer built on dbt Core and DuckDB, enabling AI agents to query predefined metric definitions for a P&C insurance dataset. Prevents metric hallucination by restricting agents to governed tools and read-only data access.-
- AlicenseAqualityDmaintenanceEnables AI agents to discover and execute analytical queries on a DuckDB dataset through typed MCP tools, with guarded read-only SQL support for complex calculations without direct database access.6MIT
- AlicenseAqualityCmaintenanceEnables any LLM client to safely inspect and query an analytical DuckDB database with read-only tools for listing tables, describing schemas, running capped SELECT statements, and retrieving named KPIs.4MIT
- AlicenseBqualityBmaintenanceEnables AI agents to safely describe, query, and compute metrics across SQL databases using open-format semantic models, custom context, and skills, with read-only and dialect-checked execution.11Apache 2.0