Skip to main content
Glama

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 --> Entry

Why 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-only SELECT / WITH queries and block DROP, 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 ChartRecommendation metadata (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 dev

2. 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.seed

Offline / Mock Mode: If no API key is set (or OFFLINE_MODE=true), LLMClient automatically 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/ -v

Developer 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 repl

MCP Server Usage

Start the MCP server over stdio (analytics_ai/mcp/server.py):

uv run python -m analytics_ai.mcp.server

Exposed MCP Tools

Tool

Description

ask_business_question(question)

Full end-to-end pipeline: SQL generation, DuckDB execution, executive summary, and chart spec.

inspect_ontology(entity_or_metric?)

Returns the business glossary, relationships, and metric formulas.

generate_sql_only(question)

Generates and AST-validates DuckDB SQL without executing it.

execute_analytics_sql(sql)

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 names

  • insight.summary: Executive narrative string

  • insight.key_findings: Bullet-point takeaways

  • insight.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:

  1. Switch on chart_recommendation.chart_type (bar, line, pie, metric_card, table).

  2. Bind data as the dataset.

  3. Map chart_recommendation.x_axis and chart_recommendation.y_axis to the chart's X and Y encodings.

  4. Render insight.summary and insight.key_findings alongside 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 tools

Available Tools

4 tools
ask_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

    A3.9/5.0

    Scored across 4 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables natural language querying of SQL databases and REST APIs through the MCP protocol, grounded in a semantic layer.
      1
      AGPL 3.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides 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
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables 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
      -