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

DuckDB に格納されたビジネスデータセットに対して、型付けされた決定的かつセキュリティ保護された分析ツールを公開する、Python 製の本番グレード Model Context Protocol (MCP) サーバーです。

外部の 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)

このプロジェクトは OpenSpec を用いた スペック駆動開発(SDD) に従って開発されました。すべての機能は、明示的な提案、デルタスペック、設計ドキュメント、検証可能なタスクを通じて追跡されます:

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