pg-readonly-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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leslie Kadenge
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,301 @@
1
+ Metadata-Version: 2.4
2
+ Name: pg-readonly-mcp
3
+ Version: 0.1.0
4
+ Summary: A read-only Postgres MCP server that parses SQL rather than pattern-matching it
5
+ Author: Leslie Kadenge
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Leslie Kadenge
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/les-k/pg-readonly-mcp
29
+ Project-URL: Issues, https://github.com/les-k/pg-readonly-mcp/issues
30
+ Keywords: mcp,postgres,sql,security,read-only
31
+ Classifier: Development Status :: 3 - Alpha
32
+ Classifier: Environment :: Console
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.11
38
+ Classifier: Programming Language :: Python :: 3.12
39
+ Classifier: Programming Language :: Python :: 3.13
40
+ Classifier: Topic :: Database
41
+ Classifier: Topic :: Security
42
+ Requires-Python: >=3.11
43
+ Description-Content-Type: text/markdown
44
+ License-File: LICENSE
45
+ Requires-Dist: mcp>=2.0
46
+ Requires-Dist: sqlglot>=27.0
47
+ Requires-Dist: psycopg[binary]>=3.2
48
+ Provides-Extra: dev
49
+ Requires-Dist: pytest>=7.4; extra == "dev"
50
+ Requires-Dist: pytest-cov>=4.1; extra == "dev"
51
+ Requires-Dist: ruff>=0.6; extra == "dev"
52
+ Dynamic: license-file
53
+
54
+ <!-- mcp-name: io.github.les-k/pg-readonly-mcp -->
55
+ # pg-readonly-mcp
56
+
57
+ [![CI](https://github.com/les-k/pg-readonly-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/les-k/pg-readonly-mcp/actions/workflows/ci.yml)
58
+ [![Python](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.13-blue)](https://www.python.org/)
59
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
60
+
61
+ > **In plain terms:** this lets an AI look at your database and do nothing else.
62
+ > Not because it was told not to write — the database login it uses is physically
63
+ > incapable of writing. The official version of this tool had a published flaw
64
+ > that let a "delete everything" command slip past its safety check; this one is
65
+ > tested against that exact attack.
66
+
67
+ A read-only Postgres MCP server that parses SQL rather than pattern-matching
68
+ it — because the alternative has already failed in public, once, in a way
69
+ that is worth being specific about.
70
+
71
+ ## The bypass this exists to close
72
+
73
+ Anthropic's reference Postgres MCP server enforced "read-only" by wrapping
74
+ each query in a read-only **transaction**. It also accepted semicolon-
75
+ delimited multi-statement input. That combination is exploitable:
76
+
77
+ ```sql
78
+ SELECT 1; COMMIT; DROP SCHEMA public CASCADE;
79
+ ```
80
+
81
+ The `COMMIT` ends the read-only transaction early. Everything after it runs
82
+ at full session privilege. [Datadog Security Labs disclosed this in
83
+ 2026](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/);
84
+ the server was deprecated and archived — and the vulnerable package was still
85
+ pulling **21,000 weekly downloads** after that.
86
+
87
+ A read-only transaction is a property of *how* a query runs. It says nothing
88
+ about *what the query is*, which is exactly why it was possible to talk your
89
+ way out of it. This server checks the second thing instead.
90
+
91
+ ## Two independent layers
92
+
93
+ Either one alone would have stopped the disclosed bypass. Both exist because
94
+ a flaw in one should not be the only thing standing between an agent and a
95
+ write.
96
+
97
+ **1. The SQL is parsed, not scanned.** [`guard.py`](src/pg_readonly_mcp/guard.py)
98
+ uses [`sqlglot`](https://github.com/tobymao/sqlglot) to build a real syntax
99
+ tree and applies three checks:
100
+
101
+ - **Exactly one statement.** `sqlglot.parse` splits on statement-terminating
102
+ semicolons the way a driver would, so the payload above becomes three
103
+ statements and is refused before any of them reach a connection.
104
+ - **The outer statement is a read shape** — `SELECT`, `UNION`, `INTERSECT`,
105
+ `EXCEPT`, or a CTE built from those. `DROP TABLE users` is refused here.
106
+ - **No write anywhere in the tree**, walked in full. This is the check the
107
+ other two cannot replace: Postgres allows a CTE to carry a data-modifying
108
+ statement, so `WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x` is,
109
+ at the outer level, a `SELECT`. A check that only looks at the outer shape
110
+ misses this completely. Walking every node finds the `DELETE` regardless of
111
+ how many levels down it sits.
112
+
113
+ An unrecognised statement shape — anything `sqlglot` has no specific rule
114
+ for — is refused by the same rule as everything else. Unfamiliar is not the
115
+ same as safe.
116
+
117
+ **2. The connection itself cannot write, independent of what it is asked to
118
+ run.** [`check_connection_is_readonly`](src/pg_readonly_mcp/server.py) refuses
119
+ to start if the connected role is a superuser, can create databases or
120
+ roles, can bypass row-level security, or holds any grant beyond `SELECT` on
121
+ any table it can see. Not exhaustive — Postgres privilege can also arrive
122
+ through ownership, `PUBLIC` grants, or RLS policies this check does not
123
+ enumerate — but it catches the two ways a misconfiguration most commonly
124
+ shows up, stated here rather than implied.
125
+
126
+ ## What it does not protect against
127
+
128
+ - **A privileged connection string handed to it anyway.** The startup check
129
+ catches the common shapes of over-privilege; it is not an exhaustive
130
+ privilege audit, and it says so above rather than implying otherwise.
131
+ - **Resource exhaustion within the limits.** A query that legally returns
132
+ 1,000 rows of very wide data, or that is legitimately expensive to plan,
133
+ still costs what it costs. Row caps and a statement timeout bound the
134
+ damage; they do not make an expensive read free.
135
+ - **What the agent does with the data once it has it.** This is a query
136
+ gate, not a data-loss-prevention tool. Read access to a table is read
137
+ access to whatever is in it.
138
+ - **A parser disagreement.** `sqlglot` and Postgres's own parser are two
139
+ independent implementations of the same grammar. It is not proven that
140
+ they agree on every edge case Postgres accepts — a genuine, if narrow,
141
+ gap in a project whose whole premise is not trusting a single layer.
142
+ Layer two exists partly because of this: even if a parser differential let
143
+ something unintended through the guard, the connection underneath still
144
+ cannot write.
145
+
146
+ ## Scanner results
147
+
148
+ Run against [`agent-audit`](https://pypi.org/project/agent-audit/) 0.19.2 on
149
+ 18 August 2026: 15 findings, 11 auto-suppressed, **4 actionable** — 1 BLOCK,
150
+ 3 WARN.
151
+
152
+ **The BLOCK finding is the most interesting one, and worth reading in
153
+ full.** `server.py:156`, confidence 1.0: `cur.execute(sql)` — flagged as SQL
154
+ injection via unparameterized execution. That line is real. It is also the
155
+ single most defended line in this codebase: by the time `sql` reaches it,
156
+ `validate_readonly()` has already parsed it, confirmed it is exactly one
157
+ statement, confirmed that statement is a read shape, and walked every node
158
+ in it checking for a write. The scanner has no way to see any of that — it
159
+ is a single-file pattern match, and the validation happens in a different
160
+ function, in a different module, several lines earlier. It correctly
161
+ identifies the *shape* that is dangerous in general and cannot see that the
162
+ shape has already been checked.
163
+
164
+ **It also could not have been satisfied by doing what it suggests.**
165
+ Parameterized queries protect *values* substituted into a fixed query
166
+ shape — `WHERE id = %s`. They do not apply here, because the query's
167
+ *structure* is the input this tool exists to accept. There is no
168
+ values-only parameterization scheme for "run whichever read-only SQL the
169
+ caller asks for." The fix for this class of tool is validating the
170
+ structure, which is what the rest of this file is for.
171
+
172
+ **The WARN on `query()`'s definition** (`AGENT-034`, "no input validation in
173
+ the function body") is the same blind spot from a different angle: the
174
+ function's first line calls `validate_readonly(sql)` inside a `try`/`except`.
175
+ A call to an imported function is not a pattern the scanner credits as
176
+ validation.
177
+
178
+ **The two WARNs on hardcoded credentials** are in `tests/conftest.py`: the
179
+ default admin DSN (`postgres:postgres@localhost:5432/postgres`, the standard
180
+ local/CI Postgres default) and the literal password used for roles the test
181
+ suite creates and drops within the same test. Both are correctly identified
182
+ as credential-shaped strings; neither is a credential that guards anything —
183
+ one points at a throwaway local database, the other lives for the duration
184
+ of a single test.
185
+
186
+ The remaining 11 findings — all `AGENT-041`, all in test fixtures that build
187
+ `CREATE SCHEMA` / `GRANT` / `DROP ROLE` statements from `uuid.uuid4()`-derived
188
+ names — were already auto-suppressed by the scanner itself.
189
+
190
+ A pattern scanner is a smoke detector, not a judge. Publishing what it finds
191
+ and why is worth more than a clean number would be on its own.
192
+
193
+ ## Install
194
+
195
+ ```bash
196
+ pip install pg-readonly-mcp
197
+ ```
198
+
199
+ From a source checkout: `pip install -e .`
200
+
201
+ ## Configure
202
+
203
+ Requires a connection string, given either as `--dsn` or via
204
+ `PG_READONLY_MCP_DSN` — the environment variable exists so a password need
205
+ not appear on a command line or in a client config file that might be
206
+ committed by accident:
207
+
208
+ ```json
209
+ {
210
+ "mcpServers": {
211
+ "pg-readonly-mcp": {
212
+ "command": "pg-readonly-mcp",
213
+ "env": { "PG_READONLY_MCP_DSN": "postgresql://readonly_role:...@host:5432/db" }
214
+ }
215
+ }
216
+ }
217
+ ```
218
+
219
+ **The role in that connection string needs to hold nothing beyond `SELECT`.**
220
+ The server checks this itself and refuses to start otherwise — see
221
+ `check_connection_is_readonly` above.
222
+
223
+ ## The tool
224
+
225
+ One tool, deliberately. A server whose entire value proposition is "we
226
+ refuse everything except reads" does not need a second surface to also get
227
+ that right.
228
+
229
+ | Tool | What it does |
230
+ |---|---|
231
+ | `query` | Runs one SELECT-shaped statement. Parsed and walked before it touches the connection. Capped at `--max-rows` (default 1000) and `--timeout-ms` (default 5000) |
232
+
233
+ ## Tests
234
+
235
+ **37 tests. 25 need no database and run anywhere — they are
236
+ [`guard.py`](src/pg_readonly_mcp/guard.py)'s whole test suite, pure string in,
237
+ decision out.** The other 12 need a live Postgres and are integration tests
238
+ by design: the point of `check_connection_is_readonly` is what it does
239
+ against real role attributes and real grants, and a mocked connection would
240
+ pass regardless of what the server actually does against a real one.
241
+
242
+ ```bash
243
+ pytest -q --cov=pg_readonly_mcp
244
+ ```
245
+
246
+ **CI runs against a real `postgres:16` service container and fails the
247
+ build if the database-backed tests report as skipped there** — the same
248
+ rule `sweep-mcp` applies to its symlink tests, for the same reason: a test
249
+ that quietly does nothing is worse than no test.
250
+
251
+ Among the 12: a live reproduction of the exact Datadog payload, driven
252
+ through the actual MCP tool call rather than through `guard.py` directly —
253
+ and an assertion that the target schema still exists afterward, not just
254
+ that an exception was raised. Also covered: a write hidden inside a CTE
255
+ through the same call path, the row cap, the statement timeout, that a
256
+ cancelled query leaves the connection usable for the next one, and that a
257
+ role with `CREATEDB` and zero table grants is refused on the role attribute
258
+ alone.
259
+
260
+ Coverage on CI, against a real Postgres: **78%, `guard.py` at 100%.** The gap
261
+ in `server.py` is the generic `psycopg.Error` catch-all — nothing in the
262
+ suite deliberately provokes a database error that isn't a cancellation — and
263
+ `main()`'s argparse and transport wiring, which the suite exercises through
264
+ `build_server` directly instead; the transport is the part least worth
265
+ mocking and least likely to be where a real mistake hides.
266
+
267
+ **The first version of this pushed did not pass.** Two bugs surfaced only
268
+ once a real Postgres service container ran the suite for the first time,
269
+ and neither was visible from the code alone: `SET statement_timeout = %s`
270
+ reached Postgres as `SET statement_timeout = $1` and failed to parse, because
271
+ `SET` is a utility statement and does not accept a bind parameter the way a
272
+ `SELECT` does — every real call to the tool would have failed identically.
273
+ Separately, the test fixtures tried to `DROP ROLE` a role that still held
274
+ live grants, which Postgres refuses; `DROP OWNED BY` has to run first. Both
275
+ are fixed, and the run since is the one these numbers describe. Left in
276
+ because a suite that only ever reports success is a suite nobody has watched
277
+ fail.
278
+
279
+ ## Layout
280
+
281
+ ```
282
+ src/pg_readonly_mcp/
283
+ guard.py parses and walks the tree. Opens no connection. 135 lines.
284
+ server.py the MCP tool, the connection check, the timeout and row cap.
285
+ tests/
286
+ test_guard.py 25 tests - no database, run anywhere
287
+ test_server.py 12 tests - live Postgres required, CI-enforced
288
+ ```
289
+
290
+ `guard.py` knows nothing about MCP or psycopg. If a query is ever refused
291
+ for a reason that lives in `server.py` instead, that is a bug — the judgement
292
+ belongs one layer down, where it can be tested with a string and nothing
293
+ else.
294
+
295
+ ## Licence
296
+
297
+ MIT.
298
+
299
+ ## Author
300
+
301
+ Built by [Leslie Kadenge](https://les-k.github.io). I do independent security reviews of MCP servers; my public survey of thirteen production servers is at [les-k.github.io/field-notes.html](https://les-k.github.io/field-notes.html).
@@ -0,0 +1,248 @@
1
+ <!-- mcp-name: io.github.les-k/pg-readonly-mcp -->
2
+ # pg-readonly-mcp
3
+
4
+ [![CI](https://github.com/les-k/pg-readonly-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/les-k/pg-readonly-mcp/actions/workflows/ci.yml)
5
+ [![Python](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.13-blue)](https://www.python.org/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
7
+
8
+ > **In plain terms:** this lets an AI look at your database and do nothing else.
9
+ > Not because it was told not to write — the database login it uses is physically
10
+ > incapable of writing. The official version of this tool had a published flaw
11
+ > that let a "delete everything" command slip past its safety check; this one is
12
+ > tested against that exact attack.
13
+
14
+ A read-only Postgres MCP server that parses SQL rather than pattern-matching
15
+ it — because the alternative has already failed in public, once, in a way
16
+ that is worth being specific about.
17
+
18
+ ## The bypass this exists to close
19
+
20
+ Anthropic's reference Postgres MCP server enforced "read-only" by wrapping
21
+ each query in a read-only **transaction**. It also accepted semicolon-
22
+ delimited multi-statement input. That combination is exploitable:
23
+
24
+ ```sql
25
+ SELECT 1; COMMIT; DROP SCHEMA public CASCADE;
26
+ ```
27
+
28
+ The `COMMIT` ends the read-only transaction early. Everything after it runs
29
+ at full session privilege. [Datadog Security Labs disclosed this in
30
+ 2026](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/);
31
+ the server was deprecated and archived — and the vulnerable package was still
32
+ pulling **21,000 weekly downloads** after that.
33
+
34
+ A read-only transaction is a property of *how* a query runs. It says nothing
35
+ about *what the query is*, which is exactly why it was possible to talk your
36
+ way out of it. This server checks the second thing instead.
37
+
38
+ ## Two independent layers
39
+
40
+ Either one alone would have stopped the disclosed bypass. Both exist because
41
+ a flaw in one should not be the only thing standing between an agent and a
42
+ write.
43
+
44
+ **1. The SQL is parsed, not scanned.** [`guard.py`](src/pg_readonly_mcp/guard.py)
45
+ uses [`sqlglot`](https://github.com/tobymao/sqlglot) to build a real syntax
46
+ tree and applies three checks:
47
+
48
+ - **Exactly one statement.** `sqlglot.parse` splits on statement-terminating
49
+ semicolons the way a driver would, so the payload above becomes three
50
+ statements and is refused before any of them reach a connection.
51
+ - **The outer statement is a read shape** — `SELECT`, `UNION`, `INTERSECT`,
52
+ `EXCEPT`, or a CTE built from those. `DROP TABLE users` is refused here.
53
+ - **No write anywhere in the tree**, walked in full. This is the check the
54
+ other two cannot replace: Postgres allows a CTE to carry a data-modifying
55
+ statement, so `WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x` is,
56
+ at the outer level, a `SELECT`. A check that only looks at the outer shape
57
+ misses this completely. Walking every node finds the `DELETE` regardless of
58
+ how many levels down it sits.
59
+
60
+ An unrecognised statement shape — anything `sqlglot` has no specific rule
61
+ for — is refused by the same rule as everything else. Unfamiliar is not the
62
+ same as safe.
63
+
64
+ **2. The connection itself cannot write, independent of what it is asked to
65
+ run.** [`check_connection_is_readonly`](src/pg_readonly_mcp/server.py) refuses
66
+ to start if the connected role is a superuser, can create databases or
67
+ roles, can bypass row-level security, or holds any grant beyond `SELECT` on
68
+ any table it can see. Not exhaustive — Postgres privilege can also arrive
69
+ through ownership, `PUBLIC` grants, or RLS policies this check does not
70
+ enumerate — but it catches the two ways a misconfiguration most commonly
71
+ shows up, stated here rather than implied.
72
+
73
+ ## What it does not protect against
74
+
75
+ - **A privileged connection string handed to it anyway.** The startup check
76
+ catches the common shapes of over-privilege; it is not an exhaustive
77
+ privilege audit, and it says so above rather than implying otherwise.
78
+ - **Resource exhaustion within the limits.** A query that legally returns
79
+ 1,000 rows of very wide data, or that is legitimately expensive to plan,
80
+ still costs what it costs. Row caps and a statement timeout bound the
81
+ damage; they do not make an expensive read free.
82
+ - **What the agent does with the data once it has it.** This is a query
83
+ gate, not a data-loss-prevention tool. Read access to a table is read
84
+ access to whatever is in it.
85
+ - **A parser disagreement.** `sqlglot` and Postgres's own parser are two
86
+ independent implementations of the same grammar. It is not proven that
87
+ they agree on every edge case Postgres accepts — a genuine, if narrow,
88
+ gap in a project whose whole premise is not trusting a single layer.
89
+ Layer two exists partly because of this: even if a parser differential let
90
+ something unintended through the guard, the connection underneath still
91
+ cannot write.
92
+
93
+ ## Scanner results
94
+
95
+ Run against [`agent-audit`](https://pypi.org/project/agent-audit/) 0.19.2 on
96
+ 18 August 2026: 15 findings, 11 auto-suppressed, **4 actionable** — 1 BLOCK,
97
+ 3 WARN.
98
+
99
+ **The BLOCK finding is the most interesting one, and worth reading in
100
+ full.** `server.py:156`, confidence 1.0: `cur.execute(sql)` — flagged as SQL
101
+ injection via unparameterized execution. That line is real. It is also the
102
+ single most defended line in this codebase: by the time `sql` reaches it,
103
+ `validate_readonly()` has already parsed it, confirmed it is exactly one
104
+ statement, confirmed that statement is a read shape, and walked every node
105
+ in it checking for a write. The scanner has no way to see any of that — it
106
+ is a single-file pattern match, and the validation happens in a different
107
+ function, in a different module, several lines earlier. It correctly
108
+ identifies the *shape* that is dangerous in general and cannot see that the
109
+ shape has already been checked.
110
+
111
+ **It also could not have been satisfied by doing what it suggests.**
112
+ Parameterized queries protect *values* substituted into a fixed query
113
+ shape — `WHERE id = %s`. They do not apply here, because the query's
114
+ *structure* is the input this tool exists to accept. There is no
115
+ values-only parameterization scheme for "run whichever read-only SQL the
116
+ caller asks for." The fix for this class of tool is validating the
117
+ structure, which is what the rest of this file is for.
118
+
119
+ **The WARN on `query()`'s definition** (`AGENT-034`, "no input validation in
120
+ the function body") is the same blind spot from a different angle: the
121
+ function's first line calls `validate_readonly(sql)` inside a `try`/`except`.
122
+ A call to an imported function is not a pattern the scanner credits as
123
+ validation.
124
+
125
+ **The two WARNs on hardcoded credentials** are in `tests/conftest.py`: the
126
+ default admin DSN (`postgres:postgres@localhost:5432/postgres`, the standard
127
+ local/CI Postgres default) and the literal password used for roles the test
128
+ suite creates and drops within the same test. Both are correctly identified
129
+ as credential-shaped strings; neither is a credential that guards anything —
130
+ one points at a throwaway local database, the other lives for the duration
131
+ of a single test.
132
+
133
+ The remaining 11 findings — all `AGENT-041`, all in test fixtures that build
134
+ `CREATE SCHEMA` / `GRANT` / `DROP ROLE` statements from `uuid.uuid4()`-derived
135
+ names — were already auto-suppressed by the scanner itself.
136
+
137
+ A pattern scanner is a smoke detector, not a judge. Publishing what it finds
138
+ and why is worth more than a clean number would be on its own.
139
+
140
+ ## Install
141
+
142
+ ```bash
143
+ pip install pg-readonly-mcp
144
+ ```
145
+
146
+ From a source checkout: `pip install -e .`
147
+
148
+ ## Configure
149
+
150
+ Requires a connection string, given either as `--dsn` or via
151
+ `PG_READONLY_MCP_DSN` — the environment variable exists so a password need
152
+ not appear on a command line or in a client config file that might be
153
+ committed by accident:
154
+
155
+ ```json
156
+ {
157
+ "mcpServers": {
158
+ "pg-readonly-mcp": {
159
+ "command": "pg-readonly-mcp",
160
+ "env": { "PG_READONLY_MCP_DSN": "postgresql://readonly_role:...@host:5432/db" }
161
+ }
162
+ }
163
+ }
164
+ ```
165
+
166
+ **The role in that connection string needs to hold nothing beyond `SELECT`.**
167
+ The server checks this itself and refuses to start otherwise — see
168
+ `check_connection_is_readonly` above.
169
+
170
+ ## The tool
171
+
172
+ One tool, deliberately. A server whose entire value proposition is "we
173
+ refuse everything except reads" does not need a second surface to also get
174
+ that right.
175
+
176
+ | Tool | What it does |
177
+ |---|---|
178
+ | `query` | Runs one SELECT-shaped statement. Parsed and walked before it touches the connection. Capped at `--max-rows` (default 1000) and `--timeout-ms` (default 5000) |
179
+
180
+ ## Tests
181
+
182
+ **37 tests. 25 need no database and run anywhere — they are
183
+ [`guard.py`](src/pg_readonly_mcp/guard.py)'s whole test suite, pure string in,
184
+ decision out.** The other 12 need a live Postgres and are integration tests
185
+ by design: the point of `check_connection_is_readonly` is what it does
186
+ against real role attributes and real grants, and a mocked connection would
187
+ pass regardless of what the server actually does against a real one.
188
+
189
+ ```bash
190
+ pytest -q --cov=pg_readonly_mcp
191
+ ```
192
+
193
+ **CI runs against a real `postgres:16` service container and fails the
194
+ build if the database-backed tests report as skipped there** — the same
195
+ rule `sweep-mcp` applies to its symlink tests, for the same reason: a test
196
+ that quietly does nothing is worse than no test.
197
+
198
+ Among the 12: a live reproduction of the exact Datadog payload, driven
199
+ through the actual MCP tool call rather than through `guard.py` directly —
200
+ and an assertion that the target schema still exists afterward, not just
201
+ that an exception was raised. Also covered: a write hidden inside a CTE
202
+ through the same call path, the row cap, the statement timeout, that a
203
+ cancelled query leaves the connection usable for the next one, and that a
204
+ role with `CREATEDB` and zero table grants is refused on the role attribute
205
+ alone.
206
+
207
+ Coverage on CI, against a real Postgres: **78%, `guard.py` at 100%.** The gap
208
+ in `server.py` is the generic `psycopg.Error` catch-all — nothing in the
209
+ suite deliberately provokes a database error that isn't a cancellation — and
210
+ `main()`'s argparse and transport wiring, which the suite exercises through
211
+ `build_server` directly instead; the transport is the part least worth
212
+ mocking and least likely to be where a real mistake hides.
213
+
214
+ **The first version of this pushed did not pass.** Two bugs surfaced only
215
+ once a real Postgres service container ran the suite for the first time,
216
+ and neither was visible from the code alone: `SET statement_timeout = %s`
217
+ reached Postgres as `SET statement_timeout = $1` and failed to parse, because
218
+ `SET` is a utility statement and does not accept a bind parameter the way a
219
+ `SELECT` does — every real call to the tool would have failed identically.
220
+ Separately, the test fixtures tried to `DROP ROLE` a role that still held
221
+ live grants, which Postgres refuses; `DROP OWNED BY` has to run first. Both
222
+ are fixed, and the run since is the one these numbers describe. Left in
223
+ because a suite that only ever reports success is a suite nobody has watched
224
+ fail.
225
+
226
+ ## Layout
227
+
228
+ ```
229
+ src/pg_readonly_mcp/
230
+ guard.py parses and walks the tree. Opens no connection. 135 lines.
231
+ server.py the MCP tool, the connection check, the timeout and row cap.
232
+ tests/
233
+ test_guard.py 25 tests - no database, run anywhere
234
+ test_server.py 12 tests - live Postgres required, CI-enforced
235
+ ```
236
+
237
+ `guard.py` knows nothing about MCP or psycopg. If a query is ever refused
238
+ for a reason that lives in `server.py` instead, that is a bug — the judgement
239
+ belongs one layer down, where it can be tested with a string and nothing
240
+ else.
241
+
242
+ ## Licence
243
+
244
+ MIT.
245
+
246
+ ## Author
247
+
248
+ Built by [Leslie Kadenge](https://les-k.github.io). I do independent security reviews of MCP servers; my public survey of thirteen production servers is at [les-k.github.io/field-notes.html](https://les-k.github.io/field-notes.html).
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pg-readonly-mcp"
7
+ version = "0.1.0"
8
+ description = "A read-only Postgres MCP server that parses SQL rather than pattern-matching it"
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "Leslie Kadenge" }]
13
+ keywords = ["mcp", "postgres", "sql", "security", "read-only"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Database",
25
+ "Topic :: Security",
26
+ ]
27
+ dependencies = [
28
+ "mcp>=2.0",
29
+ "sqlglot>=27.0",
30
+ "psycopg[binary]>=3.2",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ dev = ["pytest>=7.4", "pytest-cov>=4.1", "ruff>=0.6"]
35
+
36
+ [project.scripts]
37
+ pg-readonly-mcp = "pg_readonly_mcp.server:main"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/les-k/pg-readonly-mcp"
41
+ Issues = "https://github.com/les-k/pg-readonly-mcp/issues"
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
45
+
46
+ # No JavaScript ships here, so there are no source maps to leak. Declared
47
+ # anyway: it costs nothing, and it keeps a supply-chain scanner's checklist
48
+ # honest rather than arguing with it.
49
+ [tool.setuptools.exclude-package-data]
50
+ "*" = ["*.map", "*.pyc", "*.pyo"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ addopts = "-q"
55
+
56
+ [tool.ruff]
57
+ line-length = 100
58
+ src = ["src", "tests"]
59
+
60
+ [tool.ruff.lint]
61
+ select = ["E", "F", "I", "UP", "B", "SIM"]
62
+
63
+ [tool.coverage.run]
64
+ source = ["pg_readonly_mcp"]
65
+ branch = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """A read-only Postgres MCP server that parses SQL rather than pattern-matching it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .guard import Denied, validate_readonly
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = ["Denied", "validate_readonly", "__version__"]
@@ -0,0 +1,6 @@
1
+ """python -m pg_readonly_mcp"""
2
+
3
+ from .server import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())