Skip to main content
Glama
readonly-sql-mcp

readonly-sql-mcp

README.md
# readonly-sql-mcp

[![ci](https://github.com/andrew-myers-collab/readonly-sql-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/andrew-myers-collab/readonly-sql-mcp/actions/workflows/ci.yml)

An AI model that can query a database is useful, and an AI model that can write to one is a risk. A prompt
injection, a confused plan, or a plain mistake can turn "show me last month's orders" into `DELETE`. This
project is a small Model Context Protocol (MCP) server that gives a model read access to SQL and nothing more.
It does not rely on one check: five independent layers each stop writes on their own, every call is
authenticated with a bearer token, and every call goes to an audit log. Each token has a role that limits
which tables it can read and which columns it sees, and how many calls it can make per minute.

All data in this repository is synthetic. Company names, SKUs (`DEMO-1001` ...) and orders are made up.

## Quick start (30 seconds)

Windows (`py -3`); on macOS/Linux use `python3`.

```
py -3 -m venv .venv
.venv\Scripts\python -m pip install -r requirements.txt
.venv\Scripts\python demo.py
```

`demo.py` builds the demo database, starts the server on a free local port with three random tokens (roles
`admin`, `analyst`, `catalog` from `config/access.example.json`), then acts as MCP clients over real HTTP: it
lists tables, runs queries, tries six attacks and a wrong token, then pages through a result, explains a query,
samples rows, attacks the masks and the allowlist, hits a rate limit, and prints the audit summary.

To run the server for a real MCP client with one full-access token (the original mode):

```
.venv\Scripts\python scripts\make_demo_db.py
set SQLMCP_TOKEN=<a secret of 16+ characters>
.venv\Scripts\python -m readonly_sql_mcp
```

Or with several tokens and roles (see [Tokens and roles](#tokens-and-roles)):

```
.venv\Scripts\python -m readonly_sql_mcp.access new --name report-bot --role analyst
rem paste the printed entry into your copy of config\access.example.json
set SQLMCP_ACCESS_FILE=config\my-access.json
.venv\Scripts\python -m readonly_sql_mcp
```

The endpoint is `http://127.0.0.1:8765/mcp` (streamable HTTP). Send `Authorization: Bearer <token>`.

## Sample output (from `python demo.py`)

```
server: http://127.0.0.1:50466/mcp  (max_rows=5, timeout=1.0s)

> top 5 customers by shipped value  [ok]
   columns: ['customer', 'orders', 'value']
   ['Acme Distribution', 36, 24035.55]
   ['Umbrella Labs', 31, 23066.75]
   ['Vandelay Imports', 33, 22810.85]
   ['Hooli Health', 34, 22785.3]
   ['Wayne Medical', 29, 20955.85]
   truncated: False

> row limit (SELECT * FROM order_lines)  [ok]
   columns: ['order_id', 'line_no', 'sku', 'qty']
   [1, 1, 'DEMO-1002', 14]
   ...
   truncated: True

> attack: SELECT 1; DROP TABLE orders  [ERROR]
   Error executing tool run_select: Query rejected: only one statement is allowed

> attack: WITH x AS (SELECT 1) DELETE FROM orders  [ERROR]
   Error executing tool run_select: Query rejected: forbidden keyword: DELETE

> attack: WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c  [ERROR]
   Error executing tool run_select: Query timed out: query exceeded 1.0 s

> request with a wrong token
   refused by the server (HTTP 401): ExceptionGroup

=== new in this round: roles, masks, pagination, explain, samples, rate limits ===

> [admin] page 2 (same sql + next_cursor)  [ok]
   columns: ['order_id', 'line_no', 'sku']
   [3, 3, 'DEMO-3002']
   ...
   truncated: True

> [admin] explain_query (plan only, the query does not run)  [ok]
   SEARCH orders USING INTEGER PRIMARY KEY (rowid=?)

> [analyst] mask attack: alias, expression, WHERE  [ok]
   columns: ['n', 'count(*)']
   [None, 8]
   truncated: False

> [analyst] mask attack: through the order_totals view  [ok]
   columns: ['customer']
   [None]
   truncated: False

> [catalog] allowlist attack: CTE named like an allowed table  [ERROR]
   Error executing tool run_select: Access denied: the query reads a table or column this role may not read, or a table that does not exist

> [catalog] rate limit 5 calls/minute
   call 5: ok
   call 6: refused: Error executing tool run_select: Rate limit: more than 5 calls per minute for this token

> python -m readonly_sql_mcp.audit_summary audit.log
files: 1  events: 28  unreadable lines: 0
tool calls: 26  ok 15, rejected 5, rate_limited 3, denied 2, timeout 1
by token:
  demo-admin      ok 8, rejected 5, timeout 1
  demo-analyst    ok 4
  demo-catalog    ok 3, rate_limited 3, denied 2
auth failures: 2  127.0.0.1 2
```

## Tools

| Tool | Input | Returns |
|---|---|---|
| `list_tables` | none | the table and view names this token may read |
| `describe_table` | `table` | column, type, nullable, primary key, and `mask` for a masked column |
| `run_select` | `sql`, optional `cursor` | `columns`, `rows`, `truncated`, `next_cursor` |
| `explain_query` | `sql` | `plan`: the query plan steps; the query does not run |
| `sample_rows` | `table`, `n` (1-20, default 5) | the first `n` rows, masks applied |

| Resource | Returns |
|---|---|
| `schema://summary` | JSON: the role, and each table this token may read with its columns, types and masks |

## Safety layers

| # | Layer | Where | What it stops |
|---|---|---|---|
| 1 | SELECT-only validator | `validator.py` | stacked statements, comments, CTE writes (`WITH ... DELETE`), `PRAGMA`, `ATTACH`, `SELECT INTO`, `EXEC`, `xp_` procedures, unterminated quotes |
| 2 | Read-only connection | `backends.py` | SQLite opens with `mode=ro` and `PRAGMA query_only=ON`; SQL Server uses `readonly=True` and `ApplicationIntent=ReadOnly` |
| 3 | SQLite authorizer | `backends.py` | every action except SELECT/READ/FUNCTION is denied at compile time, plus `load_extension` and reads from attached or temp databases |
| 4 | Row limit | `backends.py` | fetches `max_rows + 1`, returns `max_rows`, sets `truncated` |
| 5 | Query timeout | `backends.py` | SQLite progress handler aborts past the deadline; SQL Server uses the per-statement timeout |
| - | Bearer token | `server.py` | ASGI middleware; the token's SHA-256 is compared in constant time with every known hash; 401 without a valid token |
| - | Table allowlist | `backends.py` | the SQLite authorizer denies a read of any table outside the role, also inside views, CTEs and subqueries |
| - | Column masks | `backends.py` | the SQLite authorizer turns a masked column into NULL, or refuses the query |
| - | Rate limit | `access.py` | sliding one-minute window per token |
| - | Audit log | `server.py` | one JSON line per tool call (token name, role, tool, SQL, outcome, ms, row count) and per failed login; the token is never written; the file rotates |

The tests attack layer 1 through the MCP tool, and attack layers 2-5 directly with the validator bypassed,
so each layer is shown to hold on its own.

## Tokens and roles

Set `SQLMCP_ACCESS_FILE` to a JSON file with roles and tokens. The file holds only the SHA-256 of each token,
so a leaked copy of the file does not leak a token. `config/access.example.json`:

```json
{
  "roles": {
    "admin":   {"tables": "*"},
    "analyst": {"tables": ["customers", "orders", "order_lines", "products", "order_totals"],
                "masks": {"customers.name": "null"}, "rate_per_minute": 60},
    "catalog": {"tables": ["products"], "masks": {"products.unit_price": "deny"}, "rate_per_minute": 10}
  },
  "tokens": [
    {"name": "report-bot", "role": "analyst", "sha256": "4fa081c7..."},
    {"name": "price-widget", "role": "catalog", "sha256": "a96a2dfd...", "rate_per_minute": 5}
  ]
}
```

- `tables` is `"*"` or a list. Names are not case sensitive.
- A view is a table for the allowlist. To use a view, list the view and every table it reads.
- `python -m readonly_sql_mcp.access new --name NAME --role ROLE` prints a random token once and the entry
  to paste. The server never stores or logs the token.
- The server refuses to start if the file has an unknown role, a bad hash, a repeated name or hash, or a bad mask.
- Without `SQLMCP_ACCESS_FILE`, `SQLMCP_TOKEN` works as before: one token, role `full`, all tables.

## Column masks

A mask is `"table.column": "null"` or `"table.column": "deny"`.

- `null`: the database reads the column as NULL. This holds everywhere in the query: the select list, aliases,
  expressions, `WHERE`, `ORDER BY`, `GROUP BY`, joins, CTEs, subqueries and views. So `WHERE name LIKE 'A%'`
  matches nothing and cannot be used to guess values.
- `deny`: any query that touches the column fails with "Access denied", also `SELECT *`.

Why it cannot be bypassed: the check is not on the SQL text. SQLite calls the authorizer for every column it
reads while it compiles the statement, with the real table and column name. An alias, an expression or a view
does not change that name. `tests/test_attacks.py` runs 58 bypass attempts (aliases, `upper()`, `hex()`,
`CAST AS BLOB`, `json_object`, `group_concat`, `UNION`, CTEs, views, `rowid` of a masked key, `LIKE` and
`CASE` inference, CTEs named like an allowed table, `sqlite_schema`, `pragma_table_info`, `temp.`, `dbstat`)
against the backend with no validator and again through the MCP tools.

One attack found during this work: SQLite passes the name of a CTE in the same argument as the name of a view.
An early version trusted that argument to let a listed view read its base tables, so
`WITH order_totals AS (SELECT name FROM customers) SELECT * FROM order_totals` got through. The authorizer now
checks the real table of every read and ignores the view argument. The test for it stays in the suite.

## Pagination

When `truncated` is true, `run_select` returns `next_cursor`. Call `run_select` again with the same `sql` and
`cursor=next_cursor` for the next page. The cursor is opaque and signed with HMAC-SHA-256. It is bound to the
SQL text and the token name, so it does not work with other SQL, with another token, or after an edit.
The server skips the rows of earlier pages, so a page costs the read of all rows before it. Use `ORDER BY`
for a stable order. Cursors stop working when the server restarts (the key is random per process).

## explain_query, sample_rows and schema://summary

- `explain_query` validates the SQL like `run_select`, then runs `EXPLAIN QUERY PLAN`. SQLite compiles the
  statement but does not run it, so a query that would never end returns its plan at once. The allowlist and
  the masks apply at compile time, so a forbidden query cannot be explained either.
- `sample_rows` reads the first `n` rows (1-20) of one table. The name must match a listed table exactly
  (any case); the server then quotes it, so a name cannot carry SQL.
- `schema://summary` gives a model the whole allowed schema in one read.

## Audit log rotation and summary

The audit file rotates at `SQLMCP_AUDIT_MAX_BYTES` and keeps `SQLMCP_AUDIT_BACKUPS` old files
(`audit.log.1` is the newest). Summarize the log and its old files:

```
.venv\Scripts\python -m readonly_sql_mcp.audit_summary audit.log
.venv\Scripts\python -m readonly_sql_mcp.audit_summary audit.log --json
```

It prints the outcome counts, calls and p50/p95 time per tool, outcomes per token, failed logins per client,
and the five most common errors.

## Configuration (environment variables)

| Variable | Default | Meaning |
|---|---|---|
| `SQLMCP_ACCESS_FILE` | (none) | access file with roles and token hashes; when set, `SQLMCP_TOKEN` is not used |
| `SQLMCP_TOKEN` | (required without an access file) | one full-access bearer token, 16+ characters |
| `SQLMCP_RATE_PER_MINUTE` | `0` (no limit) | default calls per minute per token, when the role or token sets none |
| `SQLMCP_DB_URL` | `sqlite:///data/demo.db` | backend URL |
| `SQLMCP_MAX_ROWS` | `200` | row limit per query |
| `SQLMCP_TIMEOUT_S` | `5` | query time limit, seconds |
| `SQLMCP_AUDIT_LOG` | `audit.log` | audit file path |
| `SQLMCP_AUDIT_MAX_BYTES` | `5000000` | rotate at this size; `0` turns rotation off |
| `SQLMCP_AUDIT_BACKUPS` | `5` | number of old audit files to keep |
| `SQLMCP_HOST` / `SQLMCP_PORT` | `127.0.0.1` / `8765` | listen address |

## Optional: SQL Server

`SqlServerBackend` in `backends.py` uses pyodbc (`pip install pyodbc`) and the Microsoft ODBC driver:

```
set SQLMCP_DB_URL=mssql+odbc://Driver={ODBC Driver 18 for SQL Server};Server=myhost;Database=mydb;UID=reader;PWD=...;Encrypt=yes
```

Use a login that is only in `db_datareader`. The database permission is the real guard; the validator and
the read-only connection flags are extra layers. SQL Server has no equivalent of the SQLite authorizer, so the
SQL Server backend refuses a role with a table list or masks (it fails closed). Use database permissions,
views or Dynamic Data Masking there, and give the token a role with `"tables": "*"`. `explain_query` is not
available for SQL Server.

## Design notes

- The validator does not parse SQL. It blanks out string literals and quoted identifiers, then applies plain
  rules: one statement, no comments, first word `SELECT` or `WITH`, no forbidden keyword. It prefers a false
  reject over a false accept. `REPLACE(...)` the string function is allowed; `REPLACE` the statement is not.
- The backend is a small class with three methods. Add a backend by writing one class and a URL prefix in
  `make_backend`.
- Transport is stateless streamable HTTP with JSON responses, which suits a load balancer or an API gateway.
- Built on the official `mcp` Python SDK 2.x (`mcp.server.mcpserver.MCPServer`).
- The bearer middleware finds the caller and puts it in a `contextvars.ContextVar` for the request. Every tool
  and the resource read the caller from there. An HTTP request with no valid caller never reaches a tool.
- Token hashes are plain SHA-256, not a slow password hash. That is enough for random tokens of 32 bytes made
  by the `access new` command; it is not enough for short tokens that people choose.
- Errors for a forbidden table and a missing table are the same, so a restricted token cannot probe which
  tables exist.

## Limits

- Tokens are static. There is no expiry, no OAuth and no revocation list; remove the entry and restart.
- Rate limits are in memory, per process. Several server processes each count on their own.
- Allowlists and masks are enforced only on SQLite. Mask `null` changes the value to NULL, not to a partial
  value such as the last four digits.
- Pagination re-runs the query for each page. Data that changes between pages can shift rows.
- The allowlist and masks rely on SQLite reporting every read to the authorizer. The tests show this for the
  bundled SQLite (3.50); run them again after you change the Python or SQLite version.
- The keyword deny-list blocks some legal reads, for example a column named `set` that is not quoted.
- A read can still be expensive. Row limits and timeouts bound cost. Masks protect the columns you list,
  and no others; also restrict what the database login can see.
- The SQL Server backend is not covered by the automated tests.
- No TLS in the server. Run it behind a TLS proxy outside localhost.

## Tests

```
.venv\Scripts\python -m unittest discover -s tests -t .
```

## License

MIT. See `LICENSE`.