pgleash 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mufasil Iqbal
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.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # pgleash
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/mufasil/pgleash/actions/workflows/ci.yml/badge.svg)](https://github.com/mufasil/pgleash/actions/workflows/ci.yml)
4
+
5
+ A Postgres proxy that keeps AI agents on a leash.
6
+
7
+ Point your coding agent at pgleash instead of at your database. pgleash parses every statement with Postgres's own parser and stops the dangerous ones before they reach the server. Reads go through. `DROP`, `TRUNCATE`, a `DELETE` with no `WHERE`, writes hidden inside a CTE or an `EXPLAIN ANALYZE`, and the stacked `COMMIT;` trick do not.
8
+
9
+ ```
10
+ $ npx pgleash check "SELECT 1; COMMIT; DROP TABLE users"
11
+ blocked [multi-statement]: send one statement at a time (this query has 3)
12
+ ```
13
+
14
+ ## Why
15
+
16
+ Giving an agent database access usually means one of two things: the real connection string, or an MCP server with a "read-only" switch inside it. Both have failed in public.
17
+
18
+ - In July 2025 an AI agent on Replit [deleted a production database](https://www.theregister.com/software/2025/07/21/vibe-coding-service-replit-deleted-production-database/719783) during a code freeze.
19
+ - Anthropic's reference Postgres MCP server wrapped each query in `BEGIN TRANSACTION READ ONLY`. Datadog Security Labs [showed](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/) that a query could end that transaction itself and then run any SQL. The server has been archived, and the npm package still had about 21,000 weekly downloads when they wrote it up.
20
+ - AWS's Postgres MCP server needed a fix for an incomplete list of blocked SQL ([CVE-2025-59333](https://nvd.nist.gov/vuln/detail/CVE-2025-59333)).
21
+
22
+ pgleash enforces the rules on the wire, outside the agent. The agent connects with a pgleash token and never sees the real credentials.
23
+
24
+ ## Quick start
25
+
26
+ ```sh
27
+ export PGLEASH_UPSTREAM='postgres://readonly_user:secret@db.internal:5432/app?sslmode=require'
28
+ npx pgleash
29
+ ```
30
+
31
+ ```
32
+ pgleash 0.1.0 (read-only, max 1000 rows, 10s statement timeout)
33
+ upstream: db.internal:5432/app as readonly_user (sslmode=require)
34
+ listening: 127.0.0.1:6433
35
+
36
+ Give your agent this connection string (not the upstream one):
37
+ postgres://agent:Yq3v...@127.0.0.1:6433/app
38
+ ```
39
+
40
+ pgleash speaks the Postgres wire protocol, so `psql`, node-postgres, psycopg and ORMs connect to it like any other database. (The test suite uses node-postgres.) When a query is blocked, the agent gets a normal Postgres error with the reason and a hint:
41
+
42
+ ```
43
+ app=> DELETE FROM orders;
44
+ ERROR: pgleash blocked this query: DELETE is not allowed in read-only mode
45
+ HINT: pgleash only lets this connection run the statements its mode allows. Ask a person to run this one.
46
+ ```
47
+
48
+ ### As an MCP server
49
+
50
+ For Claude Code:
51
+
52
+ ```sh
53
+ claude mcp add pgleash -e PGLEASH_UPSTREAM='postgres://...' -- npx -y pgleash mcp
54
+ ```
55
+
56
+ For Cursor and other MCP clients:
57
+
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "pgleash": {
62
+ "command": "npx",
63
+ "args": ["-y", "pgleash", "mcp", "--deny-column", "email"],
64
+ "env": { "PGLEASH_UPSTREAM": "postgres://..." }
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ MCP mode gives the agent three tools: `query`, `list_tables` and `describe_table`. Every call goes through the same proxy and the same rules.
71
+
72
+ ## What it does
73
+
74
+ **Read-only by default.** Only reads, `EXPLAIN`, `SHOW`, cursors and transaction control get through. The session is also pinned with `default_transaction_read_only = on`, and the agent can't undo that: `SET`, `RESET ALL`, `DISCARD ALL`, `BEGIN READ WRITE` and `set_config()` are blocked. So a write the parser can't see, such as one inside a user-defined function, still fails in the database.
75
+
76
+ **Guarded writes when you want them.** `--mode guarded-write` allows `INSERT`, plus `UPDATE` and `DELETE` with a `WHERE` clause that names a column. `WHERE true` and `WHERE 1 = 1` don't count. DDL, `TRUNCATE`, `COPY`, `DO`, `CALL`, `GRANT` and `MERGE` stay blocked.
77
+
78
+ **Off-limits tables and columns.** `--deny-table api_tokens` blocks every reference to the table. `--deny-column email` blocks queries that name the column, pass a whole row to a function (`row_to_json(u)`), or `SELECT *` from a table that has it. pgleash looks those tables up in the live schema and refreshes the list every minute. As a second layer, any result column with a denied name comes back as `NULL`.
79
+
80
+ **Dangerous functions blocked.** These include `pg_terminate_backend`, `pg_read_file`, `lo_import`, `dblink`, `pg_sleep`, advisory locks, `query_to_xml` (which runs SQL passed in as a string), replication slot functions and `setval`. Add your own with `--deny-function`, and end a name with `*` to block a whole prefix.
81
+
82
+ **Limits.** Each result stops at 1,000 rows by default, and the agent gets a notice saying how many rows the query really returned. There is a 10 second statement timeout and a 60 second idle-in-transaction timeout.
83
+
84
+ **Audit log.** `--audit pgleash.jsonl` writes one line per query, allowed or blocked, with the rule that blocked it.
85
+
86
+ ```json
87
+ {"ts":"2026-11-29T10:02:11.412Z","session":3,"user":"agent","app":"psql","kind":"query","sql":"DROP TABLE users","allowed":false,"rule":"statement-type","reason":"DROP is not allowed in read-only mode"}
88
+ ```
89
+
90
+ ## Configuration
91
+
92
+ Flags, environment variables or a `pgleash.json` in the working directory:
93
+
94
+ ```json
95
+ {
96
+ "upstream": "postgres://readonly_user:secret@db.internal:5432/app?sslmode=verify-full&sslrootcert=/etc/ssl/rds-global-bundle.pem",
97
+ "mode": "read-only",
98
+ "maxRows": 500,
99
+ "statementTimeout": "5s",
100
+ "denyTables": ["api_tokens", "billing.cards"],
101
+ "denyColumns": ["email", "phone", "password_hash"],
102
+ "denyFunctions": ["app_purge_*"],
103
+ "audit": "pgleash.jsonl"
104
+ }
105
+ ```
106
+
107
+ | Flag | Default | |
108
+ |---|---|---|
109
+ | `--upstream <url>` | `$PGLEASH_UPSTREAM`, then `$DATABASE_URL` | The real database. `sslmode` and `sslrootcert` work as in libpq. |
110
+ | `--host`, `--port` | `127.0.0.1`, `6433` | Where pgleash listens. |
111
+ | `--token <token>` | `$PGLEASH_TOKEN`, or random | The password the agent uses. |
112
+ | `--mode` | `read-only` | Or `guarded-write`. |
113
+ | `--max-rows <n>` | `1000` | `0` turns the cap off. |
114
+ | `--statement-timeout <t>` | `10s` | |
115
+ | `--deny-table`, `--deny-column`, `--deny-function` | | Repeat for more than one. |
116
+ | `--allow-setting <name>` | | Lets the agent `SET` another setting. |
117
+ | `--allow-multi-statement` | off | Each statement is still checked. |
118
+ | `--audit <file>` | | JSON lines. |
119
+
120
+ `pgleash check` runs the same policy without a database, so you can try rules or use it in CI and agent hooks. It exits 1 when a query is blocked, and `--json` prints the decision.
121
+
122
+ ## How it works
123
+
124
+ ```
125
+ agent ──(token)──▶ pgleash ──(real credentials, TLS)──▶ Postgres
126
+ │
127
+ ├─ parse with libpg-query (Postgres's own parser)
128
+ ├─ check statement types, functions, tables, columns
129
+ └─ cap rows, null denied columns, write the audit log
130
+ ```
131
+
132
+ pgleash speaks the Postgres wire protocol on both sides and checks the simple and the extended (prepared statement) protocol. A blocked statement isn't simply dropped. pgleash swaps it for a query that fails on the server, then replaces that error with its own. So the error comes back in the order the client expects, and an open transaction is aborted just as Postgres would abort it. Anything the parser can't parse is blocked.
133
+
134
+ ## Limits
135
+
136
+ pgleash is a guardrail, not a sandbox. Use it together with these:
137
+
138
+ - **A least-privilege role for the upstream.** For read-only work, something like:
139
+
140
+ ```sql
141
+ CREATE ROLE agent_ro LOGIN PASSWORD '...';
142
+ GRANT CONNECT ON DATABASE app TO agent_ro;
143
+ GRANT USAGE ON SCHEMA public TO agent_ro;
144
+ GRANT SELECT ON orders, products TO agent_ro;
145
+ GRANT SELECT (id, name, created_at) ON users TO agent_ro; -- leaves out email and phone
146
+ ```
147
+
148
+ Grant column lists rather than revoking columns: a column `REVOKE` has no effect while the role holds `SELECT` on the whole table.
149
+
150
+ - **Keep the real connection string away from the agent.** If it's in a `.env` file the agent can read, the agent can skip pgleash. On AWS, let only the pgleash host reach the database through its security group.
151
+
152
+ pgleash also has gaps you should know about:
153
+
154
+ - Tables and columns are matched by name. A view over a denied table, or a view that renames a denied column, isn't caught. Deny the view too, or use column privileges.
155
+ - In guarded-write mode, a user-defined function can write whatever its owner can. Block such functions with `--deny-function`.
156
+ - The agent's side of the connection is plain TCP, meant for loopback. pgleash won't listen on another address without a token.
157
+ - Not supported yet: `COPY`, fast-path function calls, replication connections, and TLS between the agent and pgleash.
158
+
159
+ ## Development
160
+
161
+ ```sh
162
+ npm install
163
+ npm test # starts an embedded Postgres; or set PGLEASH_TEST_URL to a superuser URL
164
+ npm run build
165
+ ```
166
+
167
+ The tests run a real Postgres with TLS, connect through pgleash with node-postgres, and check each guardrail end to end. They also cover the CLI and MCP mode.
168
+
169
+ ## License
170
+
171
+ MIT
@@ -0,0 +1,7 @@
1
+ /** Appends one JSON object per line. Every query the agent sends is recorded, allowed or not. */
2
+ export declare class AuditLog {
3
+ private readonly stream;
4
+ constructor(path: string);
5
+ write(entry: Record<string, unknown>): void;
6
+ close(): Promise<void>;
7
+ }
package/dist/audit.js ADDED
@@ -0,0 +1,14 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ /** Appends one JSON object per line. Every query the agent sends is recorded, allowed or not. */
3
+ export class AuditLog {
4
+ stream;
5
+ constructor(path) {
6
+ this.stream = createWriteStream(path, { flags: 'a', mode: 0o600 });
7
+ }
8
+ write(entry) {
9
+ this.stream.write(`${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\n`);
10
+ }
11
+ close() {
12
+ return new Promise((resolve) => this.stream.end(resolve));
13
+ }
14
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import { randomBytes } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { AuditLog } from './audit.js';
5
+ import { parseInvocation, policyOf } from './config.js';
6
+ import { checkSql, initPolicy } from './policy.js';
7
+ import { startProxy } from './proxy.js';
8
+ import { parseUpstreamUrl } from './upstream.js';
9
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
10
+ const HELP = `pgleash ${VERSION}: a Postgres proxy that keeps AI agents on a leash
11
+
12
+ Usage
13
+ pgleash [serve] [options] Start the proxy and print the URL to give your agent
14
+ pgleash check [options] [sql] Check one query against the policy (reads stdin if no sql)
15
+ pgleash mcp [options] Run as an MCP server over stdio
16
+
17
+ Options
18
+ --upstream <url> The real database (default: $PGLEASH_UPSTREAM, then $DATABASE_URL)
19
+ --host <host> Listen address (default 127.0.0.1)
20
+ --port <port> Listen port (default 6433)
21
+ --token <token> Password the agent must send (default: $PGLEASH_TOKEN, or a random one)
22
+ --mode <mode> read-only (default) or guarded-write
23
+ --max-rows <n> Rows per result before the rest are dropped (default 1000, 0 = no cap)
24
+ --statement-timeout <t> Per-statement limit, e.g. 10s or 500ms (default 10s)
25
+ --deny-table <name> Table the agent may not touch; repeat for more ("secrets", "billing.cards")
26
+ --deny-column <name> Column the agent may not read; repeat for more ("email", "password_hash")
27
+ --deny-function <name> Extra function to block; a trailing * matches a prefix
28
+ --allow-setting <name> Extra setting the agent may change with SET
29
+ --allow-multi-statement Allow several statements in one query string
30
+ --audit <file> Append one JSON line per query to this file
31
+ --config <file> JSON config file (default ./pgleash.json if it exists)
32
+ --json check: print the decision as JSON
33
+ -h, --help Show this help
34
+ -v, --version Show the version
35
+
36
+ Examples
37
+ PGLEASH_UPSTREAM=postgres://readonly:pw@db.internal:5432/app?sslmode=require pgleash
38
+ pgleash check "DELETE FROM users"
39
+ claude mcp add pgleash -e PGLEASH_UPSTREAM=postgres://... -- npx -y pgleash mcp
40
+ `;
41
+ function fail(message) {
42
+ process.stderr.write(`pgleash: ${message}\n`);
43
+ process.exit(2);
44
+ }
45
+ const log = (line) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);
46
+ function proxyOptions(config, upstream) {
47
+ return {
48
+ upstream,
49
+ policy: policyOf(config),
50
+ maxRows: config.maxRows,
51
+ statementTimeoutMs: config.statementTimeoutMs,
52
+ audit: config.audit ? new AuditLog(config.audit) : undefined,
53
+ log,
54
+ };
55
+ }
56
+ async function readStdin() {
57
+ const chunks = [];
58
+ for await (const chunk of process.stdin)
59
+ chunks.push(chunk);
60
+ return Buffer.concat(chunks).toString('utf8');
61
+ }
62
+ async function main() {
63
+ let inv;
64
+ try {
65
+ inv = parseInvocation(process.argv.slice(2));
66
+ }
67
+ catch (err) {
68
+ fail(`${err instanceof Error ? err.message : err}\nRun pgleash --help for usage.`);
69
+ }
70
+ if (inv.help) {
71
+ process.stdout.write(HELP);
72
+ return;
73
+ }
74
+ if (inv.version) {
75
+ process.stdout.write(`${VERSION}\n`);
76
+ return;
77
+ }
78
+ const { config } = inv;
79
+ if (inv.command === 'check') {
80
+ const sql = inv.args.length > 0 ? inv.args.join(' ') : await readStdin();
81
+ await initPolicy();
82
+ const d = checkSql(sql, policyOf(config));
83
+ if (inv.json)
84
+ process.stdout.write(`${JSON.stringify(d)}\n`);
85
+ else if (d.allowed)
86
+ process.stdout.write(`allowed (${d.statements.join(', ') || 'empty query'})\n`);
87
+ else
88
+ process.stdout.write(`blocked [${d.rule}]: ${d.reason}\n`);
89
+ process.exit(d.allowed ? 0 : 1);
90
+ }
91
+ if (!config.upstream)
92
+ fail('no upstream database. Set PGLEASH_UPSTREAM or pass --upstream postgres://...');
93
+ let upstream;
94
+ try {
95
+ upstream = parseUpstreamUrl(config.upstream);
96
+ }
97
+ catch (err) {
98
+ fail(err instanceof Error ? err.message : String(err));
99
+ }
100
+ if (inv.command === 'mcp') {
101
+ const { runMcp } = await import('./mcp.js');
102
+ await runMcp(proxyOptions(config, config.upstream), VERSION);
103
+ return;
104
+ }
105
+ const generated = config.token === undefined;
106
+ const token = config.token ?? randomBytes(18).toString('base64url');
107
+ const opts = proxyOptions(config, config.upstream);
108
+ let proxy;
109
+ try {
110
+ proxy = await startProxy({ ...opts, host: config.host, port: config.port, token });
111
+ }
112
+ catch (err) {
113
+ fail(err instanceof Error ? err.message : String(err));
114
+ }
115
+ const limits = [
116
+ config.mode,
117
+ config.maxRows > 0 ? `max ${config.maxRows} rows` : 'no row cap',
118
+ `${config.statementTimeoutMs / 1000}s statement timeout`,
119
+ ];
120
+ process.stderr.write([
121
+ `pgleash ${VERSION} (${limits.join(', ')})`,
122
+ `upstream: ${upstream.host}:${upstream.port}/${upstream.database} as ${upstream.user} (sslmode=${upstream.sslmode})`,
123
+ `listening: ${proxy.host}:${proxy.port}`,
124
+ config.denyTables.length ? `off-limits tables: ${config.denyTables.join(', ')}` : '',
125
+ config.denyColumns.length ? `off-limits columns: ${config.denyColumns.join(', ')}` : '',
126
+ config.audit ? `audit log: ${config.audit}` : '',
127
+ '',
128
+ 'Give your agent this connection string (not the upstream one):',
129
+ ` postgres://agent:${encodeURIComponent(token)}@${proxy.host}:${proxy.port}/${encodeURIComponent(upstream.database)}`,
130
+ generated ? ' (random token; set PGLEASH_TOKEN to keep it the same across restarts)' : '',
131
+ '',
132
+ ]
133
+ .filter((line, i, all) => line !== '' || all[i - 1] !== '')
134
+ .join('\n') + '\n');
135
+ const stop = async () => {
136
+ await proxy.close();
137
+ await opts.audit?.close();
138
+ process.exit(0);
139
+ };
140
+ process.on('SIGINT', () => void stop());
141
+ process.on('SIGTERM', () => void stop());
142
+ }
143
+ main().catch((err) => fail(err instanceof Error ? err.stack ?? err.message : String(err)));
@@ -0,0 +1,29 @@
1
+ import type { Mode, PolicyOptions } from './policy.ts';
2
+ export interface Config {
3
+ upstream?: string;
4
+ host: string;
5
+ port: number;
6
+ token?: string;
7
+ mode: Mode;
8
+ maxRows: number;
9
+ statementTimeoutMs: number;
10
+ denyTables: string[];
11
+ denyColumns: string[];
12
+ denyFunctions: string[];
13
+ allowSettings: string[];
14
+ allowMultiStatement: boolean;
15
+ audit?: string;
16
+ }
17
+ export interface Invocation {
18
+ command: 'serve' | 'check' | 'mcp';
19
+ config: Config;
20
+ /** Words after the command, e.g. the SQL for `check`. */
21
+ args: string[];
22
+ json: boolean;
23
+ help: boolean;
24
+ version: boolean;
25
+ }
26
+ /** "10s", "500ms", "2m" or a number of milliseconds. */
27
+ export declare function parseDuration(value: string | number): number;
28
+ export declare function parseInvocation(argv: string[], env?: NodeJS.ProcessEnv): Invocation;
29
+ export declare function policyOf(config: Config): PolicyOptions;
package/dist/config.js ADDED
@@ -0,0 +1,148 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ const DEFAULTS = {
4
+ host: '127.0.0.1',
5
+ port: 6433,
6
+ mode: 'read-only',
7
+ maxRows: 1000,
8
+ statementTimeoutMs: 10_000,
9
+ denyTables: [],
10
+ denyColumns: [],
11
+ denyFunctions: [],
12
+ allowSettings: [],
13
+ allowMultiStatement: false,
14
+ };
15
+ /** "10s", "500ms", "2m" or a number of milliseconds. */
16
+ export function parseDuration(value) {
17
+ if (typeof value === 'number')
18
+ return value;
19
+ const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m)?$/.exec(value.trim());
20
+ if (!m)
21
+ throw new Error(`invalid duration "${value}" (use e.g. 10s, 500ms or 2m)`);
22
+ const n = Number(m[1]);
23
+ return Math.round(m[2] === 's' ? n * 1000 : m[2] === 'm' ? n * 60_000 : n);
24
+ }
25
+ function list(value, name) {
26
+ if (value === undefined)
27
+ return [];
28
+ if (Array.isArray(value) && value.every((v) => typeof v === 'string'))
29
+ return value;
30
+ throw new Error(`"${name}" must be a list of strings`);
31
+ }
32
+ function fromFile(path) {
33
+ let raw;
34
+ try {
35
+ raw = JSON.parse(readFileSync(path, 'utf8'));
36
+ }
37
+ catch (err) {
38
+ throw new Error(`could not read ${path}: ${err instanceof Error ? err.message : err}`);
39
+ }
40
+ const out = {};
41
+ if (raw.upstream !== undefined)
42
+ out.upstream = String(raw.upstream);
43
+ if (raw.host !== undefined)
44
+ out.host = String(raw.host);
45
+ if (raw.port !== undefined)
46
+ out.port = Number(raw.port);
47
+ if (raw.token !== undefined)
48
+ out.token = String(raw.token);
49
+ if (raw.mode !== undefined)
50
+ out.mode = raw.mode;
51
+ if (raw.maxRows !== undefined)
52
+ out.maxRows = Number(raw.maxRows);
53
+ if (raw.statementTimeout !== undefined)
54
+ out.statementTimeoutMs = parseDuration(raw.statementTimeout);
55
+ if (raw.denyTables !== undefined)
56
+ out.denyTables = list(raw.denyTables, 'denyTables');
57
+ if (raw.denyColumns !== undefined)
58
+ out.denyColumns = list(raw.denyColumns, 'denyColumns');
59
+ if (raw.denyFunctions !== undefined)
60
+ out.denyFunctions = list(raw.denyFunctions, 'denyFunctions');
61
+ if (raw.allowSettings !== undefined)
62
+ out.allowSettings = list(raw.allowSettings, 'allowSettings');
63
+ if (raw.allowMultiStatement !== undefined)
64
+ out.allowMultiStatement = Boolean(raw.allowMultiStatement);
65
+ if (raw.audit !== undefined)
66
+ out.audit = String(raw.audit);
67
+ return out;
68
+ }
69
+ export function parseInvocation(argv, env = process.env) {
70
+ const { values, positionals } = parseArgs({
71
+ args: argv,
72
+ allowPositionals: true,
73
+ options: {
74
+ upstream: { type: 'string' },
75
+ host: { type: 'string' },
76
+ port: { type: 'string' },
77
+ token: { type: 'string' },
78
+ mode: { type: 'string' },
79
+ 'max-rows': { type: 'string' },
80
+ 'statement-timeout': { type: 'string' },
81
+ 'deny-table': { type: 'string', multiple: true },
82
+ 'deny-column': { type: 'string', multiple: true },
83
+ 'deny-function': { type: 'string', multiple: true },
84
+ 'allow-setting': { type: 'string', multiple: true },
85
+ 'allow-multi-statement': { type: 'boolean' },
86
+ audit: { type: 'string' },
87
+ config: { type: 'string' },
88
+ json: { type: 'boolean' },
89
+ help: { type: 'boolean', short: 'h' },
90
+ version: { type: 'boolean', short: 'v' },
91
+ },
92
+ });
93
+ const [first, ...rest] = positionals;
94
+ let command = 'serve';
95
+ let args = positionals;
96
+ if (first === 'serve' || first === 'check' || first === 'mcp') {
97
+ command = first;
98
+ args = rest;
99
+ }
100
+ else if (first !== undefined) {
101
+ throw new Error(`unknown command "${first}" (expected serve, check or mcp)`);
102
+ }
103
+ const configPath = values.config ?? (existsSync('pgleash.json') ? 'pgleash.json' : undefined);
104
+ const file = configPath ? fromFile(configPath) : {};
105
+ const config = { ...DEFAULTS, ...file };
106
+ config.upstream = values.upstream ?? env.PGLEASH_UPSTREAM ?? file.upstream ?? env.DATABASE_URL;
107
+ config.token = values.token ?? env.PGLEASH_TOKEN ?? file.token;
108
+ if (values.host !== undefined)
109
+ config.host = values.host;
110
+ if (values.port !== undefined)
111
+ config.port = Number(values.port);
112
+ if (values.mode !== undefined)
113
+ config.mode = values.mode;
114
+ if (values['max-rows'] !== undefined)
115
+ config.maxRows = Number(values['max-rows']);
116
+ if (values['statement-timeout'] !== undefined)
117
+ config.statementTimeoutMs = parseDuration(values['statement-timeout']);
118
+ if (values['deny-table'])
119
+ config.denyTables = [...config.denyTables, ...values['deny-table']];
120
+ if (values['deny-column'])
121
+ config.denyColumns = [...config.denyColumns, ...values['deny-column']];
122
+ if (values['deny-function'])
123
+ config.denyFunctions = [...config.denyFunctions, ...values['deny-function']];
124
+ if (values['allow-setting'])
125
+ config.allowSettings = [...config.allowSettings, ...values['allow-setting']];
126
+ if (values['allow-multi-statement'])
127
+ config.allowMultiStatement = true;
128
+ if (values.audit !== undefined)
129
+ config.audit = values.audit;
130
+ if (config.mode !== 'read-only' && config.mode !== 'guarded-write') {
131
+ throw new Error(`unknown mode "${config.mode}" (expected read-only or guarded-write)`);
132
+ }
133
+ if (!Number.isInteger(config.port) || config.port < 0 || config.port > 65535)
134
+ throw new Error('invalid port');
135
+ if (!Number.isInteger(config.maxRows) || config.maxRows < 0)
136
+ throw new Error('max-rows must be 0 or more');
137
+ return { command, config, args, json: values.json ?? false, help: values.help ?? false, version: values.version ?? false };
138
+ }
139
+ export function policyOf(config) {
140
+ return {
141
+ mode: config.mode,
142
+ allowMultiStatement: config.allowMultiStatement,
143
+ denyTables: config.denyTables,
144
+ denyColumns: config.denyColumns,
145
+ denyFunctions: config.denyFunctions,
146
+ allowSettings: config.allowSettings,
147
+ };
148
+ }
@@ -0,0 +1,5 @@
1
+ export { checkSql, initPolicy } from './policy.ts';
2
+ export type { Decision, Mode, PolicyOptions, Rule, SchemaInfo } from './policy.ts';
3
+ export { startProxy } from './proxy.ts';
4
+ export type { ProxyOptions, RunningProxy } from './proxy.ts';
5
+ export { AuditLog } from './audit.ts';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { checkSql, initPolicy } from './policy.js';
2
+ export { startProxy } from './proxy.js';
3
+ export { AuditLog } from './audit.js';
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { type ProxyOptions } from './proxy.ts';
2
+ export declare function runMcp(opts: Omit<ProxyOptions, 'host' | 'port' | 'token'>, version: string): Promise<void>;
package/dist/mcp.js ADDED
@@ -0,0 +1,96 @@
1
+ // MCP mode: the agent calls tools instead of speaking SQL over a socket. Every call still goes
2
+ // through the pgleash proxy, started in-process on a loopback port with a one-time token.
3
+ import { randomBytes } from 'node:crypto';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import pg from 'pg';
7
+ import { z } from 'zod';
8
+ import { startProxy } from './proxy.js';
9
+ import { parseUpstreamUrl } from './upstream.js';
10
+ const text = (value, isError = false) => ({ content: [{ type: 'text', text: value }], ...(isError ? { isError } : {}) });
11
+ export async function runMcp(opts, version) {
12
+ const token = randomBytes(18).toString('base64url');
13
+ const proxy = await startProxy({ ...opts, host: '127.0.0.1', port: 0, token });
14
+ const database = parseUpstreamUrl(opts.upstream).database;
15
+ const maxRows = opts.maxRows ?? 1000;
16
+ let client;
17
+ let notices = [];
18
+ const getClient = async () => {
19
+ if (client)
20
+ return client;
21
+ const c = new pg.Client({ host: proxy.host, port: proxy.port, user: 'mcp', password: token, database });
22
+ c.on('notice', (n) => notices.push(n.message ?? ''));
23
+ c.on('error', () => {
24
+ if (client === c)
25
+ client = undefined;
26
+ });
27
+ await c.connect();
28
+ client = c;
29
+ return c;
30
+ };
31
+ const run = async (sql, params) => {
32
+ notices = [];
33
+ try {
34
+ const c = await getClient();
35
+ const res = await c.query({ text: sql, values: params });
36
+ const results = Array.isArray(res) ? res : [res];
37
+ const body = results.map((r) => ({ command: r.command, rowCount: r.rowCount, rows: r.rows }));
38
+ const out = body.length === 1 ? body[0] : { results: body };
39
+ if (notices.length > 0)
40
+ out.notices = notices;
41
+ return text(JSON.stringify(out, null, 2));
42
+ }
43
+ catch (err) {
44
+ const e = err;
45
+ if (!e.code)
46
+ client = undefined; // connection-level failure; reconnect next time
47
+ return text(`${e.message ?? String(err)}${e.hint ? `\nHint: ${e.hint}` : ''}`, true);
48
+ }
49
+ };
50
+ const readOnly = opts.policy.mode === 'read-only';
51
+ const server = new McpServer({ name: 'pgleash', version }, {
52
+ instructions: `SQL runs through pgleash in ${opts.policy.mode} mode. ` +
53
+ (readOnly ? 'Only reads are allowed. ' : 'INSERT, and UPDATE/DELETE with a WHERE clause on a column, are allowed; DDL is not. ') +
54
+ `Send one statement per call. Results stop at ${maxRows} rows, so use LIMIT and name the columns you need. ` +
55
+ 'If a query is blocked, the error says why; do not try to work around it.',
56
+ });
57
+ server.registerTool('query', {
58
+ title: 'Run SQL',
59
+ description: `Run one SQL statement against the database through pgleash (${opts.policy.mode}). Use $1, $2... with params for values.`,
60
+ inputSchema: {
61
+ sql: z.string().describe('One SQL statement'),
62
+ params: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional().describe('Values for $1, $2, ...'),
63
+ },
64
+ annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false },
65
+ }, async ({ sql, params }) => run(sql, params));
66
+ server.registerTool('list_tables', {
67
+ title: 'List tables',
68
+ description: 'List the tables and views in the database.',
69
+ annotations: { readOnlyHint: true, openWorldHint: false },
70
+ }, async () => run(`SELECT table_schema, table_name, table_type
71
+ FROM information_schema.tables
72
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
73
+ ORDER BY table_schema, table_name`));
74
+ server.registerTool('describe_table', {
75
+ title: 'Describe a table',
76
+ description: 'List the columns of one table or view.',
77
+ inputSchema: {
78
+ table: z.string().describe('Table name'),
79
+ schema: z.string().optional().describe('Schema name, default public'),
80
+ },
81
+ annotations: { readOnlyHint: true, openWorldHint: false },
82
+ }, async ({ table, schema }) => run(`SELECT column_name, data_type, is_nullable, column_default
83
+ FROM information_schema.columns
84
+ WHERE table_schema = $1 AND table_name = $2
85
+ ORDER BY ordinal_position`, [schema ?? 'public', table]));
86
+ const transport = new StdioServerTransport();
87
+ const shutdown = async () => {
88
+ await client?.end().catch(() => { });
89
+ await proxy.close();
90
+ process.exit(0);
91
+ };
92
+ transport.onclose = () => void shutdown();
93
+ process.on('SIGINT', () => void shutdown());
94
+ process.on('SIGTERM', () => void shutdown());
95
+ await server.connect(transport);
96
+ }