postgres-schema-mcp 0.1.0__tar.gz

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.
Files changed (58) hide show
  1. postgres_schema_mcp-0.1.0/.gitignore +22 -0
  2. postgres_schema_mcp-0.1.0/.python-version +1 -0
  3. postgres_schema_mcp-0.1.0/CHANGELOG.md +44 -0
  4. postgres_schema_mcp-0.1.0/CONTRIBUTING.md +27 -0
  5. postgres_schema_mcp-0.1.0/Dockerfile +36 -0
  6. postgres_schema_mcp-0.1.0/LICENSE +21 -0
  7. postgres_schema_mcp-0.1.0/Makefile +54 -0
  8. postgres_schema_mcp-0.1.0/PKG-INFO +267 -0
  9. postgres_schema_mcp-0.1.0/README.md +242 -0
  10. postgres_schema_mcp-0.1.0/SECURITY.md +27 -0
  11. postgres_schema_mcp-0.1.0/docker-compose.yml +33 -0
  12. postgres_schema_mcp-0.1.0/docs/DECISIONS.md +87 -0
  13. postgres_schema_mcp-0.1.0/docs/SPEC.md +62 -0
  14. postgres_schema_mcp-0.1.0/docs/architecture.md +54 -0
  15. postgres_schema_mcp-0.1.0/docs/demo.gif +0 -0
  16. postgres_schema_mcp-0.1.0/docs/demo.tape +24 -0
  17. postgres_schema_mcp-0.1.0/evals/baseline/conformance.json +9 -0
  18. postgres_schema_mcp-0.1.0/evals/baseline/titan-bedrock.json +11 -0
  19. postgres_schema_mcp-0.1.0/evals/capture_catalog.py +71 -0
  20. postgres_schema_mcp-0.1.0/evals/check_live.py +48 -0
  21. postgres_schema_mcp-0.1.0/evals/demo.py +56 -0
  22. postgres_schema_mcp-0.1.0/evals/faults.yaml +183 -0
  23. postgres_schema_mcp-0.1.0/evals/fixtures/catalog.json +6769 -0
  24. postgres_schema_mcp-0.1.0/evals/measure.py +215 -0
  25. postgres_schema_mcp-0.1.0/evals/questions.yaml +127 -0
  26. postgres_schema_mcp-0.1.0/evals/results/latest.json +175 -0
  27. postgres_schema_mcp-0.1.0/init/10-seed.sh +44 -0
  28. postgres_schema_mcp-0.1.0/init/20-grants.sql +86 -0
  29. postgres_schema_mcp-0.1.0/pyproject.toml +104 -0
  30. postgres_schema_mcp-0.1.0/scripts/banned-words.txt +9 -0
  31. postgres_schema_mcp-0.1.0/scripts/check-readme-numbers.py +149 -0
  32. postgres_schema_mcp-0.1.0/scripts/check-writing.sh +67 -0
  33. postgres_schema_mcp-0.1.0/scripts/strip-ai-trailers.sh +13 -0
  34. postgres_schema_mcp-0.1.0/server.json +18 -0
  35. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/__init__.py +0 -0
  36. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/adapters/__init__.py +1 -0
  37. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/adapters/backends.py +101 -0
  38. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/adapters/db.py +430 -0
  39. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/core/__init__.py +1 -0
  40. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/core/ddl.py +52 -0
  41. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/core/guard.py +269 -0
  42. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/core/retrieval.py +429 -0
  43. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/core/types.py +136 -0
  44. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/py.typed +0 -0
  45. postgres_schema_mcp-0.1.0/src/postgres_schema_mcp/server.py +339 -0
  46. postgres_schema_mcp-0.1.0/tests/__init__.py +0 -0
  47. postgres_schema_mcp-0.1.0/tests/conftest.py +18 -0
  48. postgres_schema_mcp-0.1.0/tests/integration/__init__.py +0 -0
  49. postgres_schema_mcp-0.1.0/tests/integration/conftest.py +35 -0
  50. postgres_schema_mcp-0.1.0/tests/integration/test_database.py +223 -0
  51. postgres_schema_mcp-0.1.0/tests/integration/test_readonly_role.py +125 -0
  52. postgres_schema_mcp-0.1.0/tests/integration/test_server_live.py +66 -0
  53. postgres_schema_mcp-0.1.0/tests/unit/__init__.py +0 -0
  54. postgres_schema_mcp-0.1.0/tests/unit/test_db_helpers.py +163 -0
  55. postgres_schema_mcp-0.1.0/tests/unit/test_guard.py +190 -0
  56. postgres_schema_mcp-0.1.0/tests/unit/test_retrieval.py +334 -0
  57. postgres_schema_mcp-0.1.0/tests/unit/test_server.py +274 -0
  58. postgres_schema_mcp-0.1.0/uv.lock +1991 -0
