groundsql
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).
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:
- Static check: exactly one statement, starting
SELECT/WITH, no write/DDL keywords outside string literals (SELECT 'drop table'is fine,SELECT 1; DROP TABLE xis not). Comments and literals are parsed in one pass, so--inside a string is text, not a comment - Read-only connection:
mode=ro, so SQLite itself refuses writes - Authorizer callback: only read actions are allowed, even if something slipped past gate 1
- Compile before run:
EXPLAINvalidates 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 (soSELECT 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
pip install groundsql # or: pip install "groundsql[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
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:
{
"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/ 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 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.
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 goldCity = "Aberdeen"returns 0 flights; the agent matched the real valueA tie under LIMIT 13 orchestra: every conductor leads exactly one orchestra, so "the conductor with the most" is any of themA defensible reading that differs from the benchmark's 7 LEFT JOINkeeps shops with 0 employees; incar_1,Modelholds the brand ('ford') andMakeholds the model ('ford pinto')A real mistake 1 student_transcripts_tracking: counted per student and semester instead of per studentI 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 BYquestions. Run--n 0for 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.
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
pip install -e ".[dev]" && pytest -q
GROUNDSQL_TEST_PG=postgresql://postgres@localhost/postgres pytest -q # include PostgreSQL
License
MIT
Metadata
Release files for groundsql 0.2.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| groundsql-0.2.2.tar.gz | 39.0 kB | With provenance | Details for groundsql-0.2.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| groundsql-0.2.2-py3-none-any.whl | Python 3 | none | any | Details for groundsql-0.2.2-py3-none-any.whl |
Total release size: 73.0 kB
Release files / groundsql-0.2.2.tar.gz
| Download URL | groundsql-0.2.2.tar.gz |
|---|---|
| Size | 39.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5d339756b761288b72cd92c021afa3c527e94754ac8b3ff693d732231b9415a7
|
|
BLAKE2b-256 checksum How to use checksums |
dfa6aae70850c858d94c4074f06a5d58de38b3485878a715a3e6176ee46d8c15
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / groundsql-0.2.2-py3-none-any.whl
| Download URL | groundsql-0.2.2-py3-none-any.whl |
|---|---|
| Size | 34.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2e914281877caf33f2c67b082d1fec3334f9dff3fb21bae95e9dc14a485a2b85
|
|
BLAKE2b-256 checksum How to use checksums |
ce5a04ac7e05be4a2d1b5e37d30f5bba6d9d4c61cc54a0f075a4921973956e28
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for groundsql 0.2.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for groundsql-0.2.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.