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/__init__.py
ADDED
|
File without changes
|
sql_agent/adapters.py
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
"""Database adapters behind one connection string.
|
|
2
|
+
|
|
3
|
+
Everything engine-specific lives here: how to connect read-only, how to list
|
|
4
|
+
tables, how to describe one, and which sqlglot dialect the statement guard
|
|
5
|
+
should parse with. `tools.py` knows none of it, so adding MySQL means adding a
|
|
6
|
+
class and one line in `_ADAPTERS` — not touching the tools the agent calls.
|
|
7
|
+
|
|
8
|
+
The connection string comes from `SQL_AGENT_DSN`:
|
|
9
|
+
|
|
10
|
+
sqlite:///./shop.db relative path
|
|
11
|
+
sqlite:////var/data/shop.db absolute path
|
|
12
|
+
./shop.db a bare path is read as SQLite
|
|
13
|
+
postgresql://user:pw@host:5432/db libpq URL, also postgres://
|
|
14
|
+
|
|
15
|
+
Every adapter opens the database read-only. On PostgreSQL that means a READ
|
|
16
|
+
ONLY transaction and a `statement_timeout`, which is a property of the
|
|
17
|
+
connection rather than of the SQL we send — the statement guard in
|
|
18
|
+
`sqlguard.py` is the second barrier, not the first.
|
|
19
|
+
|
|
20
|
+
Connections are opened per call and closed again. An MCP server is long-lived
|
|
21
|
+
and a cached connection would eventually be a stale one; reconnecting costs a
|
|
22
|
+
few milliseconds and removes a whole class of bug.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import datetime as _dt
|
|
28
|
+
import decimal
|
|
29
|
+
import os
|
|
30
|
+
import sqlite3
|
|
31
|
+
import uuid
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any
|
|
34
|
+
from urllib.parse import unquote, urlparse
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Adapter",
|
|
38
|
+
"ConfigError",
|
|
39
|
+
"QueryError",
|
|
40
|
+
"SQLiteAdapter",
|
|
41
|
+
"PostgresAdapter",
|
|
42
|
+
"resolve",
|
|
43
|
+
"describe_dsn",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ConfigError(RuntimeError):
|
|
48
|
+
"""The connection string, or what it points at, is unusable.
|
|
49
|
+
|
|
50
|
+
Always a user-fixable mistake: a typo in the DSN, a database file that is
|
|
51
|
+
not there, an engine we do not speak yet. Reported as an error, never
|
|
52
|
+
papered over by creating something.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class QueryError(RuntimeError):
|
|
57
|
+
"""The database refused the query. Carries the database's own wording.
|
|
58
|
+
|
|
59
|
+
The agent reads this string. `no such column: total` is the single most
|
|
60
|
+
useful thing a database can say to an agent, so it is passed through
|
|
61
|
+
untouched rather than wrapped in our own prose.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# --------------------------------------------------------------------------
|
|
66
|
+
# value coercion
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _jsonable(value: Any) -> Any:
|
|
70
|
+
"""Make one cell safe to put in a tool result.
|
|
71
|
+
|
|
72
|
+
SQLite hands back str/int/float/bytes/None. A real PostgreSQL database
|
|
73
|
+
hands back `Decimal`, `date`, `datetime`, `UUID`, `timedelta` and more, and
|
|
74
|
+
those have to survive both JSON serialisation and the eval grader's
|
|
75
|
+
comparison. Decimals become floats on purpose: the grader rounds floats to
|
|
76
|
+
two places, so money compares the way a person would compare it.
|
|
77
|
+
"""
|
|
78
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
79
|
+
return value
|
|
80
|
+
if isinstance(value, decimal.Decimal):
|
|
81
|
+
return float(value)
|
|
82
|
+
if isinstance(value, (_dt.datetime, _dt.date, _dt.time)):
|
|
83
|
+
return value.isoformat()
|
|
84
|
+
if isinstance(value, _dt.timedelta):
|
|
85
|
+
return value.total_seconds()
|
|
86
|
+
if isinstance(value, uuid.UUID):
|
|
87
|
+
return str(value)
|
|
88
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
89
|
+
return f"<{len(bytes(value))} bytes>"
|
|
90
|
+
if isinstance(value, (list, tuple)):
|
|
91
|
+
return [_jsonable(v) for v in value]
|
|
92
|
+
if isinstance(value, dict):
|
|
93
|
+
return {str(k): _jsonable(v) for k, v in value.items()}
|
|
94
|
+
return str(value)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --------------------------------------------------------------------------
|
|
98
|
+
# base
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Adapter:
|
|
102
|
+
"""What the tools are allowed to assume about a database.
|
|
103
|
+
|
|
104
|
+
A subclass owns its own connection, its own catalogue queries and its own
|
|
105
|
+
read-only enforcement. It must raise `QueryError` for anything the database
|
|
106
|
+
itself rejected, and `ConfigError` for anything the user has to fix.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
name: str = "" # "sqlite" | "postgresql"
|
|
110
|
+
dialect: str = "" # sqlglot dialect name
|
|
111
|
+
read_only_note: str = "" # one line, for the describe output
|
|
112
|
+
|
|
113
|
+
def __init__(self, dsn: str, *, timeout_s: float = 5.0):
|
|
114
|
+
self.dsn = dsn
|
|
115
|
+
self.timeout_s = timeout_s
|
|
116
|
+
|
|
117
|
+
# -- identity --------------------------------------------------------
|
|
118
|
+
@property
|
|
119
|
+
def label(self) -> str:
|
|
120
|
+
"""Safe to show a user: never contains a password."""
|
|
121
|
+
raise NotImplementedError
|
|
122
|
+
|
|
123
|
+
# -- catalogue -------------------------------------------------------
|
|
124
|
+
def table_names(self) -> list[str]:
|
|
125
|
+
raise NotImplementedError
|
|
126
|
+
|
|
127
|
+
def tables(self) -> list[dict[str, Any]]:
|
|
128
|
+
"""`[{"table": name, "rows": n}]`, one entry per base table."""
|
|
129
|
+
raise NotImplementedError
|
|
130
|
+
|
|
131
|
+
def describe(self, table: str) -> dict[str, Any] | None:
|
|
132
|
+
"""Columns, foreign keys and three real rows. `None` if no such table.
|
|
133
|
+
|
|
134
|
+
The sample rows are the point. `INTEGER` does not tell you a column
|
|
135
|
+
holds cents; `18900` does.
|
|
136
|
+
"""
|
|
137
|
+
raise NotImplementedError
|
|
138
|
+
|
|
139
|
+
# -- queries ---------------------------------------------------------
|
|
140
|
+
def select(self, sql: str, limit: int) -> list[dict[str, Any]]:
|
|
141
|
+
"""Run one already-validated read-only statement.
|
|
142
|
+
|
|
143
|
+
Returns at most `limit` rows. Raises `QueryError` with the database's
|
|
144
|
+
own message if the database rejected it.
|
|
145
|
+
"""
|
|
146
|
+
raise NotImplementedError
|
|
147
|
+
|
|
148
|
+
def check(self) -> None:
|
|
149
|
+
"""Raise `ConfigError` if the database cannot be reached at all."""
|
|
150
|
+
raise NotImplementedError
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# --------------------------------------------------------------------------
|
|
154
|
+
# SQLite
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class SQLiteAdapter(Adapter):
|
|
158
|
+
name = "sqlite"
|
|
159
|
+
dialect = "sqlite"
|
|
160
|
+
read_only_note = "opened with mode=ro; the connection itself cannot write"
|
|
161
|
+
|
|
162
|
+
def __init__(self, dsn: str, *, timeout_s: float = 5.0):
|
|
163
|
+
super().__init__(dsn, timeout_s=timeout_s)
|
|
164
|
+
self.path = _sqlite_path(dsn)
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def label(self) -> str:
|
|
168
|
+
return f"sqlite:{self.path}"
|
|
169
|
+
|
|
170
|
+
# -- connection ------------------------------------------------------
|
|
171
|
+
def _connect(self) -> sqlite3.Connection:
|
|
172
|
+
if not self.path.exists():
|
|
173
|
+
raise ConfigError(
|
|
174
|
+
f"no SQLite database at {self.path}. "
|
|
175
|
+
"Point SQL_AGENT_DSN at an existing file, or pass --demo "
|
|
176
|
+
"(or set SQL_AGENT_DEMO=1) to build the bundled sample database."
|
|
177
|
+
)
|
|
178
|
+
if self.path.is_dir():
|
|
179
|
+
raise ConfigError(f"{self.path} is a directory, not a SQLite database")
|
|
180
|
+
try:
|
|
181
|
+
conn = sqlite3.connect(f"file:{self.path}?mode=ro", uri=True,
|
|
182
|
+
timeout=self.timeout_s)
|
|
183
|
+
except sqlite3.Error as exc:
|
|
184
|
+
raise ConfigError(f"could not open {self.path}: {exc}") from exc
|
|
185
|
+
conn.row_factory = sqlite3.Row
|
|
186
|
+
conn.execute(f"PRAGMA busy_timeout = {int(self.timeout_s * 1000)}")
|
|
187
|
+
return conn
|
|
188
|
+
|
|
189
|
+
def check(self) -> None:
|
|
190
|
+
self._connect().close()
|
|
191
|
+
|
|
192
|
+
# -- catalogue -------------------------------------------------------
|
|
193
|
+
_TABLES = (
|
|
194
|
+
"SELECT name FROM sqlite_master WHERE type='table' "
|
|
195
|
+
"AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
def table_names(self) -> list[str]:
|
|
199
|
+
conn = self._connect()
|
|
200
|
+
try:
|
|
201
|
+
return [r[0] for r in conn.execute(self._TABLES)]
|
|
202
|
+
finally:
|
|
203
|
+
conn.close()
|
|
204
|
+
|
|
205
|
+
def tables(self) -> list[dict[str, Any]]:
|
|
206
|
+
conn = self._connect()
|
|
207
|
+
try:
|
|
208
|
+
names = [r[0] for r in conn.execute(self._TABLES)]
|
|
209
|
+
return [
|
|
210
|
+
{
|
|
211
|
+
"table": n,
|
|
212
|
+
# Identifier comes from sqlite_master, not from the model.
|
|
213
|
+
"rows": conn.execute(f'SELECT count(*) FROM "{n}"').fetchone()[0],
|
|
214
|
+
}
|
|
215
|
+
for n in names
|
|
216
|
+
]
|
|
217
|
+
finally:
|
|
218
|
+
conn.close()
|
|
219
|
+
|
|
220
|
+
def describe(self, table: str) -> dict[str, Any] | None:
|
|
221
|
+
conn = self._connect()
|
|
222
|
+
try:
|
|
223
|
+
exists = conn.execute(
|
|
224
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
|
|
225
|
+
(table,),
|
|
226
|
+
).fetchone()
|
|
227
|
+
if not exists:
|
|
228
|
+
return None
|
|
229
|
+
real = exists[0]
|
|
230
|
+
columns = [
|
|
231
|
+
{
|
|
232
|
+
"name": r["name"],
|
|
233
|
+
"type": r["type"],
|
|
234
|
+
"notnull": bool(r["notnull"]),
|
|
235
|
+
"pk": bool(r["pk"]),
|
|
236
|
+
}
|
|
237
|
+
for r in conn.execute(f'PRAGMA table_info("{real}")')
|
|
238
|
+
]
|
|
239
|
+
foreign_keys = [
|
|
240
|
+
{"column": r["from"], "references": f"{r['table']}.{r['to']}"}
|
|
241
|
+
for r in conn.execute(f'PRAGMA foreign_key_list("{real}")')
|
|
242
|
+
]
|
|
243
|
+
sample = [
|
|
244
|
+
{k: _jsonable(v) for k, v in dict(r).items()}
|
|
245
|
+
for r in conn.execute(f'SELECT * FROM "{real}" LIMIT 3')
|
|
246
|
+
]
|
|
247
|
+
return {
|
|
248
|
+
"table": real,
|
|
249
|
+
"columns": columns,
|
|
250
|
+
"foreign_keys": foreign_keys,
|
|
251
|
+
"sample_rows": sample,
|
|
252
|
+
}
|
|
253
|
+
finally:
|
|
254
|
+
conn.close()
|
|
255
|
+
|
|
256
|
+
# -- queries ---------------------------------------------------------
|
|
257
|
+
def select(self, sql: str, limit: int) -> list[dict[str, Any]]:
|
|
258
|
+
conn = self._connect()
|
|
259
|
+
try:
|
|
260
|
+
cur = conn.execute(sql)
|
|
261
|
+
return [
|
|
262
|
+
{k: _jsonable(v) for k, v in dict(r).items()}
|
|
263
|
+
for r in cur.fetchmany(limit)
|
|
264
|
+
]
|
|
265
|
+
except sqlite3.Error as exc:
|
|
266
|
+
# Keep SQLite's own wording; the agent is expected to read it.
|
|
267
|
+
raise QueryError(str(exc)) from exc
|
|
268
|
+
finally:
|
|
269
|
+
conn.close()
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _sqlite_path(dsn: str) -> Path:
|
|
273
|
+
"""Turn a SQLite DSN or a bare filesystem path into a Path."""
|
|
274
|
+
if "://" not in dsn:
|
|
275
|
+
return Path(dsn).expanduser()
|
|
276
|
+
parsed = urlparse(dsn)
|
|
277
|
+
# sqlite:///rel/path → netloc "", path "/rel/path"
|
|
278
|
+
# sqlite:////abs/path → netloc "", path "//abs/path"
|
|
279
|
+
raw = unquote(parsed.path)
|
|
280
|
+
if parsed.netloc and parsed.netloc not in ("", "localhost"):
|
|
281
|
+
raise ConfigError(
|
|
282
|
+
f"SQLite DSNs have no host; got {parsed.netloc!r}. "
|
|
283
|
+
"Write sqlite:///relative/path.db or sqlite:////absolute/path.db"
|
|
284
|
+
)
|
|
285
|
+
if raw.startswith("//"):
|
|
286
|
+
return Path(raw[1:])
|
|
287
|
+
if raw.startswith("/"):
|
|
288
|
+
return Path(raw[1:]).expanduser()
|
|
289
|
+
if not raw:
|
|
290
|
+
raise ConfigError(
|
|
291
|
+
"SQLite DSN has no path. Write sqlite:///relative/path.db "
|
|
292
|
+
"or sqlite:////absolute/path.db"
|
|
293
|
+
)
|
|
294
|
+
return Path(raw).expanduser()
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# --------------------------------------------------------------------------
|
|
298
|
+
# PostgreSQL
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class PostgresAdapter(Adapter):
|
|
302
|
+
name = "postgresql"
|
|
303
|
+
dialect = "postgres"
|
|
304
|
+
read_only_note = (
|
|
305
|
+
"every statement runs in a READ ONLY transaction with a statement_timeout; "
|
|
306
|
+
"use a database role that only has SELECT"
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
# Schemas that belong to the server, not to the user's data.
|
|
310
|
+
_SYSTEM_SCHEMAS = ("pg_catalog", "information_schema", "pg_toast")
|
|
311
|
+
|
|
312
|
+
def __init__(self, dsn: str, *, timeout_s: float = 5.0):
|
|
313
|
+
super().__init__(dsn, timeout_s=timeout_s)
|
|
314
|
+
self._psycopg = _import_psycopg()
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def label(self) -> str:
|
|
318
|
+
parsed = urlparse(self.dsn)
|
|
319
|
+
host = parsed.hostname or "localhost"
|
|
320
|
+
port = f":{parsed.port}" if parsed.port else ""
|
|
321
|
+
database = (parsed.path or "/").lstrip("/") or "?"
|
|
322
|
+
return f"postgresql://{host}{port}/{database}"
|
|
323
|
+
|
|
324
|
+
# -- connection ------------------------------------------------------
|
|
325
|
+
def _connect(self):
|
|
326
|
+
"""Open a connection that cannot write and cannot run forever.
|
|
327
|
+
|
|
328
|
+
Three separate things say read-only here, and that is deliberate:
|
|
329
|
+
|
|
330
|
+
* `default_transaction_read_only=on` is set on the connection, so it
|
|
331
|
+
holds even for a transaction psycopg did not open.
|
|
332
|
+
* `read_only = True` makes psycopg emit `BEGIN ... READ ONLY`.
|
|
333
|
+
* `statement_timeout` bounds any single statement.
|
|
334
|
+
|
|
335
|
+
None of it replaces giving the agent a database role that only has
|
|
336
|
+
SELECT. It is what stops a mistake, not what stops an attacker.
|
|
337
|
+
"""
|
|
338
|
+
psycopg = self._psycopg
|
|
339
|
+
timeout_ms = max(int(self.timeout_s * 1000), 1)
|
|
340
|
+
options = (
|
|
341
|
+
f"-c default_transaction_read_only=on "
|
|
342
|
+
f"-c statement_timeout={timeout_ms} "
|
|
343
|
+
f"-c idle_in_transaction_session_timeout={timeout_ms * 4}"
|
|
344
|
+
)
|
|
345
|
+
try:
|
|
346
|
+
conn = psycopg.connect(
|
|
347
|
+
self.dsn,
|
|
348
|
+
options=options,
|
|
349
|
+
connect_timeout=max(int(self.timeout_s), 3),
|
|
350
|
+
row_factory=psycopg.rows.dict_row,
|
|
351
|
+
)
|
|
352
|
+
except psycopg.OperationalError as exc:
|
|
353
|
+
raise ConfigError(
|
|
354
|
+
f"could not connect to {self.label}: {str(exc).strip()}"
|
|
355
|
+
) from exc
|
|
356
|
+
conn.read_only = True
|
|
357
|
+
return conn
|
|
358
|
+
|
|
359
|
+
def check(self) -> None:
|
|
360
|
+
conn = self._connect()
|
|
361
|
+
try:
|
|
362
|
+
with conn.cursor() as cur:
|
|
363
|
+
cur.execute("SELECT 1")
|
|
364
|
+
finally:
|
|
365
|
+
conn.close()
|
|
366
|
+
|
|
367
|
+
def _query(self, sql: str, params: tuple = (), *, limit: int | None = None):
|
|
368
|
+
psycopg = self._psycopg
|
|
369
|
+
conn = self._connect()
|
|
370
|
+
try:
|
|
371
|
+
with conn.cursor() as cur:
|
|
372
|
+
cur.execute(sql, params)
|
|
373
|
+
rows = cur.fetchmany(limit) if limit else cur.fetchall()
|
|
374
|
+
return [{k: _jsonable(v) for k, v in row.items()} for row in rows]
|
|
375
|
+
except psycopg.Error as exc:
|
|
376
|
+
raise QueryError(_pg_message(exc)) from exc
|
|
377
|
+
finally:
|
|
378
|
+
conn.close()
|
|
379
|
+
|
|
380
|
+
# -- catalogue -------------------------------------------------------
|
|
381
|
+
def _split(self, table: str) -> tuple[str | None, str]:
|
|
382
|
+
"""`schema.table` → (schema, table); a bare name → (None, name)."""
|
|
383
|
+
if "." in table:
|
|
384
|
+
schema, _, name = table.partition(".")
|
|
385
|
+
return schema.strip('"'), name.strip('"')
|
|
386
|
+
return None, table.strip('"')
|
|
387
|
+
|
|
388
|
+
def table_names(self) -> list[str]:
|
|
389
|
+
return [t["table"] for t in self.tables()]
|
|
390
|
+
|
|
391
|
+
def tables(self) -> list[dict[str, Any]]:
|
|
392
|
+
"""Base tables and views, with the planner's row estimate.
|
|
393
|
+
|
|
394
|
+
An exact `count(*)` per table is the wrong default here. `list_tables`
|
|
395
|
+
is the cheapest way to orient, and on a real warehouse counting every
|
|
396
|
+
row would blow the statement timeout on the agent's very first call.
|
|
397
|
+
`reltuples` is what the planner itself uses; the result says so.
|
|
398
|
+
"""
|
|
399
|
+
rows = self._query(
|
|
400
|
+
"""
|
|
401
|
+
SELECT n.nspname AS schema,
|
|
402
|
+
c.relname AS name,
|
|
403
|
+
c.relkind AS kind,
|
|
404
|
+
CASE WHEN c.reltuples < 0 THEN NULL
|
|
405
|
+
ELSE c.reltuples::bigint END AS approx_rows
|
|
406
|
+
FROM pg_class c
|
|
407
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
408
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
409
|
+
AND n.nspname <> ALL(%s)
|
|
410
|
+
ORDER BY n.nspname, c.relname
|
|
411
|
+
""",
|
|
412
|
+
(list(self._SYSTEM_SCHEMAS),),
|
|
413
|
+
)
|
|
414
|
+
out = []
|
|
415
|
+
for row in rows:
|
|
416
|
+
schema = row["schema"]
|
|
417
|
+
name = row["name"] if schema == "public" else f"{schema}.{row['name']}"
|
|
418
|
+
out.append({
|
|
419
|
+
"table": name,
|
|
420
|
+
"rows": row["approx_rows"],
|
|
421
|
+
"rows_estimated": True,
|
|
422
|
+
"kind": {"r": "table", "p": "partitioned table", "v": "view",
|
|
423
|
+
"m": "materialized view", "f": "foreign table"}[row["kind"]],
|
|
424
|
+
})
|
|
425
|
+
return out
|
|
426
|
+
|
|
427
|
+
def describe(self, table: str) -> dict[str, Any] | None:
|
|
428
|
+
psycopg = self._psycopg
|
|
429
|
+
schema, name = self._split(table)
|
|
430
|
+
|
|
431
|
+
found = self._query(
|
|
432
|
+
"""
|
|
433
|
+
SELECT n.nspname AS schema, c.relname AS name
|
|
434
|
+
FROM pg_class c
|
|
435
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
436
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
437
|
+
AND c.relname = %s
|
|
438
|
+
AND (%s::text IS NULL OR n.nspname = %s)
|
|
439
|
+
AND n.nspname <> ALL(%s)
|
|
440
|
+
ORDER BY (n.nspname = 'public') DESC, n.nspname
|
|
441
|
+
LIMIT 1
|
|
442
|
+
""",
|
|
443
|
+
(name, schema, schema, list(self._SYSTEM_SCHEMAS)),
|
|
444
|
+
)
|
|
445
|
+
if not found:
|
|
446
|
+
return None
|
|
447
|
+
schema, name = found[0]["schema"], found[0]["name"]
|
|
448
|
+
|
|
449
|
+
columns = self._query(
|
|
450
|
+
"""
|
|
451
|
+
SELECT c.column_name AS name,
|
|
452
|
+
c.data_type AS type,
|
|
453
|
+
c.is_nullable AS is_nullable,
|
|
454
|
+
EXISTS (
|
|
455
|
+
SELECT 1
|
|
456
|
+
FROM information_schema.table_constraints tc
|
|
457
|
+
JOIN information_schema.key_column_usage k
|
|
458
|
+
ON k.constraint_name = tc.constraint_name
|
|
459
|
+
AND k.constraint_schema = tc.constraint_schema
|
|
460
|
+
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
461
|
+
AND tc.table_schema = c.table_schema
|
|
462
|
+
AND tc.table_name = c.table_name
|
|
463
|
+
AND k.column_name = c.column_name
|
|
464
|
+
) AS is_pk
|
|
465
|
+
FROM information_schema.columns c
|
|
466
|
+
WHERE c.table_schema = %s AND c.table_name = %s
|
|
467
|
+
ORDER BY c.ordinal_position
|
|
468
|
+
""",
|
|
469
|
+
(schema, name),
|
|
470
|
+
)
|
|
471
|
+
foreign_keys = self._query(
|
|
472
|
+
"""
|
|
473
|
+
SELECT k.column_name AS column,
|
|
474
|
+
ccu.table_schema AS ref_schema,
|
|
475
|
+
ccu.table_name AS ref_table,
|
|
476
|
+
ccu.column_name AS ref_column
|
|
477
|
+
FROM information_schema.table_constraints tc
|
|
478
|
+
JOIN information_schema.key_column_usage k
|
|
479
|
+
ON k.constraint_name = tc.constraint_name
|
|
480
|
+
AND k.constraint_schema = tc.constraint_schema
|
|
481
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
482
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
483
|
+
AND ccu.constraint_schema = tc.constraint_schema
|
|
484
|
+
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
485
|
+
AND tc.table_schema = %s AND tc.table_name = %s
|
|
486
|
+
ORDER BY k.ordinal_position
|
|
487
|
+
""",
|
|
488
|
+
(schema, name),
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
conn = self._connect()
|
|
492
|
+
try:
|
|
493
|
+
with conn.cursor() as cur:
|
|
494
|
+
cur.execute(
|
|
495
|
+
psycopg.sql.SQL("SELECT * FROM {} LIMIT 3").format(
|
|
496
|
+
psycopg.sql.Identifier(schema, name)
|
|
497
|
+
)
|
|
498
|
+
)
|
|
499
|
+
sample = [
|
|
500
|
+
{k: _jsonable(v) for k, v in row.items()} for row in cur.fetchall()
|
|
501
|
+
]
|
|
502
|
+
except psycopg.Error as exc:
|
|
503
|
+
raise QueryError(_pg_message(exc)) from exc
|
|
504
|
+
finally:
|
|
505
|
+
conn.close()
|
|
506
|
+
|
|
507
|
+
display = name if schema == "public" else f"{schema}.{name}"
|
|
508
|
+
return {
|
|
509
|
+
"table": display,
|
|
510
|
+
"columns": [
|
|
511
|
+
{
|
|
512
|
+
"name": c["name"],
|
|
513
|
+
"type": c["type"],
|
|
514
|
+
"notnull": c["is_nullable"] == "NO",
|
|
515
|
+
"pk": bool(c["is_pk"]),
|
|
516
|
+
}
|
|
517
|
+
for c in columns
|
|
518
|
+
],
|
|
519
|
+
"foreign_keys": [
|
|
520
|
+
{
|
|
521
|
+
"column": fk["column"],
|
|
522
|
+
"references": (
|
|
523
|
+
f"{fk['ref_table']}.{fk['ref_column']}"
|
|
524
|
+
if fk["ref_schema"] == "public"
|
|
525
|
+
else f"{fk['ref_schema']}.{fk['ref_table']}.{fk['ref_column']}"
|
|
526
|
+
),
|
|
527
|
+
}
|
|
528
|
+
for fk in foreign_keys
|
|
529
|
+
],
|
|
530
|
+
"sample_rows": sample,
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
# -- queries ---------------------------------------------------------
|
|
534
|
+
def select(self, sql: str, limit: int) -> list[dict[str, Any]]:
|
|
535
|
+
return self._query(sql, limit=limit)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _pg_message(exc: Exception) -> str:
|
|
539
|
+
"""PostgreSQL's own wording, without psycopg's traceback furniture."""
|
|
540
|
+
diag = getattr(exc, "diag", None)
|
|
541
|
+
primary = getattr(diag, "message_primary", None) if diag else None
|
|
542
|
+
detail = getattr(diag, "message_hint", None) if diag else None
|
|
543
|
+
if primary:
|
|
544
|
+
return f"{primary}" + (f" ({detail})" if detail else "")
|
|
545
|
+
return str(exc).strip()
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _import_psycopg():
|
|
549
|
+
try:
|
|
550
|
+
import psycopg
|
|
551
|
+
import psycopg.rows # noqa: F401 (attribute access below)
|
|
552
|
+
import psycopg.sql # noqa: F401
|
|
553
|
+
except ModuleNotFoundError as exc: # pragma: no cover - depends on install
|
|
554
|
+
raise ConfigError(
|
|
555
|
+
"PostgreSQL support needs psycopg. Install it with "
|
|
556
|
+
'pip install "sql-agent-mcp[postgres]" (or pip install "psycopg[binary]").'
|
|
557
|
+
) from exc
|
|
558
|
+
return psycopg
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
# --------------------------------------------------------------------------
|
|
562
|
+
# resolution
|
|
563
|
+
|
|
564
|
+
#: scheme → adapter. Adding MySQL is a class and one line here; the tools the
|
|
565
|
+
#: agent calls do not change.
|
|
566
|
+
_ADAPTERS: dict[str, type[Adapter]] = {
|
|
567
|
+
"sqlite": SQLiteAdapter,
|
|
568
|
+
"sqlite3": SQLiteAdapter,
|
|
569
|
+
"file": SQLiteAdapter,
|
|
570
|
+
"postgres": PostgresAdapter,
|
|
571
|
+
"postgresql": PostgresAdapter,
|
|
572
|
+
"postgresql+psycopg": PostgresAdapter,
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
#: Engines we recognise but do not speak yet, so the error can say so.
|
|
576
|
+
_PLANNED = {
|
|
577
|
+
"mysql": "MySQL",
|
|
578
|
+
"mariadb": "MariaDB",
|
|
579
|
+
"mysql+pymysql": "MySQL",
|
|
580
|
+
"duckdb": "DuckDB",
|
|
581
|
+
"bigquery": "BigQuery",
|
|
582
|
+
"snowflake": "Snowflake",
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def describe_dsn(dsn: str) -> str:
|
|
587
|
+
"""The scheme of a DSN, for error messages."""
|
|
588
|
+
scheme, sep, _ = dsn.partition("://")
|
|
589
|
+
return scheme.lower() if sep else "sqlite"
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def resolve(
|
|
593
|
+
target: str | Path | None = None,
|
|
594
|
+
*,
|
|
595
|
+
timeout_s: float = 5.0,
|
|
596
|
+
env: dict[str, str] | None = None,
|
|
597
|
+
) -> Adapter:
|
|
598
|
+
"""Pick an adapter for `target`, or for `SQL_AGENT_DSN`, or for the demo.
|
|
599
|
+
|
|
600
|
+
Resolution order, first hit wins:
|
|
601
|
+
|
|
602
|
+
1. `target`, if given — a DSN or a filesystem path.
|
|
603
|
+
2. `SQL_AGENT_DSN`.
|
|
604
|
+
3. The bundled sample database, but only when `SQL_AGENT_DEMO=1`.
|
|
605
|
+
|
|
606
|
+
With none of those, raise `ConfigError` saying what to set. Guessing a
|
|
607
|
+
database is how you end up querying the wrong one.
|
|
608
|
+
"""
|
|
609
|
+
env = os.environ if env is None else env
|
|
610
|
+
|
|
611
|
+
if isinstance(target, Path):
|
|
612
|
+
target = str(target)
|
|
613
|
+
dsn = (target or "").strip() or (env.get("SQL_AGENT_DSN") or "").strip()
|
|
614
|
+
|
|
615
|
+
if not dsn:
|
|
616
|
+
if _demo_requested(env):
|
|
617
|
+
from sql_agent import db
|
|
618
|
+
|
|
619
|
+
return SQLiteAdapter(str(db.ensure_demo()), timeout_s=timeout_s)
|
|
620
|
+
raise ConfigError(
|
|
621
|
+
"no database configured. Set SQL_AGENT_DSN (for example "
|
|
622
|
+
"sqlite:///./shop.db or postgresql://user:pw@host/db), pass --dsn, "
|
|
623
|
+
"or use --demo / SQL_AGENT_DEMO=1 for the bundled sample database."
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
scheme = describe_dsn(dsn)
|
|
627
|
+
adapter = _ADAPTERS.get(scheme)
|
|
628
|
+
if adapter is None:
|
|
629
|
+
if scheme in _PLANNED:
|
|
630
|
+
raise ConfigError(
|
|
631
|
+
f"{_PLANNED[scheme]} is not supported yet. Supported schemes: "
|
|
632
|
+
f"{', '.join(sorted(set(_ADAPTERS)))}. Adding one is a subclass "
|
|
633
|
+
"of sql_agent.adapters.Adapter plus an entry in _ADAPTERS."
|
|
634
|
+
)
|
|
635
|
+
raise ConfigError(
|
|
636
|
+
f"unsupported connection string {scheme!r}. Supported schemes: "
|
|
637
|
+
f"{', '.join(sorted(set(_ADAPTERS)))}, or a plain path to a SQLite file."
|
|
638
|
+
)
|
|
639
|
+
return adapter(dsn, timeout_s=timeout_s)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _demo_requested(env: dict[str, str]) -> bool:
|
|
643
|
+
return (env.get("SQL_AGENT_DEMO") or "").strip().lower() in ("1", "true", "yes", "on")
|