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/tools.py ADDED
@@ -0,0 +1,225 @@
1
+ """The four tools the agent can call.
2
+
3
+ Every tool returns a dict and never raises. A tool that fails returns
4
+ `{"ok": False, "error": ...}`, because a raised exception ends the run while a
5
+ returned error is something the agent can read and act on. The whole point of
6
+ this project is what happens on the step *after* a failure.
7
+
8
+ Nothing here knows which database engine it is talking to. The engine lives in
9
+ `sql_agent.adapters`, the statement guard in `sql_agent.sqlguard`; adding MySQL
10
+ means adding an adapter, not editing this file.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from sql_agent import sqlguard
19
+ from sql_agent.adapters import Adapter, ConfigError, QueryError, resolve
20
+
21
+ MAX_ROWS = 50
22
+
23
+
24
+ class Tools:
25
+ """Bound to one database, so tests can point at a scratch one.
26
+
27
+ `target` is a DSN (`postgresql://…`, `sqlite:///…`) or a plain path to a
28
+ SQLite file. With nothing given it falls back to `SQL_AGENT_DSN`, and then
29
+ to the bundled sample database if `SQL_AGENT_DEMO=1`.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ target: str | Path | None = None,
35
+ *,
36
+ timeout_s: float = 5.0,
37
+ adapter: Adapter | None = None,
38
+ ):
39
+ self.timeout_s = timeout_s
40
+ self._target = target
41
+ self._adapter = adapter
42
+ self._config_error: str | None = None
43
+ if adapter is None:
44
+ try:
45
+ self._adapter = resolve(target, timeout_s=timeout_s)
46
+ except ConfigError as exc:
47
+ # Deferred, not raised: an unusable DSN should reach the model
48
+ # (and the MCP client) as a readable error, not as a traceback
49
+ # on import.
50
+ self._config_error = str(exc)
51
+
52
+ # -- identity --------------------------------------------------------
53
+ @property
54
+ def adapter(self) -> Adapter:
55
+ if self._adapter is None:
56
+ raise ConfigError(self._config_error or "no database configured")
57
+ return self._adapter
58
+
59
+ @property
60
+ def engine(self) -> str:
61
+ return self._adapter.name if self._adapter else "unconfigured"
62
+
63
+ @property
64
+ def label(self) -> str:
65
+ return self._adapter.label if self._adapter else "unconfigured"
66
+
67
+ def _unconfigured(self) -> dict[str, Any] | None:
68
+ if self._adapter is None:
69
+ return {"ok": False, "error": self._config_error or "no database configured"}
70
+ return None
71
+
72
+ # -- tool 1 ----------------------------------------------------------
73
+ def list_tables(self) -> dict[str, Any]:
74
+ """Every table, with its row count. The cheapest way to orient."""
75
+ if (err := self._unconfigured()):
76
+ return err
77
+ try:
78
+ tables = self.adapter.tables()
79
+ except (ConfigError, QueryError) as exc:
80
+ return {"ok": False, "error": str(exc)}
81
+ except Exception as exc: # pragma: no cover - defensive
82
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
83
+ return {"ok": True, "engine": self.engine, "tables": tables}
84
+
85
+ # -- tool 2 ----------------------------------------------------------
86
+ def describe_table(self, table: str) -> dict[str, Any]:
87
+ """Columns, types, foreign keys and three real rows.
88
+
89
+ The sample rows matter more than the types: they are what reveals that
90
+ money is stored in cents and that dates are ISO strings.
91
+ """
92
+ if (err := self._unconfigured()):
93
+ return err
94
+ table = (table or "").strip()
95
+ if not table:
96
+ return {"ok": False, "error": "no table name given"}
97
+ try:
98
+ described = self.adapter.describe(table)
99
+ if described is None:
100
+ known = self.adapter.table_names()
101
+ return {
102
+ "ok": False,
103
+ "error": f"no such table: {table}",
104
+ "hint": f"tables are: {', '.join(known)}" if known
105
+ else "this database has no tables",
106
+ }
107
+ except (ConfigError, QueryError) as exc:
108
+ return {"ok": False, "error": str(exc)}
109
+ except Exception as exc: # pragma: no cover - defensive
110
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
111
+ return {"ok": True, "engine": self.engine, **described}
112
+
113
+ # -- tool 3 ----------------------------------------------------------
114
+ def run_sql(self, query: str) -> dict[str, Any]:
115
+ """Run one read-only SELECT.
116
+
117
+ Errors come back as text, deliberately. `no such column: total` is the
118
+ single most useful thing this database can tell an agent, because it is
119
+ the moment it has to stop guessing and go read the schema.
120
+ """
121
+ if (err := self._unconfigured()):
122
+ return err
123
+ query = (query or "").strip().rstrip(";").strip()
124
+ if not query:
125
+ return {"ok": False, "error": "empty query"}
126
+
127
+ refused = sqlguard.check(query, dialect=self.adapter.dialect)
128
+ if refused:
129
+ return {"ok": False, "error": refused, "query": query}
130
+
131
+ try:
132
+ rows = self.adapter.select(query, MAX_ROWS + 1)
133
+ except QueryError as exc:
134
+ # The agent reads this string. Keep the database's own wording.
135
+ return {"ok": False, "error": str(exc), "query": query}
136
+ except ConfigError as exc:
137
+ return {"ok": False, "error": str(exc), "query": query}
138
+ except Exception as exc: # pragma: no cover - defensive
139
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}", "query": query}
140
+
141
+ truncated = len(rows) > MAX_ROWS
142
+ return {
143
+ "ok": True,
144
+ "query": query,
145
+ "rows": rows[:MAX_ROWS],
146
+ "row_count": len(rows[:MAX_ROWS]),
147
+ "truncated": truncated,
148
+ }
149
+
150
+ # -- tool 4 ----------------------------------------------------------
151
+ def finish(self, answer: str, sql: str = "") -> dict[str, Any]:
152
+ """Terminal step. The agent states its answer and the SQL behind it."""
153
+ return {"ok": True, "answer": answer, "sql": sql}
154
+
155
+ # --------------------------------------------------------------------
156
+ def call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
157
+ fn = {
158
+ "list_tables": lambda a: self.list_tables(),
159
+ "describe_table": lambda a: self.describe_table(a.get("table", "")),
160
+ "run_sql": lambda a: self.run_sql(a.get("query", "")),
161
+ "finish": lambda a: self.finish(a.get("answer", ""), a.get("sql", "")),
162
+ }.get(name)
163
+ if fn is None:
164
+ return {"ok": False, "error": f"unknown tool: {name}"}
165
+ return fn(arguments)
166
+
167
+
168
+ SCHEMAS: list[dict[str, Any]] = [
169
+ {
170
+ "type": "function",
171
+ "function": {
172
+ "name": "list_tables",
173
+ "description": "List every table in the database with its row count.",
174
+ "parameters": {"type": "object", "properties": {}, "required": []},
175
+ },
176
+ },
177
+ {
178
+ "type": "function",
179
+ "function": {
180
+ "name": "describe_table",
181
+ "description": (
182
+ "Show a table's columns, types, foreign keys and three sample rows. "
183
+ "Read this before writing SQL against a table you have not inspected."
184
+ ),
185
+ "parameters": {
186
+ "type": "object",
187
+ "properties": {"table": {"type": "string", "description": "Table name."}},
188
+ "required": ["table"],
189
+ },
190
+ },
191
+ },
192
+ {
193
+ "type": "function",
194
+ "function": {
195
+ "name": "run_sql",
196
+ "description": (
197
+ "Execute one read-only SELECT (or WITH) query and return up to 50 rows. "
198
+ "If the query is invalid you get the database error back; read it and fix the query."
199
+ ),
200
+ "parameters": {
201
+ "type": "object",
202
+ "properties": {"query": {"type": "string", "description": "A single SELECT statement."}},
203
+ "required": ["query"],
204
+ },
205
+ },
206
+ },
207
+ {
208
+ "type": "function",
209
+ "function": {
210
+ "name": "finish",
211
+ "description": (
212
+ "Give the final answer. Call this only once you have run a query whose "
213
+ "result actually answers the question."
214
+ ),
215
+ "parameters": {
216
+ "type": "object",
217
+ "properties": {
218
+ "answer": {"type": "string", "description": "The answer, in plain prose, with the figures."},
219
+ "sql": {"type": "string", "description": "The final SQL the answer rests on."},
220
+ },
221
+ "required": ["answer"],
222
+ },
223
+ },
224
+ },
225
+ ]
sql_agent/trace.py ADDED
@@ -0,0 +1,175 @@
1
+ """Per-step accounting.
2
+
3
+ An agent you cannot read is an agent you cannot debug, evaluate or put a budget
4
+ on. Every model call and every tool call lands here with its latency, its token
5
+ usage and what it cost, and the whole run serialises to JSON so the evaluation
6
+ harness can assert on the *path*, not just the final answer.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ import uuid
15
+ from dataclasses import dataclass, field, asdict
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+
21
+ def _usd_per_mtok(var: str, default: float) -> float:
22
+ try:
23
+ return float(os.getenv(var, default))
24
+ except (TypeError, ValueError):
25
+ return default
26
+
27
+
28
+ @dataclass
29
+ class Step:
30
+ n: int
31
+ kind: str # "model" | "tool"
32
+ name: str # model name, or tool name
33
+ latency_ms: int
34
+ ok: bool = True
35
+ arguments: dict[str, Any] = field(default_factory=dict)
36
+ summary: str = "" # one line, for humans
37
+ error: str | None = None
38
+ prompt_tokens: int = 0
39
+ completion_tokens: int = 0
40
+ cost_usd: float = 0.0
41
+
42
+
43
+ @dataclass
44
+ class Trace:
45
+ question: str
46
+ run_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
47
+ started_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
48
+ steps: list[Step] = field(default_factory=list)
49
+ answer: str | None = None
50
+ final_sql: str | None = None # SQL that was actually executed
51
+ claimed_sql: str | None = None # SQL the model typed into `finish`
52
+ stopped_reason: str | None = None # "finished" | "max_steps" | "error"
53
+ engine: str | None = None # "sqlite" | "postgresql" | …
54
+
55
+ # -- recording -------------------------------------------------------
56
+ def add_model(self, model: str, latency_ms: int, usage: Any, summary: str) -> Step:
57
+ pin = _usd_per_mtok("SQL_AGENT_COST_IN", 0.25)
58
+ pout = _usd_per_mtok("SQL_AGENT_COST_OUT", 0.85)
59
+ p = int(getattr(usage, "prompt_tokens", 0) or 0)
60
+ c = int(getattr(usage, "completion_tokens", 0) or 0)
61
+ step = Step(
62
+ n=len(self.steps) + 1, kind="model", name=model, latency_ms=latency_ms,
63
+ summary=summary, prompt_tokens=p, completion_tokens=c,
64
+ cost_usd=round(p / 1e6 * pin + c / 1e6 * pout, 6),
65
+ )
66
+ self.steps.append(step)
67
+ return step
68
+
69
+ def add_tool(self, name: str, arguments: dict[str, Any], result: dict[str, Any],
70
+ latency_ms: int) -> Step:
71
+ ok = bool(result.get("ok"))
72
+ step = Step(
73
+ n=len(self.steps) + 1, kind="tool", name=name, latency_ms=latency_ms,
74
+ ok=ok, arguments=arguments, summary=_summarise(name, result),
75
+ error=None if ok else str(result.get("error", "")),
76
+ )
77
+ self.steps.append(step)
78
+ return step
79
+
80
+ # -- totals ----------------------------------------------------------
81
+ @property
82
+ def cost_usd(self) -> float:
83
+ return round(sum(s.cost_usd for s in self.steps), 6)
84
+
85
+ @property
86
+ def latency_ms(self) -> int:
87
+ return sum(s.latency_ms for s in self.steps)
88
+
89
+ @property
90
+ def tool_calls(self) -> int:
91
+ return sum(1 for s in self.steps if s.kind == "tool")
92
+
93
+ @property
94
+ def recoveries(self) -> int:
95
+ """Failed tool calls that were followed by a successful one.
96
+
97
+ This is the number the project exists to produce. A run with zero
98
+ failures proves nothing about recovery; a run that fails and then
99
+ stops proves the opposite of what we want.
100
+ """
101
+ tools = [s for s in self.steps if s.kind == "tool"]
102
+ return sum(
103
+ 1 for i, s in enumerate(tools)
104
+ if not s.ok and any(t.ok for t in tools[i + 1:])
105
+ )
106
+
107
+ @property
108
+ def tool_path(self) -> list[str]:
109
+ return [f"{s.name}{'' if s.ok else '!'}" for s in self.steps if s.kind == "tool"]
110
+
111
+ # -- serialisation ---------------------------------------------------
112
+ def to_dict(self) -> dict[str, Any]:
113
+ return {
114
+ "run_id": self.run_id,
115
+ "started_at": self.started_at,
116
+ "question": self.question,
117
+ "engine": self.engine,
118
+ "answer": self.answer,
119
+ "final_sql": self.final_sql,
120
+ "claimed_sql": self.claimed_sql,
121
+ "sql_was_executed": bool(self.final_sql),
122
+ "stopped_reason": self.stopped_reason,
123
+ "totals": {
124
+ "steps": len(self.steps),
125
+ "tool_calls": self.tool_calls,
126
+ "recoveries": self.recoveries,
127
+ "latency_ms": self.latency_ms,
128
+ "cost_usd": self.cost_usd,
129
+ "tool_path": self.tool_path,
130
+ },
131
+ "steps": [asdict(s) for s in self.steps],
132
+ }
133
+
134
+ def save(self, directory: Path | str = "traces") -> Path:
135
+ directory = Path(directory)
136
+ directory.mkdir(parents=True, exist_ok=True)
137
+ path = directory / f"{self.run_id}.json"
138
+ path.write_text(json.dumps(self.to_dict(), indent=2, ensure_ascii=False), encoding="utf-8")
139
+ return path
140
+
141
+ def render(self) -> str:
142
+ """The plain-text trace that goes in the README."""
143
+ lines = [f"question: {self.question}", ""]
144
+ for s in self.steps:
145
+ if s.kind == "model":
146
+ lines.append(f" [{s.n}] think {s.latency_ms:>5} ms "
147
+ f"{s.prompt_tokens}+{s.completion_tokens} tok ${s.cost_usd:.4f}")
148
+ else:
149
+ mark = "ok " if s.ok else "ERR"
150
+ detail = s.summary if s.ok else (s.error or "")
151
+ lines.append(f" [{s.n}] {s.name:<16} {s.latency_ms:>5} ms {mark} {detail}")
152
+ lines += [
153
+ "",
154
+ f" {len(self.steps)} steps · {self.tool_calls} tool calls · "
155
+ f"{self.recoveries} recoveries · {self.latency_ms/1000:.1f}s · ${self.cost_usd:.4f}",
156
+ ]
157
+ if self.stopped_reason and self.stopped_reason != "finished":
158
+ lines.append(f" stopped: {self.stopped_reason}")
159
+ return "\n".join(lines)
160
+
161
+
162
+ def _summarise(name: str, result: dict[str, Any]) -> str:
163
+ if not result.get("ok"):
164
+ return str(result.get("error", ""))
165
+ if name == "list_tables":
166
+ return f"{len(result.get('tables', []))} tables"
167
+ if name == "describe_table":
168
+ cols = len(result.get("columns", []))
169
+ return f"{result.get('table')}: {cols} columns"
170
+ if name == "run_sql":
171
+ n = result.get("row_count", 0)
172
+ return f"{n} row{'s' if n != 1 else ''}" + (" (truncated)" if result.get("truncated") else "")
173
+ if name == "finish":
174
+ return "answered"
175
+ return ""