Skip to main content
Glama
Safe Warehouse MCP

Safe Warehouse MCP

by AffanBasra
README.md
# Safe Warehouse MCP

A read-only [Model Context Protocol](https://modelcontextprotocol.io) server that lets Claude explore a Postgres data warehouse and do root-cause analysis in plain English, **without** being able to change data, read tables it should not see, or run away with a slow query.

```
You:    Why did revenue drop in mid-October?
Claude: list_tables -> describe_table(orders, payments) -> run_query x3
        Revenue fell ~20% from Oct 14-17. Failed checkouts jumped from ~8/day to ~55/day.
        Almost all failures are card payments via provider "paygate" with code
        3ds_timeout, only on Android app 5.2.0, which shipped Oct 14.
```

The repo ships a demo warehouse with that incident planted in it, so you can try this in five minutes.

## Why this exists

Connecting an LLM to a real database is the first thing most enterprise customers ask for and the first thing their security team blocks. This server is built around the questions that team will ask:

| Question | Answer |
|---|---|
| Can it change or delete data? | No. Three independent layers say no (see below). |
| Can it see the salaries table? | Only schemas you list are exposed, and the DB role is not granted anything else. |
| Can it take down the warehouse? | Every query has a statement timeout, an optional planner-cost ceiling, and a row cap per page. |
| Will it blow up the context window? | Schemas are discovered lazily, results are paged, and long cells are truncated. |
| Can we see what it ran? | Every query is written to an audit log as JSON on stderr. |

## Architecture

```mermaid
flowchart LR
    C[Claude Desktop / Claude Code] -- MCP over stdio --> S

    subgraph S[safe-warehouse-mcp]
        T[Tools<br/>list_tables · describe_table<br/>explain_query · run_query]
        G[Layer 1: SQL guard<br/>sqlglot AST check]
        D[DB layer<br/>pool · paging · JSON-safe output · audit log]
        T --> G --> D
    end

    D -- "Layer 2: BEGIN READ ONLY<br/>statement_timeout · search_path" --> P
    subgraph P[Postgres]
        R[Layer 3: claude_readonly role<br/>SELECT on allowed schemas only]
        PUB[(public)]
        HR[(hr - not granted)]
        R --> PUB
        R -. denied .-> HR
    end
```

### Safety model: defense in depth

1. **SQL guard** (`sql_guard.py`). Parses the query into an AST with [sqlglot](https://github.com/tobymao/sqlglot) and walks the whole tree, not just the first keyword. It rejects:
   - anything other than one `SELECT` / `UNION` / CTE query
   - `INSERT`, `UPDATE`, `DELETE`, `MERGE`, DDL, `COPY`, `SET`, `GRANT`, transaction control
   - data-modifying CTEs: `WITH x AS (DELETE ... RETURNING *) SELECT * FROM x`
   - `SELECT INTO` (creates a table) and `FOR UPDATE` (takes locks)
   - risky functions: `pg_sleep`, `pg_read_file`, `dblink`, `set_config`, `nextval`, and `query_to_xml` (which runs a SQL string the guard never saw)
   - tables in schemas that are not on the allowlist
2. **Read-only transaction.** Every call runs in `BEGIN READ ONLY` with `SET LOCAL statement_timeout`, `lock_timeout`, and a `search_path` pinned to the allowed schemas. Postgres itself refuses writes here, even if layer 1 has a bug.
3. **Read-only role.** The server logs in as `claude_readonly`, which only has `SELECT` on `public` and defaults to read-only transactions. This is the real security boundary. Layers 1 and 2 exist so Claude gets a clear, fixable error instead of a permission failure.

The tests prove each layer on its own: `test_read_only_transaction_blocks_writes_that_skip_the_guard` sends a `DELETE` straight to the DB layer, and `test_role_cannot_read_ungranted_schema_even_if_allowlisted` misconfigures the allowlist on purpose.

## Tools

| Tool | What it does |
|---|---|
| `list_tables(schema?)` | Tables and views Claude can read, with estimated row counts and table comments. Cheap: no columns. |
| `describe_table(table)` | Columns, types, nullability, comments, primary key, foreign keys, indexes for one table. |
| `explain_query(query)` | Planner cost, estimated rows and plan tree, without running the query. |
| `run_query(query, limit?, offset?)` | Runs one validated `SELECT`. Returns `{columns, rows, has_more, next_offset}`. |

All four are marked `readOnlyHint: true` so clients can skip confirmation prompts.

Design choices that keep the context window small:

- **Lazy schema discovery.** Claude sees table names first and only pulls columns for tables it needs. A 500-table warehouse does not land in the prompt.
- **Server-side row cap.** The query is wrapped as `SELECT * FROM (<query>) LIMIT n+1 OFFSET m`, so the cap holds even if Claude forgets `LIMIT`. The extra row tells us whether there is another page.
- **Compact results.** Rows come back as arrays under a single `columns` header, not one object per row.
- **Cell truncation.** Long text and JSON cells are cut to `WAREHOUSE_MAX_CELL_CHARS`.
- **Actionable errors.** Timeouts, cost rejections and Postgres errors come back as tool errors with a hint ("aggregate first", "call list_tables"), so Claude can fix the query and retry.

## Quickstart

Needs Python 3.11+ and Docker (for the demo database).

```bash
git clone https://github.com/AffanBasra/safe-warehouse-mcp.git
cd safe-warehouse-mcp

# 1. Start the demo warehouse (~22k orders, one planted incident)
docker compose up -d db

# 2. Install the server
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# 3. Run the tests against it
export WAREHOUSE_TEST_DSN=postgresql://claude_readonly:readonly_dev_only@localhost:5433/shop
pytest
```

### Install the plugin (easiest)

This repository is also a plugin marketplace. You need [uv](https://docs.astral.sh/uv/) on your PATH; the plugin runs the server with `uv`, which installs Python and the dependencies.

**Claude Code:**

```
/plugin install safe-warehouse-mcp --marketplace AffanBasra/safe-warehouse-mcp
```

On older versions: `/plugin marketplace add AffanBasra/safe-warehouse-mcp`, then `/plugin install safe-warehouse-mcp@affanbasra-plugins`. Claude Code asks for the database URL and stores it in your system's secure credential store.

**Claude Desktop:** Customize → Plugins → Add → Add marketplace → `AffanBasra/safe-warehouse-mcp`, then add **Safe Warehouse**. Desktop does not ask for settings: the database URL defaults to the demo warehouse. To use your own database, set it on the plugin's Settings tab.

The plugin runs a local server, so it is not in Anthropic's plugin directory: the directory accepts local servers only from verified organizations.

| Where you use Claude | Use |
|---|---|
| Claude Code, and Cowork in the desktop app | The plugin (above) |
| Regular chats in Claude Desktop | The `.mcpb` bundle: drag it onto the Claude Desktop window. Build it with `npx @anthropic-ai/mcpb pack . dist/safe-warehouse-mcp.mcpb`. |
| Anything else | Manual config (below) |

### Connect Claude Desktop (manual config)

Add this to `claude_desktop_config.json` (Settings → Developer → Edit Config) and restart Claude Desktop:

```json
{
  "mcpServers": {
    "warehouse": {
      "command": "/absolute/path/to/safe-warehouse-mcp/.venv/bin/safe-warehouse-mcp",
      "env": {
        "WAREHOUSE_DSN": "postgresql://claude_readonly:readonly_dev_only@localhost:5433/shop",
        "WAREHOUSE_ALLOWED_SCHEMAS": "public",
        "WAREHOUSE_MAX_QUERY_COST": "500000"
      }
    }
  }
}
```

On Windows the command is `C:\\path\\to\\safe-warehouse-mcp\\.venv\\Scripts\\safe-warehouse-mcp.exe`.

To run the server in Docker instead, use `"command": "docker"` with `"args": ["compose", "-f", "/absolute/path/to/docker-compose.yml", "--profile", "mcp", "run", "--rm", "-T", "mcp"]`.

### Connect Claude Code

```bash
claude mcp add warehouse \
  -e WAREHOUSE_DSN=postgresql://claude_readonly:readonly_dev_only@localhost:5433/shop \
  -- /absolute/path/to/safe-warehouse-mcp/.venv/bin/safe-warehouse-mcp
```

### Things to ask Claude

- "What tables do we have and what's in them?"
- "Why did revenue drop in mid-October? Find the root cause."
- "Which customer segment has the highest refund rate?"
- "Delete all cancelled orders." (watch it get refused)
- "Show me the hr.salaries table." (also refused)

## Configuration

| Variable | Default | Purpose |
|---|---|---|
| `WAREHOUSE_DSN` | required | Connection string for a **read-only** login |
| `WAREHOUSE_ALLOWED_SCHEMAS` | `public` | Comma-separated schemas Claude may see |
| `WAREHOUSE_DEFAULT_PAGE_SIZE` | `50` | Rows per page when Claude does not set `limit` |
| `WAREHOUSE_MAX_PAGE_SIZE` | `200` | Hard ceiling on `limit` |
| `WAREHOUSE_STATEMENT_TIMEOUT_MS` | `15000` | Per-query timeout |
| `WAREHOUSE_MAX_CELL_CHARS` | `500` | Truncate longer cells |
| `WAREHOUSE_MAX_QUERY_COST` | `0` (off) | Reject queries with a higher planner cost estimate |
| `WAREHOUSE_POOL_MAX_SIZE` | `4` | Connection pool size |

## Using it on a real database

1. Create a dedicated role. Copy `db/init/03_readonly_role.sql` and change the password and schema names.
2. Point it at a **read replica**, not the primary.
3. Expose the fewest schemas you can. Prefer curated views over raw tables for anything with PII.
4. Turn on `WAREHOUSE_MAX_QUERY_COST` and tune it with `explain_query` on your real workloads.
5. Ship the stderr audit log to wherever your security team already looks.

## Project layout

```
src/warehouse_mcp/
  server.py      MCP tools, descriptions, server instructions
  db.py          connection pool, read-only transactions, paging, audit log
  sql_guard.py   AST-based query validation
  config.py      env var settings
db/init/         demo schema, seed data with planted incident, read-only role
tests/           guard unit tests + end-to-end tests through a real MCP client
```

## Docs

| Doc | For |
|---|---|
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Request flow, safety layers, design trade-offs |
| [docs/CONTEXT_GRAPH.md](docs/CONTEXT_GRAPH.md) | Auto-generated map of every function, tool, test and table (`python scripts/build_context_graph.py`) |
| [docs/CODE_TOUR.md](docs/CODE_TOUR.md) | Reading order for the codebase |
| [docs/KNOWN_ISSUES.md](docs/KNOWN_ISSUES.md) | Confirmed bugs and feature ideas |

## Roadmap

- BigQuery and Snowflake adapters (dry-run bytes billed instead of planner cost)
- Column-level masking for PII (emails, phone numbers)
- Streamable HTTP transport with OAuth for shared team deployments
- Saved "metric definitions" exposed as MCP resources so Claude uses the company's own revenue formula

## License

Licensed under the [Apache License 2.0](LICENSE). Free to use, change and share, including commercially.

If you redistribute this project or a modified version, keep the `LICENSE` and `NOTICE` files and mark the files you changed, as the license requires.

## Credit

If you use this project, please credit it, for example in your README, docs or talk slides:

> Based on [safe-warehouse-mcp](https://github.com/AffanBasra/safe-warehouse-mcp) by Affan Ahmad Basra.