analytics-ai
Provides tools to generate and execute read-only analytical SQL queries against a local DuckDB database, returning query results, executive summaries, and chart recommendations.
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-ai What is our total revenue by product category?"
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 AI: Semantic & Ontology-Driven Text-to-SQL Agent
An AI analytics system that translates plain-English business questions into safe, accurate DuckDB SQL using a Semantic & Ontology Knowledge Graph, summarizes results into executive narratives with declarative chart specifications, and exposes the entire pipeline over the Model Context Protocol (MCP).
Architecture Overview
flowchart LR
Client["Client / User\n(MCP Client, CLI, Dashboard)"] <-->|MCP stdio / CLI| Entry["MCP Server / CLI"]
subgraph Core Pipeline
Entry --> Graph["1. Semantic & Ontology Graph\n(NetworkX + YAML)"]
Graph --> SQLGen["2. Constrained SQL Generation\n(LiteLLM + Prompt Context)"]
SQLGen --> Safety["3. AST Safety Guard\n(SQLGlot Read-Only Check)"]
Safety --> DB[("4. DuckDB Engine\n(Columnar OLAP)")]
DB --> Summary["5. Business Insight Summarizer\n(Narrative + Chart Spec)"]
end
Summary --> EntryWhy This Architecture?
Semantic & Ontology Graph (
NetworkX+ontology.yaml): Prevents LLM join hallucinations by computing shortest valid join paths between entities and injecting canonical metric formulas (e.g.,net_revenue,average_order_value).AST-Level SQL Safety (
SQLGlot): Parses generated SQL into a DuckDB Abstract Syntax Tree to enforce read-onlySELECT/WITHqueries and blockDROP,DELETE,UPDATE,INSERT,ALTER, and stacked statements.In-Process OLAP (
DuckDB): Fast, zero-server columnar analytical queries over local e-commerce data (customers,products,orders,order_items).Declarative Visualization Specs: Returns structured
ChartRecommendationmetadata (bar,line,pie,metric_card,table) alongside raw records so any frontend can render interactive charts natively.
Related MCP server: Atlas MCP
Quickstart
1. Prerequisites & Installation
Ensure Python 3.12+ and uv are installed, then clone the repository and install dependencies:
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment and install project + dev dependencies
uv sync --extra dev2. Environment & Seed Data
# Copy environment template and optionally add GEMINI_API_KEY or OPENAI_API_KEY
cp .env.example .env
# Seed the local DuckDB database
uv run python -m analytics_ai.data.seedOffline / Mock Mode: If no API key is set (or
OFFLINE_MODE=true),LLMClientautomatically uses deterministic mock responses so the entire pipeline and test suite run offline at zero cost.
3. Run the Test Suite
uv run pytest tests/ -vDeveloper CLI Usage
Run analytics_ai/cli.py from the terminal:
# Ask a business question end-to-end (Markdown report)
uv run python -m analytics_ai.cli ask "What is our total revenue by product category?"
# Output raw JSON
uv run python -m analytics_ai.cli ask "What is our total revenue by product category?" --json
# Generate and validate SQL without executing
uv run python -m analytics_ai.cli sql "Show me top customers by revenue"
# Inspect the business ontology
uv run python -m analytics_ai.cli ontology
uv run python -m analytics_ai.cli ontology net_revenue
# Start an interactive REPL
uv run python -m analytics_ai.cli replMCP Server Usage
Start the MCP server over stdio (analytics_ai/mcp/server.py):
uv run python -m analytics_ai.mcp.serverExposed MCP Tools
Tool | Description |
| Full end-to-end pipeline: SQL generation, DuckDB execution, executive summary, and chart spec. |
| Returns the business glossary, relationships, and metric formulas. |
| Generates and AST-validates DuckDB SQL without executing it. |
| Executes a read-only SQL query directly against DuckDB (rejects DDL/DML). |
Example MCP Client Configuration (Claude Desktop / Cursor)
{
"mcpServers": {
"analytics-ai": {
"command": "/path/to/analytics-ai/.venv/bin/python",
"args": ["-m", "analytics_ai.mcp.server"],
"cwd": "/path/to/analytics-ai"
}
}
}Frontend Integration Guide
When a dashboard or UI calls ask_business_question(question), it receives a JSON payload containing:
data: Array of record objects (e.g.,[{"category": "Electronics", "net_revenue": 881876.71}, ...])columns: Ordered list of column namesinsight.summary: Executive narrative stringinsight.key_findings: Bullet-point takeawaysinsight.chart_recommendation:{ "chart_type": "bar", "title": "Net Revenue by Category", "x_axis": "category", "y_axis": "net_revenue", "description": "Bar chart ranking net_revenue across category." }
A frontend charting library (e.g., Vega-Lite, Chart.js, Recharts, or Plotly) can map chart_recommendation directly:
Switch on
chart_recommendation.chart_type(bar,line,pie,metric_card,table).Bind
dataas the dataset.Map
chart_recommendation.x_axisandchart_recommendation.y_axisto the chart's X and Y encodings.Render
insight.summaryandinsight.key_findingsalongside the visualization.
Project Structure
analytics_ai/
├── config.py # Pydantic Settings configuration
├── cli.py # Developer CLI (ask, sql, ontology, repl)
├── data/
│ ├── db.py # DuckDB connection & query helpers
│ └── seed.py # Synthetic e-commerce data generator
├── semantic/
│ ├── models.py # Pydantic v2 ontology schemas
│ ├── ontology.yaml # Declarative entities, joins, metrics, synonyms
│ └── graph.py # NetworkX shortest-path & term resolver
├── engine/
│ ├── llm.py # LiteLLM wrapper with offline mock fallback
│ ├── safety.py # SQLGlot AST read-only validator
│ ├── sql_generator.py # Context-injected Text-to-SQL generator
│ ├── executor.py # Safe DuckDB query executor
│ ├── summarizer.py # Executive insight & chart spec generator
│ └── pipeline.py # End-to-end AnalyticsPipeline orchestrator
└── mcp/
└── server.py # MCPServer exposing 4 analytics toolsAvailable Tools
4 toolsask_business_questionA
Answer a plain-English business question using the full analytics pipeline.
Runs semantic resolution, safe DuckDB SQL generation, query execution, and returns an executive summary, key findings, and a chart recommendation.
Inputs: question (required). Returns: object
execute_analytics_sqlA
Execute a read-only analytical SQL query directly against DuckDB.
Rejects any non-SELECT/WITH statements or DDL/DML commands via SQLGlot AST validation.
Inputs: sql (required). Returns: object
generate_sql_onlyA
Generate and validate DuckDB SQL for a question without executing it.
Inputs: question (required). Returns: object
inspect_ontologyA
Inspect the business ontology, entities, relationships, and metrics.
If entity_or_metric is provided, returns detailed information for that
specific entity or metric. Otherwise, returns a complete glossary overview.
Inputs: entity_or_metric. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
The tools have distinct pipeline roles: full Q&A, ontology inspection, SQL generation without execution, and direct SQL execution. There is mild overlap between ask_business_question and generate_sql_only since both generate SQL, but the execute/no-execute distinction is clear.
All names use consistent snake_case with verb-first phrasing. Minor deviation: generate_sql_only includes a qualifier suffix rather than a clean verb_noun pattern, but it remains readable and predictable.
Four tools is well-scoped for a focused analytics pipeline: ask, inspect metadata, generate SQL, and execute SQL. Each tool has a clear purpose within that flow.
The surface covers the main analytics lifecycle from question to execution, plus ontology inspection and safe SQL validation. Minor gaps include no dedicated schema/table discovery beyond ontology inspection and no chart rendering, only recommendation.
Maintenance
Related MCP Connectors
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Governed data discovery, exact queries, decisions, simulations, and runtime utilities over MCP.
One governed MCP endpoint for 40+ business systems. Read-only, source-cited answers.
Related MCP Servers
- FlicenseNot gradedqualityNot gradedmaintenanceEnables natural-language Q&A, human-approved actions, and dashboard generation over a data ontology via MCP.-

Atlas MCPofficial
AlicenseNot gradedqualityBmaintenanceEnables natural language querying of SQL databases and REST APIs through the MCP protocol, grounded in a semantic layer.1AGPL 3.0- AlicenseNot gradedqualityBmaintenanceProvides read-only, guarded access to business databases via MCP. Enables natural language querying with built-in security barriers like table allowlists, PII masking, and audit logging.MIT
- FlicenseNot gradedqualityCmaintenanceEnables 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-