sql-agent-mcp 0.2.0__py3-none-any.whl
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.
- sql_agent/__init__.py +0 -0
- sql_agent/adapters.py +643 -0
- sql_agent/agent.py +239 -0
- sql_agent/cli.py +122 -0
- sql_agent/data/golden.yaml +483 -0
- sql_agent/db.py +213 -0
- sql_agent/evaluate.py +324 -0
- sql_agent/llm.py +58 -0
- sql_agent/mcp_server.py +391 -0
- sql_agent/schema.sql +66 -0
- sql_agent/sqlguard.py +167 -0
- sql_agent/tools.py +225 -0
- sql_agent/trace.py +175 -0
- sql_agent_mcp-0.2.0.dist-info/METADATA +654 -0
- sql_agent_mcp-0.2.0.dist-info/RECORD +18 -0
- sql_agent_mcp-0.2.0.dist-info/WHEEL +4 -0
- sql_agent_mcp-0.2.0.dist-info/entry_points.txt +3 -0
- sql_agent_mcp-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sql-agent-mcp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: An MCP server for natural-language SQL that measures whether its answers are right.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Nachodusan/sql-agent
|
|
6
|
+
Project-URL: Repository, https://github.com/Nachodusan/sql-agent
|
|
7
|
+
Project-URL: Issues, https://github.com/Nachodusan/sql-agent/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/Nachodusan/sql-agent/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Ignacio Duque Sandoval
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,llm-evaluation,mcp,postgresql,sqlite,text-to-sql
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Database
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Topic :: Software Development :: Testing
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: langchain-core>=0.3
|
|
26
|
+
Requires-Dist: langgraph>=0.2
|
|
27
|
+
Requires-Dist: mcp>=2.0
|
|
28
|
+
Requires-Dist: openai>=1.40
|
|
29
|
+
Requires-Dist: python-dotenv>=1.0
|
|
30
|
+
Requires-Dist: pyyaml>=6.0
|
|
31
|
+
Requires-Dist: rich>=13.7
|
|
32
|
+
Requires-Dist: sqlglot>=25.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
37
|
+
Provides-Extra: postgres
|
|
38
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
|
|
39
|
+
Description-Content-Type: text/markdown
|
|
40
|
+
|
|
41
|
+
<!-- mcp-name: io.github.Nachodusan/sql-agent -->
|
|
42
|
+
|
|
43
|
+
# sql-agent
|
|
44
|
+
|
|
45
|
+
[](https://github.com/Nachodusan/sql-agent/actions/workflows/tests.yml)
|
|
46
|
+
|
|
47
|
+
**An MCP server that answers questions about your SQL database, and measures
|
|
48
|
+
whether the answers are right.** SQLite and PostgreSQL, read-only.
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
uvx sql-agent-mcp --demo
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**Why it exists.** Of the thirteen unambiguous questions DeepSeek-V3 got wrong
|
|
55
|
+
on this project's golden set, **eleven were valid SQL**. No error, no NULL, no
|
|
56
|
+
empty result: a query that runs, a number that is wrong, and prose that is sure
|
|
57
|
+
of it. Reading the SQL does not catch that, and neither does asking the model.
|
|
58
|
+
So this server ships the two things that do:
|
|
59
|
+
|
|
60
|
+
- **`evaluate`** runs a golden set of *your* questions against *your* database
|
|
61
|
+
and grades the agent by executing its SQL and comparing the rows with a
|
|
62
|
+
hand-written reference. Not by reading the query, and not by asking a model.
|
|
63
|
+
- **`sql_was_executed`** separates the SQL that actually ran from SQL the model
|
|
64
|
+
only says it ran. Every `ask` returns both, with the rows and a trace of each
|
|
65
|
+
step's latency and cost.
|
|
66
|
+
|
|
67
|
+
<!-- demo: record it with `vhs demo/demo.tape`, commit demo/demo.gif, then uncomment the next line.
|
|
68
|
+

|
|
69
|
+
-->
|
|
70
|
+
|
|
71
|
+
> **Measured, not claimed.** On the bundled sample database, DeepSeek-V3 gets
|
|
72
|
+
> **17 of the 30 unambiguous cases right** — 18/34 overall, $0.07 for the run.
|
|
73
|
+
> A second run scored 19/30, and four cases flipped between the two, so read
|
|
74
|
+
> that as "a bit over half", not as a decimal.
|
|
75
|
+
> [The whole table is below](#current-numbers), failure by failure.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## Install
|
|
80
|
+
|
|
81
|
+
Nothing to install by hand: [`uvx`](https://docs.astral.sh/uv/) fetches and
|
|
82
|
+
runs it. Point your MCP client at `uvx sql-agent-mcp` and give it a database.
|
|
83
|
+
|
|
84
|
+
**Claude Code**
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
claude mcp add sql-agent \
|
|
88
|
+
--env SQL_AGENT_DSN=sqlite:///./shop.db \
|
|
89
|
+
--env OPENAI_API_KEY=sk-your-key \
|
|
90
|
+
-- uvx sql-agent-mcp
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**Claude Desktop** — `claude_desktop_config.json`
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"mcpServers": {
|
|
98
|
+
"sql-agent": {
|
|
99
|
+
"command": "uvx",
|
|
100
|
+
"args": ["sql-agent-mcp"],
|
|
101
|
+
"env": {
|
|
102
|
+
"SQL_AGENT_DSN": "sqlite:///./shop.db",
|
|
103
|
+
"OPENAI_API_KEY": "sk-your-key",
|
|
104
|
+
"OPENAI_BASE_URL": "https://api.deepinfra.com/v1/openai",
|
|
105
|
+
"SQL_AGENT_MODEL": "deepseek-ai/DeepSeek-V3"
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
**Cursor** — `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json`
|
|
113
|
+
|
|
114
|
+
```json
|
|
115
|
+
{
|
|
116
|
+
"mcpServers": {
|
|
117
|
+
"sql-agent": {
|
|
118
|
+
"command": "uvx",
|
|
119
|
+
"args": ["sql-agent-mcp"],
|
|
120
|
+
"env": {
|
|
121
|
+
"SQL_AGENT_DSN": "sqlite:///./shop.db",
|
|
122
|
+
"OPENAI_API_KEY": "sk-your-key",
|
|
123
|
+
"OPENAI_BASE_URL": "https://api.deepinfra.com/v1/openai",
|
|
124
|
+
"SQL_AGENT_MODEL": "deepseek-ai/DeepSeek-V3"
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**PostgreSQL** needs the driver, which is an extra. Use a `postgresql://` DSN
|
|
132
|
+
and swap the command for:
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
uvx --from "sql-agent-mcp[postgres]" sql-agent-mcp
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
In the JSON configs that is
|
|
139
|
+
`"args": ["--from", "sql-agent-mcp[postgres]", "sql-agent-mcp"]`. Give it a
|
|
140
|
+
database role that only has `SELECT` — [the `GRANT`s are below](#your-own-database).
|
|
141
|
+
|
|
142
|
+
**No database of your own?** Drop `SQL_AGENT_DSN` and add `--demo` for the
|
|
143
|
+
bundled sample one. Its schema is deliberately awkward, and
|
|
144
|
+
[the traps are listed below](#the-database).
|
|
145
|
+
|
|
146
|
+
`OPENAI_API_KEY` is only needed by `ask` and `evaluate`, the two tools that
|
|
147
|
+
call a model; any OpenAI-compatible endpoint works. `list_tables`,
|
|
148
|
+
`describe_table` and `run_sql` need no key at all.
|
|
149
|
+
|
|
150
|
+
Prefer a plain install? `pip install sql-agent-mcp` puts `sql-agent-mcp` (the
|
|
151
|
+
server) and `sql-agent` (the same agent [from the command line](#from-the-command-line))
|
|
152
|
+
on your path.
|
|
153
|
+
|
|
154
|
+
### The tools
|
|
155
|
+
|
|
156
|
+
| Tool | What it does |
|
|
157
|
+
|---|---|
|
|
158
|
+
| `ask` | Runs the whole agent loop. Returns the answer, **the SQL that actually executed**, the rows, and the trace. |
|
|
159
|
+
| `evaluate` | Runs a golden set against this database. Returns accuracy, every failure with its reason, the tool path and the cost. |
|
|
160
|
+
| `list_tables` | Every table with its row count. |
|
|
161
|
+
| `describe_table` | Columns, types, foreign keys **and three real rows**. |
|
|
162
|
+
| `run_sql` | One read-only `SELECT`, up to 50 rows, or the database's own error text. |
|
|
163
|
+
|
|
164
|
+
`ask` reports `final_sql` and `claimed_sql` separately, and
|
|
165
|
+
`sql_was_executed` tells them apart. That distinction exists because of a real
|
|
166
|
+
bug: asked how many orders there were, the agent read the count off
|
|
167
|
+
`list_tables` and typed a `SELECT COUNT(*)` into its answer that it had never
|
|
168
|
+
run. A client must never quote unexecuted SQL to a user as evidence.
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## What this project actually found
|
|
173
|
+
|
|
174
|
+
I built it expecting to demonstrate error recovery: the database is seeded with
|
|
175
|
+
traps, `run_sql` hands SQLite's error text back to the model, and there is a
|
|
176
|
+
test proving a failed call is followed by a successful one.
|
|
177
|
+
|
|
178
|
+
**On eight questions, the recovery path never fired.** Across two models the
|
|
179
|
+
measured recovery rate was **0%**: both DeepSeek-V3 and Llama-3.1-8B call
|
|
180
|
+
`describe_table` before writing SQL, so neither ever hit `no such column:
|
|
181
|
+
total`.
|
|
182
|
+
|
|
183
|
+
**On thirty-four questions it fires — and it has never once saved the
|
|
184
|
+
answer.** Four runs recovered from a failed query, 12% of them, and all four
|
|
185
|
+
still came back wrong. Three of those four then spent the rest of their step
|
|
186
|
+
budget and never answered at all. So the machinery works, the harder questions
|
|
187
|
+
do trip it, and tripping it is not where correctness comes from. Widening the
|
|
188
|
+
golden set changed the claim; that is what the golden set is for.
|
|
189
|
+
|
|
190
|
+
What goes wrong is worse than an error. The agent writes **valid SQL that
|
|
191
|
+
returns a plausible wrong answer**, and then describes it fluently.
|
|
192
|
+
|
|
193
|
+
### The failure that makes the case
|
|
194
|
+
|
|
195
|
+
Asked for the top 5 customers by net spend, in the 8-case run, DeepSeek-V3
|
|
196
|
+
produced this:
|
|
197
|
+
|
|
198
|
+
```sql
|
|
199
|
+
JOIN order_items oi ON o.id = oi.order_id
|
|
200
|
+
LEFT JOIN refunds r ON o.id = r.order_id
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Hanging both `order_items` and `refunds` off `orders` fans out the join: each
|
|
204
|
+
refund is counted once per line item in its order. `SUM(r.amount_cents)`
|
|
205
|
+
over-counts, and net spend is deflated for exactly the customers who bought the
|
|
206
|
+
most items.
|
|
207
|
+
|
|
208
|
+
| | reference | agent |
|
|
209
|
+
|---|---|---|
|
|
210
|
+
| 1 | Joaquín Figueroa — 11,104.00 | Joaquín Figueroa — 11,104.00 |
|
|
211
|
+
| 2 | Isabella Lagos — 10,584.00 | Isabella Lagos — 10,584.00 |
|
|
212
|
+
| 3 | **Paz Cabrera — 8,552.50** | Thiago Rojas — 8,012.00 |
|
|
213
|
+
| 4 | **Dante Figueroa — 8,082.00** | Sofía Muñoz — 7,094.00 |
|
|
214
|
+
| 5 | Thiago Rojas — 8,012.00 | **Paz Cabrera — 6,841.00** |
|
|
215
|
+
|
|
216
|
+
The top two are right. The prose was confident. No error, no NULL, no
|
|
217
|
+
suspicious zero — just a number that is wrong by $1,711.50 and a customer who
|
|
218
|
+
silently drops two places.
|
|
219
|
+
|
|
220
|
+
Nothing short of running the query and comparing rows catches this.
|
|
221
|
+
|
|
222
|
+
Llama-3.1-8B failed the same question differently: it filtered
|
|
223
|
+
`status = 'completed'` (dropping shipped orders, which nobody asked to exclude),
|
|
224
|
+
returned customer IDs instead of names, and used `SUM(r.amount_cents)` without
|
|
225
|
+
`COALESCE`, so every customer with no refunds evaluated to NULL and fell out of
|
|
226
|
+
the ranking entirely. Same loop, same prompt, a different wrong answer.
|
|
227
|
+
|
|
228
|
+
The golden set now has a labelled case for each of those three shapes —
|
|
229
|
+
`join_fanout`, `missing_group_by`, `nulls_without_coalesce` — because a failure
|
|
230
|
+
you have seen once and not written down is a failure you will ship again.
|
|
231
|
+
|
|
232
|
+
Which was the right call: on the 34-case run DeepSeek-V3 fans out the join
|
|
233
|
+
again, this time on `items_and_refunds_per_order`, and over-filters to
|
|
234
|
+
`status = 'completed'` on `top_customers_net` — the failure that had been
|
|
235
|
+
Llama's. The shapes recur across questions and across models. The specific
|
|
236
|
+
case they land on does not.
|
|
237
|
+
|
|
238
|
+
## A real run
|
|
239
|
+
|
|
240
|
+
```
|
|
241
|
+
question: Who are the top 5 customers by how much they actually spent? …
|
|
242
|
+
|
|
243
|
+
[1] think 3747 ms 856+18 tok $0.0002
|
|
244
|
+
[2] list_tables 6 ms ok 6 tables
|
|
245
|
+
[3] think 5203 ms 1005+88 tok $0.0003
|
|
246
|
+
[4] describe_table 0 ms ok customers: 5 columns
|
|
247
|
+
[5] describe_table 0 ms ok orders: 5 columns
|
|
248
|
+
[6] describe_table 0 ms ok order_items: 5 columns
|
|
249
|
+
[7] describe_table 0 ms ok refunds: 5 columns
|
|
250
|
+
[8] think 45766 ms 2428+523 tok $0.0011
|
|
251
|
+
[9] run_sql 4 ms ok 5 rows
|
|
252
|
+
[10] think 30060 ms 3105+329 tok $0.0011
|
|
253
|
+
[11] finish 0 ms ok answered
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
```
|
|
257
|
+
11 steps · 7 tool calls · 0 recoveries · 84.8s · $0.0027
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
That is the run from the table above — the one with the wrong answer. Eleven
|
|
261
|
+
steps, no errors, under three tenths of a cent, and incorrect. This is why the
|
|
262
|
+
trace alone is not enough and the grader has to execute.
|
|
263
|
+
|
|
264
|
+
(That trace is from the 8-case run, under the earlier system prompt. It is kept
|
|
265
|
+
because it is the run the table above came from; the current numbers are
|
|
266
|
+
[further down](#current-numbers).)
|
|
267
|
+
|
|
268
|
+
## The database
|
|
269
|
+
|
|
270
|
+
The bundled sample database is shaped like a real operational schema rather
|
|
271
|
+
than a tutorial one, so that guessing is punished:
|
|
272
|
+
|
|
273
|
+
| Trap | What a guessing agent does | What it has to do |
|
|
274
|
+
|---|---|---|
|
|
275
|
+
| `orders` has **no total column** | `SELECT total FROM orders` → `no such column` | join `order_items`, sum `quantity * unit_price_cents` |
|
|
276
|
+
| Money is **INTEGER cents** | reports `78900` as a dollar figure | divide by `100.0` |
|
|
277
|
+
| `unit_price_cents` ≠ `products.list_price_cents` | joins to today's catalogue price | use the price actually paid |
|
|
278
|
+
| `status` includes `cancelled` | counts cancelled orders as revenue | filter them out |
|
|
279
|
+
| `refunds` is its own table | reports gross as net | subtract, **without fanning out the join** |
|
|
280
|
+
| `support_tickets` | joins it for no reason | ignore it |
|
|
281
|
+
|
|
282
|
+
A test asserts `orders` never grows a `total` column, because the day it does,
|
|
283
|
+
the trap becomes theatre. Seeding is deterministic, so the golden answers hold
|
|
284
|
+
across machines.
|
|
285
|
+
|
|
286
|
+
It is built only when you ask for it — `--demo`, `SQL_AGENT_DEMO=1` or
|
|
287
|
+
`--build-db`. That used to be automatic whenever the path did not exist, which
|
|
288
|
+
meant a typo in a path produced a working agent confidently answering questions
|
|
289
|
+
about data the user had never seen.
|
|
290
|
+
|
|
291
|
+
## Your own database
|
|
292
|
+
|
|
293
|
+
One connection string, in `SQL_AGENT_DSN` or `--dsn`:
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
SQL_AGENT_DSN=sqlite:///./shop.db
|
|
297
|
+
SQL_AGENT_DSN=postgresql://readonly:password@localhost:5432/shop
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
A path with no scheme is read as SQLite. MySQL says so rather than failing
|
|
301
|
+
obscurely: engines live in [`sql_agent/adapters.py`](https://github.com/Nachodusan/sql-agent/blob/main/sql_agent/adapters.py)
|
|
302
|
+
behind one small interface — connect, list, describe, select — so adding one is
|
|
303
|
+
a subclass and a line in `_ADAPTERS`, with no change to the tools the agent
|
|
304
|
+
calls.
|
|
305
|
+
|
|
306
|
+
**On PostgreSQL, give it a role that only has `SELECT`.** The server already
|
|
307
|
+
opens every connection with `default_transaction_read_only=on`, runs each
|
|
308
|
+
statement in a `READ ONLY` transaction and sets a `statement_timeout`:
|
|
309
|
+
|
|
310
|
+
```sql
|
|
311
|
+
CREATE ROLE sql_agent LOGIN PASSWORD '…';
|
|
312
|
+
GRANT CONNECT ON DATABASE shop TO sql_agent;
|
|
313
|
+
GRANT USAGE ON SCHEMA public TO sql_agent;
|
|
314
|
+
GRANT SELECT ON ALL TABLES IN SCHEMA public TO sql_agent;
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Those three rails stop a mistake. The role is what stops everything else, and
|
|
318
|
+
it does not depend on this code being correct.
|
|
319
|
+
|
|
320
|
+
One difference worth knowing: on PostgreSQL `list_tables` reports the planner's
|
|
321
|
+
row estimate, marked `rows_estimated`, instead of `count(*)` per table.
|
|
322
|
+
`list_tables` is meant to be the cheapest way to orient, and counting every row
|
|
323
|
+
of every table would blow the statement timeout on the agent's first call.
|
|
324
|
+
`describe_table` still returns three real rows on both engines.
|
|
325
|
+
|
|
326
|
+
## How it works
|
|
327
|
+
|
|
328
|
+
```
|
|
329
|
+
START → think → (tool calls?) → act → think → … → END
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
A LangGraph state machine with two nodes. `think` asks the model what to do
|
|
333
|
+
next; `act` runs it and writes the result back as an observation.
|
|
334
|
+
|
|
335
|
+
**Tools never raise.** A failing tool returns `{"ok": false, "error": ...}`. An
|
|
336
|
+
exception ends the run; a returned error is something the agent can act on.
|
|
337
|
+
|
|
338
|
+
**`describe_table` returns sample rows, not just types.** `INTEGER` does not
|
|
339
|
+
tell you a column holds cents. `18900` does.
|
|
340
|
+
|
|
341
|
+
**The loop is bounded** by `SQL_AGENT_MAX_STEPS`, enforced in the graph rather
|
|
342
|
+
than requested in the prompt. The failure mode of an unbounded agent is not a
|
|
343
|
+
wrong answer, it is a bill.
|
|
344
|
+
|
|
345
|
+
### Two barriers, not one
|
|
346
|
+
|
|
347
|
+
The connection is read-only — `mode=ro` on SQLite, a `READ ONLY` transaction
|
|
348
|
+
with a timeout on PostgreSQL. That is the first barrier, and the one that holds
|
|
349
|
+
if everything above it is wrong.
|
|
350
|
+
|
|
351
|
+
The second is [`sql_agent/sqlguard.py`](https://github.com/Nachodusan/sql-agent/blob/main/sql_agent/sqlguard.py), which parses
|
|
352
|
+
the statement with sqlglot in the dialect it is headed for and accepts exactly
|
|
353
|
+
one query: a `SELECT`, a set operation, or a parenthesised one, with no write,
|
|
354
|
+
`ATTACH`, `PRAGMA`, `SET`, `COPY` or row lock anywhere in the tree.
|
|
355
|
+
|
|
356
|
+
It used to be a regular expression over a list of forbidden words, which was
|
|
357
|
+
wrong in both directions. It rejected valid work:
|
|
358
|
+
|
|
359
|
+
```sql
|
|
360
|
+
SELECT replace(name, 'a', 'b') FROM products -- the word REPLACE
|
|
361
|
+
SELECT * FROM logs WHERE body LIKE '%create%' -- the word CREATE
|
|
362
|
+
SELECT created_at FROM orders -- \b did not save it either
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
and a word-list cannot tell where in a statement a word sits, so it had no
|
|
366
|
+
answer for a second statement after a semicolon, or for a write hidden in a
|
|
367
|
+
CTE — `WITH d AS (DELETE FROM orders RETURNING id) SELECT * FROM d` is a delete
|
|
368
|
+
that begins with the letters W-I-T-H, and PostgreSQL really runs it. Parsing
|
|
369
|
+
catches both. [Its tests](https://github.com/Nachodusan/sql-agent/blob/main/tests/test_sqlguard.py) are half false positives and
|
|
370
|
+
half those.
|
|
371
|
+
|
|
372
|
+
*A parser is not a security boundary either.* `pg_read_file`, a hostile
|
|
373
|
+
function in a user's own schema, and anything else a `SELECT` can legally reach
|
|
374
|
+
are the role's problem, not the parser's.
|
|
375
|
+
|
|
376
|
+
## Evaluation
|
|
377
|
+
|
|
378
|
+
```bash
|
|
379
|
+
python evals/run_eval.py --demo --json report.json
|
|
380
|
+
python evals/run_eval.py --dsn postgresql://… --golden my_questions.yaml
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Thirty-four cases in [`evals/golden.yaml`](https://github.com/Nachodusan/sql-agent/blob/main/evals/golden.yaml), each with a
|
|
384
|
+
reference query written by hand, **executed to verify it**, and labelled with
|
|
385
|
+
the traps it tests — twenty-six distinct ones, including join fan-out, a
|
|
386
|
+
missing `GROUP BY`, `SUM` over a `LEFT JOIN` with no `COALESCE`, and date
|
|
387
|
+
filters where the boundary is the whole question.
|
|
388
|
+
|
|
389
|
+
**Grading compares result sets, not text.** Not the prose, and not the SQL
|
|
390
|
+
string either — two correct queries rarely look alike, so grading the text
|
|
391
|
+
mostly measures style. The agent's final query and the reference both run
|
|
392
|
+
against the same database.
|
|
393
|
+
|
|
394
|
+
Three rules, each of which cost a round of false failures to learn:
|
|
395
|
+
|
|
396
|
+
- **Row order is compared only when the question asked for one.** Cases carry
|
|
397
|
+
`ordered: true` when the ranking is the answer.
|
|
398
|
+
- **Extra columns are allowed.** Asking for `name, spend` and getting back
|
|
399
|
+
`id, name, gross, refunds, spend` is cosmetic.
|
|
400
|
+
- **A case with tied values at the cut is never graded on order**, however much
|
|
401
|
+
the question reads like a ranking. Two equally correct queries break a tie
|
|
402
|
+
differently, and failing one of them measures the grader's `ORDER BY`. Every
|
|
403
|
+
ordered case was checked for ties by running it.
|
|
404
|
+
|
|
405
|
+
The first version of this harness had none of them and reported **3/8** on the
|
|
406
|
+
original eight cases. Two of
|
|
407
|
+
those failures were correct answers returned in a different row order, on
|
|
408
|
+
questions that never specified one, and a third was an ambiguous question —
|
|
409
|
+
*"what share"* got `0.1553` against a reference of `15.53`, and both readings
|
|
410
|
+
are defensible. The real number was 6/8. A grader that can be wrong about the
|
|
411
|
+
agent needs [its own tests](https://github.com/Nachodusan/sql-agent/blob/main/tests/test_eval_matching.py).
|
|
412
|
+
|
|
413
|
+
That ambiguous question is now a case in its own right. Four cases are marked
|
|
414
|
+
`ambiguous: true`, each carrying the reading its reference encodes, and they
|
|
415
|
+
are reported apart from the headline accuracy: a question with two defensible
|
|
416
|
+
answers measures the question at least as much as the agent, and averaging it
|
|
417
|
+
in hides both.
|
|
418
|
+
|
|
419
|
+
Reported per run, alongside accuracy: recovery rate, average steps, cost per
|
|
420
|
+
question, and the **tool path** — which tools in what order. An agent that
|
|
421
|
+
reaches the right number in nine confused steps and one that does it in three
|
|
422
|
+
are not the same agent, and only one of them is affordable.
|
|
423
|
+
|
|
424
|
+
Point `--golden` at your own file to grade the agent on your own questions
|
|
425
|
+
against your own database. The `evaluate` MCP tool takes the same path.
|
|
426
|
+
|
|
427
|
+
### Current numbers
|
|
428
|
+
|
|
429
|
+
DeepSeek-V3 via DeepInfra, on the **34-case set**, sample database, one run per
|
|
430
|
+
case. Full report: [`evals/report.json`](https://github.com/Nachodusan/sql-agent/blob/main/evals/report.json).
|
|
431
|
+
|
|
432
|
+
| | |
|
|
433
|
+
|---|---|
|
|
434
|
+
| accuracy | **18/34** — 53% |
|
|
435
|
+
| accuracy, unambiguous cases only | **17/30** — 57% |
|
|
436
|
+
| ambiguous cases matching the reference reading | 1/4 |
|
|
437
|
+
| recovery rate | **12%** (4 runs), none of which produced a right answer |
|
|
438
|
+
| ran out of step budget | 3/34 |
|
|
439
|
+
| avg steps | 9.6 |
|
|
440
|
+
| total cost | **$0.0679** |
|
|
441
|
+
|
|
442
|
+
<details>
|
|
443
|
+
<summary>The earlier 8-case numbers, for the record</summary>
|
|
444
|
+
|
|
445
|
+
| | |
|
|
446
|
+
|---|---|
|
|
447
|
+
| accuracy | 6/8 |
|
|
448
|
+
| recovery rate | 0% |
|
|
449
|
+
| avg steps | 8.8 |
|
|
450
|
+
| total cost | $0.0136 |
|
|
451
|
+
|
|
452
|
+
Report: [`evals/report-8case.json`](https://github.com/Nachodusan/sql-agent/blob/main/evals/report-8case.json). Not comparable
|
|
453
|
+
with the table above: the set is different and the system prompt has changed
|
|
454
|
+
since (it no longer asserts that money is in cents, which was a fact about
|
|
455
|
+
*this* sample database being told to an agent pointed at somebody else's).
|
|
456
|
+
|
|
457
|
+
</details>
|
|
458
|
+
|
|
459
|
+
#### Every failure, and why
|
|
460
|
+
|
|
461
|
+
The point of the set is this table, not the percentage.
|
|
462
|
+
|
|
463
|
+
| Case | What it did | Trap |
|
|
464
|
+
|---|---|---|
|
|
465
|
+
| `items_and_refunds_per_order` | joined `refunds` to `order_items`, counting each refund once per line item | `join_fanout` |
|
|
466
|
+
| `net_revenue_total` | summed `products.list_price_cents` — today's catalogue price — instead of the price paid | `historic_vs_list_price` |
|
|
467
|
+
| `top_customers_net` | filtered `status = 'completed'`, dropping shipped orders nobody asked to exclude | `cancelled_orders` |
|
|
468
|
+
| `price_drift` | omitted the `GROUP BY` and returned one row per order line until it hit the 50-row cap | `missing_group_by` |
|
|
469
|
+
| `channel_order_value` | averaged line items instead of order totals | `avg_of_sums` |
|
|
470
|
+
| `refund_total_per_channel` | right logic, right rows, never divided the cents by 100 | `cents` |
|
|
471
|
+
| `units_per_product` | returned `product_id` where the question asked which product | — |
|
|
472
|
+
| `orders_per_product` | same | — |
|
|
473
|
+
| `repeat_customers` | returned the 30 matching customers instead of counting them | `having` |
|
|
474
|
+
| `refund_rate` | returned two counts and left the division to the reader | `ratio` |
|
|
475
|
+
| `refund_reasons_share` | computed each reason's share by refund *count* instead of by amount | `ratio` |
|
|
476
|
+
| `net_spend_by_country` | failed a query, recovered, ran out of steps without answering | `join_fanout` |
|
|
477
|
+
| `bottom_customers_net` | same | `nulls_without_coalesce` |
|
|
478
|
+
| `refunded_share_of_revenue` | same | `ambiguous_units` |
|
|
479
|
+
| `how_much_did_we_make` | gross over every order, cancelled included, refunds not subtracted | ambiguous |
|
|
480
|
+
| `most_loyal_customer` | counted cancelled orders as loyalty | ambiguous |
|
|
481
|
+
|
|
482
|
+
Three things worth saying out loud about that table.
|
|
483
|
+
|
|
484
|
+
**Eleven of the thirteen unambiguous failures are valid SQL.** No error, no NULL,
|
|
485
|
+
no empty result — a number that is wrong and prose that is sure of it. This is
|
|
486
|
+
the case for executing the query and comparing rows, and nothing weaker
|
|
487
|
+
catches any of them.
|
|
488
|
+
|
|
489
|
+
**Two cases fail for returning an id where the question asked for a product.**
|
|
490
|
+
That is the grader making a judgment, and it is the same judgment it made of
|
|
491
|
+
Llama-3.1-8B returning customer IDs instead of names. A foreign key is not an
|
|
492
|
+
answer a person can read. Reasonable people could grade those two the other
|
|
493
|
+
way; this set grades them as wrong and says so here rather than burying it.
|
|
494
|
+
|
|
495
|
+
**Three cases spent the budget and never answered.** `SQL_AGENT_MAX_STEPS`
|
|
496
|
+
counts model *and* tool steps, so a question that needs four `describe_table`
|
|
497
|
+
calls has already spent nine of its twelve before writing any SQL. All three
|
|
498
|
+
had executed a query by then, and this run found a bug in the reporting of
|
|
499
|
+
that: the step-budget exit was the one path that never recorded `final_sql`, so
|
|
500
|
+
all three were reported as having produced no SQL at all while their own step
|
|
501
|
+
list showed a successful `run_sql`. The trace now records the query and the
|
|
502
|
+
grader still fails the case, saying *"stopped on the step budget without
|
|
503
|
+
answering"* — an agent that never commits to an answer has not answered, and
|
|
504
|
+
crediting that query would be the same mistake as crediting SQL typed into
|
|
505
|
+
`finish` and never run. Whether the default budget should be higher was a real
|
|
506
|
+
question, so it was [measured](#a-second-run-with-a-20-step-budget). It should
|
|
507
|
+
not.
|
|
508
|
+
|
|
509
|
+
One operational note: the run took 16 minutes of wall clock, 10 of which were a
|
|
510
|
+
single stall at the provider on `items_and_refunds_per_order` (614s for a
|
|
511
|
+
10-step run). That is the endpoint, not the agent.
|
|
512
|
+
|
|
513
|
+
#### A second run, with a 20-step budget
|
|
514
|
+
|
|
515
|
+
Same 34 cases, same model, `SQL_AGENT_MAX_STEPS=20`. Report:
|
|
516
|
+
[`evals/report-steps20.json`](https://github.com/Nachodusan/sql-agent/blob/main/evals/report-steps20.json).
|
|
517
|
+
|
|
518
|
+
| | 12 steps | 20 steps |
|
|
519
|
+
|---|---|---|
|
|
520
|
+
| accuracy | 18/34 | 20/34 |
|
|
521
|
+
| unambiguous only | 17/30 | 19/30 |
|
|
522
|
+
| ran out of budget | 3 | 0 |
|
|
523
|
+
| most steps any case used | 13 | 14 |
|
|
524
|
+
| recoveries that ended in a right answer | 0 of 4 | 0 of 2 |
|
|
525
|
+
| total cost | $0.0679 | $0.0680 |
|
|
526
|
+
|
|
527
|
+
**The bigger budget rescued none of the three.** All three finished this time,
|
|
528
|
+
and all three finished wrong:
|
|
529
|
+
|
|
530
|
+
| Case | With room to answer, it answered |
|
|
531
|
+
|---|---|
|
|
532
|
+
| `net_spend_by_country` | the right logic, in cents — `1470000` where the answer is `14,700.00` |
|
|
533
|
+
| `bottom_customers_net` | in cents again, and with cancelled orders counted as spend |
|
|
534
|
+
| `refunded_share_of_revenue` | a join fan-out so thorough that refunds came out larger than revenue, and no share computed |
|
|
535
|
+
|
|
536
|
+
So at 12 steps those three runs said nothing, and at 20 they said something
|
|
537
|
+
wrong with confidence. Of the two, saying nothing is the better failure. The
|
|
538
|
+
default stays at 12, and nothing needed more than 14 anyway.
|
|
539
|
+
|
|
540
|
+
**The two extra passes are noise, not budget.** Four cases that never came
|
|
541
|
+
near the limit changed result between the runs: `top_customers_net`,
|
|
542
|
+
`items_and_refunds_per_order` and `refund_rate` went from wrong to right, and
|
|
543
|
+
`monthly_revenue` from right to wrong — by filtering `status = 'completed'`,
|
|
544
|
+
the same over-filter again, on a third case. That is with `temperature=0`.
|
|
545
|
+
Seventeen cases passed both times and thirteen failed both times; the other
|
|
546
|
+
four are coin flips, which is what
|
|
547
|
+
[the outside evaluation](#evaluated-from-the-outside) said about the 8-case
|
|
548
|
+
set too. One run per case is a sample, and the difference between 18 and 20 is
|
|
549
|
+
inside it.
|
|
550
|
+
|
|
551
|
+
Across both runs the recovery path fired six times and has still not produced
|
|
552
|
+
a correct answer.
|
|
553
|
+
|
|
554
|
+
## Evaluated from the outside
|
|
555
|
+
|
|
556
|
+
[agent-evals](https://github.com/Nachodusan/agent-evals) runs this agent's own
|
|
557
|
+
golden set three times per case and checks the trajectory, not just the answer.
|
|
558
|
+
It found two bugs this harness could not:
|
|
559
|
+
|
|
560
|
+
- **The agent reported SQL it never executed.** Asked how many orders there
|
|
561
|
+
were, it read the count off `list_tables` and typed a `SELECT COUNT(*)` into
|
|
562
|
+
its final answer. The outcome grader scored it correct, on fabricated
|
|
563
|
+
evidence. `final_sql` now only ever holds SQL that actually ran; what the
|
|
564
|
+
model claimed is kept separately as `claimed_sql`.
|
|
565
|
+
- **Malformed tool arguments crashed the run.** Llama-3.1-8B sends `arguments`
|
|
566
|
+
as a JSON array where the schema asks for an object; the parsed list reached
|
|
567
|
+
`.get()` and the whole attempt died. Six of its twenty-four attempts were
|
|
568
|
+
crashes scored as model failures. They now come back as a tool error the
|
|
569
|
+
model can correct.
|
|
570
|
+
|
|
571
|
+
That evaluation also disagrees with the 8-case number: three runs per case put
|
|
572
|
+
this agent at **4/8 strict**, not 6/8. One of the passing cases was a coin
|
|
573
|
+
flip.
|
|
574
|
+
|
|
575
|
+
## From the command line
|
|
576
|
+
|
|
577
|
+
Python ≥ 3.11 and any OpenAI-compatible endpoint.
|
|
578
|
+
|
|
579
|
+
```bash
|
|
580
|
+
git clone https://github.com/Nachodusan/sql-agent
|
|
581
|
+
cd sql-agent
|
|
582
|
+
uv venv && uv pip install ".[dev,postgres]" # or: pip install ".[dev,postgres]"
|
|
583
|
+
|
|
584
|
+
cp .env.example .env # add your key and your DSN
|
|
585
|
+
python -m sql_agent.cli --build-db # generate the sample database
|
|
586
|
+
|
|
587
|
+
python -m sql_agent.cli --demo "how many orders came through each channel in Q1?"
|
|
588
|
+
python -m sql_agent.cli --dsn postgresql://… "top 5 customers by spend" --save
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
`--save` writes the full trace to `traces/<run-id>.json`. There is no default
|
|
592
|
+
database: pass `--dsn`, `--db` or `--demo`, or set `SQL_AGENT_DSN`. Picking the
|
|
593
|
+
wrong database is a mistake worth catching before the first token is spent.
|
|
594
|
+
|
|
595
|
+
> Editable installs (`pip install -e`) rely on `.pth` files, which Python 3.15
|
|
596
|
+
> no longer processes. The flat layout does not need one — running from the
|
|
597
|
+
> repository root works.
|
|
598
|
+
|
|
599
|
+
### Tests
|
|
600
|
+
|
|
601
|
+
```bash
|
|
602
|
+
pytest
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
All offline, no network, no API keys, no services. The agent tests drive the
|
|
606
|
+
loop with a **scripted model** replaying fixed turns, and `conftest.py` strips
|
|
607
|
+
the model credentials out of the environment for every test, so a test that
|
|
608
|
+
forgets to inject a scripted model fails loudly instead of quietly billing
|
|
609
|
+
whoever ran it. (That guard exists because a smoke test picked up a real key
|
|
610
|
+
from a local `.env` and asked DeepSeek-V3 a question nobody meant to pay for.)
|
|
611
|
+
|
|
612
|
+
Testing against a live model tests the model; these test the loop, the
|
|
613
|
+
statement guard, the adapters, the grader and the MCP server's tool contract.
|
|
614
|
+
|
|
615
|
+
The PostgreSQL adapter tests need PostgreSQL, so they are skipped unless you
|
|
616
|
+
opt in with a throwaway database:
|
|
617
|
+
|
|
618
|
+
```bash
|
|
619
|
+
SQL_AGENT_TEST_PG_DSN=postgresql:///sql_agent_test pytest
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
They create and drop a schema of their own. A suite that needs a service is a
|
|
623
|
+
suite that fails for the wrong reasons, which is why it is not the default.
|
|
624
|
+
|
|
625
|
+
## Publishing
|
|
626
|
+
|
|
627
|
+
On PyPI as [`sql-agent-mcp`](https://pypi.org/project/sql-agent-mcp/) and in the
|
|
628
|
+
official MCP registry as `io.github.Nachodusan/sql-agent`. The import package
|
|
629
|
+
is `sql_agent`; the commands are `sql-agent-mcp` and `sql-agent`.
|
|
630
|
+
|
|
631
|
+
[`server.json`](https://github.com/Nachodusan/sql-agent/blob/main/server.json) is the registry manifest, validated against the
|
|
632
|
+
published `2025-12-11` schema. Pushing a version tag runs
|
|
633
|
+
[`publish.yml`](https://github.com/Nachodusan/sql-agent/blob/main/.github/workflows/publish.yml), which publishes to PyPI
|
|
634
|
+
through Trusted Publishing and then to the registry through GitHub OIDC — no
|
|
635
|
+
stored token for either. [`RELEASING.md`](https://github.com/Nachodusan/sql-agent/blob/main/RELEASING.md) has the steps, and
|
|
636
|
+
[`CHANGELOG.md`](https://github.com/Nachodusan/sql-agent/blob/main/CHANGELOG.md) what changed.
|
|
637
|
+
|
|
638
|
+
The [`Dockerfile`](https://github.com/Nachodusan/sql-agent/blob/main/Dockerfile) is for container hosts, which cannot speak
|
|
639
|
+
stdio: `sql-agent-mcp --transport streamable-http` serves on `$PORT`.
|
|
640
|
+
|
|
641
|
+
## What this is not
|
|
642
|
+
|
|
643
|
+
- **Not a text-to-SQL benchmark entry.** It is a working loop with honest
|
|
644
|
+
instrumentation and a golden set that executes.
|
|
645
|
+
- **Not a substitute for a read-only database role.** A read-only connection
|
|
646
|
+
and a parser are two barriers against a mistake, not against an attacker.
|
|
647
|
+
- **Not a recovery demo, as it turns out.** The recovery path is implemented
|
|
648
|
+
and tested. It never fired on the 8-case set, fires on 12% of the 34-case
|
|
649
|
+
set, and has not yet produced a single correct answer when it does.
|
|
650
|
+
Reporting that is more useful than engineering a run that trips it.
|
|
651
|
+
|
|
652
|
+
## Licence
|
|
653
|
+
|
|
654
|
+
[MIT](https://github.com/Nachodusan/sql-agent/blob/main/LICENSE).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
sql_agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
sql_agent/adapters.py,sha256=aVSljnyuOcrrFPAkbT2EoMUJI_lQA4APJL-nwCqTpNU,23531
|
|
3
|
+
sql_agent/agent.py,sha256=4IOjQnknV4RYW9lk73D9rrSAuYWpXfUxMLTCti2do8A,9477
|
|
4
|
+
sql_agent/cli.py,sha256=Q0tYY9pjXJ2M2EHBk018ORmtilcSZ7hd9bXX8Jl8evs,3961
|
|
5
|
+
sql_agent/db.py,sha256=lj1foqwmijJ6HmH-SP9TnFF8JJx9AXQnAel22-bYUHg,9072
|
|
6
|
+
sql_agent/evaluate.py,sha256=AA45Ultwj_nVi1DabnudyfI-cbmerFeH9588a84pM8U,11953
|
|
7
|
+
sql_agent/llm.py,sha256=t51wqG0LMMe9vWa7y2zbE2BfsUmu_DrcUHTYcrwukzs,1768
|
|
8
|
+
sql_agent/mcp_server.py,sha256=Mwib503QEL9L682YJoCdXefbb415jg83Q25olnSE2mM,13572
|
|
9
|
+
sql_agent/schema.sql,sha256=7UTn4wHYXZdk_UJVU1GjPJqHrvunyRRG0lUXz-BtD_U,2682
|
|
10
|
+
sql_agent/sqlguard.py,sha256=By-ZzgV9P9sJ3VlgvNJ-_eSHhfVk3tDr-EQLlySKZXc,5704
|
|
11
|
+
sql_agent/tools.py,sha256=1XqLTJDu62nkZl6NjQWgD8klYwvN9X1DlrUFbgdPkms,8809
|
|
12
|
+
sql_agent/trace.py,sha256=P9yZacbEKTMSnOLS8BvUImxEvvJ6JdPXAGWxMAmgc-U,6745
|
|
13
|
+
sql_agent/data/golden.yaml,sha256=c0NxL_r02OAVbHfFQqFQBKOm89fT8YL-OidwCVETWyM,17690
|
|
14
|
+
sql_agent_mcp-0.2.0.dist-info/METADATA,sha256=L2-yuJ6CAHT1ckRL-88U4uT9NqmFnA9PbyY3sLaiEWA,29688
|
|
15
|
+
sql_agent_mcp-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
16
|
+
sql_agent_mcp-0.2.0.dist-info/entry_points.txt,sha256=fU_QDlQrIi29plbKzmQ8FF-xgD6YSildEgYEzbVztwc,91
|
|
17
|
+
sql_agent_mcp-0.2.0.dist-info/licenses/LICENSE,sha256=Di9m4HHWAXbAcFs7o5DESIjq_3zEshFfY10WtyauwnA,1079
|
|
18
|
+
sql_agent_mcp-0.2.0.dist-info/RECORD,,
|