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

Python으로 구축된 프로덕션 등급의 Model Context Protocol (MCP) 서버로, DuckDB에 저장된 비즈니스 데이터셋에 대해 타입이 지정되고 결정적이며 보안이 강화된 분석 도구를 제공합니다.

외부 AI 에이전트(예: OpenAI Agents SDK를 통한 GPT, Claude Desktop, Cursor)는 직접 데이터베이스에 접근하거나 제약 없는 SQL을 실행하지 않고도 분석 쿼리를 동적으로 발견하고 실행할 수 있습니다.


✨ 핵심 기능

  • Python 우선 MCP 서버: stdio를 통한 공식 Model Context Protocol 표준을 완전히 준수합니다.

  • 모델 비종속 아키텍처: 서버 내부에는 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

숫자 열에 대한 통계 지표(min, max, mean, median) 또는 범주형 열에 대한 범주 분포.

column: str

NumericColumnDescription / CategoricalColumnDescription

get_churn_summary

전체 고객 수, 이탈 수, 유지 수, 그리고 [0.0, 1.0] 범위의 이탈률.

없음

ChurnSummary

get_churn_by_dimension

승인된 차원(contract, internet_service, payment_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을 사용한 Spec-Driven Development (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