@@ -0,0 +1,22 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .mypy_cache/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+ *.tmp
13
+ .DS_Store
14
+ .env
15
+ .env.*
16
+ !.env.example
17
+ CLAUDE.local.md
18
+
19
+ # Seed data is downloaded at image build time, never committed.
20
+ init/data/
21
+ *.zip
22
+ *.csv
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-11-20
8
+
9
+ First release.
10
+
11
+ ### Added
12
+
13
+ - The `mcp-name` line the MCP Registry reads in the README, and a `uvx postgres-schema-mcp` client config next to the clone-based one.
14
+ - Result caps: rows are read from a server-side cursor in batches, with a row cap, a per-cell cap (`PGSS_MAX_CELL_CHARS`) and a total size cap (`PGSS_MAX_RESULT_BYTES`). Each cut is reported to the model.
15
+ - A tighter database role, the third layer, in `init/20-grants.sql`: `EXECUTE` revoked from `PUBLIC` on the functions the guard refuses, and a connection limit and temp-file limit on `scout_ro`.
16
+ - Nine planted faults and three clean inputs for the guard bypasses below. The matrix is 21 must-block and 12 must-allow.
17
+ - The release workflow checks that the tag matches `pyproject.toml` and `server.json` and is on `main`, and every action is pinned by commit SHA.
18
+ - Four MCP tools: `search_schema`, `describe_table`, `explain_query` and `run_query`.
19
+ - Retrieval over one document per table with BM25, plus one damped round of score propagation across foreign keys.
20
+ - Read-only enforced in three layers: tool annotations, an AST policy, and a `scout_ro` database role that holds only SELECT.
21
+ - An optional Amazon Titan embedding backend through Bedrock, not the default.
22
+ - A seeded AdventureWorks Postgres in Docker, so every number is reproducible.
23
+ - Evals: a two-sided fault matrix, retrieval quality, and the schema-context measurement, all printed as one JSON object by `make evals` and re-measured in CI.
24
+ - A frozen copy of the schema in `evals/fixtures/catalog.json`, so figures are measured without a database and checked against a freshly seeded one.
25
+ - README figures wrapped in eval markers that CI checks against `evals/results/latest.json`.
26
+ - `server.json` for the MCP Registry.
27
+ - A terminal demo in the README. `docs/demo.tape` records it with `vhs`, and `evals/demo.py` is what it runs, offline.
28
+
29
+ ### Security
30
+
31
+ A review before this release found and fixed these. They are recorded in `docs/DECISIONS.md`.
32
+
33
+ - A double-quoted function name (`"pg_sleep"(1)`) or a `U&"..."` escape bypassed the function denylist. Names are now compared unquoted, and a name that is not a plain identifier is refused.
34
+ - Side-effect functions outside the list ran inside a SELECT: advisory locks, `nextval`, `pg_notify`, large objects and `crosstab`. The denylist now covers whole families by prefix.
35
+ - Transactions were not explicitly read-only, so `set_config('default_transaction_read_only', 'off', false)` could change the session default. Every transaction is now `BEGIN READ ONLY`, and a connection is reset when it returns to the pool.
36
+ - The HTTP transport refuses a non-loopback bind unless `PGSS_ALLOW_REMOTE=1`, because it has no authentication.
37
+ - Database comments shown to the model are joined onto one line and capped, and the instructions call comments and rows untrusted.
38
+
39
+ ### Changed
40
+
41
+ - Renamed from `pg-schema-scout` to `postgres-schema-mcp`. Nothing had been published under the old name.
42
+ - Code is split into `core/` (no I/O) and `adapters/` (Postgres, Bedrock).
43
+ - Python 3.12 or newer. CI runs 3.12 and 3.13 through `make check`.
44
+ - `BlockedQuery` is now `BlockedQueryError`.
@@ -0,0 +1,27 @@
1
+ # Contributing
2
+
3
+ Issues and pull requests are welcome.
4
+
5
+ ## Set up
6
+
7
+ You need [uv](https://docs.astral.sh/uv/), `make` and Docker.
8
+
9
+ ```bash
10
+ make setup
11
+ make db
12
+ ```
13
+
14
+ `make setup` installs the dependencies and the git hooks. `make db` starts the seeded Postgres that the integration tests run against. The first run builds the image and downloads the AdventureWorks sample, which takes a few minutes.
15
+
16
+ ## Before you open a pull request
17
+
18
+ - Run `make check` with the database up. It runs the same checks as CI: hooks, types, tests with coverage, and the evals. Integration tests fail, not skip, when the database is down.
19
+ - `make test-fast` is a quicker loop with no database. It is not what CI runs.
20
+ - Add a test for what you changed.
21
+ - If your change moves a number the README quotes, run `make evals` and commit `evals/results/latest.json`. CI fails when a README figure and the measured result disagree.
22
+ - If you change the schema the evals run on, run `make fixtures` and review the diff of `evals/fixtures/catalog.json`.
23
+ - Keep writing plain and specific. A pre-commit hook rejects em dashes and a short list of marketing words.
24
+
25
+ ## Reporting bugs
26
+
27
+ Use the bug report template. For security problems, see [SECURITY.md](SECURITY.md) instead of opening an issue.
@@ -0,0 +1,36 @@
1
+ # Postgres seeded with AdventureWorks (OLTP), 68 base tables across five schemas.
2
+ #
3
+ # The sample data is downloaded at image build time rather than vendored, so no
4
+ # 40 MB blob lives in this repo. Both sources are pinned: the loader scripts to a
5
+ # commit SHA, the data to Microsoft's immutable release asset.
6
+ FROM postgres:16-bookworm
7
+
8
+ # lorint/AdventureWorks-for-Postgres, master as of 2026-06-29. Pinned by SHA so a
9
+ # rebuild cannot silently pick up a different schema.
10
+ ARG AW_REPO_SHA=b474991f0df1c4bf55ca4735eb0254ca0709eed2
11
+ ARG AW_ZIP_URL=https://github.com/Microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorks-oltp-install-script.zip
12
+
13
+ RUN apt-get update \
14
+ && apt-get install -y --no-install-recommends ca-certificates curl unzip ruby dos2unix \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ WORKDIR /seed
18
+
19
+ # install.sql uses psql \copy with paths relative to the working directory, so the
20
+ # CSVs have to sit flat in /seed. The find|mv flattens the archive if Microsoft ever
21
+ # nests it, rather than failing obscurely at load time.
22
+ RUN set -eux; \
23
+ curl -fsSL -o aw.zip "${AW_ZIP_URL}"; \
24
+ unzip -q -o aw.zip; \
25
+ rm aw.zip; \
26
+ find . -mindepth 2 -name '*.csv' -exec mv -t . {} +; \
27
+ base="https://raw.githubusercontent.com/lorint/AdventureWorks-for-Postgres/${AW_REPO_SHA}"; \
28
+ curl -fsSL -o install.sql "${base}/install.sql"; \
29
+ curl -fsSL -o update_csvs.rb "${base}/update_csvs.rb"; \
30
+ ruby update_csvs.rb; \
31
+ rm update_csvs.rb; \
32
+ test -s install.sql; \
33
+ echo "CSV files staged: $(ls -1 *.csv | wc -l)"
34
+
35
+ COPY init/ /docker-entrypoint-initdb.d/
36
+ RUN dos2unix /docker-entrypoint-initdb.d/* && chmod +x /docker-entrypoint-initdb.d/*.sh
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Akshay Swaminathan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,54 @@
1
+ .PHONY: setup db fmt check test-fast evals evals-check evals-db fixtures
2
+
3
+ setup:
4
+ uv sync
5
+ uv run pre-commit install
6
+
7
+ # The seeded Postgres the integration tests and the live evals run against. The first
8
+ # run builds the image and seeds AdventureWorks, which takes a few minutes. --build makes
9
+ # a change under init/ reach the image; with nothing changed the build is all cache hits.
10
+ # An existing volume is not re-seeded: after changing init/, run `docker compose down -v`.
11
+ db:
12
+ docker compose up -d --build --wait --wait-timeout 900
13
+
14
+ fmt:
15
+ uv run ruff format .
16
+ uv run ruff check --fix .
17
+
18
+ # Runs exactly what CI runs. Needs `make db` first: the integration tests fail, not
19
+ # skip, when the database is down, so a green check always touched Postgres.
20
+ check:
21
+ uv run pre-commit run --all-files
22
+ uv run mypy
23
+ uv run pytest --cov
24
+ $(MAKE) evals-check
25
+ $(MAKE) evals-db
26
+
27
+ # Everything that needs no database. A quick loop while editing; not what CI runs.
28
+ test-fast:
29
+ uv run pytest -m "not db"
30
+ $(MAKE) evals-check
31
+
32
+ # Re-measure and overwrite evals/results/latest.json. Commit the result.
33
+ evals:
34
+ uv run python evals/measure.py > evals/results/latest.json.tmp
35
+ mv evals/results/latest.json.tmp evals/results/latest.json
36
+
37
+ # Fail if measure.py disagrees with the committed latest.json, or a README figure disagrees with it.
38
+ evals-check:
39
+ @tmp="$$(mktemp)"; \
40
+ uv run python evals/measure.py > "$$tmp"; rc=$$?; \
41
+ if [ $$rc -eq 0 ]; then diff -u evals/results/latest.json "$$tmp"; rc=$$?; fi; \
42
+ rm -f "$$tmp"; \
43
+ if [ $$rc -ne 0 ]; then echo "evals-check: measure.py output differs from evals/results/latest.json (run make evals)"; exit $$rc; fi
44
+ uv run python scripts/check-readme-numbers.py
45
+
46
+ # The checks that need the seeded Postgres: every must_allow query really executes, and the
47
+ # frozen catalog still matches the database.
48
+ evals-db:
49
+ uv run python evals/check_live.py
50
+ uv run python evals/capture_catalog.py --check
51
+
52
+ # Re-freeze the catalog from the running database. Review the diff before committing.
53
+ fixtures:
54
+ uv run python evals/capture_catalog.py
@@ -0,0 +1,267 @@
1
+ Metadata-Version: 2.5
2
+ Name: postgres-schema-mcp
3
+ Version: 0.1.0
4
+ Summary: An MCP server that retrieves the relevant slice of a wide Postgres schema instead of dumping all of it, with read-only enforced in three layers.
5
+ Project-URL: Homepage, https://github.com/akshayyswami/postgres-schema-mcp
6
+ Project-URL: Issues, https://github.com/akshayyswami/postgres-schema-mcp/issues
7
+ Author: Akshay Swaminathan
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: mcp,model-context-protocol,postgres,retrieval,sql
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Database
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: mcp==2.0.0
17
+ Requires-Dist: psycopg[binary,pool]<4,>=3.2
18
+ Requires-Dist: pyyaml<7,>=6.0
19
+ Requires-Dist: rank-bm25<0.3,>=0.2.2
20
+ Requires-Dist: sqlglot<31,>=30.0
21
+ Requires-Dist: tiktoken<1,>=0.9
22
+ Provides-Extra: bedrock
23
+ Requires-Dist: boto3>=1.35; extra == 'bedrock'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # postgres-schema-mcp
27
+
28
+ [![CI](https://github.com/akshayyswami/postgres-schema-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/akshayyswami/postgres-schema-mcp/actions/workflows/ci.yml)
29
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
30
+ [![MCP 2026-07-28](https://img.shields.io/badge/MCP-2026--07--28-blue.svg)](https://modelcontextprotocol.io)
31
+
32
+ **Schema access for an agent is a retrieval problem, not a dump.**
33
+
34
+ An MCP server that gives an AI agent the relevant slice of a wide Postgres schema instead of all of it, and enforces read-only in three layers rather than annotating it.
35
+
36
+ <!-- mcp-name: io.github.akshayyswami/postgres-schema-mcp -->
37
+
38
+ ![Terminal demo: one question retrieves a small slice of the schema, and the read-only guard blocks a DELETE hidden inside a CTE.](docs/demo.gif)
39
+
40
+ ---
41
+
42
+ ## The number
43
+
44
+ Measured on the seeded AdventureWorks database in this repo: <!-- eval:context.tables -->68<!-- /eval --> tables across <!-- eval:context.schemas -->5<!-- /eval --> schemas, over the <!-- eval:context.questions -->26<!-- /eval --> questions in [`evals/questions.yaml`](evals/questions.yaml).
45
+
46
+ | | Tokens |
47
+ |---|---|
48
+ | Baseline: the full schema DDL, dumped in one blob | **<!-- eval:context.full_schema_tokens:,d -->10,927<!-- /eval -->** |
49
+ | Retrieved slice, mean over the questions (k=<!-- eval:context.k -->8<!-- /eval -->) | **<!-- eval:retrieval.slice_tokens_mean:,.0f -->1,816<!-- /eval -->** |
50
+ | | **<!-- eval:context.reduction_x:.1f -->6.0<!-- /eval -->× less schema context (<!-- eval:context.fewer_tokens:.0% -->83%<!-- /eval --> fewer tokens)** |
51
+
52
+ Median slice <!-- eval:retrieval.slice_tokens_median:,.0f -->1,858<!-- /eval -->, range <!-- eval:retrieval.slice_tokens_min:,d -->1,071<!-- /eval -->–<!-- eval:retrieval.slice_tokens_max:,d -->2,368<!-- /eval -->. Tokenizer: <!-- eval:context.tokenizer -->tiktoken/cl100k_base<!-- /eval -->. Ranking backend: <!-- eval:context.backend -->bm25<!-- /eval -->.
53
+
54
+ Reproduce: `make evals` prints the numbers as one JSON object. It needs no database: it reads the frozen schema in `evals/fixtures/catalog.json`, which is names, comments and keys only, no rows. CI re-measures on every push and fails if any figure in this README differs from the measurement, and checks the frozen schema against a freshly seeded database.
55
+
56
+ What the number leaves out: it counts schema context only, the DDL a model is given before it writes SQL. It excludes tool descriptions and the rows a query returns.
57
+
58
+ The ratio is the boring half of the argument. The interesting half is a schema too wide to dump at all. A dump-everything server truncates, and if the table you need falls outside the cutoff, the model has no way to ask for it. `describe_table`, below, is this server's answer.
59
+
60
+ ---
61
+
62
+ ## Quickstart
63
+
64
+ ```bash
65
+ git clone https://github.com/akshayyswami/postgres-schema-mcp && cd postgres-schema-mcp
66
+ docker compose up -d --wait
67
+ uv sync
68
+ ```
69
+
70
+ You need Docker and [uv](https://docs.astral.sh/uv/). The first `docker compose up` builds Postgres, downloads the AdventureWorks OLTP sample, seeds <!-- eval:context.tables -->68<!-- /eval --> tables and creates both database roles. It takes a few minutes; afterwards it is instant.
71
+
72
+ Then point your MCP client at it:
73
+
74
+ ```json
75
+ {
76
+ "mcpServers": {
77
+ "postgres-schema-mcp": {
78
+ "command": "uv",
79
+ "args": ["run", "--directory", "/path/to/postgres-schema-mcp", "postgres-schema-mcp"],
80
+ "env": {
81
+ "PGSS_DSN": "postgresql://scout_ro:scout_ro_pw@localhost:55432/adventureworks"
82
+ }
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ The package is also on PyPI, so a client can run it without a clone. Set `"command": "uvx"` and `"args": ["postgres-schema-mcp"]`, with the same `env`, and point `PGSS_DSN` at your own database through a role that can only `SELECT`.
89
+
90
+ stdio by default. `postgres-schema-mcp --http` serves Streamable HTTP on port 3000 instead. The credentials above belong to a local throwaway container holding public sample data. There are no real credentials in this repo.
91
+
92
+ ---
93
+
94
+ ## How it works
95
+
96
+ ```mermaid
97
+ flowchart LR
98
+ Q[question] --> S[search_schema]
99
+ S -->|"BM25 over one document per table"| R[ranked tables]
100
+ R -->|"plus a share of the best foreign-key neighbour"| T["slice: top tables, DDL, joins"]
101
+ T --> M[model writes SQL]
102
+ M --> G["run_query: AST guard"]
103
+ G --> D[("scout_ro role: SELECT only")]
104
+ ```
105
+
106
+ At start-up the server reads the schema once and builds one document per table: its name, comments, column names and types, and the tables it joins to. `search_schema` ranks those documents against the question with BM25, which needs no credentials and no per-query cost.
107
+
108
+ Ranking alone returns slices you cannot join, so it adds one damped round of score propagation across foreign keys: a table next to a strong match is likely to be needed, because you cannot join to what you have not been shown. The share is <!-- eval:fk_sweep.2.neighbour_weight:.2f -->0.35<!-- /eval -->. Retrieval can still rank a needed table below the cutoff, so `describe_table` fetches any table by name without using the ranking.
109
+
110
+ ### The four tools
111
+
112
+ Four, not fourteen. Every tool description is paid for on every request, so mirroring a REST surface into tools taxes each call. These four match the loop an agent actually runs.
113
+
114
+ | Tool | Signature | Annotations |
115
+ |---|---|---|
116
+ | `search_schema` | `(question: str, limit: int = 8) -> SchemaSlice` | `readOnlyHint=true`, `idempotentHint=true`, `openWorldHint=false`, `destructiveHint=false` |
117
+ | `describe_table` | `(name: str) -> TableDetail` | same |
118
+ | `explain_query` | `(sql: str) -> QueryPlan` | same |
119
+ | `run_query` | `(sql: str, max_rows: int = 200) -> QueryResult` | same |
120
+
121
+ All four return Pydantic models, so `outputSchema` and `structuredContent` are generated, not hand-written.
122
+
123
+ The spec's annotation defaults are pessimistic: omitting them declares a tool destructive, open-world and non-idempotent. So all four set them explicitly, in a fixed order, because the spec cites prompt-cache hit rate as the reason to keep the tool list stable. `tools/list` carries `ttlMs: 300000` and `cacheScope: "public"`. The list comes from this server's own code, so it is the same for every caller, but a redeploy can change it, so it is not cached longer.
124
+
125
+ ### Safety model
126
+
127
+ Three layers, weakest first.
128
+
129
+ | Layer | What it does | Why it is not enough alone |
130
+ |---|---|---|
131
+ | `readOnlyHint=true` | Tells the client the tool is safe to auto-approve | **An untrusted hint.** Decorative |
132
+ | AST policy (`core/guard.py`) | Parses with sqlglot and rejects anything that is not a single read-only SELECT | A parser bug is a bypass |
133
+ | `scout_ro` database role | Holds `SELECT` and nothing else, anywhere | This is the layer that actually holds |
134
+
135
+ **The annotation is the weakest layer, on purpose.** The specification says clients must treat tool annotations from an untrusted server as untrusted. A malicious server can set `readOnlyHint=true` and delete your data. It is documentation, not a control. Anyone who says their database MCP server is read-only because of the annotation has misread the spec.
136
+
137
+ #### The query a regex guard misses
138
+
139
+ ```sql
140
+ WITH gone AS (DELETE FROM customer RETURNING *) SELECT * FROM gone;
141
+ ```
142
+
143
+ It begins with `WITH`. It contains `SELECT`. It empties the table. A regex allowlist that checks the statement's prefix passes it straight through. sqlglot parses it to a top-level `Select` whose tree contains a `Delete` node, so walking the AST rejects it.
144
+
145
+ The same argument runs the other way. A text denylist wrongly rejects
146
+
147
+ ```sql
148
+ SELECT 'DROP TABLE customer' AS note FROM person.person;
149
+ ```
150
+
151
+ which is an ordinary read-only query. Both directions are in the fault matrix.
152
+
153
+ The guard fails closed: unparseable input, empty input, statement stacking, and anything sqlglot can only represent as an opaque `Command` are all refused. It also blocks `SELECT ... FOR UPDATE` (row locks are not read-only), `SELECT ... INTO` (DDL wearing a SELECT costume), and a denylist of filesystem, network, administrative and denial-of-service functions, checked against every function node in the tree rather than the raw string.
154
+
155
+ #### Blocked is a tool error, not a protocol error
156
+
157
+ A rejected query returns HTTP 200 with a JSON-RPC result carrying `isError: true` and a message the model can act on. Only real protocol faults become JSON-RPC errors. Verified on the wire:
158
+
159
+ ```json
160
+ {"jsonrpc":"2.0","id":1,"result":{
161
+ "content":[{"type":"text","text":"Error executing tool run_query: Blocked: the statement contains a DELETE nested inside the query (in a CTE or subquery), which a prefix check would miss. This server is read-only. Rewrite the request as a plain SELECT."}],
162
+ "isError":true,"resultType":"complete"}}
163
+ ```
164
+
165
+ #### Below the parser
166
+
167
+ The server authenticates as `scout_ro`, which is granted `SELECT` and nothing else, with `TEMPORARY` revoked on the database and no `CREATE` on any schema. Every transaction starts as `BEGIN READ ONLY`, so a query that flips `default_transaction_read_only` for the session changes nothing. A connection is reset with `DISCARD ALL` when it goes back to the pool, so a lock or setting one request leaves behind is gone before the next. Sessions run with `statement_timeout` and `idle_in_transaction_session_timeout`. Rows are read from a server-side cursor in batches, with a row cap, a per-cell cap and a total size cap, and each cut is reported to the model.
168
+
169
+ The seeded database goes one step further. `init/20-grants.sql` revokes `EXECUTE` from `PUBLIC` on the functions the guard refuses (`pg_sleep`, `set_config`, advisory locks, `nextval`, large objects, `crosstab`), and gives `scout_ro` a connection limit and a temp-file limit. A name the guard missed is then refused by the database. Point `PGSS_DSN` at your own database and you need to give that role the same limits yourself.
170
+
171
+ [`tests/integration/test_readonly_role.py`](tests/integration/test_readonly_role.py) sends `DELETE`, `UPDATE`, `INSERT`, `TRUNCATE`, `DROP`, `ALTER`, `CREATE TABLE`, `CREATE TEMP TABLE`, `CREATE INDEX` and `GRANT` straight to Postgres, bypassing the guard, and asserts the database refuses each one. That test is the proof the bottom layer holds without the parser.
172
+
173
+ ---
174
+
175
+ ## Evals
176
+
177
+ Everything below comes from `make evals` (offline) and `make evals-db` (against the seeded database), and both run in CI.
178
+
179
+ **Fault matrix: <!-- eval:faults.must_block_caught -->21<!-- /eval -->/<!-- eval:faults.must_block_total -->21<!-- /eval --> blocked, <!-- eval:faults.must_allow_passed -->12<!-- /eval -->/<!-- eval:faults.must_allow_total -->12<!-- /eval --> allowed.**
180
+
181
+ Two-sided on purpose. The `must_allow` half is the half people skip, and it proves the guard is a guard and not a policy that refuses everything. `make evals-db` also executes all <!-- eval:faults.must_allow_total -->12<!-- /eval --> allowed queries against the database, so "allowed" means it actually runs.
182
+
183
+ **Retrieval: recall@<!-- eval:context.k -->8<!-- /eval --> <!-- eval:retrieval.recall_at_k:.3f -->0.955<!-- /eval -->, precision@<!-- eval:context.k -->8<!-- /eval --> <!-- eval:retrieval.precision_at_k:.3f -->0.260<!-- /eval -->, <!-- eval:retrieval.complete -->24<!-- /eval -->/<!-- eval:retrieval.questions -->26<!-- /eval --> questions with complete recall.**
184
+
185
+ Precision is structurally capped: a question needs 1 to 4 tables but <!-- eval:context.k -->8<!-- /eval --> slots come back. Recall is the number that matters, because a missing table breaks the query and a spare one costs a few tokens.
186
+
187
+ ### Foreign-key propagation, and what it bought
188
+
189
+ The first run failed. Purely lexical ranking scored recall@<!-- eval:context.k -->8<!-- /eval --> <!-- eval:fk_sweep.0.recall_at_k:.3f -->0.840<!-- /eval -->, and <!-- eval:fk_sweep.0.incomplete -->9<!-- /eval --> questions were missing a required table. The misses had a shape: `production.product` was missed <!-- eval:fk_sweep.0.missed.0.count -->4<!-- /eval --> times and `person.person` <!-- eval:fk_sweep.0.missed.1.count -->2<!-- /eval --> times. These are join hubs. A slice containing `salesorderdetail` without `product` names a `productid` the model cannot resolve, so it is not a usable slice.
190
+
191
+ Ranking now adds one damped round of score propagation across foreign keys. Measured over the <!-- eval:context.questions -->26<!-- /eval --> questions:
192
+
193
+ | neighbour weight | recall@8 | complete recall | mean slice tokens |
194
+ |---|---|---|---|
195
+ | <!-- eval:fk_sweep.0.neighbour_weight:.2f -->0.00<!-- /eval --> (off) | <!-- eval:fk_sweep.0.recall_at_k:.3f -->0.840<!-- /eval --> | <!-- eval:fk_sweep.0.complete -->17<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> | <!-- eval:fk_sweep.0.slice_tokens_mean:,.0f -->1,684<!-- /eval --> |
196
+ | <!-- eval:fk_sweep.1.neighbour_weight:.2f -->0.25<!-- /eval --> | <!-- eval:fk_sweep.1.recall_at_k:.3f -->0.955<!-- /eval --> | <!-- eval:fk_sweep.1.complete -->24<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> | <!-- eval:fk_sweep.1.slice_tokens_mean:,.0f -->1,800<!-- /eval --> |
197
+ | **<!-- eval:fk_sweep.2.neighbour_weight:.2f -->0.35<!-- /eval --> (shipped)** | **<!-- eval:fk_sweep.2.recall_at_k:.3f -->0.955<!-- /eval -->** | **<!-- eval:fk_sweep.2.complete -->24<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval -->** | **<!-- eval:fk_sweep.2.slice_tokens_mean:,.0f -->1,816<!-- /eval -->** |
198
+ | <!-- eval:fk_sweep.3.neighbour_weight:.2f -->0.50<!-- /eval --> | <!-- eval:fk_sweep.3.recall_at_k:.3f -->0.965<!-- /eval --> | <!-- eval:fk_sweep.3.complete -->24<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> | <!-- eval:fk_sweep.3.slice_tokens_mean:,.0f -->1,864<!-- /eval --> |
199
+
200
+ 0.35 takes nearly all the gain. Past 0.5 the graph term starts to swamp the lexical signal, which is how you end up returning the whole schema again.
201
+
202
+ **Two honest caveats.** The weight was chosen on the same <!-- eval:context.questions -->26<!-- /eval --> questions that recall is measured on, so <!-- eval:fk_sweep.2.recall_at_k:.3f -->0.955<!-- /eval --> is optimistic: it is not a held-out score. And better recall costs tokens. The mean slice grew from <!-- eval:fk_sweep.0.slice_tokens_mean:,.0f -->1,684<!-- /eval --> to <!-- eval:fk_sweep.2.slice_tokens_mean:,.0f -->1,816<!-- /eval -->, which moved the headline ratio from <!-- eval:fk_sweep.0.reduction_x:.1f -->6.5<!-- /eval -->× to <!-- eval:fk_sweep.2.reduction_x:.1f -->6.0<!-- /eval -->×. Recall was judged worth more than the ratio.
203
+
204
+ ### BM25 vs Titan embeddings: the lexical backend wins
205
+
206
+ Both backends were measured on the same <!-- eval:context.questions -->26<!-- /eval --> questions. The Titan figures are **recorded, not re-measured here**: they come from a run on <!-- eval:baseline.titan.recorded -->2026-08-07<!-- /eval --> against the real Bedrock service (<!-- eval:baseline.titan.model_id -->amazon.titan-embed-text-v2:0<!-- /eval -->, <!-- eval:baseline.titan.invocations -->94<!-- /eval --> invocations), and are kept with that date in [`evals/baseline/titan-bedrock.json`](evals/baseline/titan-bedrock.json). CI has no AWS credentials, so it does not re-run them. The BM25 rows are measured on every push.
207
+
208
+ | Backend | FK propagation | recall@8 | precision@8 | complete recall |
209
+ |---|---|---|---|---|
210
+ | **BM25 (default)** | **0.35** | **<!-- eval:fk_sweep.2.recall_at_k:.3f -->0.955<!-- /eval -->** | **<!-- eval:fk_sweep.2.precision_at_k:.3f -->0.260<!-- /eval -->** | **<!-- eval:fk_sweep.2.complete -->24<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval -->** |
211
+ | Titan V2 | 0.35 | <!-- eval:baseline.titan.with_fk.recall:.3f -->0.926<!-- /eval --> | <!-- eval:baseline.titan.with_fk.precision:.3f -->0.255<!-- /eval --> | <!-- eval:baseline.titan.with_fk.complete -->22<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> |
212
+ | BM25 | off | <!-- eval:fk_sweep.0.recall_at_k:.3f -->0.840<!-- /eval --> | <!-- eval:fk_sweep.0.precision_at_k:.3f -->0.226<!-- /eval --> | <!-- eval:fk_sweep.0.complete -->17<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> |
213
+ | Titan V2 | off | <!-- eval:baseline.titan.without_fk.recall:.3f -->0.833<!-- /eval --> | <!-- eval:baseline.titan.without_fk.precision:.3f -->0.226<!-- /eval --> | <!-- eval:baseline.titan.without_fk.complete -->17<!-- /eval -->/<!-- eval:context.questions -->26<!-- /eval --> |
214
+
215
+ **The embeddings lose.** Before propagation the two are indistinguishable, so the embeddings were not finding anything the lexical path missed. After propagation BM25 pulls ahead. That is a reasonable outcome, not a surprising one: a table's document here is mostly identifiers and a one-line comment, not prose, which is the regime BM25 is built for. Foreign-key structure mattered far more than semantic similarity.
216
+
217
+ Two caveats cut against the winner. Titan was handed the same identifier-heavy text as BM25, and a prose rendering of each table might suit it better. And the lexicon and stemmer were written with BM25 in mind, so the comparison is not perfectly even.
218
+
219
+ BM25 stays the default, which also means the repo runs offline with no credentials and no per-query cost. To try Titan, install the `bedrock` extra and set `PGSS_RETRIEVAL_BACKEND=titan`.
220
+
221
+ ---
222
+
223
+ ## Limits
224
+
225
+ - **Retrieval has a recall ceiling, and this is the design's real failure mode.** At k=<!-- eval:context.k -->8<!-- /eval --> it misses a required table on <!-- eval:retrieval.incomplete -->2<!-- /eval --> of <!-- eval:retrieval.questions -->26<!-- /eval --> questions: `revenue-by-category` (a four-table join through the category hierarchy) and `reseller-locations` (the store-to-address path runs through a cross-reference table that matches nothing in the question's wording). When it misses, the table is absent and the slice alone cannot recover.
226
+ - **`describe_table` is the escape hatch for exactly that.** It does not use the ranking, so a model that knows or guesses a table name can always reach it. Every `SchemaSlice` carries a note telling the model to do this.
227
+ - **The lexical backend cannot do irregular morphology.** Stemming reduces `employees` to `employee`, but `paid` does not reduce to `pay`. A test asserts the limit instead of hiding it. Embeddings were the obvious fix, they were measured, and they did not help overall.
228
+ - **The identifier lexicon is specific to this schema.** AdventureWorks names are lowercase concatenations (`salesorderheader`), and splitting them needs a word list. The one in `core/retrieval.py` covers this schema's vocabulary. Another database would want its own.
229
+ - **The Titan backend is measured but not the default**, because it measured worse. It has only ever been exercised over 68 documents and 26 questions, with no retry, batching or rate-limit handling.
230
+ - **Not implemented, on purpose:** no prompts, no resources, no write path of any kind, no `EXPLAIN ANALYZE` (it would execute the query), no cross-database or multi-tenant support, and no auth. The server is expected to run locally over stdio, and the security boundary is the database role, not the transport.
231
+ - **The headline number is for one schema.** It is measured on AdventureWorks, a sample with <!-- eval:context.tables -->68<!-- /eval --> tables. A different schema will give different figures, and the lexicon above is part of why.
232
+
233
+ ### Conformance: does not pass, and here is why
234
+
235
+ `npx @modelcontextprotocol/conformance@`<!-- eval:baseline.conformance.version -->0.1.16<!-- /eval --> `server --url http://localhost:3000/mcp` reported **<!-- eval:baseline.conformance.passed -->11<!-- /eval --> passed, <!-- eval:baseline.conformance.failed -->21<!-- /eval --> failed** on <!-- eval:baseline.conformance.recorded -->2026-08-07<!-- /eval -->. That is not a green check, and it is not a defect in this server:
236
+
237
+ 1. **The tool has no knowledge of protocol revision 2026-07-28.** `--spec-version` accepts only `2025-03-26`, `2025-06-18`, `2025-11-25`, `draft` and `extension`. So it exercised the legacy handshake path the SDK still supports for older clients, which is why `server-initialize` and `ping` appear in the passing column although both were removed in the revision this server targets.
238
+ 2. **Its scenarios assert against a reference fixture server.** The failures are things like `Unknown resource: test://static-text`, `Unknown prompt: test_simple_prompt` and `No image content found`. A server with four tools and no prompts or resources cannot satisfy them. `logging-set-level` fails with `Method not found`, which is correct behaviour for this revision.
239
+
240
+ Every scenario that tests protocol behaviour rather than fixture presence passes: `tools-list`, `tools-call-simple-text`, `tools-call-error`, `resources-list`, `prompts-list`, `ping`, `server-initialize`, `server-sse-multiple-streams` and `dns-rebinding-protection`.
241
+
242
+ This result is recorded in [`evals/baseline/conformance.json`](evals/baseline/conformance.json), not re-run in CI. Wiring it in would mean checking in a baseline of <!-- eval:baseline.conformance.failed -->21<!-- /eval --> expected failures, and a baseline that large hides regressions instead of catching them.
243
+
244
+ ### Spec version
245
+
246
+ Built against MCP protocol revision **2026-07-28** on the official Python SDK `mcp==2.0.0`, pinned exactly because the v1 line continues in parallel and the two APIs are not compatible. That revision made the protocol stateless, so there is no session handling anywhere in this codebase. Details, and what changed in the SDK, are in [`docs/architecture.md`](docs/architecture.md).
247
+
248
+ ---
249
+
250
+ ## Development
251
+
252
+ ```bash
253
+ make setup # uv sync, install the git hooks
254
+ make db # start the seeded Postgres (first run takes a few minutes)
255
+ make check # exactly what CI runs: hooks, mypy, tests with coverage, evals
256
+ make test-fast # no database: unit tests and the offline evals
257
+ make evals # re-measure and rewrite evals/results/latest.json
258
+ make fixtures # re-freeze the schema from the running database
259
+ ```
260
+
261
+ Inspect the server with `mcp dev src/postgres_schema_mcp/server.py`. Design decisions, with dates and the alternatives considered, are in [`docs/DECISIONS.md`](docs/DECISIONS.md). Contributions: [CONTRIBUTING.md](CONTRIBUTING.md).
262
+
263
+ ## License
264
+
265
+ MIT. The AdventureWorks sample data is Microsoft's, downloaded at build time and not redistributed here. The frozen schema in `evals/fixtures/` holds table and column metadata, not rows.
266
+
267
+ Not affiliated with the PostgreSQL project, Microsoft or the Model Context Protocol maintainers.