sqlite-analyst
README.md
# MCP SQL Agent: Chat with Your Database
   
Two pieces that work together, and each is useful on its own:
1. **`sqlite-analyst`**: a **Model Context Protocol (MCP) server** that gives any AI client safe, **read-only** access to a SQLite database. It works with Claude Code, Claude Desktop, IDEs, or your own agents.
2. **A LangGraph agent** that connects to that server, **discovers its tools at runtime**, and answers business questions by exploring the schema, writing SQL, fixing its own errors and explaining the result.
Example output:
```text
$ python -m mcp_sql_agent "Which product category made the most revenue, and how did it trend month by month?"
Connected to MCP server. Tools: list_tables, describe_table, run_query
> list_tables
> describe_table orders
> describe_table order_items
> run_query SELECT p.category, SUM(oi.quantity * oi.unit_price) AS revenue ...
> run_query SELECT strftime('%Y-%m', o.order_date) AS month, ...
**Electronics** is the top category with $273,235 in completed-order revenue,
more than double the next category (Home, $114,623) ...
```
## Architecture
```mermaid
flowchart LR
subgraph Agent["LangGraph agent (MCP client)"]
A[agent node<br/>Claude] -->|tool calls| T[ToolNode]
T -->|results / errors| A
end
T <-->|MCP over stdio| S
subgraph S["sqlite-analyst MCP server"]
L[list_tables]
D[describe_table]
Q[run_query]
R[(schema:// resource)]
end
S --> DB[(SQLite, read-only)]
O[Claude Code / Claude Desktop / IDE] <-->|MCP| S
```
## Safety: defense in depth
The model is never trusted to write safe SQL. The server enforces read-only access in four independent layers:
1. The database is opened with SQLite's `mode=ro` URI.
2. A **SQLite authorizer callback** denies every operation except reads, at the engine level.
3. Only a single `SELECT`/`WITH` statement is accepted.
4. A progress handler kills queries after 5 seconds, and results are capped at 200 rows to protect the model's context window.
The tests try `DROP`, `ATTACH`, statement stacking and write-CTEs, and all of them are blocked.
## Quickstart
```bash
git clone <this-repo> && cd mcp-sql-agent
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env # add your ANTHROPIC_API_KEY
python -m mcp_sql_agent.seed # creates data/shop.db (sample e-commerce data)
python -m mcp_sql_agent # interactive chat with memory for follow-ups
python -m mcp_sql_agent "Who are our top 5 customers by lifetime revenue?"
python -m mcp_sql_agent --db path/to/your.db # use your own SQLite database
```
### Use the server from Claude Code or Claude Desktop
```bash
claude mcp add sqlite-analyst -- python -m mcp_sql_agent.server --db /absolute/path/to/shop.db
```
Claude Desktop (`claude_desktop_config.json`):
```json
{
"mcpServers": {
"sqlite-analyst": {
"command": "/absolute/path/to/.venv/bin/python",
"args": ["-m", "mcp_sql_agent.server", "--db", "/absolute/path/to/shop.db"],
"cwd": "/absolute/path/to/mcp-sql-agent"
}
}
}
```
## What this project demonstrates
- **Building an MCP server**: tools, a resource (`schema://database`) and a reusable prompt (`analyze`) with the official `mcp` SDK
- **Consuming MCP from an agent**: `langchain-mcp-adapters` turns MCP tools into LangGraph tools at runtime
- **The ReAct loop as an explicit graph**: `agent ⇄ tools` with `tools_condition`, plus a checkpointer for multi-turn memory
- **Error recovery**: SQL errors are returned to the model as tool results, so it can fix its query and retry (covered by a test)
- **Secure tool design** for LLMs, as described above
## Tests
```bash
pytest
```
They cover the safety layers, a real MCP round-trip over stdio, and the full agent loop with a scripted model, including recovery from a bad query.
## Ideas to extend
- Add a PostgreSQL backend that uses a read-only role
- Add a `chart` tool that returns a PNG with matplotlib
- Expose the server over Streamable HTTP for remote clients
## License
MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues