MCP Analytics 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., "@MCP Analytics Server What's the churn rate by contract type?"
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.
MCP Analytics Server
A production-grade Model Context Protocol (MCP) server built in Python that exposes typed, deterministic, and security-guarded analytical tools over a business dataset stored in DuckDB.
An external AI agent (e.g. GPT through the OpenAI Agents SDK, Claude Desktop, or Cursor) can dynamically discover and execute analytical queries without needing direct database access or running unconstrained SQL.
โจ Key Highlights
Python-First MCP Server: Fully compliant with the official Model Context Protocol standard over
stdio.Model-Agnostic Architecture: The server contains no LLM inside. It exposes clean, deterministic tool contracts that any MCP-compatible agent can invoke.
Embedded Columnar Analytics: Powered by DuckDB for fast, efficient columnar aggregations on normalized enterprise data.
AST-Based SQL Guard: Uses
sqlglotto parse and validate ad-hoc queries, strictly allowing read-onlySELECTstatements and eliminating SQL injection or mutation risks.Strict Typed Contracts: All responses are validated through Pydantic v2 models before reaching the client.
Interactive GPT Demo Client: Out-of-the-box demonstration agent leveraging the OpenAI Agents SDK and evidence-based reasoning prompts.
Spec-Driven Development: Engineered incrementally using OpenSpec for complete requirements traceability.
Related MCP server: databricks-mcp
๐๏ธ System Architecture
flowchart TD
User([User]) <--> Agent[GPT Agent / OpenAI Agents SDK]
Agent <-->|MCP Protocol / stdio| Server[MCP Analytics Server]
subgraph Server_Internal [MCP Analytics Server Boundary]
Server --> Tools[Tool Layer]
Tools --> DataTools[Dataset Tools]
Tools --> ChurnTools[Churn Analytics Tools]
Tools --> SQLTool[Read-Only SQL Tool]
SQLTool --> SQLGuard[SQL Guard Security Layer]
DataTools --> AnalyticsSvc[AnalyticsService]
ChurnTools --> AnalyticsSvc
SQLGuard --> DBSvc[DatabaseService]
AnalyticsSvc --> DBSvc
DBSvc --> DuckDB[(DuckDB)]
end
DuckDB --> Table[(customers Table - Telco Dataset)]๐ก๏ธ Safe SQL Execution & Security Boundaries
Any SQL input received from an AI agent is treated as untrusted input. The server enforces strict AST validation via sqlglot before query execution:
Allowed Operations:
โ
SELECT contract, AVG(monthly_charges) FROM customers GROUP BY contract
โ
WITH cohorts AS (SELECT * FROM customers WHERE tenure > 24) SELECT COUNT(*) FROM cohorts
Blocked Operations:
โ DELETE FROM customers WHERE churn = true (Mutation Rejected)
โ DROP TABLE customers (DDL Rejected)
โ SELECT * FROM customers; DROP TABLE customers (Multi-statement Rejected)
โ ATTACH 'external.db' (Engine I/O Rejected)Row Limit Guard: Ad-hoc queries are capped at
MAX_RESULT_ROWS = 100to protect the agent's context window.Table Allowlists: Only authorized analytics tables (
customers) can be queried.
๐งฐ MCP Tools Catalog
Tool Name | Purpose | Key Parameters | Return Type |
| High-level dataset metadata, row and column counts, primary table name, target variable. | None |
|
| Schema inspection returning all available columns and their database data types. | None |
|
| Statistical metrics ( |
|
|
| Overall customer count, churned count, retained count, and historical churn rate in | None |
|
| Segmented churn metrics grouped by an approved dimension ( |
|
|
| Guarded analytical SQL execution for complex custom calculations not covered by standard tools. |
|
|
๐ Quickstart Guide
1. Prerequisites
Python 3.11+
Git
2. Installation
# Clone repository
git clone https://github.com/Jojeda96/mcp-analytics-server.git
cd mcp-analytics-server
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .\.venv\Scripts\Activate.ps1
# Install in editable mode with development tools
pip install -e ".[dev]"3. Build Analytics Database
# Ingest raw Telco CSV, validate schema, normalize, and build DuckDB
python scripts/build_database.py4. Run the MCP Server
# Run server standalone over stdio
mcp-analytics
# or
python -m mcp_analytics.server5. Run the Interactive GPT Demo Client
Configure your OpenAI API key in .env:
cp .env.example .env
# Edit .env and set OPENAI_API_KEY=sk-...Run the interactive demo:
# Interactive REPL mode
python client/gpt_demo.py
# Or evaluate all 10 standard demonstration questions in batch
python client/gpt_demo.py --all-examples๐ Connecting to MCP Clients
Claude Desktop / Cursor
Add the following configuration to your claude_desktop_config.json or Cursor MCP settings:
{
"mcpServers": {
"telco-analytics": {
"command": "python",
"args": ["-m", "mcp_analytics.server"],
"cwd": "/absolute/path/to/mcp-analytics-server",
"env": {
"DUCKDB_PATH": "data/processed/telco.duckdb",
"LOG_LEVEL": "INFO",
"MAX_RESULT_ROWS": "100"
}
}
}
}๐งช Testing & Quality Assurance
# Run complete test suite (Unit & Integration) with coverage
pytest --cov=src --cov-report=term-missing
# Run Ruff linter and formatter checks
ruff check .
ruff format --check .
# Run static type checking
mypy src client scripts tests๐ Development Workflow (OpenSpec)
This project was developed following Spec-Driven Development (SDD) with OpenSpec. Every capability is tracked through explicit proposals, delta specs, design documents, and verifiable tasks:
openspec/
โโโ specs/ # Consolidated capabilities
โ โโโ project-foundation/
โ โโโ telco-data-foundation/
โ โโโ core-analytics-service/
โ โโโ core-mcp-tools/
โ โโโ safe-readonly-sql-tool/
โ โโโ openai-gpt-demo-client/
โ โโโ portfolio-hardening/
โโโ changes/archive/ # Historical change audit trail๐ Project Structure
mcp-analytics-server/
โโโ .github/workflows/ci.yml # GitHub Actions CI matrix pipeline
โโโ assets/ # Diagrams and visual assets
โโโ client/
โ โโโ gpt_demo.py # Interactive OpenAI Agents SDK demo client
โโโ data/
โ โโโ raw/ # Source CSV files
โ โโโ processed/ # Generated DuckDB database
โโโ docs/
โ โโโ architecture.md # Deep-dive architecture and layers
โ โโโ security.md # Threat model and AST SQL Guard details
โ โโโ decisions.md # Architecture Decision Records (ADRs)
โโโ examples/
โ โโโ questions.md # 10 evaluated demo business questions
โ โโโ mcp-config.example.json # Standard client configuration
โโโ scripts/
โ โโโ download_dataset.py # Dataset provenance & download instructions
โ โโโ validate_dataset.py # Strict raw data schema & domain validator
โ โโโ build_database.py # Data cleaner and DuckDB table builder
โโโ src/mcp_analytics/
โ โโโ config.py # Pydantic Settings and environment config
โ โโโ errors.py # Domain exception hierarchy
โ โโโ server.py # MCP server lifecycle and CLI entrypoint
โ โโโ schemas/ # Pydantic response models
โ โโโ security/ # AST SQLGuard parser
โ โโโ services/ # DatabaseService & AnalyticsService
โ โโโ tools/ # Dataset, Analytics & SQL MCP tools
โโโ tests/
โ โโโ fixtures/ # Curated sample CSV test fixtures
โ โโโ unit/ # Fast unit tests for logic and security
โ โโโ integration/ # Database and MCP tool integration tests
โโโ Dockerfile # Containerization recipe
โโโ pyproject.toml # Package definition & tool configs
โโโ CHANGELOG.md # Version release notes
โโโ LICENSE # MIT License
โโโ README.md๐ License
This project is licensed under the MIT License โ see the LICENSE file for details.
Available Tools
6 toolsdescribe_columnB
Provides statistical summaries for a specified column in the customers table. For numeric columns, returns min, max, mean, median, and null count. For categorical columns, returns unique category count and top frequent categories.
Inputs: column (required). Returns: object
get_churn_by_dimensionA
Calculates customer count, churned customer count, and historical churn rate grouped by one approved categorical dimension such as contract, internet_service, payment_method, paperless_billing, tech_support, online_security, etc.
Inputs: dimension (required). Returns: object
get_churn_summaryA
Calculates overall customer count, churned customer count, retained customer count, and historical churn rate across the entire Telco dataset. Churn rate is returned as a ratio between 0.0 and 1.0.
Inputs: no named parameters. Returns: object
get_dataset_infoA
Returns high-level metadata for the Telco Customer Churn dataset, including the available analytics table, row count, column count and target variable. Use this tool before deeper analysis when dataset context is unknown.
Inputs: no named parameters. Returns: object
list_columnsA
Lists all available columns in the customers dataset along with their data types. Use this tool to discover available fields before running specific column queries.
Inputs: no named parameters. Returns: result
run_readonly_sqlA
Executes one read-only analytical SQL query against the customers dataset. Use this tool only when the predefined analytics tools cannot answer the requested question. Mutation, DDL and multi-statement queries are strictly rejected by security boundaries. Results are capped at a maximum of 100 rows.
Inputs: query (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 6 tools
Each tool serves a distinct purpose: dataset overview, column discovery, column statistics, overall churn summary, grouped churn analysis, and custom SQL fallback. The overlap between churn summary and churn by dimension is clearly differentiated by the latter's grouping parameter, and SQL is explicitly a last resort. No ambiguity remains for the agent.
All tools follow a consistent verb_noun snake_case pattern: get_dataset_info, list_columns, describe_column, get_churn_summary, get_churn_by_dimension, run_readonly_sql. The verbs (get, list, describe, run) and noun phrases (dataset_info, columns, column, churn_summary, etc.) are uniform, creating a predictable and readable API surface.
With 6 tools, the server is well-scoped for its purpose of analyzing a single churn dataset. Each tool addresses a distinct analytical need, and none feel redundant or extraneous. The count sits comfortably within the ideal 3-15 range.
The tool set covers the full analytics lifecycle: discovery (dataset info, columns), exploration (describe column), summary statistics (churn summary), dimension breakdowns (churn by dimension), and arbitrary ad-hoc queries (SQL fallback). The inclusion of read-only SQL ensures no analytical question remains unanswered, making the surface effectively complete for a read-only analytics server.
Maintenance
Related MCP Connectors
Query, join, profile, clean and convert CSV/JSON/Parquet with server-side DuckDB over MCP.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Query your org's data in natural language โ read-only MCP access to SQL, NoSQL, files & warehouses.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables LLMs to interact with DuckDB databases through MCP tools for SQL queries, table management, data import/export, and schema inspection, with optional read-only mode for safety.12MIT
- AlicenseAqualityDmaintenanceSafe, read-only SQL analytics for AI agents over MCP, enabling exploration, profiling, and querying of data without mutation risk.5MIT
- FlicenseNot gradedqualityBmaintenanceEnables AI assistants and MCP clients to ask natural-language questions about DuckDB or CSV data and receive safe, read-only SQL-generated tabular insights with automatic schema discovery and multi-table joins.1-
- FlicenseNot gradedqualityAmaintenanceEnables MCP clients and LLMs to interact with a DuckDB database through SQL query execution, table creation, and schema inspection, with optional read-only operation.-