Skip to main content
Glama
Jojeda96

MCP Analytics Server

by Jojeda96

MCP 分析服务器

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

一个基于 Python 构建的生产级 Model Context Protocol (MCP) 服务器,针对存储在 DuckDB 中的业务数据集,对外暴露类型化、确定性且具备安全防护的分析工具。

外部 AI 代理(例如通过 OpenAI Agents SDK 接入的 GPT、Claude Desktop 或 Cursor)可以动态发现并执行分析查询,而无需直接访问数据库或运行不受约束的 SQL。


✨ 核心亮点

  • Python 优先的 MCP 服务器:完全符合官方 Model Context Protocol 标准,通过 stdio 通信。

  • 模型无关架构:服务器内部不包含任何 LLM。它对外暴露清晰、确定性的工具契约,任何兼容 MCP 的代理均可调用。

  • 嵌入式列式分析引擎:由 DuckDB 驱动,对规范化企业数据执行快速高效的列式聚合。

  • 基于 AST 的 SQL 防护:使用 sqlglot 解析并校验临时查询,严格只允许只读 SELECT 语句,彻底消除 SQL 注入或数据篡改风险。

  • 严格类型化契约:所有响应在到达客户端之前均通过 Pydantic v2 模型进行校验。

  • 交互式 GPT 演示客户端:开箱即用的演示代理,基于 OpenAI Agents SDK 和基于证据的推理提示。

  • 规范驱动开发:使用 OpenSpec 增量式工程化实现,确保需求完全可追溯。


Related MCP server: databricks-mcp

🏛️ 系统架构

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

🛡️ 安全 SQL 执行与安全边界

从 AI 代理接收到的任何 SQL 输入均被视为不可信输入。服务器在执行查询之前,通过 sqlglot 强制执行严格的 AST 校验:

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)
  • 行数限制防护:临时查询的行数上限为 MAX_RESULT_ROWS = 100,以保护代理的上下文窗口。

  • 表白名单:仅允许查询经过授权的分析表(customers)。


🧰 MCP 工具目录

工具名称

用途

关键参数

返回类型

get_dataset_info

数据集高层元数据,包括行数、列数、主表名称和目标变量。

DatasetInfo

list_columns

模式检查,返回所有可用列及其数据库数据类型。

list[ColumnInfo]

describe_column

数值列的统计指标(minmaxmeanmedian),或分类列的类别分布。

column: str

NumericColumnDescription / CategoricalColumnDescription

get_churn_summary

总体客户数、流失客户数、留存客户数,以及 [0.0, 1.0] 区间内的历史流失率。

ChurnSummary

get_churn_by_dimension

按经批准的维度(contractinternet_servicepayment_method 等)分组的细分流失指标。

dimension: str

DimensionChurnResult

run_readonly_sql

受防护的分析型 SQL 执行,用于标准工具未覆盖的复杂自定义计算。

query: str

SQLResult


🚀 快速入门指南

1. 前置条件

  • Python 3.11+

  • Git

2. 安装

# 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. 构建分析数据库

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

4. 运行 MCP 服务器

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

5. 运行交互式 GPT 演示客户端

.env 中配置你的 OpenAI API 密钥:

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

运行交互式演示:

# Interactive REPL mode
python client/gpt_demo.py

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

🔌 连接 MCP 客户端

Claude Desktop / Cursor

将以下配置添加到你的 claude_desktop_config.json 或 Cursor MCP 设置中:

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

🧪 测试与质量保障

# 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

📐 开发工作流(OpenSpec)

本项目遵循**规范驱动开发(SDD)**方法论,使用 OpenSpec 进行开发。每项能力都通过明确的提案、增量规范、设计文档和可验证任务进行跟踪:

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

📂 项目结构

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

📄 许可证

本项目采用 MIT 许可证授权——详情请参阅 LICENSE 文件。

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