Skip to main content
Glama
Jojeda96

MCP Analytics Server

by Jojeda96

MCP Analytics Server

Python SDK Database Validation Code Style Type Checked Spec-Driven License: MIT

Ein produktionsreifer Model Context Protocol (MCP)-Server in Python, der typisierte, deterministische und sicherheitsgeschützte Analysetools über einen in DuckDB gespeicherten Geschäftsdatenbestand bereitstellt.

Ein externer KI-Agent (z. B. GPT über das OpenAI Agents SDK, Claude Desktop oder Cursor) kann analytische Abfragen dynamisch entdecken und ausführen, ohne direkten Datenbankzugriff zu benötigen oder uneingeschränktes SQL auszuführen.


✨ Wichtigste Highlights

  • Python-First-MCP-Server: Vollständig konform mit dem offiziellen Model Context Protocol-Standard über stdio.

  • Modellagnostische Architektur: Der Server enthält kein LLM im Inneren. Er stellt saubere, deterministische Tool-Verträge bereit, die jeder MCP-kompatible Agent aufrufen kann.

  • Eingebettete spaltenorientierte Analytik: Angetrieben von DuckDB für schnelle, effiziente spaltenorientierte Aggregationen auf normalisierten Unternehmensdaten.

  • AST-basierter SQL-Schutz: Verwendet sqlglot, um Ad-hoc-Abfragen zu parsen und zu validieren, erlaubt strikt nur lesende SELECT-Anweisungen und eliminiert SQL-Injection- oder Mutationsrisiken.

  • Strikt typisierte Verträge: Alle Antworten werden vor dem Erreichen des Clients durch Pydantic v2-Modelle validiert.

  • Interaktiver GPT-Demo-Client: Sofort einsatzbereiter Demonstrationsagent, der das OpenAI Agents SDK und evidenzbasierte Reasoning-Prompts nutzt.

  • Spec-getriebene Entwicklung: Inkrementell entwickelt mit OpenSpec für vollständige Rückverfolgbarkeit von Anforderungen.


Related MCP server: databricks-mcp

🏛️ Systemarchitektur

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)]

🛡️ Sichere SQL-Ausführung & Sicherheitsgrenzen

Jede von einem KI-Agenten empfangene SQL-Eingabe wird als nicht vertrauenswürdige Eingabe behandelt. Der Server erzwingt vor der Abfrageausführung eine strikte AST-Validierung über sqlglot:

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)
  • Zeilenlimit-Schutz: Ad-hoc-Abfragen sind auf MAX_RESULT_ROWS = 100 begrenzt, um das Kontextfenster des Agenten zu schützen.

  • Tabellen-Allowlists: Nur autorisierte Analysetabellen (customers) können abgefragt werden.


🧰 MCP-Toolkatalog

Tool-Name

Zweck

Wichtige Parameter

Rückgabetyp

get_dataset_info

Metadaten des Datensatzes auf hoher Ebene, Zeilen- und Spaltenanzahl, Name der primären Tabelle, Zielvariable.

Keine

DatasetInfo

list_columns

Schema-Inspektion, die alle verfügbaren Spalten und ihre Datenbank-Datentypen zurückgibt.

Keine

list[ColumnInfo]

describe_column

Statistische Kennzahlen (min, max, mean, median) für numerische Spalten oder Kategorieverteilungen für kategoriale Spalten.

column: str

NumericColumnDescription / CategoricalColumnDescription

get_churn_summary

Gesamtzahl der Kunden, Anzahl der Abwanderungen, Anzahl der Bestandskunden und historische Abwanderungsrate in [0.0, 1.0].

Keine

ChurnSummary

get_churn_by_dimension

Segmentierte Abwanderungskennzahlen, gruppiert nach einer zugelassenen Dimension (contract, internet_service, payment_method usw.).

dimension: str

DimensionChurnResult

run_readonly_sql

Geschützte analytische SQL-Ausführung für komplexe benutzerdefinierte Berechnungen, die nicht von Standardtools abgedeckt werden.

query: str

SQLResult


🚀 Schnellstart-Anleitung

1. Voraussetzungen

  • 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. Analysedatenbank erstellen

# Ingest raw Telco CSV, validate schema, normalize, and build DuckDB
python scripts/build_database.py

4. MCP-Server ausführen

# Run server standalone over stdio
mcp-analytics
# or
python -m mcp_analytics.server

5. Interaktiven GPT-Demo-Client ausführen

Konfigurieren Sie Ihren OpenAI-API-Schlüssel in .env:

cp .env.example .env
# Edit .env and set OPENAI_API_KEY=sk-...

Führen Sie die interaktive Demo aus:

# Interactive REPL mode
python client/gpt_demo.py

# Or evaluate all 10 standard demonstration questions in batch
python client/gpt_demo.py --all-examples

🔌 Verbindung zu MCP-Clients herstellen

Claude Desktop / Cursor

Fügen Sie die folgende Konfiguration zu Ihrer claude_desktop_config.json oder den Cursor-MCP-Einstellungen hinzu:

{
  "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"
      }
    }
  }
}

🧪 Tests & Qualitätssicherung

# 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

📐 Entwicklungs-Workflow (OpenSpec)

Dieses Projekt wurde nach der Spec-getriebenen Entwicklung (SDD) mit OpenSpec entwickelt. Jede Fähigkeit wird über explizite Vorschläge, Delta-Spezifikationen, Designdokumente und überprüfbare Aufgaben nachverfolgt:

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

📂 Projektstruktur

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

📄 Lizenz

Dieses Projekt ist unter der MIT-Lizenz lizenziert – siehe die Datei LICENSE für Details.

Install Server
A
license - permissive license
A
quality
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    B
    quality
    C
    maintenance
    Enables 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.
    12
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables running read-only SQL queries and exploring DuckDB databases through MCP tools like listing tables, describing schemas, and fetching paginated data.
  • A
    license
    A
    quality
    C
    maintenance
    A read-only DuckDB MCP server offering context-efficient analytics tools (list_datasets, describe_table, profile_column, explain, query) with a semantic layer for business rules, security guards, and disclosed truncation to help LLMs produce correct answers while minimizing token usage.
    5
    MIT

View all related MCP servers

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Jojeda96/mcp-analytics-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server