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
sql_agent/mcp_server.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""MCP server, over stdio.
|
|
2
|
+
|
|
3
|
+
Five tools, in two groups.
|
|
4
|
+
|
|
5
|
+
`list_tables`, `describe_table` and `run_sql` are the plumbing: a client whose
|
|
6
|
+
own model is good at SQL can read the schema and write the query itself. Every
|
|
7
|
+
other database MCP server offers roughly this.
|
|
8
|
+
|
|
9
|
+
`ask` and `evaluate` are the reason this one exists. `ask` runs the whole agent
|
|
10
|
+
loop and hands back the answer *together with the SQL that actually executed*,
|
|
11
|
+
the rows it returned and the trace — steps, tool path, latency, cost — so the
|
|
12
|
+
client can check the answer instead of trusting it. `evaluate` runs a golden
|
|
13
|
+
set of the user's own questions against the user's own database and reports how
|
|
14
|
+
many the agent got right, with the failures and why. Measuring whether the
|
|
15
|
+
answers are correct is the part nobody else ships.
|
|
16
|
+
|
|
17
|
+
Nothing here prints to stdout. On stdio that is not a style rule: stdout is the
|
|
18
|
+
protocol, and one stray print corrupts the session.
|
|
19
|
+
|
|
20
|
+
sql-agent-mcp # stdio, the usual case
|
|
21
|
+
sql-agent-mcp --transport streamable-http # for container hosting
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import logging
|
|
28
|
+
import os
|
|
29
|
+
import sys
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from mcp.server.mcpserver import MCPServer
|
|
33
|
+
|
|
34
|
+
from sql_agent import db
|
|
35
|
+
from sql_agent.adapters import ConfigError
|
|
36
|
+
from sql_agent.tools import MAX_ROWS, Tools
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger("sql_agent.mcp")
|
|
39
|
+
|
|
40
|
+
def _version() -> str:
|
|
41
|
+
"""The version of the installed distribution.
|
|
42
|
+
|
|
43
|
+
Read from the package metadata so the number the server announces over MCP
|
|
44
|
+
cannot drift from the one in pyproject.toml and server.json. The fallback
|
|
45
|
+
is for running straight from a checkout that was never installed.
|
|
46
|
+
"""
|
|
47
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
return version("sql-agent-mcp")
|
|
51
|
+
except PackageNotFoundError:
|
|
52
|
+
return "0.0.0+checkout"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
VERSION = _version()
|
|
56
|
+
|
|
57
|
+
INSTRUCTIONS = """Query a SQL database in plain language, and check the answer.
|
|
58
|
+
|
|
59
|
+
Two ways to use this server:
|
|
60
|
+
|
|
61
|
+
- `ask` runs an agent that inspects the schema, writes SQL, runs it and
|
|
62
|
+
answers. It returns the SQL that actually executed (`final_sql`), the rows,
|
|
63
|
+
and a trace of every step with its latency and cost. If the agent typed SQL
|
|
64
|
+
into its answer without running it, that is reported separately as
|
|
65
|
+
`claimed_sql` and `sql_was_executed` is false — do not quote unexecuted SQL
|
|
66
|
+
to the user as evidence.
|
|
67
|
+
- `list_tables`, `describe_table` and `run_sql` let you write the SQL yourself.
|
|
68
|
+
`run_sql` accepts one read-only SELECT or WITH statement.
|
|
69
|
+
|
|
70
|
+
`evaluate` runs a golden set — questions with hand-written reference SQL —
|
|
71
|
+
against this database and reports accuracy, the failures and what each cost.
|
|
72
|
+
It calls the model once per step of every case, so it is not free.
|
|
73
|
+
|
|
74
|
+
The database is opened read-only. Writes are refused twice over: by the
|
|
75
|
+
connection and by a parser that accepts a single SELECT and nothing else.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --------------------------------------------------------------------------
|
|
80
|
+
# shared state
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Session:
|
|
84
|
+
"""What the tools share: one database target and one model client.
|
|
85
|
+
|
|
86
|
+
Both are resolved lazily. A server that exits because `SQL_AGENT_DSN` has
|
|
87
|
+
a typo in it shows up in the client as "failed to connect", which tells the
|
|
88
|
+
user nothing; a server that starts and returns the actual error from the
|
|
89
|
+
first tool call tells them what to fix.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
*,
|
|
95
|
+
target: str | None = None,
|
|
96
|
+
timeout_s: float = 5.0,
|
|
97
|
+
max_steps: int | None = None,
|
|
98
|
+
model: str | None = None,
|
|
99
|
+
llm: Any = None,
|
|
100
|
+
tools: Tools | None = None,
|
|
101
|
+
):
|
|
102
|
+
self.target = target
|
|
103
|
+
self.timeout_s = timeout_s
|
|
104
|
+
self.max_steps = max_steps
|
|
105
|
+
self.model = model
|
|
106
|
+
self._llm = llm
|
|
107
|
+
self._tools = tools
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def tools(self) -> Tools:
|
|
111
|
+
if self._tools is None:
|
|
112
|
+
self._tools = Tools(self.target, timeout_s=self.timeout_s)
|
|
113
|
+
return self._tools
|
|
114
|
+
|
|
115
|
+
def llm(self) -> Any:
|
|
116
|
+
"""The model client, or a ConfigError naming what to set."""
|
|
117
|
+
if self._llm is None:
|
|
118
|
+
from sql_agent.llm import LLM
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
self._llm = LLM(self.model)
|
|
122
|
+
except RuntimeError as exc:
|
|
123
|
+
raise ConfigError(str(exc)) from exc
|
|
124
|
+
return self._llm
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _failure(error: str, **extra: Any) -> dict[str, Any]:
|
|
128
|
+
return {"ok": False, "error": error, **extra}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _trace_summary(trace: Any) -> dict[str, Any]:
|
|
132
|
+
return {
|
|
133
|
+
"run_id": trace.run_id,
|
|
134
|
+
"steps": len(trace.steps),
|
|
135
|
+
"tool_calls": trace.tool_calls,
|
|
136
|
+
"recoveries": trace.recoveries,
|
|
137
|
+
"tool_path": trace.tool_path,
|
|
138
|
+
"latency_ms": trace.latency_ms,
|
|
139
|
+
"cost_usd": trace.cost_usd,
|
|
140
|
+
"stopped_reason": trace.stopped_reason,
|
|
141
|
+
"step_detail": [
|
|
142
|
+
{
|
|
143
|
+
"n": s.n,
|
|
144
|
+
"kind": s.kind,
|
|
145
|
+
"name": s.name,
|
|
146
|
+
"ok": s.ok,
|
|
147
|
+
"latency_ms": s.latency_ms,
|
|
148
|
+
"summary": s.summary,
|
|
149
|
+
"error": s.error,
|
|
150
|
+
}
|
|
151
|
+
for s in trace.steps
|
|
152
|
+
],
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# --------------------------------------------------------------------------
|
|
157
|
+
# the server
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_server(session: Session | None = None, **kwargs: Any) -> MCPServer:
|
|
161
|
+
"""Build the server. `session` is injectable, which is how the tests
|
|
162
|
+
drive every tool offline against a scripted model."""
|
|
163
|
+
state = session or Session(**kwargs)
|
|
164
|
+
|
|
165
|
+
server = MCPServer(
|
|
166
|
+
name="sql-agent",
|
|
167
|
+
title="SQL Agent",
|
|
168
|
+
version=VERSION,
|
|
169
|
+
instructions=INSTRUCTIONS,
|
|
170
|
+
website_url="https://github.com/Nachodusan/sql-agent",
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# -- the distinctive two ---------------------------------------------
|
|
174
|
+
|
|
175
|
+
@server.tool(
|
|
176
|
+
title="Ask the database a question",
|
|
177
|
+
description=(
|
|
178
|
+
"Answer a question about the database in plain language. Returns the "
|
|
179
|
+
"answer, the SQL that was actually executed, the rows it returned, "
|
|
180
|
+
"and a trace of every step with its latency and cost. "
|
|
181
|
+
"`sql_was_executed` is false when the agent answered without running "
|
|
182
|
+
"a query; in that case `final_sql` is null and `claimed_sql` holds "
|
|
183
|
+
"whatever SQL the model typed into its answer without running it."
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
def ask(question: str) -> dict[str, Any]:
|
|
187
|
+
question = (question or "").strip()
|
|
188
|
+
if not question:
|
|
189
|
+
return _failure("no question given")
|
|
190
|
+
|
|
191
|
+
from sql_agent.agent import ask as run_agent
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
llm = state.llm()
|
|
195
|
+
except ConfigError as exc:
|
|
196
|
+
return _failure(str(exc))
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
trace = run_agent(
|
|
200
|
+
question,
|
|
201
|
+
tools=state.tools,
|
|
202
|
+
llm=llm,
|
|
203
|
+
max_steps=state.max_steps,
|
|
204
|
+
)
|
|
205
|
+
except ConfigError as exc:
|
|
206
|
+
return _failure(str(exc))
|
|
207
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
208
|
+
log.exception("ask failed")
|
|
209
|
+
return _failure(f"{type(exc).__name__}: {exc}")
|
|
210
|
+
|
|
211
|
+
# Re-run the SQL that actually executed, so the client gets the rows
|
|
212
|
+
# the answer rests on and not a summary of them.
|
|
213
|
+
rows: list[dict[str, Any]] | None = None
|
|
214
|
+
rows_error: str | None = None
|
|
215
|
+
if trace.final_sql:
|
|
216
|
+
result = state.tools.run_sql(trace.final_sql)
|
|
217
|
+
if result.get("ok"):
|
|
218
|
+
rows = result["rows"]
|
|
219
|
+
else:
|
|
220
|
+
rows_error = result.get("error")
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
"ok": True,
|
|
224
|
+
"question": question,
|
|
225
|
+
"answer": trace.answer,
|
|
226
|
+
"engine": state.tools.engine,
|
|
227
|
+
"final_sql": trace.final_sql,
|
|
228
|
+
"claimed_sql": trace.claimed_sql,
|
|
229
|
+
"sql_was_executed": bool(trace.final_sql),
|
|
230
|
+
"rows": rows,
|
|
231
|
+
"row_count": None if rows is None else len(rows),
|
|
232
|
+
"rows_truncated_at": MAX_ROWS,
|
|
233
|
+
"rows_error": rows_error,
|
|
234
|
+
"trace": _trace_summary(trace),
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
@server.tool(
|
|
238
|
+
title="Evaluate the agent on a golden set",
|
|
239
|
+
description=(
|
|
240
|
+
"Run a golden set of questions with hand-written reference SQL "
|
|
241
|
+
"against this database and report accuracy, every failure with its "
|
|
242
|
+
"reason, the tool path taken and the cost. Pass the path to a YAML "
|
|
243
|
+
"file of cases; omit it to use the one bundled with the sample "
|
|
244
|
+
"database. Each case runs the full agent loop, so this calls the "
|
|
245
|
+
"model once per step of every case and is not free — use `only` to "
|
|
246
|
+
"run a single case first."
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
def evaluate(golden_path: str | None = None, only: str | None = None) -> dict[str, Any]:
|
|
250
|
+
from sql_agent.evaluate import run_suite
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
llm = state.llm()
|
|
254
|
+
except ConfigError as exc:
|
|
255
|
+
return _failure(str(exc))
|
|
256
|
+
|
|
257
|
+
try:
|
|
258
|
+
report = run_suite(
|
|
259
|
+
golden_path or None,
|
|
260
|
+
target=state.target,
|
|
261
|
+
only=only or None,
|
|
262
|
+
timeout_s=state.timeout_s,
|
|
263
|
+
max_steps=state.max_steps,
|
|
264
|
+
llm=llm,
|
|
265
|
+
)
|
|
266
|
+
except ConfigError as exc:
|
|
267
|
+
return _failure(str(exc))
|
|
268
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
269
|
+
log.exception("evaluate failed")
|
|
270
|
+
return _failure(f"{type(exc).__name__}: {exc}")
|
|
271
|
+
|
|
272
|
+
return {"ok": True, **report}
|
|
273
|
+
|
|
274
|
+
# -- the plumbing ----------------------------------------------------
|
|
275
|
+
|
|
276
|
+
@server.tool(
|
|
277
|
+
title="List tables",
|
|
278
|
+
description=(
|
|
279
|
+
"Every table in the database with its row count. On PostgreSQL the "
|
|
280
|
+
"count is the planner's estimate, marked `rows_estimated`, because "
|
|
281
|
+
"counting every row of every table to orient is not cheap."
|
|
282
|
+
),
|
|
283
|
+
)
|
|
284
|
+
def list_tables() -> dict[str, Any]:
|
|
285
|
+
result = state.tools.list_tables()
|
|
286
|
+
if result.get("ok"):
|
|
287
|
+
result["database"] = state.tools.label
|
|
288
|
+
return result
|
|
289
|
+
|
|
290
|
+
@server.tool(
|
|
291
|
+
title="Describe a table",
|
|
292
|
+
description=(
|
|
293
|
+
"A table's columns, types, foreign keys and three real rows. Read "
|
|
294
|
+
"this before writing SQL against a table you have not inspected: "
|
|
295
|
+
"the sample rows are what reveal that an INTEGER column holds cents "
|
|
296
|
+
"and that a TEXT column holds ISO dates."
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
def describe_table(table: str) -> dict[str, Any]:
|
|
300
|
+
return state.tools.describe_table(table)
|
|
301
|
+
|
|
302
|
+
@server.tool(
|
|
303
|
+
title="Run a read-only query",
|
|
304
|
+
description=(
|
|
305
|
+
f"Execute one read-only SELECT or WITH statement and return up to "
|
|
306
|
+
f"{MAX_ROWS} rows. Anything else is refused: several statements, a "
|
|
307
|
+
f"write, a write inside a CTE, ATTACH, PRAGMA, SET, a row lock. "
|
|
308
|
+
f"When the database rejects the query you get its own error text "
|
|
309
|
+
f"back, which is usually enough to fix it."
|
|
310
|
+
),
|
|
311
|
+
)
|
|
312
|
+
def run_sql(query: str) -> dict[str, Any]:
|
|
313
|
+
return state.tools.run_sql(query)
|
|
314
|
+
|
|
315
|
+
return server
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# --------------------------------------------------------------------------
|
|
319
|
+
# entry point
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def main(argv: list[str] | None = None) -> int:
|
|
323
|
+
parser = argparse.ArgumentParser(
|
|
324
|
+
prog="sql-agent-mcp",
|
|
325
|
+
description="Run sql-agent as an MCP server.",
|
|
326
|
+
)
|
|
327
|
+
parser.add_argument(
|
|
328
|
+
"--dsn",
|
|
329
|
+
default=None,
|
|
330
|
+
help="Connection string. Defaults to $SQL_AGENT_DSN.",
|
|
331
|
+
)
|
|
332
|
+
parser.add_argument(
|
|
333
|
+
"--db", dest="db_path", default=None, help="Path to a SQLite file.",
|
|
334
|
+
)
|
|
335
|
+
parser.add_argument(
|
|
336
|
+
"--demo",
|
|
337
|
+
action="store_true",
|
|
338
|
+
help="Serve the bundled sample database, building it if it is not there.",
|
|
339
|
+
)
|
|
340
|
+
parser.add_argument("--model", default=None, help="Override SQL_AGENT_MODEL.")
|
|
341
|
+
parser.add_argument("--max-steps", type=int, default=None, help="Hard cap on steps.")
|
|
342
|
+
parser.add_argument(
|
|
343
|
+
"--transport",
|
|
344
|
+
default="stdio",
|
|
345
|
+
choices=["stdio", "streamable-http", "sse"],
|
|
346
|
+
help="stdio for a local client; streamable-http when hosted in a container.",
|
|
347
|
+
)
|
|
348
|
+
parser.add_argument("--host", default="0.0.0.0", help="For the HTTP transports.")
|
|
349
|
+
parser.add_argument(
|
|
350
|
+
"--port",
|
|
351
|
+
type=int,
|
|
352
|
+
default=int(os.getenv("PORT", "8000")),
|
|
353
|
+
help="For the HTTP transports. Defaults to $PORT, which is what "
|
|
354
|
+
"container hosts set.",
|
|
355
|
+
)
|
|
356
|
+
args = parser.parse_args(argv)
|
|
357
|
+
|
|
358
|
+
# Load .env for the model credentials, but never let it write to stdout.
|
|
359
|
+
from dotenv import load_dotenv
|
|
360
|
+
|
|
361
|
+
load_dotenv()
|
|
362
|
+
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
|
|
363
|
+
|
|
364
|
+
target = args.dsn or args.db_path
|
|
365
|
+
if args.demo or _demo_env():
|
|
366
|
+
if target:
|
|
367
|
+
print("error: pass one of --demo, --dsn or --db", file=sys.stderr)
|
|
368
|
+
return 2
|
|
369
|
+
target = str(db.ensure_demo())
|
|
370
|
+
|
|
371
|
+
session = Session(
|
|
372
|
+
target=target,
|
|
373
|
+
timeout_s=float(os.getenv("SQL_AGENT_SQL_TIMEOUT_S", "5")),
|
|
374
|
+
max_steps=args.max_steps,
|
|
375
|
+
model=args.model,
|
|
376
|
+
)
|
|
377
|
+
server = build_server(session)
|
|
378
|
+
|
|
379
|
+
if args.transport == "stdio":
|
|
380
|
+
server.run("stdio")
|
|
381
|
+
else:
|
|
382
|
+
server.run(args.transport, host=args.host, port=args.port)
|
|
383
|
+
return 0
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _demo_env() -> bool:
|
|
387
|
+
return (os.getenv("SQL_AGENT_DEMO") or "").strip().lower() in ("1", "true", "yes", "on")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
if __name__ == "__main__":
|
|
391
|
+
sys.exit(main())
|
sql_agent/schema.sql
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
-- Deliberately shaped like a real operational database, not a tutorial one.
|
|
2
|
+
--
|
|
3
|
+
-- The traps are the point. An agent that guesses a schema instead of reading it
|
|
4
|
+
-- will write SQL that either errors or returns a confidently wrong number:
|
|
5
|
+
--
|
|
6
|
+
-- 1. `orders` has no total column. Order value lives in `order_items`.
|
|
7
|
+
-- 2. Money is INTEGER cents everywhere. Averaging without /100.0 is wrong.
|
|
8
|
+
-- 3. `order_items.unit_price_cents` is the price paid at the time of the order.
|
|
9
|
+
-- `products.list_price_cents` is today's catalogue price. They differ.
|
|
10
|
+
-- 4. `orders.status` includes 'cancelled'. Those are not revenue.
|
|
11
|
+
-- 5. `refunds` exists. Net spend has to subtract them.
|
|
12
|
+
-- 6. `support_tickets` is a distractor: plausible, rarely relevant.
|
|
13
|
+
|
|
14
|
+
CREATE TABLE customers (
|
|
15
|
+
id INTEGER PRIMARY KEY,
|
|
16
|
+
name TEXT NOT NULL,
|
|
17
|
+
email TEXT NOT NULL UNIQUE,
|
|
18
|
+
country TEXT NOT NULL,
|
|
19
|
+
signed_up_at TEXT NOT NULL -- ISO-8601 date
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
CREATE TABLE products (
|
|
23
|
+
id INTEGER PRIMARY KEY,
|
|
24
|
+
name TEXT NOT NULL,
|
|
25
|
+
category TEXT NOT NULL,
|
|
26
|
+
list_price_cents INTEGER NOT NULL, -- today's catalogue price
|
|
27
|
+
discontinued INTEGER NOT NULL DEFAULT 0
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
CREATE TABLE orders (
|
|
31
|
+
id INTEGER PRIMARY KEY,
|
|
32
|
+
customer_id INTEGER NOT NULL REFERENCES customers(id),
|
|
33
|
+
ordered_at TEXT NOT NULL, -- ISO-8601 date
|
|
34
|
+
status TEXT NOT NULL, -- 'completed' | 'shipped' | 'cancelled'
|
|
35
|
+
channel TEXT NOT NULL -- 'web' | 'mobile' | 'phone'
|
|
36
|
+
-- No total column. On purpose.
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
CREATE TABLE order_items (
|
|
40
|
+
id INTEGER PRIMARY KEY,
|
|
41
|
+
order_id INTEGER NOT NULL REFERENCES orders(id),
|
|
42
|
+
product_id INTEGER NOT NULL REFERENCES products(id),
|
|
43
|
+
quantity INTEGER NOT NULL,
|
|
44
|
+
unit_price_cents INTEGER NOT NULL -- price paid then, not products.list_price_cents
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
CREATE TABLE refunds (
|
|
48
|
+
id INTEGER PRIMARY KEY,
|
|
49
|
+
order_id INTEGER NOT NULL REFERENCES orders(id),
|
|
50
|
+
amount_cents INTEGER NOT NULL,
|
|
51
|
+
refunded_at TEXT NOT NULL,
|
|
52
|
+
reason TEXT NOT NULL
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
CREATE TABLE support_tickets (
|
|
56
|
+
id INTEGER PRIMARY KEY,
|
|
57
|
+
customer_id INTEGER NOT NULL REFERENCES customers(id),
|
|
58
|
+
opened_at TEXT NOT NULL,
|
|
59
|
+
severity TEXT NOT NULL, -- 'low' | 'medium' | 'high'
|
|
60
|
+
resolved INTEGER NOT NULL DEFAULT 0
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
CREATE INDEX idx_orders_customer ON orders(customer_id);
|
|
64
|
+
CREATE INDEX idx_orders_date ON orders(ordered_at);
|
|
65
|
+
CREATE INDEX idx_items_order ON order_items(order_id);
|
|
66
|
+
CREATE INDEX idx_refunds_order ON refunds(order_id);
|
sql_agent/sqlguard.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The second barrier: is this one read-only statement?
|
|
2
|
+
|
|
3
|
+
The first barrier is the connection — `mode=ro` on SQLite, a READ ONLY
|
|
4
|
+
transaction on PostgreSQL, and ideally a database role that only has SELECT.
|
|
5
|
+
This module is what stops a query before it gets there.
|
|
6
|
+
|
|
7
|
+
It used to be a regular expression over a list of forbidden words, which was
|
|
8
|
+
wrong in both directions. It rejected perfectly good queries:
|
|
9
|
+
|
|
10
|
+
SELECT replace(name, 'a', 'b') FROM products -- "REPLACE"
|
|
11
|
+
SELECT * FROM logs WHERE body LIKE '%create%' -- "CREATE"
|
|
12
|
+
SELECT created_at FROM orders -- "CREATE", with \\b
|
|
13
|
+
-- not saving it either
|
|
14
|
+
|
|
15
|
+
and it was easy to walk past, because a word-list does not know where in the
|
|
16
|
+
statement a word sits.
|
|
17
|
+
|
|
18
|
+
So the statement is parsed instead. The rule is small enough to state in full:
|
|
19
|
+
|
|
20
|
+
* it has to parse, in the dialect of the database it is going to run against;
|
|
21
|
+
* it has to be exactly one statement;
|
|
22
|
+
* the top of the tree has to be a query — SELECT, a set operation, or a
|
|
23
|
+
parenthesised one;
|
|
24
|
+
* nowhere in the tree, including inside a CTE, may there be a statement that
|
|
25
|
+
writes, attaches, configures or locks anything.
|
|
26
|
+
|
|
27
|
+
The third rule is what makes `SELECT 1; DROP TABLE orders` fail, and the
|
|
28
|
+
fourth is what makes `WITH d AS (DELETE FROM orders RETURNING id) SELECT * FROM d`
|
|
29
|
+
fail — a write that a word-list placed before the first SELECT would also have
|
|
30
|
+
caught, but that a "starts with SELECT" check would not.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import sqlglot
|
|
36
|
+
from sqlglot import exp
|
|
37
|
+
|
|
38
|
+
__all__ = ["check", "SUPPORTED_DIALECTS"]
|
|
39
|
+
|
|
40
|
+
SUPPORTED_DIALECTS = ("sqlite", "postgres")
|
|
41
|
+
|
|
42
|
+
#: A statement may only be one of these at the top. Anything else — ATTACH,
|
|
43
|
+
#: PRAGMA, VACUUM, SET, a bare TRUNCATE — is refused by not being on the list,
|
|
44
|
+
#: so a statement type sqlglot learns about tomorrow is refused by default
|
|
45
|
+
#: rather than allowed by oversight.
|
|
46
|
+
_TOP_LEVEL_OK: tuple[type[exp.Expression], ...] = (
|
|
47
|
+
exp.Select,
|
|
48
|
+
exp.SetOperation, # UNION / INTERSECT / EXCEPT
|
|
49
|
+
exp.Subquery, # (SELECT …)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
#: Statements that must not appear anywhere in the tree, including as the body
|
|
53
|
+
#: of a CTE. `exp.Command` is sqlglot's fallback for syntax it does not model
|
|
54
|
+
#: (VACUUM, EXPLAIN, REPLACE INTO on SQLite), which is exactly the kind of
|
|
55
|
+
#: thing we do not want to run blind.
|
|
56
|
+
#:
|
|
57
|
+
#: `exp.Replace` is deliberately absent: that node is the `REPLACE(a, b, c)`
|
|
58
|
+
#: *function*, and treating it as a write is the false positive that started
|
|
59
|
+
#: all this. `REPLACE INTO` parses as `exp.Insert` or `exp.Command`.
|
|
60
|
+
_FORBIDDEN_NODES: tuple[type[exp.Expression], ...] = (
|
|
61
|
+
exp.Insert,
|
|
62
|
+
exp.Update,
|
|
63
|
+
exp.Delete,
|
|
64
|
+
exp.Merge,
|
|
65
|
+
exp.Drop,
|
|
66
|
+
exp.Create,
|
|
67
|
+
exp.Alter,
|
|
68
|
+
exp.TruncateTable,
|
|
69
|
+
exp.Attach,
|
|
70
|
+
exp.Detach,
|
|
71
|
+
exp.Pragma,
|
|
72
|
+
exp.Set,
|
|
73
|
+
exp.Grant,
|
|
74
|
+
exp.Revoke,
|
|
75
|
+
exp.Use,
|
|
76
|
+
exp.Copy,
|
|
77
|
+
exp.Transaction,
|
|
78
|
+
exp.Commit,
|
|
79
|
+
exp.Rollback,
|
|
80
|
+
exp.Analyze,
|
|
81
|
+
exp.Lock, # SELECT … FOR UPDATE takes a write lock
|
|
82
|
+
exp.Command,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
_LABELS = {
|
|
86
|
+
exp.Insert: "INSERT",
|
|
87
|
+
exp.Update: "UPDATE",
|
|
88
|
+
exp.Delete: "DELETE",
|
|
89
|
+
exp.Merge: "MERGE",
|
|
90
|
+
exp.Drop: "DROP",
|
|
91
|
+
exp.Create: "CREATE",
|
|
92
|
+
exp.Alter: "ALTER",
|
|
93
|
+
exp.TruncateTable: "TRUNCATE",
|
|
94
|
+
exp.Attach: "ATTACH",
|
|
95
|
+
exp.Detach: "DETACH",
|
|
96
|
+
exp.Pragma: "PRAGMA",
|
|
97
|
+
exp.Set: "SET",
|
|
98
|
+
exp.Grant: "GRANT",
|
|
99
|
+
exp.Revoke: "REVOKE",
|
|
100
|
+
exp.Use: "USE",
|
|
101
|
+
exp.Copy: "COPY",
|
|
102
|
+
exp.Transaction: "BEGIN/START TRANSACTION",
|
|
103
|
+
exp.Commit: "COMMIT",
|
|
104
|
+
exp.Rollback: "ROLLBACK",
|
|
105
|
+
exp.Analyze: "ANALYZE",
|
|
106
|
+
exp.Lock: "FOR UPDATE / FOR SHARE",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _label(node: exp.Expression) -> str:
|
|
111
|
+
for kind, name in _LABELS.items():
|
|
112
|
+
if isinstance(node, kind):
|
|
113
|
+
return name
|
|
114
|
+
if isinstance(node, exp.Command):
|
|
115
|
+
word = (str(node.this) or "").strip().upper().split()[:1]
|
|
116
|
+
return word[0] if word else "that statement"
|
|
117
|
+
return type(node).__name__.upper()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def check(sql: str, *, dialect: str = "sqlite") -> str | None:
|
|
121
|
+
"""`None` if `sql` is one read-only query; otherwise why it is not.
|
|
122
|
+
|
|
123
|
+
The returned string goes straight back to the model, so it says what to do
|
|
124
|
+
rather than only what went wrong.
|
|
125
|
+
"""
|
|
126
|
+
text = (sql or "").strip()
|
|
127
|
+
if not text:
|
|
128
|
+
return "empty query"
|
|
129
|
+
|
|
130
|
+
if dialect not in SUPPORTED_DIALECTS:
|
|
131
|
+
dialect = "sqlite"
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
statements = [s for s in sqlglot.parse(text, dialect=dialect) if s is not None]
|
|
135
|
+
except sqlglot.ParseError as exc:
|
|
136
|
+
first = str(exc).strip().splitlines()[0]
|
|
137
|
+
return f"could not parse this as SQL ({dialect}): {first}"
|
|
138
|
+
except Exception as exc: # pragma: no cover - sqlglot internals
|
|
139
|
+
return f"could not parse this as SQL ({dialect}): {type(exc).__name__}: {exc}"
|
|
140
|
+
|
|
141
|
+
if not statements:
|
|
142
|
+
return "empty query"
|
|
143
|
+
|
|
144
|
+
if len(statements) > 1:
|
|
145
|
+
kinds = ", ".join(_label(s) for s in statements)
|
|
146
|
+
return (
|
|
147
|
+
f"send one statement at a time; this is {len(statements)} ({kinds}). "
|
|
148
|
+
"Semicolon-separated batches are not allowed."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
statement = statements[0]
|
|
152
|
+
|
|
153
|
+
if not isinstance(statement, _TOP_LEVEL_OK):
|
|
154
|
+
return (
|
|
155
|
+
f"only read-only queries are allowed, and this is "
|
|
156
|
+
f"{_label(statement)}. Use a single SELECT or WITH … SELECT."
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
for node in statement.walk():
|
|
160
|
+
if isinstance(node, _FORBIDDEN_NODES):
|
|
161
|
+
where = "inside the query" if node is not statement else "here"
|
|
162
|
+
return (
|
|
163
|
+
f"only read-only queries are allowed; found {_label(node)} "
|
|
164
|
+
f"{where}. A CTE that writes is still a write."
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
return None
|