groundsql 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aryan Sinha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: groundsql
3
+ Version: 0.2.1
4
+ 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.
5
+ Author-email: Aryan Sinha <aryan.sinha1212@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/aryansinha16/groundsql
8
+ Project-URL: Issues, https://github.com/aryansinha16/groundsql/issues
9
+ Keywords: text-to-sql,llm,agents,mcp,sqlite,postgresql,evals,spider
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: postgres
20
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7; extra == "dev"
23
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # groundsql
27
+
28
+ [![tests](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml/badge.svg)](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml)
29
+
30
+ **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.
31
+
32
+ **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)).
33
+
34
+ Zero runtime dependencies for SQLite: standard library only, any LLM (Ollama, Groq, OpenAI-compatible, Anthropic) over plain HTTP. PostgreSQL adds `psycopg`.
35
+
36
+ ```
37
+ $ groundsql ask --db shop.db --model ollama:llama3.2:1b "How many customers are based in India?"
38
+ SELECT COUNT(*)
39
+ FROM customers AS T1
40
+ WHERE country = 'India'
41
+
42
+ COUNT(*)
43
+ --------
44
+ 98
45
+ ```
46
+
47
+ ## Why
48
+
49
+ Text-to-SQL demos break in production in three predictable ways. Each one has a mechanism here:
50
+
51
+ | Failure | What groundsql does |
52
+ |---|---|
53
+ | 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 |
54
+ | 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 |
55
+ | The query is dangerous | **Four independent safety gates** (below). Writes are impossible, not just discouraged |
56
+
57
+ 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.
58
+
59
+ ## Safety gates
60
+
61
+ Every query passes all four:
62
+
63
+ 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
64
+ 2. **Read-only connection**: `mode=ro`, so SQLite itself refuses writes
65
+ 3. **Authorizer callback**: only read actions are allowed, even if something slipped past gate 1
66
+ 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)
67
+
68
+ The tests bypass gate 1 deliberately to prove gates 2 and 3 still hold.
69
+
70
+ 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`.
71
+
72
+ ## Quick start
73
+
74
+ ```bash
75
+ pip install -e . # or: pip install -e ".[postgres]"
76
+ groundsql sample shop.db # deterministic 6-table retail database
77
+
78
+ # any of these model specs work
79
+ groundsql ask --db shop.db --model ollama:llama3.2 "How many orders were cancelled?"
80
+ groundsql ask --db shop.db --model groq:openai/gpt-oss-120b "Revenue per category for delivered orders"
81
+ groundsql ask --db shop.db --model anthropic:claude-sonnet-4-6 "Top 3 most returned products" --json
82
+
83
+ groundsql sql --db shop.db "SELECT channel, COUNT(*) FROM orders GROUP BY channel" # safety gates, no LLM
84
+ groundsql schema --db shop.db "revenue from Footwear" # what the model will see
85
+
86
+ # PostgreSQL: any --db that is a postgresql:// URL
87
+ groundsql sample --postgres postgresql://admin@localhost/shop # load the same data (needs CREATE)
88
+ groundsql ask --db postgresql://readonly@localhost/shop "How many orders were cancelled?"
89
+ ```
90
+
91
+ 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.
92
+
93
+ ## MCP server
94
+
95
+ ```bash
96
+ groundsql serve --db shop.db # tools: list_tables, describe_table, run_sql
97
+ groundsql serve --db shop.db --model ollama:llama3.2 # + ask
98
+ ```
99
+
100
+ Claude Desktop / Claude Code config:
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "shop-db": { "command": "groundsql", "args": ["serve", "--db", "/path/to/shop.db"] }
106
+ }
107
+ }
108
+ ```
109
+
110
+ 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.
111
+
112
+ ## Evals
113
+
114
+ 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.
115
+
116
+ ### Spider (cross-domain, unseen schemas)
117
+
118
+ [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.
119
+
120
+ ```bash
121
+ groundsql spider --n 100 --seed 0 --model groq:openai/gpt-oss-120b --out evals/results/spider-dev-100-gpt-oss-120b.json
122
+ ```
123
+
124
+ 100 questions over 19 databases (seed 0):
125
+
126
+ | Model | Execution accuracy | Valid SQL | single-table | join | nested / set ops |
127
+ |---|---|---|---|---|---|
128
+ | `gpt-oss-120b` (Groq) | **79%** | 100% | 40/45 | 27/40 | 12/15 |
129
+ | `gpt-oss-120b`, `--repairs 0` | 76% | 100% | 38/45 | 26/40 | 12/15 |
130
+ | Llama 3.2 1B (Ollama, laptop) | 35% | 62% | 24/45 | 11/40 | 0/15 |
131
+
132
+ How to read this, honestly:
133
+
134
+ - **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.
135
+ - **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:
136
+
137
+ | Why it was scored wrong | Count | Example |
138
+ |---|---|---|
139
+ | 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 |
140
+ | A tie under `LIMIT 1` | 3 | `orchestra`: every conductor leads exactly one orchestra, so "the conductor with the most" is any of them |
141
+ | 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'`) |
142
+ | A real mistake | 1 | `student_transcripts_tracking`: counted per student and semester instead of per student |
143
+
144
+ 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.
145
+ - **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.
146
+
147
+ ### Built-in eval (sample retail database)
148
+
149
+ `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.
150
+
151
+ ```bash
152
+ groundsql eval --db shop.db --model groq:openai/gpt-oss-120b
153
+ groundsql eval --db postgresql://localhost/shop --model groq:openai/gpt-oss-120b # same questions on Postgres
154
+ ```
155
+
156
+ | Model | Database | Execution accuracy | Valid SQL | easy | medium | hard |
157
+ |---|---|---|---|---|---|---|
158
+ | `gpt-oss-120b` | SQLite | **100%** | 100% | 4/4 | 6/6 | 5/5 |
159
+ | `gpt-oss-120b` | PostgreSQL 18 | **100%** | 100% | 4/4 | 6/6 | 5/5 |
160
+ | Llama 3.2 1B | SQLite | 33% | 53% | 3/4 | 1/6 | 1/5 |
161
+ | Llama 3.2 1B, `--repairs 0` | SQLite | 33% | 40% | 3/4 | 1/6 | 1/5 |
162
+
163
+ 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.
164
+
165
+ 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.
166
+
167
+ ## Layout
168
+
169
+ ```
170
+ groundsql/
171
+ schema.py introspection, sample values, table retrieval + FK expansion
172
+ db.py SQLite backend, the shared static check, open_database()
173
+ postgres.py PostgreSQL backend: read-only session, function blocklist, statement_timeout
174
+ agent.py dialect-aware prompt, SQL extraction, repair loop, CANNOT_ANSWER handling
175
+ llm.py Ollama / Groq / OpenAI-compatible / Anthropic over urllib, retries, + Scripted for tests
176
+ mcp_server.py MCP stdio server
177
+ evals.py execution-accuracy scoring
178
+ spider.py Spider download (checksum-pinned), sampling, scoring
179
+ sample.py deterministic sample database, SQLite or PostgreSQL
180
+ tests/ 55 tests: safety gates, retrieval, repair loop, evals, Spider runner, MCP over a
181
+ real subprocess; the 15 PostgreSQL tests run against a real server in CI
182
+ ```
183
+
184
+ ```bash
185
+ pip install -e ".[dev]" && pytest -q
186
+ GROUNDSQL_TEST_PG=postgresql://postgres@localhost/postgres pytest -q # include PostgreSQL
187
+ ```
188
+
189
+ ## License
190
+
191
+ MIT
@@ -0,0 +1,166 @@
1
+ # groundsql
2
+
3
+ [![tests](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml/badge.svg)](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml)
4
+
5
+ **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.
6
+
7
+ **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)).
8
+
9
+ Zero runtime dependencies for SQLite: standard library only, any LLM (Ollama, Groq, OpenAI-compatible, Anthropic) over plain HTTP. PostgreSQL adds `psycopg`.
10
+
11
+ ```
12
+ $ groundsql ask --db shop.db --model ollama:llama3.2:1b "How many customers are based in India?"
13
+ SELECT COUNT(*)
14
+ FROM customers AS T1
15
+ WHERE country = 'India'
16
+
17
+ COUNT(*)
18
+ --------
19
+ 98
20
+ ```
21
+
22
+ ## Why
23
+
24
+ Text-to-SQL demos break in production in three predictable ways. Each one has a mechanism here:
25
+
26
+ | Failure | What groundsql does |
27
+ |---|---|
28
+ | 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 |
29
+ | 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 |
30
+ | The query is dangerous | **Four independent safety gates** (below). Writes are impossible, not just discouraged |
31
+
32
+ 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.
33
+
34
+ ## Safety gates
35
+
36
+ Every query passes all four:
37
+
38
+ 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
39
+ 2. **Read-only connection**: `mode=ro`, so SQLite itself refuses writes
40
+ 3. **Authorizer callback**: only read actions are allowed, even if something slipped past gate 1
41
+ 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)
42
+
43
+ The tests bypass gate 1 deliberately to prove gates 2 and 3 still hold.
44
+
45
+ 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`.
46
+
47
+ ## Quick start
48
+
49
+ ```bash
50
+ pip install -e . # or: pip install -e ".[postgres]"
51
+ groundsql sample shop.db # deterministic 6-table retail database
52
+
53
+ # any of these model specs work
54
+ groundsql ask --db shop.db --model ollama:llama3.2 "How many orders were cancelled?"
55
+ groundsql ask --db shop.db --model groq:openai/gpt-oss-120b "Revenue per category for delivered orders"
56
+ groundsql ask --db shop.db --model anthropic:claude-sonnet-4-6 "Top 3 most returned products" --json
57
+
58
+ groundsql sql --db shop.db "SELECT channel, COUNT(*) FROM orders GROUP BY channel" # safety gates, no LLM
59
+ groundsql schema --db shop.db "revenue from Footwear" # what the model will see
60
+
61
+ # PostgreSQL: any --db that is a postgresql:// URL
62
+ groundsql sample --postgres postgresql://admin@localhost/shop # load the same data (needs CREATE)
63
+ groundsql ask --db postgresql://readonly@localhost/shop "How many orders were cancelled?"
64
+ ```
65
+
66
+ 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.
67
+
68
+ ## MCP server
69
+
70
+ ```bash
71
+ groundsql serve --db shop.db # tools: list_tables, describe_table, run_sql
72
+ groundsql serve --db shop.db --model ollama:llama3.2 # + ask
73
+ ```
74
+
75
+ Claude Desktop / Claude Code config:
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "shop-db": { "command": "groundsql", "args": ["serve", "--db", "/path/to/shop.db"] }
81
+ }
82
+ }
83
+ ```
84
+
85
+ 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.
86
+
87
+ ## Evals
88
+
89
+ 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.
90
+
91
+ ### Spider (cross-domain, unseen schemas)
92
+
93
+ [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.
94
+
95
+ ```bash
96
+ groundsql spider --n 100 --seed 0 --model groq:openai/gpt-oss-120b --out evals/results/spider-dev-100-gpt-oss-120b.json
97
+ ```
98
+
99
+ 100 questions over 19 databases (seed 0):
100
+
101
+ | Model | Execution accuracy | Valid SQL | single-table | join | nested / set ops |
102
+ |---|---|---|---|---|---|
103
+ | `gpt-oss-120b` (Groq) | **79%** | 100% | 40/45 | 27/40 | 12/15 |
104
+ | `gpt-oss-120b`, `--repairs 0` | 76% | 100% | 38/45 | 26/40 | 12/15 |
105
+ | Llama 3.2 1B (Ollama, laptop) | 35% | 62% | 24/45 | 11/40 | 0/15 |
106
+
107
+ How to read this, honestly:
108
+
109
+ - **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.
110
+ - **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:
111
+
112
+ | Why it was scored wrong | Count | Example |
113
+ |---|---|---|
114
+ | 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 |
115
+ | A tie under `LIMIT 1` | 3 | `orchestra`: every conductor leads exactly one orchestra, so "the conductor with the most" is any of them |
116
+ | 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'`) |
117
+ | A real mistake | 1 | `student_transcripts_tracking`: counted per student and semester instead of per student |
118
+
119
+ 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.
120
+ - **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.
121
+
122
+ ### Built-in eval (sample retail database)
123
+
124
+ `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.
125
+
126
+ ```bash
127
+ groundsql eval --db shop.db --model groq:openai/gpt-oss-120b
128
+ groundsql eval --db postgresql://localhost/shop --model groq:openai/gpt-oss-120b # same questions on Postgres
129
+ ```
130
+
131
+ | Model | Database | Execution accuracy | Valid SQL | easy | medium | hard |
132
+ |---|---|---|---|---|---|---|
133
+ | `gpt-oss-120b` | SQLite | **100%** | 100% | 4/4 | 6/6 | 5/5 |
134
+ | `gpt-oss-120b` | PostgreSQL 18 | **100%** | 100% | 4/4 | 6/6 | 5/5 |
135
+ | Llama 3.2 1B | SQLite | 33% | 53% | 3/4 | 1/6 | 1/5 |
136
+ | Llama 3.2 1B, `--repairs 0` | SQLite | 33% | 40% | 3/4 | 1/6 | 1/5 |
137
+
138
+ 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.
139
+
140
+ 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.
141
+
142
+ ## Layout
143
+
144
+ ```
145
+ groundsql/
146
+ schema.py introspection, sample values, table retrieval + FK expansion
147
+ db.py SQLite backend, the shared static check, open_database()
148
+ postgres.py PostgreSQL backend: read-only session, function blocklist, statement_timeout
149
+ agent.py dialect-aware prompt, SQL extraction, repair loop, CANNOT_ANSWER handling
150
+ llm.py Ollama / Groq / OpenAI-compatible / Anthropic over urllib, retries, + Scripted for tests
151
+ mcp_server.py MCP stdio server
152
+ evals.py execution-accuracy scoring
153
+ spider.py Spider download (checksum-pinned), sampling, scoring
154
+ sample.py deterministic sample database, SQLite or PostgreSQL
155
+ tests/ 55 tests: safety gates, retrieval, repair loop, evals, Spider runner, MCP over a
156
+ real subprocess; the 15 PostgreSQL tests run against a real server in CI
157
+ ```
158
+
159
+ ```bash
160
+ pip install -e ".[dev]" && pytest -q
161
+ GROUNDSQL_TEST_PG=postgresql://postgres@localhost/postgres pytest -q # include PostgreSQL
162
+ ```
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,13 @@
1
+ """groundsql: schema-grounded, read-only Text-to-SQL agent with an MCP server."""
2
+
3
+ __version__ = "0.2.1"
4
+
5
+ from .agent import Agent, Answer, format_table # noqa: E402
6
+ from .db import ( # noqa: E402
7
+ BaseDatabase, Database, InvalidSQL, SQLError, SQLiteDatabase, UnsafeSQL, open_database,
8
+ )
9
+
10
+ __all__ = [
11
+ "Agent", "Answer", "BaseDatabase", "Database", "InvalidSQL", "SQLError", "SQLiteDatabase",
12
+ "UnsafeSQL", "format_table", "open_database",
13
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,147 @@
1
+ """Question -> SQL -> rows, with schema grounding and a bounded repair loop.
2
+
3
+ Design rule: the model writes SQL, the database computes every number. The answer is
4
+ the result set itself, never a model-written summary of it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import time
11
+ from dataclasses import dataclass, field
12
+
13
+ from .db import BaseDatabase, Result, SQLError
14
+ from .llm import LLM
15
+
16
+ SYSTEM_PROMPT = """You translate a question into ONE {dialect} query.
17
+
18
+ Rules:
19
+ - Use only the tables and columns in the schema you are given. Never invent names.
20
+ - Read-only: a single SELECT (CTEs allowed). No INSERT/UPDATE/DELETE/DDL/PRAGMA.
21
+ - Match text values exactly as they appear in the schema samples.
22
+ - Give computed columns short descriptive aliases.
23
+ - Prefer explicit JOIN ... ON using the listed foreign keys.
24
+ - If the question cannot be answered from this schema, reply with exactly: CANNOT_ANSWER
25
+
26
+ Reply with the query in a ```sql code block and nothing else."""
27
+
28
+ _FENCE = re.compile(r"```(?:sql|sqlite)?\s*(.*?)```", re.DOTALL | re.IGNORECASE)
29
+ _BARE = re.compile(r"\b(SELECT|WITH)\b.*", re.DOTALL | re.IGNORECASE)
30
+
31
+
32
+ def extract_sql(text: str) -> str | None:
33
+ """Pull the query out of a model reply. Returns None for CANNOT_ANSWER."""
34
+ if "CANNOT_ANSWER" in text:
35
+ return None
36
+ m = _FENCE.search(text)
37
+ if m:
38
+ return m.group(1).strip()
39
+ m = _BARE.search(text)
40
+ return m.group(0).strip() if m else text.strip()
41
+
42
+
43
+ @dataclass
44
+ class Attempt:
45
+ sql: str | None
46
+ error: str | None
47
+
48
+
49
+ @dataclass
50
+ class Answer:
51
+ question: str
52
+ result: Result | None
53
+ attempts: list[Attempt] = field(default_factory=list)
54
+ tables_shown: list[str] = field(default_factory=list)
55
+ elapsed_ms: float = 0.0
56
+ error: str | None = None
57
+
58
+ @property
59
+ def ok(self) -> bool:
60
+ return self.result is not None
61
+
62
+ @property
63
+ def sql(self) -> str | None:
64
+ return self.result.sql if self.result else None
65
+
66
+ def as_dict(self) -> dict:
67
+ r = self.result
68
+ return {
69
+ "question": self.question,
70
+ "ok": self.ok,
71
+ "sql": self.sql,
72
+ "columns": r.columns if r else [],
73
+ "rows": [list(row) for row in r.rows] if r else [],
74
+ "truncated": r.truncated if r else False,
75
+ "attempts": [a.__dict__ for a in self.attempts],
76
+ "tables_shown": self.tables_shown,
77
+ "elapsed_ms": round(self.elapsed_ms, 1),
78
+ "error": self.error,
79
+ }
80
+
81
+
82
+ class AgentError(RuntimeError):
83
+ pass
84
+
85
+
86
+ class Agent:
87
+ def __init__(self, db: BaseDatabase, llm: LLM, max_repairs: int = 2, top_k: int = 4):
88
+ self.db = db
89
+ self.llm = llm
90
+ self.max_repairs = max_repairs
91
+ self.top_k = top_k
92
+
93
+ def ask(self, question: str) -> Answer:
94
+ start = time.perf_counter()
95
+ tables = self.db.relevant_tables(question, self.top_k)
96
+ shown = {t.name for t in tables}
97
+ answer = Answer(question=question, result=None, tables_shown=sorted(shown))
98
+ messages = [{
99
+ "role": "user",
100
+ "content": f"Schema:\n{self.db.schema_text(tables)}\n\nQuestion: {question}",
101
+ }]
102
+
103
+ for _ in range(self.max_repairs + 1):
104
+ reply = self.llm.complete(SYSTEM_PROMPT.format(dialect=self.db.dialect), messages)
105
+ sql = extract_sql(reply)
106
+ if sql is None:
107
+ answer.attempts.append(Attempt(sql=None, error="model said CANNOT_ANSWER"))
108
+ answer.error = "the model could not answer this from the schema"
109
+ break
110
+ try:
111
+ answer.result = self.db.run(sql)
112
+ answer.attempts.append(Attempt(sql=answer.result.sql, error=None))
113
+ break
114
+ except SQLError as e:
115
+ answer.attempts.append(Attempt(sql=sql, error=str(e)))
116
+ feedback = f"That query failed: {e}\nFix it and reply with the corrected query."
117
+ # Retrieval can miss a table; on a 'no such table/column' error,
118
+ # show the full schema so the repair has what it needs.
119
+ if "no such" in str(e) and len(shown) < len(self.db.tables):
120
+ shown = set(self.db.tables)
121
+ answer.tables_shown = sorted(shown)
122
+ feedback += f"\n\nFull schema:\n{self.db.schema_text()}"
123
+ messages += [
124
+ {"role": "assistant", "content": reply},
125
+ {"role": "user", "content": feedback},
126
+ ]
127
+ else:
128
+ answer.error = f"no valid query after {len(answer.attempts)} attempts"
129
+
130
+ answer.elapsed_ms = (time.perf_counter() - start) * 1000
131
+ return answer
132
+
133
+
134
+ def format_table(result: Result, max_width: int = 40) -> str:
135
+ """Plain-text table for terminals."""
136
+ def cell(v) -> str:
137
+ s = "NULL" if v is None else (f"{v:,.2f}" if isinstance(v, float) else str(v))
138
+ return s if len(s) <= max_width else s[: max_width - 1] + "…"
139
+
140
+ header = [cell(c) for c in result.columns]
141
+ body = [[cell(v) for v in row] for row in result.rows]
142
+ widths = [max(len(r[i]) for r in [header, *body]) for i in range(len(header))]
143
+ line = lambda r: " ".join(v.ljust(w) for v, w in zip(r, widths)) # noqa: E731
144
+ out = [line(header), " ".join("-" * w for w in widths), *map(line, body)]
145
+ if result.truncated:
146
+ out.append(f"... truncated at {len(result.rows)} rows")
147
+ return "\n".join(out)