Metadata-Version: 2.4
Name: groundsql
Version: 0.2.1
Summary: Schema-grounded, read-only Text-to-SQL agent for SQLite and PostgreSQL: repair loop, layered SQL safety, execution-accuracy evals (incl. Spider), MCP server.
Author-email: Aryan Sinha <aryan.sinha1212@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/aryansinha16/groundsql
Project-URL: Issues, https://github.com/aryansinha16/groundsql/issues
Keywords: text-to-sql,llm,agents,mcp,sqlite,postgresql,evals,spider
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
Dynamic: license-file

# groundsql

[![tests](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml/badge.svg)](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml)

**Ask a SQLite or PostgreSQL database questions in plain English, safely.** A schema-grounded Text-to-SQL agent with a repair loop, layered read-only safety, execution-accuracy evals (including the Spider benchmark), and an MCP server for Claude, Cursor or any MCP client.

**79% execution accuracy on a 100-question sample of Spider dev** with `gpt-oss-120b`, and 15/15 on the built-in eval on both SQLite and PostgreSQL ([results](#evals)).

Zero runtime dependencies for SQLite: standard library only, any LLM (Ollama, Groq, OpenAI-compatible, Anthropic) over plain HTTP. PostgreSQL adds `psycopg`.

```
$ groundsql ask --db shop.db --model ollama:llama3.2:1b "How many customers are based in India?"
SELECT COUNT(*)
FROM customers AS T1
WHERE country = 'India'

COUNT(*)
--------
98
```

## Why

Text-to-SQL demos break in production in three predictable ways. Each one has a mechanism here:

| Failure | What groundsql does |
|---|---|
| The model invents tables or columns | **Schema grounding**: the prompt holds only the relevant tables (matched on table names, column names *and sample values*), plus their foreign-key neighbours so join paths stay visible. Low-cardinality text columns list *every* value (`status TEXT -- one of 'delivered', 'shipped', ...`), so the model never guesses a spelling |
| The query is wrong but plausible | **Repair loop**: the database compiles the query with `EXPLAIN` before it runs, and the exact error (`no such column: revenue`) goes back to the model. If retrieval missed a table, the repair turn gets the full schema |
| The query is dangerous | **Four independent safety gates** (below). Writes are impossible, not just discouraged |

And one rule from running this kind of system for real: **the model writes SQL, the database computes every number.** The answer is the result set, never a model-written summary of it, so totals can't be hallucinated.

## Safety gates

Every query passes all four:

1. **Static check**: exactly one statement, starting `SELECT`/`WITH`, no write/DDL keywords outside string literals (`SELECT 'drop table'` is fine, `SELECT 1; DROP TABLE x` is not). Comments and literals are parsed in one pass, so `--` inside a string is text, not a comment
2. **Read-only connection**: `mode=ro`, so SQLite itself refuses writes
3. **Authorizer callback**: only read actions are allowed, even if something slipped past gate 1
4. **Compile before run**: `EXPLAIN` validates names first; execution then has a wall-clock timeout (a runaway recursive CTE is killed), a row cap, and on SQLite a 10 MB cap on any single value (so `SELECT randomblob(1e9)` fails instead of allocating a gigabyte)

The tests bypass gate 1 deliberately to prove gates 2 and 3 still hold.

On **PostgreSQL** the same four, in Postgres terms: the static check plus a blocklist of side-effecting functions a read-only transaction would still allow (`pg_sleep`, `pg_terminate_backend`, `pg_read_file`, `dblink`, `set_config`, `nextval`...); a session with `default_transaction_read_only=on` and every query in a transaction that is always rolled back; `statement_timeout` on the server; and `EXPLAIN` first. For defence in depth, connect as a role that only has `SELECT`.

## Quick start

```bash
pip install -e .                         # or: pip install -e ".[postgres]"
groundsql sample shop.db                 # deterministic 6-table retail database

# any of these model specs work
groundsql ask --db shop.db --model ollama:llama3.2 "How many orders were cancelled?"
groundsql ask --db shop.db --model groq:openai/gpt-oss-120b "Revenue per category for delivered orders"
groundsql ask --db shop.db --model anthropic:claude-sonnet-4-6 "Top 3 most returned products" --json

groundsql sql    --db shop.db "SELECT channel, COUNT(*) FROM orders GROUP BY channel"   # safety gates, no LLM
groundsql schema --db shop.db "revenue from Footwear"                                   # what the model will see

# PostgreSQL: any --db that is a postgresql:// URL
groundsql sample --postgres postgresql://admin@localhost/shop   # load the same data (needs CREATE)
groundsql ask --db postgresql://readonly@localhost/shop "How many orders were cancelled?"
```

Keys come from `GROQ_API_KEY`, `OPENAI_API_KEY` (+ optional `OPENAI_BASE_URL`), `ANTHROPIC_API_KEY`; Ollama needs none. A `.env` file in the working directory is read too (git-ignored), and shell variables win over it. Rate limits (HTTP 429/5xx) are retried with backoff.

## MCP server

```bash
groundsql serve --db shop.db                          # tools: list_tables, describe_table, run_sql
groundsql serve --db shop.db --model ollama:llama3.2  # + ask
```

Claude Desktop / Claude Code config:

```json
{
  "mcpServers": {
    "shop-db": { "command": "groundsql", "args": ["serve", "--db", "/path/to/shop.db"] }
  }
}
```

The server is a small, dependency-free JSON-RPC 2.0 implementation of the MCP stdio transport (`initialize`, `tools/list`, `tools/call`, `ping`). `run_sql` goes through the same four safety gates, so an MCP client can't write to the database either.

## Evals

Scoring everywhere is **execution accuracy**: does the agent's result set equal the gold query's result set? Row order and float noise are ignored, and extra columns are allowed (returning `city, count` when only `city` was asked still passes). Every number below comes from a JSON report in [`evals/results/`](evals/results) with the exact SQL the model wrote for each question. Models ran at temperature 0, with the default 2 repairs unless noted.

### Spider (cross-domain, unseen schemas)

[Spider](https://yale-lily.github.io/spider) dev uses 20 databases that no training question touched, so it measures how well the agent copes with a schema it has never seen. `groundsql spider` downloads a checksum-pinned copy once (about 206 MB, CC BY-SA 4.0, not shipped in this repo) and samples questions with a fixed seed.

```bash
groundsql spider --n 100 --seed 0 --model groq:openai/gpt-oss-120b --out evals/results/spider-dev-100-gpt-oss-120b.json
```

100 questions over 19 databases (seed 0):

| Model | Execution accuracy | Valid SQL | single-table | join | nested / set ops |
|---|---|---|---|---|---|
| `gpt-oss-120b` (Groq) | **79%** | 100% | 40/45 | 27/40 | 12/15 |
| `gpt-oss-120b`, `--repairs 0` | 76% | 100% | 38/45 | 26/40 | 12/15 |
| Llama 3.2 1B (Ollama, laptop) | 35% | 62% | 24/45 | 11/40 | 0/15 |

How to read this, honestly:

- **The big model never needed a repair**: every first query compiled. The 79% vs 76% gap is run-to-run variation of a hosted model, not the repair loop. The repair loop earns its keep on small models: 9 of Llama 1B's 100 questions went through a repair, and 5 of those then passed.
- **Joins look like the weak spot (27/40), but most of those misses are not wrong SQL.** I read all 13 by hand and checked the data:

  | Why it was scored wrong | Count | Example |
  |---|---|---|
  | The gold answer is wrong | 2 | `flight_2`: cities are stored as `'Aberdeen '` (trailing space), so the gold `City = "Aberdeen"` returns 0 flights; the agent matched the real value |
  | A tie under `LIMIT 1` | 3 | `orchestra`: every conductor leads exactly one orchestra, so "the conductor with the most" is any of them |
  | A defensible reading that differs from the benchmark's | 7 | `LEFT JOIN` keeps shops with 0 employees; in `car_1`, `Model` holds the brand (`'ford'`) and `Make` holds the model (`'ford pinto'`) |
  | A real mistake | 1 | `student_transcripts_tracking`: counted per student and semester instead of per student |

  I tried prompt rules aimed at these conventions (inner joins by default, prefer the column named in the question). Accuracy stayed at 79% on this sample and on a fresh held-out sample (seed 1, 79% before and after), and the model ignored the rules. So that change was not shipped.
- **This is a sample, not the official leaderboard.** It is 100 of 1,034 dev questions, the difficulty buckets come from the gold SQL's shape (not Spider's official hardness), and the comparison is order-insensitive, which is a little more lenient than Spider's official evaluator for `ORDER BY` questions. Run `--n 0` for the full dev set.

### Built-in eval (sample retail database)

`groundsql/data/questions.jsonl` has 15 questions (easy / medium / hard: filters, joins, multi-hop aggregates, anti-joins) with gold SQL, run against the deterministic sample database.

```bash
groundsql eval --db shop.db --model groq:openai/gpt-oss-120b
groundsql eval --db postgresql://localhost/shop --model groq:openai/gpt-oss-120b   # same questions on Postgres
```

| Model | Database | Execution accuracy | Valid SQL | easy | medium | hard |
|---|---|---|---|---|---|---|
| `gpt-oss-120b` | SQLite | **100%** | 100% | 4/4 | 6/6 | 5/5 |
| `gpt-oss-120b` | PostgreSQL 18 | **100%** | 100% | 4/4 | 6/6 | 5/5 |
| Llama 3.2 1B | SQLite | 33% | 53% | 3/4 | 1/6 | 1/5 |
| Llama 3.2 1B, `--repairs 0` | SQLite | 33% | 40% | 3/4 | 1/6 | 1/5 |

The PostgreSQL row found a real grounding bug. With three arbitrary sample values per column, Postgres happened to show `status` as `'cancelled', 'shipped', 'processing'`, so the model filtered "delivered" orders on `'shipped'` and scored 80%. Now low-cardinality columns list every value, most common first, and both databases score 15/15. The 1B model went from 40% to 33% between versions; at that size, small prompt changes move single questions either way.

Two eval design choices worth copying: questions with a `LIMIT 1` answer also ask for the count, so a wrong query can't pass by landing on the same top row; and no gold answer is zero, so a wrong filter can't pass by accident.

## Layout

```
groundsql/
  schema.py      introspection, sample values, table retrieval + FK expansion
  db.py          SQLite backend, the shared static check, open_database()
  postgres.py    PostgreSQL backend: read-only session, function blocklist, statement_timeout
  agent.py       dialect-aware prompt, SQL extraction, repair loop, CANNOT_ANSWER handling
  llm.py         Ollama / Groq / OpenAI-compatible / Anthropic over urllib, retries, + Scripted for tests
  mcp_server.py  MCP stdio server
  evals.py       execution-accuracy scoring
  spider.py      Spider download (checksum-pinned), sampling, scoring
  sample.py      deterministic sample database, SQLite or PostgreSQL
tests/           55 tests: safety gates, retrieval, repair loop, evals, Spider runner, MCP over a
                 real subprocess; the 15 PostgreSQL tests run against a real server in CI
```

```bash
pip install -e ".[dev]" && pytest -q
GROUNDSQL_TEST_PG=postgresql://postgres@localhost/postgres pytest -q   # include PostgreSQL
```

## License

MIT
