Skip to main content
Glama
mcp-sql-analyst

mcp-sql-analyst

by dakshgorana
README.md
# mcp-sql-analyst

[![CI](https://github.com/dakshgorana/mcp-sql-analyst/actions/workflows/ci.yml/badge.svg)](https://github.com/dakshgorana/mcp-sql-analyst/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.10%2B-blue)
![MCP](https://img.shields.io/badge/Model%20Context%20Protocol-v2-purple)
![License](https://img.shields.io/badge/license-MIT-green)

A **Model Context Protocol (MCP) server** that lets any AI agent — Claude Desktop, Cursor, VS Code agents, or your own LangGraph/OpenAI-Agents app — explore and query a SQL database **safely**.

Giving an LLM raw database access is risky. This server exposes a small set of well-described tools and enforces read-only access in **two independent layers**, so a prompt-injected or confused model still can't modify data or run away with resources.

## How it works

```mermaid
sequenceDiagram
    participant U as User
    participant A as AI agent (MCP client)
    participant S as mcp-sql-analyst
    participant D as SQLite (read-only)
    U->>A: "Which category made the most revenue in Q2?"
    A->>S: list_tables()
    A->>S: describe_table("order_items"), describe_table("products")
    A->>S: run_query("SELECT p.category, SUM(...) ...")
    S->>S: Layer 1: static guard (single SELECT, no DDL/DML)
    S->>D: Layer 2: ro connection + authorizer + timeout + row cap
    D-->>S: rows
    S-->>A: {columns, rows, truncated, elapsed_ms}
    A-->>U: Answer with the numbers
```

## Tools

| Tool | Purpose |
|---|---|
| `list_tables` | Tables and row counts — the agent's starting map |
| `describe_table(table)` | Columns, types, PK/FKs and sample rows, so the model never guesses column names |
| `run_query(sql)` | One read-only `SELECT`; returns columns, rows, `truncated`, latency. SQL errors are returned (not raised) so the agent can self-correct |
| `schema://database` (resource) | Whole schema as JSON for clients that preload context |

## Safety model

| Layer | Control |
|---|---|
| Static guard | Comments stripped, string literals masked, single statement only, must start with `SELECT`/`WITH`, DDL/DML/`PRAGMA`/`ATTACH` keywords rejected |
| Connection | SQLite opened with `mode=ro` URI |
| Authorizer | `sqlite3.set_authorizer` allows only `SELECT`, `READ`, `FUNCTION` actions |
| Resources | Progress-handler timeout (default 5 s) and hard row cap (default 200, with `truncated` flag) |

Tests prove the database layer rejects writes **even if the static guard is bypassed**.

## Quickstart

```bash
pip install -e ".[dev]"
python scripts/seed_db.py data/shop.db          # demo e-commerce DB (customers, products, orders, items)
SQL_ANALYST_DB=data/shop.db mcp-sql-analyst      # stdio transport
SQL_ANALYST_DB=data/shop.db mcp-sql-analyst --http   # streamable HTTP transport
```

### Use with Claude Desktop

```json
{
  "mcpServers": {
    "sql-analyst": {
      "command": "mcp-sql-analyst",
      "env": { "SQL_ANALYST_DB": "/absolute/path/to/data/shop.db" }
    }
  }
}
```

Then ask: *"What's the monthly revenue trend, and which city has the highest return rate?"*

## Configuration

| Env var | Default | Meaning |
|---|---|---|
| `SQL_ANALYST_DB` | `data/shop.db` | Path to the SQLite file |
| `SQL_ANALYST_MAX_ROWS` | `200` | Max rows returned per query |

## Tests

```bash
pytest -q     # guardrail cases, read-only enforcement, and end-to-end MCP tool calls
```

## Roadmap

- Postgres backend using a read-only role and `statement_timeout`
- Query-plan cost check before execution
- Per-table / per-column allow-lists for PII

## License

MIT