postgres-schema-mcp 0.1.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.
@@ -0,0 +1,269 @@
1
+ """Layer 2 of the safety model: an AST policy over the submitted SQL.
2
+
3
+ The policy is deliberately an allowlist of *shapes* rather than a denylist of
4
+ strings. A single statement is accepted only when it is a SELECT (or a set
5
+ operation over SELECTs, or a WITH whose body is one of those) and when no node
6
+ anywhere in the tree is DML, DDL, a lock, or a call to a denylisted function.
7
+
8
+ Why not a regex. The query that defeats a regex allowlist is:
9
+
10
+ WITH gone AS (DELETE FROM customer RETURNING *) SELECT * FROM gone;
11
+
12
+ It begins with WITH, it contains SELECT, and it empties the table. sqlglot parses
13
+ it to a top-level Select whose tree contains a Delete node, so walking the AST
14
+ catches it and a prefix match does not. The same argument runs in the other
15
+ direction: a text denylist rejects
16
+
17
+ SELECT 'DROP TABLE customer' AS note FROM person.person;
18
+
19
+ which is an ordinary read-only query. Both cases are in the fault matrix.
20
+
21
+ This layer is not the last line of defence. It sits above a database role that
22
+ holds only SELECT, because a parser bug here should not be a write there.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ from typing import Final
29
+
30
+ import sqlglot
31
+ from sqlglot import exp
32
+
33
+ __all__ = ["DENYLISTED_FUNCTIONS", "DENYLISTED_PREFIXES", "BlockedQueryError", "check_read_only"]
34
+
35
+ _DIALECT: Final = "postgres"
36
+
37
+ _REMEDY: Final = "This server is read-only. Rewrite the request as a plain SELECT."
38
+
39
+
40
+ class BlockedQueryError(Exception):
41
+ """Raised when a statement fails the read-only policy.
42
+
43
+ The string form is written to be read by a model: it names the construct
44
+ that was rejected and says what to do instead. server.py turns this into a
45
+ tool execution error (isError: true), not a protocol error.
46
+ """
47
+
48
+ def __init__(self, reason: str) -> None:
49
+ self.reason = reason
50
+ super().__init__(f"Blocked: {reason} {_REMEDY}")
51
+
52
+
53
+ # Every node type below is either a write, a schema change, a privilege change,
54
+ # or a lock. Mapped to the wording used in the message back to the model.
55
+ _FORBIDDEN_NODES: Final[dict[type[exp.Expr], str]] = {
56
+ exp.Insert: "INSERT",
57
+ exp.Update: "UPDATE",
58
+ exp.Delete: "DELETE",
59
+ exp.Merge: "MERGE",
60
+ exp.Drop: "DROP",
61
+ exp.Create: "CREATE",
62
+ exp.Alter: "ALTER",
63
+ exp.TruncateTable: "TRUNCATE",
64
+ exp.Grant: "GRANT",
65
+ exp.Revoke: "REVOKE",
66
+ exp.Copy: "COPY",
67
+ # SELECT ... INTO creates a new table in Postgres, so it is DDL wearing a
68
+ # SELECT costume.
69
+ exp.Into: "SELECT ... INTO",
70
+ # FOR UPDATE / FOR SHARE take row locks, which is a write to shared state
71
+ # even though no column value changes.
72
+ exp.Lock: "row-locking clause (FOR UPDATE / FOR SHARE)",
73
+ # sqlglot represents statements it has no grammar for as a Command
74
+ # passthrough. Anything the parser cannot describe cannot be vouched for, so
75
+ # it is refused rather than forwarded.
76
+ exp.Command: "statement the parser could not classify",
77
+ exp.Set: "SET",
78
+ exp.Transaction: "transaction control",
79
+ exp.Commit: "COMMIT",
80
+ exp.Rollback: "ROLLBACK",
81
+ }
82
+
83
+ # Checked against every function node in the tree, never against the raw text.
84
+ # Names are compared case-folded, and a schema qualifier such as
85
+ # pg_catalog.pg_read_file still resolves to the bare name here.
86
+ DENYLISTED_FUNCTIONS: Final[frozenset[str]] = frozenset(
87
+ {
88
+ # Filesystem access
89
+ "pg_read_file",
90
+ "pg_read_binary_file",
91
+ "pg_ls_dir",
92
+ "pg_stat_file",
93
+ "pg_ls_logdir",
94
+ "pg_ls_waldir",
95
+ "pg_ls_tmpdir",
96
+ "pg_ls_archive_statusdir",
97
+ # Large objects, which are a second path to the filesystem
98
+ "lo_import",
99
+ "lo_export",
100
+ "lo_get",
101
+ "lo_put",
102
+ "lo_from_bytea",
103
+ "lo_unlink",
104
+ # Network egress
105
+ "dblink",
106
+ "dblink_exec",
107
+ "dblink_connect",
108
+ "dblink_connect_u",
109
+ "dblink_open",
110
+ "dblink_send_query",
111
+ "http",
112
+ "http_get",
113
+ "http_post",
114
+ "http_put",
115
+ "http_delete",
116
+ # Executes an arbitrary SQL string, so it is a way around this whole
117
+ # policy if left reachable.
118
+ "query_to_xml",
119
+ "query_to_xmlschema",
120
+ "query_to_xml_and_xmlschema",
121
+ # Denial of service
122
+ "pg_sleep",
123
+ "pg_sleep_for",
124
+ "pg_sleep_until",
125
+ # Server administration
126
+ "pg_reload_conf",
127
+ "pg_rotate_logfile",
128
+ "pg_terminate_backend",
129
+ "pg_cancel_backend",
130
+ "pg_create_restore_point",
131
+ "pg_switch_wal",
132
+ "pg_promote",
133
+ "pg_backup_start",
134
+ "pg_backup_stop",
135
+ "set_config",
136
+ "pg_logical_emit_message",
137
+ "pg_notify",
138
+ "pg_import_system_collations",
139
+ "pg_start_backup",
140
+ "pg_stop_backup",
141
+ # Change database state although they sit inside a SELECT
142
+ "nextval",
143
+ "setval",
144
+ "txid_current",
145
+ "pg_current_xact_id",
146
+ "loread",
147
+ "lowrite",
148
+ # Execute an SQL string passed as an argument, outside this policy
149
+ "cursor_to_xml",
150
+ "cursor_to_xmlschema",
151
+ "connectby",
152
+ "ts_stat",
153
+ "xpath_table",
154
+ }
155
+ )
156
+
157
+ # Whole families of functions. A name that starts with one of these is refused, so a
158
+ # function added in a later PostgreSQL release, or one this list missed, is still caught.
159
+ # The cost is that a user function with such a prefix is refused too.
160
+ DENYLISTED_PREFIXES: Final[tuple[str, ...]] = (
161
+ "lo_", # large objects: filesystem access and writes
162
+ "dblink", # network egress and remote execution
163
+ "http_", # network egress
164
+ "crosstab", # tablefunc: runs an SQL string passed as an argument
165
+ "pg_sleep", # denial of service
166
+ "pg_advisory_", # session-level locks outlive the statement on a pooled connection
167
+ "pg_try_advisory_",
168
+ "pg_read_", # filesystem
169
+ "pg_ls_",
170
+ "pg_file_",
171
+ "pg_replication_", # replication slots and origins
172
+ "pg_create_",
173
+ "pg_drop_",
174
+ "pg_copy_",
175
+ "pg_stat_reset", # clears statistics
176
+ "pg_set_",
177
+ "pg_clear_",
178
+ "pg_wal_replay",
179
+ "pg_log_", # writes to the server log
180
+ "pg_logical_",
181
+ )
182
+
183
+ # A function name that is not a plain identifier cannot be matched against a list of
184
+ # plain names, so it is refused. This covers U&"..." escapes, where the name PostgreSQL
185
+ # calls is not the text that was written.
186
+ _PLAIN_NAME: Final = re.compile(r"[a-z_][a-z0-9_$]*")
187
+
188
+ # A statement is acceptable only if its root is one of these.
189
+ _ALLOWED_ROOTS: Final[tuple[type[exp.Expr], ...]] = (
190
+ exp.Select,
191
+ exp.Union,
192
+ exp.Except,
193
+ exp.Intersect,
194
+ exp.Subquery,
195
+ )
196
+
197
+
198
+ def _function_names(node: exp.Expr) -> list[str]:
199
+ """Every name by which this node might be a denylisted function call."""
200
+ names: list[str] = []
201
+ if isinstance(node, exp.Anonymous):
202
+ # Unknown-to-sqlglot function. `name` is the text without quotes, so
203
+ # "pg_sleep"(1) and pg_sleep(1) give the same name. `str(node.this)` is not
204
+ # that: for a quoted name it is an Identifier node and never matches.
205
+ names.append(node.name)
206
+ elif isinstance(node, exp.Func):
207
+ # Known function: compare on sqlglot's canonical name.
208
+ names.append(node.sql_name())
209
+ return [n.casefold() for n in names if n]
210
+
211
+
212
+ def check_read_only(sql: str) -> None:
213
+ """Raise BlockedQueryError unless `sql` is a single read-only statement.
214
+
215
+ Returns None on success. Fails closed: anything that cannot be parsed, or
216
+ that parses to something other than exactly one SELECT-shaped statement, is
217
+ blocked.
218
+ """
219
+ try:
220
+ statements = sqlglot.parse(sql, dialect=_DIALECT, error_level=sqlglot.ErrorLevel.RAISE)
221
+ except Exception as exc: # sqlglot raises several types; all mean "unverifiable"
222
+ raise BlockedQueryError(
223
+ f"the statement could not be parsed as PostgreSQL ({type(exc).__name__}), "
224
+ "so it cannot be checked."
225
+ ) from exc
226
+
227
+ # sqlglot yields None for an empty segment and an exp.Semicolon placeholder
228
+ # for a segment that is only a comment, e.g. the tail of "SELECT 1; -- note".
229
+ # Neither is a statement. Note this does not weaken the stacking check:
230
+ # "SELECT 1; /* c */ DROP TABLE t;" still parses to two real statements.
231
+ real = [s for s in statements if s is not None and not isinstance(s, exp.Semicolon)]
232
+ if not real:
233
+ raise BlockedQueryError(
234
+ "no SQL statement was found (the input was empty or only comments)."
235
+ )
236
+ if len(real) > 1:
237
+ raise BlockedQueryError(
238
+ f"the input contains {len(real)} statements; statement stacking is not allowed. "
239
+ "Send exactly one statement."
240
+ )
241
+
242
+ root = real[0]
243
+ if not isinstance(root, _ALLOWED_ROOTS):
244
+ label = _FORBIDDEN_NODES.get(type(root), type(root).__name__.upper())
245
+ raise BlockedQueryError(f"the statement is a {label}, and only SELECT is permitted.")
246
+
247
+ for node in root.walk():
248
+ for forbidden, label in _FORBIDDEN_NODES.items():
249
+ if isinstance(node, forbidden):
250
+ if node is root:
251
+ raise BlockedQueryError(
252
+ f"the statement is a {label}, and only SELECT is permitted."
253
+ )
254
+ raise BlockedQueryError(
255
+ f"the statement contains a {label} nested inside the query "
256
+ "(in a CTE or subquery), which a prefix check would miss."
257
+ )
258
+
259
+ for name in _function_names(node):
260
+ if _PLAIN_NAME.fullmatch(name) is None:
261
+ raise BlockedQueryError(
262
+ "the statement calls a function whose name is not a plain identifier "
263
+ '(for example one written with U&"..." escapes), so it cannot be checked.'
264
+ )
265
+ if name in DENYLISTED_FUNCTIONS or name.startswith(DENYLISTED_PREFIXES):
266
+ raise BlockedQueryError(
267
+ f"the statement calls {name}(), which is not permitted "
268
+ "(filesystem, network, administrative, locking or denial-of-service function)."
269
+ )
@@ -0,0 +1,429 @@
1
+ """Schema index and search: the retrieval half of the thesis.
2
+
3
+ The whole point of this server is that an agent should be handed the tables
4
+ relevant to its question, not the entire schema. This module builds one document
5
+ per table at startup and ranks those documents against the question.
6
+
7
+ Two backends sit behind one interface:
8
+
9
+ * BM25 (rank_bm25). The default, so the repo runs offline with no credentials
10
+ and no per-query cost.
11
+ * Amazon Titan Text Embeddings V2 via Bedrock, enabled with
12
+ PGSS_RETRIEVAL_BACKEND=titan. It lives in adapters/backends.py, because it
13
+ makes network calls and this module does none.
14
+
15
+ The honest failure mode, stated here because it is stated in the README too:
16
+ retrieval can rank a needed table below the cutoff, and when that happens the
17
+ table is absent from the slice entirely and the model cannot recover from the
18
+ slice alone. That is exactly why describe_table exists, and why every
19
+ SchemaSlice carries a note telling the model to use it.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from collections.abc import Callable, Sequence
26
+ from typing import Any, Final, Protocol
27
+
28
+ from .types import TableDetail
29
+
30
+ __all__ = [
31
+ "BM25Backend",
32
+ "BackendFactory",
33
+ "RetrievalBackend",
34
+ "SchemaIndex",
35
+ "build_document",
36
+ "count_tokens",
37
+ "tokenize",
38
+ "tokenizer_name",
39
+ ]
40
+
41
+ # How much of a table's score propagates to its foreign-key neighbours. Tuned on
42
+ # the eval set: see SchemaIndex.search for why the mechanism exists, and the
43
+ # README for the measured before/after.
44
+ DEFAULT_NEIGHBOUR_WEIGHT: Final = 0.35
45
+
46
+ # AdventureWorks identifiers are lowercase concatenations: salesorderheader,
47
+ # businessentityid, productsubcategory. A whitespace tokenizer sees one opaque
48
+ # token, so "how many sales orders" never matches "salesorderheader".
49
+ #
50
+ # This lexicon lets the tokenizer split those names back into words by greedy
51
+ # longest-match. It is a deliberate design decision rather than an accident: the
52
+ # alternative, character n-grams, retrieves more noise, and a general English
53
+ # dictionary splits domain terms badly. The cost is that the lexicon is specific
54
+ # to this schema's vocabulary; a different database would want its own.
55
+ _LEXICON: Final[tuple[str, ...]] = (
56
+ "address",
57
+ "archive",
58
+ "assembly",
59
+ "bill",
60
+ "business",
61
+ "candidate",
62
+ "card",
63
+ "cart",
64
+ "catalog",
65
+ "category",
66
+ "contact",
67
+ "cost",
68
+ "country",
69
+ "credit",
70
+ "culture",
71
+ "currency",
72
+ "customer",
73
+ "date",
74
+ "department",
75
+ "description",
76
+ "detail",
77
+ "document",
78
+ "email",
79
+ "employee",
80
+ "entity",
81
+ "flag",
82
+ "group",
83
+ "header",
84
+ "history",
85
+ "illustration",
86
+ "inventory",
87
+ "item",
88
+ "job",
89
+ "level",
90
+ "line",
91
+ "list",
92
+ "location",
93
+ "manufacture",
94
+ "materials",
95
+ "measure",
96
+ "method",
97
+ "model",
98
+ "name",
99
+ "number",
100
+ "offer",
101
+ "order",
102
+ "password",
103
+ "pay",
104
+ "person",
105
+ "phone",
106
+ "photo",
107
+ "price",
108
+ "product",
109
+ "quota",
110
+ "rate",
111
+ "reason",
112
+ "region",
113
+ "review",
114
+ "routing",
115
+ "sales",
116
+ "scrap",
117
+ "shift",
118
+ "ship",
119
+ "shopping",
120
+ "special",
121
+ "state",
122
+ "status",
123
+ "store",
124
+ "sub",
125
+ "subcategory",
126
+ "tax",
127
+ "territory",
128
+ "transaction",
129
+ "type",
130
+ "unit",
131
+ "vendor",
132
+ "work",
133
+ # Common suffixes that carry meaning in a schema.
134
+ "id",
135
+ "key",
136
+ "code",
137
+ "qty",
138
+ "quantity",
139
+ "amount",
140
+ "total",
141
+ "due",
142
+ "start",
143
+ "end",
144
+ "modified",
145
+ )
146
+ _LEXICON_BY_LENGTH: Final[tuple[str, ...]] = tuple(sorted(_LEXICON, key=len, reverse=True))
147
+
148
+ # Runs of letters, not camelCase humps. Splitting humps here would make
149
+ # "SalesOrderHeader" and "salesorderheader" tokenize differently, and the
150
+ # lexicon below already recovers the words either way.
151
+ _WORD_RE: Final = re.compile(r"[A-Za-z]+|\d+")
152
+
153
+
154
+ def _stem(word: str) -> str:
155
+ """Strip regular plurals so a question's wording matches a schema's.
156
+
157
+ Questions say "how many orders did employees place"; the schema says
158
+ `salesorderheader` and `employee`. Without this, neither term matches.
159
+
160
+ Deliberately conservative suffix-stripping rather than a real stemmer: it
161
+ handles the regular plurals that dominate these questions and leaves
162
+ everything else alone. It does not handle irregular morphology -- "paid"
163
+ does not reduce to "pay" -- which is a real ceiling on the lexical backend.
164
+
165
+ Swapping in embeddings was the obvious fix for that ceiling, and it was
166
+ tried: see TitanBackend, where it measured slightly worse overall.
167
+ """
168
+ if len(word) > 4 and word.endswith("ies"):
169
+ return word[:-3] + "y"
170
+ if len(word) > 4 and word.endswith(("ses", "xes", "zes", "ches", "shes")):
171
+ return word[:-2]
172
+ if len(word) > 3 and word.endswith("s") and not word.endswith(("ss", "us", "is")):
173
+ return word[:-1]
174
+ return word
175
+
176
+
177
+ def _split_identifier(token: str) -> list[str]:
178
+ """Break a concatenated identifier into words using the lexicon.
179
+
180
+ Returns the pieces plus the original token, so an exact match on the raw name
181
+ still scores.
182
+ """
183
+ lowered = token.lower()
184
+ pieces: list[str] = []
185
+ i = 0
186
+ while i < len(lowered):
187
+ for word in _LEXICON_BY_LENGTH:
188
+ if lowered.startswith(word, i):
189
+ pieces.append(word)
190
+ i += len(word)
191
+ break
192
+ else:
193
+ i += 1 # character belongs to no known word; skip it
194
+ return pieces
195
+
196
+
197
+ def tokenize(text: str) -> list[str]:
198
+ """Lowercase word tokens, with concatenated identifiers split and stemmed.
199
+
200
+ Tokens are added rather than replaced, so an exact match on the raw
201
+ identifier still scores alongside its parts.
202
+ """
203
+ tokens: list[str] = []
204
+
205
+ def emit(token: str) -> None:
206
+ tokens.append(token)
207
+ stemmed = _stem(token)
208
+ if stemmed != token:
209
+ tokens.append(stemmed)
210
+
211
+ for raw in _WORD_RE.findall(text):
212
+ lowered = raw.lower()
213
+ emit(lowered)
214
+ if len(lowered) > 6:
215
+ parts = _split_identifier(lowered)
216
+ if len(parts) > 1:
217
+ for part in parts:
218
+ emit(part)
219
+ return tokens
220
+
221
+
222
+ # --------------------------------------------------------------------------
223
+ # Token counting. The README's headline number depends on this, so the
224
+ # tokenizer that produced a count is always reported alongside it.
225
+ # --------------------------------------------------------------------------
226
+
227
+ _APPROXIMATE_TOKENIZER: Final = "approximate/4-chars-per-token"
228
+ _encoder: Any = None
229
+ _tokenizer_name: str | None = None
230
+
231
+
232
+ def _load_tokenizer() -> None:
233
+ global _encoder, _tokenizer_name
234
+ if _tokenizer_name is not None:
235
+ return
236
+ try:
237
+ import tiktoken
238
+
239
+ _encoder = tiktoken.get_encoding("cl100k_base")
240
+ _tokenizer_name = "tiktoken/cl100k_base"
241
+ except Exception:
242
+ # tiktoken fetches its BPE table on first use; without network this is
243
+ # the fallback. It is an approximation and says so in its name, so a
244
+ # number produced by it is never mistaken for a measured one.
245
+ _encoder = None
246
+ _tokenizer_name = _APPROXIMATE_TOKENIZER
247
+
248
+
249
+ def tokenizer_name() -> str:
250
+ _load_tokenizer()
251
+ return _tokenizer_name or _APPROXIMATE_TOKENIZER
252
+
253
+
254
+ def count_tokens(text: str) -> int:
255
+ _load_tokenizer()
256
+ if _encoder is not None:
257
+ return len(_encoder.encode(text))
258
+ return max(1, len(text) // 4)
259
+
260
+
261
+ # --------------------------------------------------------------------------
262
+ # Backends
263
+ # --------------------------------------------------------------------------
264
+
265
+
266
+ class RetrievalBackend(Protocol):
267
+ """Ranks table documents against a question."""
268
+
269
+ name: str
270
+
271
+ def rank(self, question: str, limit: int) -> list[tuple[int, float]]:
272
+ """Return (document index, score) pairs, best first, at most `limit`."""
273
+ ...
274
+
275
+
276
+ class BM25Backend:
277
+ """Lexical ranking with Okapi BM25. Default because it needs nothing."""
278
+
279
+ name = "bm25"
280
+
281
+ def __init__(self, documents: Sequence[str]) -> None:
282
+ from rank_bm25 import BM25Okapi
283
+
284
+ self._corpus = [tokenize(d) for d in documents]
285
+ # BM25Okapi divides by the average document length, which is zero for an
286
+ # empty corpus.
287
+ self._bm25 = BM25Okapi(self._corpus) if self._corpus else None
288
+
289
+ def rank(self, question: str, limit: int) -> list[tuple[int, float]]:
290
+ if self._bm25 is None:
291
+ return []
292
+ scores = self._bm25.get_scores(tokenize(question))
293
+ ordered = sorted(enumerate(scores), key=lambda pair: (-pair[1], pair[0]))
294
+ return [(i, float(s)) for i, s in ordered[:limit]]
295
+
296
+
297
+ # --------------------------------------------------------------------------
298
+ # The index
299
+ # --------------------------------------------------------------------------
300
+
301
+
302
+ def build_document(table: TableDetail) -> str:
303
+ """The text that represents one table to the ranker.
304
+
305
+ Names, comments, column names and types, and the names of tables it joins to.
306
+ Column comments matter most here: AdventureWorks ships them, and they are the
307
+ only natural language in an otherwise concatenated-identifier schema.
308
+ """
309
+ parts: list[str] = [table.schema_name, table.name, table.qualified_name]
310
+ if table.comment:
311
+ parts.append(table.comment)
312
+ for col in table.columns:
313
+ parts.append(col.name)
314
+ parts.append(col.type)
315
+ if col.comment:
316
+ parts.append(col.comment)
317
+ for fk in table.foreign_keys:
318
+ parts.append(f"{fk.references_schema}.{fk.references_table}")
319
+ parts.extend(fk.columns)
320
+ return "\n".join(parts)
321
+
322
+
323
+ BackendFactory = Callable[[Sequence[str]], RetrievalBackend]
324
+
325
+
326
+ class SchemaIndex:
327
+ """Every table indexed once, plus the search over them.
328
+
329
+ The ranking backend is passed in as a factory so this module does no I/O:
330
+ BM25 is the default, and the Bedrock-backed one lives in the adapters.
331
+ """
332
+
333
+ def __init__(
334
+ self,
335
+ tables: Sequence[TableDetail],
336
+ backend_factory: BackendFactory = BM25Backend,
337
+ neighbour_weight: float = DEFAULT_NEIGHBOUR_WEIGHT,
338
+ ) -> None:
339
+ self.tables: list[TableDetail] = list(tables)
340
+ self._documents = [build_document(t) for t in self.tables]
341
+ self._backend: RetrievalBackend = backend_factory(self._documents)
342
+ self.neighbour_weight = neighbour_weight
343
+ self._adjacency = self._build_adjacency()
344
+ self._by_name: dict[str, TableDetail] = {}
345
+ for table in self.tables:
346
+ self._by_name[table.qualified_name.lower()] = table
347
+ # Bare names are ambiguous across schemas in principle; in this
348
+ # schema they are not, and accepting them makes describe_table
349
+ # forgiving about how the model spells the name.
350
+ self._by_name.setdefault(table.name.lower(), table)
351
+
352
+ @property
353
+ def backend_name(self) -> str:
354
+ return self._backend.name
355
+
356
+ @property
357
+ def full_schema_ddl(self) -> str:
358
+ """Every table's DDL concatenated: the baseline a dump-everything server sends."""
359
+ return "\n\n".join(t.ddl for t in self.tables)
360
+
361
+ def full_schema_tokens(self) -> int:
362
+ return count_tokens(self.full_schema_ddl)
363
+
364
+ def lookup(self, name: str) -> TableDetail | None:
365
+ """Find a table by qualified or bare name, case-insensitively."""
366
+ return self._by_name.get(name.strip().lower())
367
+
368
+ def _build_adjacency(self) -> list[set[int]]:
369
+ """Undirected foreign-key adjacency between table indices."""
370
+ position = {t.qualified_name: i for i, t in enumerate(self.tables)}
371
+ adjacency: list[set[int]] = [set() for _ in self.tables]
372
+ for i, table in enumerate(self.tables):
373
+ for fk in table.foreign_keys:
374
+ j = position.get(f"{fk.references_schema}.{fk.references_table}")
375
+ if j is not None and j != i:
376
+ adjacency[i].add(j)
377
+ adjacency[j].add(i)
378
+ return adjacency
379
+
380
+ def search(self, question: str, limit: int) -> list[tuple[TableDetail, float]]:
381
+ """The top `limit` tables for this question, best first.
382
+
383
+ Ranking is lexical (or embedding) score plus one round of propagation
384
+ across foreign keys.
385
+
386
+ The propagation is not a trick to flatter the numbers; it is what makes a
387
+ slice *usable*. Purely lexical ranking reliably returned
388
+ sales.salesorderdetail without production.product, and
389
+ sales.personcreditcard without person.person. Those slices name a
390
+ productid or a businessentityid the model cannot resolve, so it has to
391
+ spend another round trip on describe_table to write the join at all.
392
+ A table adjacent to a strongly-matching table is likely to be needed,
393
+ precisely because you cannot join to what you have not been shown.
394
+
395
+ Only one round, and damped: two hops from the question is far enough to
396
+ start pulling in the whole schema, which is the thing this server exists
397
+ to avoid.
398
+ """
399
+ limit = max(1, min(limit, len(self.tables)))
400
+ base = dict(self._backend.rank(question, len(self.tables)))
401
+ if self.neighbour_weight <= 0:
402
+ ranked = sorted(base.items(), key=lambda kv: (-kv[1], kv[0]))
403
+ return [(self.tables[i], s) for i, s in ranked[:limit]]
404
+
405
+ combined: list[tuple[int, float]] = []
406
+ for i in range(len(self.tables)):
407
+ neighbour_best = max((base.get(j, 0.0) for j in self._adjacency[i]), default=0.0)
408
+ combined.append((i, base.get(i, 0.0) + self.neighbour_weight * neighbour_best))
409
+
410
+ combined.sort(key=lambda kv: (-kv[1], kv[0]))
411
+ return [(self.tables[i], score) for i, score in combined[:limit]]
412
+
413
+ def edges_within(self, tables: Sequence[TableDetail]) -> list[Any]:
414
+ """Foreign keys whose *both* ends are in `tables`.
415
+
416
+ Edges pointing outside the slice are omitted on purpose: the model cannot
417
+ join to a table whose columns it has not been shown, so listing those
418
+ edges would spend tokens on an unusable hint.
419
+ """
420
+ present = {t.qualified_name for t in tables}
421
+ edges = []
422
+ for table in tables:
423
+ for fk in table.foreign_keys:
424
+ if f"{fk.references_schema}.{fk.references_table}" in present:
425
+ edges.append(fk)
426
+ return edges
427
+
428
+
429
+ CountFn = Callable[[str], int]