@hibira-io/mcp-approval-gate 0.0.0-stage → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - The assistant no longer gets the approval link when the request reaches a
6
+ supervisor by push (`--push-interests`, `--push-users`) or a channel
7
+ (`--channel`), so the person in the chat cannot approve their own change.
8
+ Without either, the link is still shown so you can forward it.
9
+ `--show-link auto|always|never` (`GATE_SHOW_LINK`) controls this.
10
+ - New demo and screenshots: the request reaches the store manager's phone and
11
+ the assistant continues once she approves.
12
+
13
+ ## 0.1.0
14
+
15
+ - First release: an MCP proxy that puts supervisor approval in front of any
16
+ database MCP server. Reads pass through; writes, schema changes and other
17
+ changing tools wait for approval on a Hibira-hosted page (with push), then
18
+ run once with exactly the approved arguments.
19
+ - SQL classifier (Postgres, MySQL, SQLite, SQL Server dialects) that skips
20
+ comments, strings and dollar quotes and fails closed.
21
+ - `check_approval` tool for answers that take longer than the client waits.
22
+ - stdio and Streamable HTTP (with `GATE_TOKEN`) downstream; stdio command or
23
+ Streamable HTTP URL upstream.
24
+ - Tested with DBHub, postgres-mcp and Supabase MCP.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hibira
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,258 @@
1
- # Temporary Holding Version
1
+ # Approval gate for database MCP servers
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
+ `@hibira-io/mcp-approval-gate` sits in front of the MCP server that connects
4
+ your assistant to a database. Reads go straight through. Anything that changes
5
+ data or schema waits until **another person approves it** on a hosted approval
6
+ page, sent to their phone as a push notification. Then it runs once, exactly
7
+ as approved.
8
+
9
+ ![An assistant asks to update an order; the change waits until a supervisor approves it on their phone, then runs once](https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/demo.gif)
10
+
11
+ <sub>A real session: Claude Code asks to mark order 1042 as refunded through DBHub. The `UPDATE` waits and the assistant never gets the approval link. The store manager's phone gets the request, she approves it, and the assistant finishes the change. ([MP4](https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/demo.mp4))</sub>
12
+
13
+ It works with any MCP server, and is tested with:
14
+
15
+ - [DBHub](https://github.com/bytebase/dbhub) (Postgres, MySQL, MariaDB, SQL Server, SQLite)
16
+ - [Postgres MCP Pro](https://github.com/crystaldba/postgres-mcp) (`postgres-mcp`)
17
+ - [Supabase MCP](https://github.com/supabase-community/supabase-mcp) (local or `mcp.supabase.com`)
18
+
19
+ and with Claude (Desktop, Code and claude.ai), Cursor, ChatGPT and any other
20
+ MCP client.
21
+
22
+ ```
23
+ assistant ──► approval gate ──► database MCP server ──► database
24
+ │ writes only
25
+ ▼
26
+ Hibira approval page + push ──► supervisor taps Approve / Reject
27
+ ```
28
+
29
+ ## Why
30
+
31
+ Most database MCP servers offer two choices: read-only, or let the assistant
32
+ write anything. Client-side "allow this tool?" prompts are answered by the same
33
+ person who asked. The gate adds the step a team usually wants for production
34
+ data: a **supervisor approval** by someone else, with the exact statement in
35
+ front of them.
36
+
37
+ - **Bound to the exact call.** The approval covers one tool call with one set
38
+ of arguments (shown with its fingerprint). If the statement changes, it needs
39
+ a new approval. An approved call runs once.
40
+ - **Fails closed.** SQL the gate cannot read, and tools it does not know to be
41
+ read-only, wait for approval. If the approval service cannot be reached,
42
+ nothing runs.
43
+ - **Your database stays yours.** The gate runs where your database MCP server
44
+ runs. Hibira only sees the approval request (title, statement, tool name),
45
+ never your connection string or query results.
46
+ - **Clear for the reviewer.** The page shows the database label, the kind of
47
+ change (`UPDATE`, `DROP TABLE`, ...), warnings such as "DELETE without WHERE
48
+ changes every row", and the full statement.
49
+
50
+ <p>
51
+ <img src="https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/supervisor-notification.png" width="240" alt="The supervisor's phone gets the request: UPDATE on shop-production">
52
+ <img src="https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/approval-page.png" width="240" alt="The approval page: database, kind of change, the full statement and its fingerprint">
53
+ <img src="https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/approval-approved.png" width="240" alt="The same request after the supervisor approved it">
54
+ </p>
55
+
56
+ ## Setup
57
+
58
+ 1. Sign in at [hibira.io](https://hibira.io), create an app (Free works), and
59
+ copy its **App ID, Key and Secret**.
60
+ 2. Turn on Push for the app and subscribe the supervisors' devices to an
61
+ interest such as `db-approvals`, so requests reach their phones (or pass
62
+ `--channel` to show them in your own approvals inbox). Without either, the
63
+ assistant shows the approval link and you forward it to a supervisor.
64
+ 3. Put the gate in front of your database MCP server in your client's config
65
+ (below). Everything after `--` is the database server's usual command.
66
+
67
+ The Hibira credentials are read from the environment only, and they are not
68
+ passed on to the database server.
69
+
70
+ ### Claude Code
71
+
72
+ ```sh
73
+ claude mcp add shop-db \
74
+ -e HIBIRA_APP_ID=app_... -e HIBIRA_KEY=... -e HIBIRA_SECRET=... \
75
+ -e GATE_LABEL=shop-production -e GATE_PUSH_INTERESTS=db-approvals \
76
+ -- npx -y @hibira-io/mcp-approval-gate \
77
+ -- npx -y @bytebase/dbhub --transport stdio --dsn "postgres://user:pass@host:5432/shop"
78
+ ```
79
+
80
+ ### Claude Desktop, Cursor, Windsurf, VS Code
81
+
82
+ `claude_desktop_config.json`, `.cursor/mcp.json` and the others take the same
83
+ shape:
84
+
85
+ ```json
86
+ {
87
+ "mcpServers": {
88
+ "shop-db": {
89
+ "command": "npx",
90
+ "args": [
91
+ "-y", "@hibira-io/mcp-approval-gate",
92
+ "--label", "shop-production",
93
+ "--push-interests", "db-approvals",
94
+ "--",
95
+ "npx", "-y", "@bytebase/dbhub", "--transport", "stdio",
96
+ "--dsn", "postgres://user:pass@host:5432/shop"
97
+ ],
98
+ "env": {
99
+ "HIBIRA_APP_ID": "app_...",
100
+ "HIBIRA_KEY": "...",
101
+ "HIBIRA_SECRET": "..."
102
+ }
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ **postgres-mcp:**
109
+
110
+ ```json
111
+ "args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "analytics", "--",
112
+ "uvx", "postgres-mcp", "--access-mode=unrestricted"],
113
+ "env": { "DATABASE_URI": "postgresql://...", "HIBIRA_APP_ID": "...", "HIBIRA_KEY": "...", "HIBIRA_SECRET": "..." }
114
+ ```
115
+
116
+ `--access-mode=unrestricted` is fine here: the gate is what holds writes back.
117
+
118
+ **Supabase (local server):**
119
+
120
+ ```json
121
+ "args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "supabase-prod", "--",
122
+ "npx", "-y", "@supabase/mcp-server-supabase@latest", "--project-ref=<project-ref>"],
123
+ "env": { "SUPABASE_ACCESS_TOKEN": "sbp_...", "HIBIRA_APP_ID": "...", "HIBIRA_KEY": "...", "HIBIRA_SECRET": "..." }
124
+ ```
125
+
126
+ `execute_sql` with a `SELECT` runs right away; writes, `apply_migration`,
127
+ `deploy_edge_function`, branch merges and project pauses wait for approval.
128
+
129
+ **Supabase (hosted server):**
130
+
131
+ ```json
132
+ "args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "supabase-prod",
133
+ "--upstream-url", "https://mcp.supabase.com/mcp?project_ref=<project-ref>",
134
+ "--header", "Authorization: Bearer ${SUPABASE_ACCESS_TOKEN}"],
135
+ ```
136
+
137
+ ### ChatGPT and claude.ai (remote)
138
+
139
+ Web clients need an HTTPS URL, so run the gate as a small server next to your
140
+ database and put HTTPS in front of it (your reverse proxy, a tunnel, or a
141
+ platform such as Fly.io or Railway):
142
+
143
+ ```sh
144
+ export HIBIRA_APP_ID=app_... HIBIRA_KEY=... HIBIRA_SECRET=...
145
+ export GATE_TOKEN="$(openssl rand -hex 24)" # keep it secret
146
+ npx -y @hibira-io/mcp-approval-gate --http --host 0.0.0.0 --port 8787 \
147
+ --label shop-production --push-interests db-approvals \
148
+ -- npx -y @bytebase/dbhub --transport stdio --dsn "$DATABASE_URL"
149
+ ```
150
+
151
+ The endpoint is `https://your-host/mcp/<GATE_TOKEN>`; clients that can send
152
+ headers may use `https://your-host/mcp` with `Authorization: Bearer <GATE_TOKEN>`.
153
+
154
+ - **ChatGPT:** Settings → Apps & Connectors → Advanced → Developer mode, then
155
+ Create: paste the URL with the token, authentication "No authentication".
156
+ - **claude.ai:** Settings → Connectors → Add custom connector, paste the URL
157
+ with the token.
158
+
159
+ The gate refuses to listen on a non-local address without `GATE_TOKEN`.
160
+ A [Dockerfile](Dockerfile) is included.
161
+
162
+ ## What the assistant sees
163
+
164
+ A write call waits up to 50 seconds (`--wait`) for the decision, sending
165
+ progress updates so the client does not give up early:
166
+
167
+ - **Approved:** the call runs and its normal result comes back, with a line
168
+ saying it was approved.
169
+ - **Rejected or expired:** an error saying it did not run, with the
170
+ supervisor's comment if they left one.
171
+ - **Still waiting:** a short answer saying a supervisor has to approve it,
172
+ with an `approval_id`. The gate adds one tool, `check_approval`: when the
173
+ person says it is decided, the assistant calls it with that `approval_id`,
174
+ and the call runs if it was approved. Asking for the same call again reuses
175
+ the same request.
176
+
177
+ **The assistant does not get the approval link** when the request reaches
178
+ the supervisor another way (`--push-interests`, `--push-users` or
179
+ `--channel`), so the person chatting with it cannot approve their own change
180
+ from the chat. Without any of those, the link is the only way to reach a
181
+ supervisor, so the assistant shows it for you to forward. `--show-link always`
182
+ or `never` overrides this.
183
+
184
+ ## What waits for approval
185
+
186
+ With the default `--mode writes`:
187
+
188
+ 1. Tools listed in `--gate` always wait; tools in `--allow` never do (a
189
+ trailing `*` matches a prefix).
190
+ 2. Calls with SQL (an argument named `sql`, `query`, `statement`, `queries`,
191
+ ...) wait if any statement changes something: `INSERT`, `UPDATE`,
192
+ `DELETE`, `MERGE`, `CREATE`, `ALTER`, `DROP`, `TRUNCATE`, `GRANT`, `COPY`,
193
+ `CALL`, `DO`, `SET`, `VACUUM`, data-changing `WITH`, `SELECT ... INTO`,
194
+ `EXPLAIN ANALYZE` of a write, `SELECT` of functions such as `setval` or
195
+ `pg_terminate_backend`, and anything it cannot parse. Comments, strings and
196
+ dollar-quoted bodies are skipped, so `SELECT 'DROP TABLE x'` is a read.
197
+ 3. Other tools pass if they are marked `readOnlyHint` or named like a read
198
+ (`list_`, `get_`, `search_`, `describe_`, `explain_`, `analyze_`, ...).
199
+ Everything else waits.
200
+
201
+ `--mode all` sends every call for approval, reads included. `--mode none` turns
202
+ the gate off (useful while testing).
203
+
204
+ The gate is a second pair of eyes, not a permission system. Give the database
205
+ user only the rights it needs too.
206
+
207
+ ## Options
208
+
209
+ | Flag | Env | Default | |
210
+ | --- | --- | --- | --- |
211
+ | | `HIBIRA_APP_ID`, `HIBIRA_KEY`, `HIBIRA_SECRET` | required | your Hibira app |
212
+ | | `HIBIRA_API_URL` | `https://ws.hibira.io` | |
213
+ | `--label` | `GATE_LABEL` | `database` | the database's name on the approval page |
214
+ | `--mode` | `GATE_MODE` | `writes` | `writes`, `all` or `none` |
215
+ | `--allow` | `GATE_ALLOW_TOOLS` | | tools that never wait |
216
+ | `--gate` | `GATE_TOOLS` | | tools that always wait |
217
+ | `--push-interests` | `GATE_PUSH_INTERESTS` | | push the request to these interests |
218
+ | `--push-users` | `GATE_PUSH_USERS` | | ...or to these user ids |
219
+ | `--channel` | `GATE_CHANNEL` | | also announce requests on this channel, e.g. for an [approvals inbox](https://github.com/hibira-io/approvals) |
220
+ | `--show-link` | `GATE_SHOW_LINK` | `auto` | give the assistant the approval link: `auto` (only without push or a channel), `always`, `never` |
221
+ | `--options` | `GATE_OPTIONS` | `Approve,Reject` | answer buttons; the first one approves |
222
+ | `--wait` | `GATE_WAIT_SECONDS` | `50` | how long a call waits before answering "still waiting" |
223
+ | `--expires` | `GATE_EXPIRES_MINUTES` | `60` | how long a request stays open (up to 7 days) |
224
+ | `-- <command>` | `GATE_COMMAND` | | the database MCP server to start |
225
+ | `--upstream-url` | `GATE_UPSTREAM_URL` | | ...or a remote one (Streamable HTTP) |
226
+ | `--header` | `GATE_UPSTREAM_HEADERS` | | headers for the remote server; `${VAR}` reads the environment |
227
+ | `--http` | | off | serve Streamable HTTP instead of stdio |
228
+ | `--host`, `--port` | `GATE_HOST`, `PORT` | `127.0.0.1`, `8787` | |
229
+ | | `GATE_TOKEN` | | required for `--http` on a non-local address |
230
+
231
+ Pending calls live in the gate's memory. If the gate restarts, a waiting call
232
+ is forgotten (nothing runs) and the assistant simply asks again.
233
+
234
+ ## Development
235
+
236
+ ```sh
237
+ npm install
238
+ npm test
239
+ # against real servers and a local Postgres:
240
+ DATABASE_URL=postgres://... node --test test/real-servers.e2e.js
241
+ ```
242
+
243
+ ## License
244
+
245
+ MIT
246
+
247
+ ---
248
+
249
+ ## 中文摘要
250
+
251
+ `@hibira-io/mcp-approval-gate` 套在任何数据库 MCP server(DBHub、postgres-mcp、Supabase MCP 等)外面:**读取直接通过;写入、改表、删除会先停下,等另一个人(主管)在 Hibira 托管的审批页或手机推播上核准**,核准后只按原样执行一次。
252
+
253
+ - 审批绑定这一次调用的完整参数(附指纹),SQL 改了就要重新审批。
254
+ - 设定了推播或频道时,助手拿不到审批链接,只有收到推播的主管能核准。
255
+ - 看不懂的 SQL、不确定是否只读的工具一律要审批;审批服务连不上就不执行。
256
+ - Gate 跑在你自己的环境,Hibira 只经手审批内容,不碰数据库密码,也看不到查询结果。
257
+ - Claude(Desktop / Code / claude.ai)、Cursor、ChatGPT 都能用;网页端用 `--http` 加 `GATE_TOKEN`。
258
+ - 设定:在 hibira.io 建 app,把 App ID / Key / Secret 放进环境变量,在 `--` 后面接原本的数据库 MCP 指令。
package/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './src/cli.js';
3
+
4
+ main();
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@hibira-io/mcp-approval-gate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "mcpName": "io.hibira/mcp-approval-gate",
5
+ "description": "Supervisor approval for database MCP servers: wrap DBHub, postgres-mcp or Supabase MCP so reads pass through and writes wait for another person to approve them on a hosted page, with push",
6
+ "keywords": [
7
+ "mcp",
8
+ "model-context-protocol",
9
+ "mcp-server",
10
+ "mcp-proxy",
11
+ "approval",
12
+ "human-in-the-loop",
13
+ "supervisor-approval",
14
+ "sql",
15
+ "database",
16
+ "postgres",
17
+ "mysql",
18
+ "sqlite",
19
+ "supabase",
20
+ "dbhub",
21
+ "postgres-mcp",
22
+ "claude",
23
+ "cursor",
24
+ "chatgpt",
25
+ "hibira"
26
+ ],
27
+ "homepage": "https://hibira.io",
28
+ "bugs": {
29
+ "url": "https://github.com/hibira-io/mcp-approval-gate/issues"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/hibira-io/mcp-approval-gate.git"
34
+ },
35
+ "license": "MIT",
36
+ "author": "Hibira (https://hibira.io)",
37
+ "type": "module",
38
+ "bin": {
39
+ "mcp-approval-gate": "bin.js"
40
+ },
41
+ "exports": {
42
+ ".": "./src/gate.js",
43
+ "./sql": "./src/sql.js",
44
+ "./policy": "./src/policy.js",
45
+ "./hibira": "./src/hibira.js"
46
+ },
47
+ "files": [
48
+ "bin.js",
49
+ "src",
50
+ "README.md",
51
+ "CHANGELOG.md",
52
+ "LICENSE"
53
+ ],
54
+ "engines": {
55
+ "node": ">=20"
56
+ },
57
+ "scripts": {
58
+ "test": "node --test test/*.test.js"
59
+ },
60
+ "dependencies": {
61
+ "@modelcontextprotocol/sdk": "1.32.2"
62
+ },
63
+ "devDependencies": {
64
+ "zod": "4.6.7"
65
+ }
66
+ }
package/src/cli.js ADDED
@@ -0,0 +1,272 @@
1
+ // mcp-approval-gate [options] -- <database MCP server command...>
2
+ // mcp-approval-gate [options] --upstream-url https://.../mcp
3
+
4
+ import { createServer as createHttpServer } from 'node:http';
5
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
6
+ import { parseArgs } from 'node:util';
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
9
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
10
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
11
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
12
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
13
+ import { ApprovalsClient } from './hibira.js';
14
+ import { Gate, VERSION } from './gate.js';
15
+
16
+ const HELP = `Usage:
17
+ mcp-approval-gate [options] -- <command> [args...] wrap a local (stdio) database MCP server
18
+ mcp-approval-gate [options] --upstream-url <url> wrap a remote (Streamable HTTP) MCP server
19
+ GATE_COMMAND="<command> [args...]" mcp-approval-gate the same as after --, from the environment
20
+
21
+ Reads pass through. Calls that change data or schema wait for a supervisor's
22
+ approval on a Hibira-hosted page (with push), then run once.
23
+
24
+ Hibira app (from the Hibira portal; env only, never flags):
25
+ HIBIRA_APP_ID, HIBIRA_KEY, HIBIRA_SECRET required
26
+ HIBIRA_API_URL default https://ws.hibira.io
27
+
28
+ Options (each also as an env var, shown in brackets):
29
+ --label <name> name of the database on the approval page [GATE_LABEL]
30
+ --mode <writes|all|none> what waits: writes (default), every call, or nothing [GATE_MODE]
31
+ --allow <tools> comma-separated tools that never wait (* suffix ok) [GATE_ALLOW_TOOLS]
32
+ --gate <tools> comma-separated tools that always wait [GATE_TOOLS]
33
+ --push-interests <list> send the approval link as a push to these interests [GATE_PUSH_INTERESTS]
34
+ --push-users <list> ...or to these user ids [GATE_PUSH_USERS]
35
+ --channel <name> also announce requests on this channel (approvals inbox) [GATE_CHANNEL]
36
+ --options <a,b> answer buttons, first one approves (default Approve,Reject) [GATE_OPTIONS]
37
+ --show-link <auto|always|never> give the assistant the approval link; auto (default) only when
38
+ no push or channel delivers it to the supervisor [GATE_SHOW_LINK]
39
+ --wait <seconds> how long a call waits before answering "pending" (default 50) [GATE_WAIT_SECONDS]
40
+ --expires <minutes> how long a request stays open (default 60) [GATE_EXPIRES_MINUTES]
41
+ --upstream-url <url> remote MCP server to wrap [GATE_UPSTREAM_URL]
42
+ --header "Name: value" header for the remote server, repeatable; \${VAR} reads the environment [GATE_UPSTREAM_HEADERS, one per line]
43
+ --http serve Streamable HTTP instead of stdio (for ChatGPT and remote clients)
44
+ --port <n> HTTP port (default 8787) [PORT]
45
+ --host <addr> HTTP bind address (default 127.0.0.1) [GATE_HOST]
46
+ GATE_TOKEN HTTP access token: Authorization: Bearer <token>, or the URL /mcp/<token>
47
+ --version, --help
48
+ `;
49
+
50
+ function list(v) {
51
+ return (v ?? '').split(',').map((s) => s.trim()).filter(Boolean);
52
+ }
53
+
54
+ /** Splits a command line on spaces, honouring '...' and "..." quotes (no shell). */
55
+ export function splitCommand(line) {
56
+ const out = [];
57
+ let cur = '';
58
+ let quote = '';
59
+ let has = false;
60
+ for (const ch of line) {
61
+ if (quote) {
62
+ if (ch === quote) quote = '';
63
+ else cur += ch;
64
+ } else if (ch === '"' || ch === "'") {
65
+ quote = ch;
66
+ has = true;
67
+ } else if (/\s/.test(ch)) {
68
+ if (has || cur) out.push(cur);
69
+ cur = '';
70
+ has = false;
71
+ } else {
72
+ cur += ch;
73
+ }
74
+ }
75
+ if (quote) throw new Error('GATE_COMMAND has an unclosed quote');
76
+ if (has || cur) out.push(cur);
77
+ return out;
78
+ }
79
+
80
+ function fail(msg) {
81
+ process.stderr.write(`mcp-approval-gate: ${msg}\n`);
82
+ process.exit(2);
83
+ }
84
+
85
+ export function parse(argv, env) {
86
+ const dash = argv.indexOf('--');
87
+ const own = dash === -1 ? argv : argv.slice(0, dash);
88
+ const command = dash === -1 ? splitCommand(env.GATE_COMMAND ?? '') : argv.slice(dash + 1);
89
+ const { values } = parseArgs({
90
+ args: own,
91
+ options: {
92
+ label: { type: 'string' }, mode: { type: 'string' }, allow: { type: 'string' }, gate: { type: 'string' },
93
+ 'push-interests': { type: 'string' }, 'push-users': { type: 'string' }, channel: { type: 'string' },
94
+ options: { type: 'string' }, wait: { type: 'string' }, expires: { type: 'string' }, 'show-link': { type: 'string' },
95
+ 'upstream-url': { type: 'string' }, header: { type: 'string', multiple: true },
96
+ http: { type: 'boolean' }, port: { type: 'string' }, host: { type: 'string' },
97
+ version: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
98
+ },
99
+ strict: true,
100
+ });
101
+ const mode = values.mode ?? env.GATE_MODE ?? 'writes';
102
+ if (!['writes', 'all', 'none'].includes(mode)) throw new Error('--mode must be writes, all or none');
103
+ const headerLines = values.header ?? (env.GATE_UPSTREAM_HEADERS ? env.GATE_UPSTREAM_HEADERS.split('\n') : []);
104
+ const headers = {};
105
+ for (const h of headerLines) {
106
+ const i = h.indexOf(':');
107
+ if (i < 1) throw new Error(`bad header "${h}", expected "Name: value"`);
108
+ // ${NAME} reads an environment variable, so tokens stay out of configs.
109
+ headers[h.slice(0, i).trim()] = h.slice(i + 1).trim().replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, k) => env[k] ?? '');
110
+ }
111
+ const num = (v, d, name, lo, hi) => {
112
+ if (v === undefined || v === '') return d;
113
+ const n = Number(v);
114
+ if (!Number.isInteger(n) || n < lo || n > hi) throw new Error(`${name} must be a whole number from ${lo} to ${hi}`);
115
+ return n;
116
+ };
117
+ const opts = {
118
+ help: values.help, version: values.version,
119
+ command,
120
+ upstreamUrl: values['upstream-url'] ?? env.GATE_UPSTREAM_URL,
121
+ headers,
122
+ label: values.label ?? env.GATE_LABEL,
123
+ mode,
124
+ allowTools: list(values.allow ?? env.GATE_ALLOW_TOOLS),
125
+ gateTools: list(values.gate ?? env.GATE_TOOLS),
126
+ pushInterests: list(values['push-interests'] ?? env.GATE_PUSH_INTERESTS),
127
+ pushUsers: list(values['push-users'] ?? env.GATE_PUSH_USERS),
128
+ channel: values.channel ?? env.GATE_CHANNEL,
129
+ options: list(values.options ?? env.GATE_OPTIONS),
130
+ waitSeconds: num(values.wait ?? env.GATE_WAIT_SECONDS, 50, '--wait', 0, 3600),
131
+ expiresMinutes: num(values.expires ?? env.GATE_EXPIRES_MINUTES, 60, '--expires', 1, 10080),
132
+ showLink: values['show-link'] ?? env.GATE_SHOW_LINK ?? 'auto',
133
+ http: values.http ?? false,
134
+ port: num(values.port ?? env.PORT, 8787, '--port', 1, 65535),
135
+ host: values.host ?? env.GATE_HOST ?? '127.0.0.1',
136
+ token: env.GATE_TOKEN,
137
+ };
138
+ if (!['auto', 'always', 'never'].includes(opts.showLink)) throw new Error('--show-link must be auto, always or never');
139
+ if (opts.pushInterests.length && opts.pushUsers.length) throw new Error('give --push-interests or --push-users, not both');
140
+ if (!opts.help && !opts.version && !opts.command.length && !opts.upstreamUrl) {
141
+ throw new Error('give the database MCP server to wrap after -- (or in GATE_COMMAND), or --upstream-url');
142
+ }
143
+ if (opts.command.length && opts.upstreamUrl) throw new Error('give a command after -- or --upstream-url, not both');
144
+ return opts;
145
+ }
146
+
147
+ /** The environment for the wrapped server: everything but the Hibira credentials. */
148
+ export function childEnv(env) {
149
+ return Object.fromEntries(Object.entries(env).filter(([k, v]) => v !== undefined && !k.startsWith('HIBIRA_') && k !== 'GATE_TOKEN'));
150
+ }
151
+
152
+ async function connectUpstream(opts) {
153
+ const client = new Client({ name: 'hibira-mcp-approval-gate', version: VERSION }, { capabilities: {} });
154
+ const transport = opts.upstreamUrl
155
+ ? new StreamableHTTPClientTransport(new URL(opts.upstreamUrl), { requestInit: { headers: opts.headers } })
156
+ : new StdioClientTransport({ command: opts.command[0], args: opts.command.slice(1), env: childEnv(process.env), stderr: 'inherit' });
157
+ await client.connect(transport);
158
+ return client;
159
+ }
160
+
161
+ function tokenOk(given, want) {
162
+ if (!given) return false;
163
+ const a = Buffer.from(given);
164
+ const b = Buffer.from(want);
165
+ return a.length === b.length && timingSafeEqual(a, b);
166
+ }
167
+
168
+ function serveHttp(gate, opts, log) {
169
+ const loopback = ['127.0.0.1', '::1', 'localhost'].includes(opts.host);
170
+ if (!opts.token && !loopback) fail('set GATE_TOKEN before serving HTTP on a non-local address');
171
+ const sessions = new Map();
172
+ const http = createHttpServer(async (req, res) => {
173
+ const url = new URL(req.url, 'http://localhost');
174
+ if (url.pathname === '/healthz') {
175
+ res.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
176
+ return;
177
+ }
178
+ const m = /^\/mcp(?:\/([^/]+))?\/?$/.exec(url.pathname);
179
+ if (!m) {
180
+ res.writeHead(404).end();
181
+ return;
182
+ }
183
+ if (opts.token) {
184
+ const bearer = /^Bearer (.+)$/i.exec(req.headers.authorization ?? '')?.[1];
185
+ if (!tokenOk(m[1] ?? bearer, opts.token)) {
186
+ res.writeHead(401, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'unauthorized' }));
187
+ return;
188
+ }
189
+ }
190
+ let body;
191
+ if (req.method === 'POST') {
192
+ const chunks = [];
193
+ for await (const c of req) chunks.push(c);
194
+ try {
195
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
196
+ } catch {
197
+ res.writeHead(400).end('bad JSON');
198
+ return;
199
+ }
200
+ }
201
+ const sid = req.headers['mcp-session-id'];
202
+ let transport = sid && sessions.get(sid);
203
+ if (!transport) {
204
+ if (req.method !== 'POST' || !isInitializeRequest(body)) {
205
+ res.writeHead(sid ? 404 : 400, { 'Content-Type': 'application/json' })
206
+ .end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: sid ? 'unknown session' : 'initialize first' }, id: null }));
207
+ return;
208
+ }
209
+ transport = new StreamableHTTPServerTransport({
210
+ sessionIdGenerator: () => randomUUID(),
211
+ onsessioninitialized: (id) => sessions.set(id, transport),
212
+ });
213
+ transport.onclose = () => transport.sessionId && sessions.delete(transport.sessionId);
214
+ await gate.createServer().connect(transport);
215
+ }
216
+ await transport.handleRequest(req, res, body);
217
+ });
218
+ http.listen(opts.port, opts.host, () => log(`serving MCP on http://${opts.host}:${opts.port}/mcp`));
219
+ return http;
220
+ }
221
+
222
+ export async function main() {
223
+ let opts;
224
+ try {
225
+ opts = parse(process.argv.slice(2), process.env);
226
+ } catch (err) {
227
+ fail(`${err.message}\n\n${HELP}`);
228
+ }
229
+ if (opts.help) {
230
+ process.stdout.write(HELP);
231
+ return;
232
+ }
233
+ if (opts.version) {
234
+ process.stdout.write(`${VERSION}\n`);
235
+ return;
236
+ }
237
+ const log = (msg) => process.stderr.write(`[approval-gate] ${msg}\n`);
238
+ let approvals;
239
+ try {
240
+ approvals = new ApprovalsClient({
241
+ appId: process.env.HIBIRA_APP_ID, key: process.env.HIBIRA_KEY, secret: process.env.HIBIRA_SECRET,
242
+ baseUrl: process.env.HIBIRA_API_URL || undefined,
243
+ });
244
+ } catch (err) {
245
+ fail(err.message);
246
+ }
247
+ let upstream;
248
+ try {
249
+ upstream = await connectUpstream(opts);
250
+ } catch (err) {
251
+ fail(`could not start the database MCP server: ${err.message}`);
252
+ }
253
+ const gate = new Gate({ ...opts, upstream, approvals, log });
254
+ if (opts.http) {
255
+ serveHttp(gate, opts, log);
256
+ } else {
257
+ const server = gate.createServer();
258
+ await server.connect(new StdioServerTransport());
259
+ process.stdin.on('end', () => stop());
260
+ }
261
+ async function stop() {
262
+ await upstream.close().catch(() => {});
263
+ process.exit(0);
264
+ }
265
+ process.on('SIGINT', stop);
266
+ process.on('SIGTERM', stop);
267
+ upstream.onclose = () => {
268
+ log('the database MCP server exited');
269
+ process.exit(1);
270
+ };
271
+ }
272
+
package/src/gate.js ADDED
@@ -0,0 +1,346 @@
1
+ // The proxy: one upstream MCP client, shared by every downstream session.
2
+ // Reads pass straight through. A call that changes something becomes a
3
+ // Hibira approval request; it is forwarded once, with exactly the arguments
4
+ // that were approved, after a supervisor approves it.
5
+
6
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
+ import {
8
+ CallToolRequestSchema,
9
+ ListToolsRequestSchema,
10
+ ListResourcesRequestSchema,
11
+ ListResourceTemplatesRequestSchema,
12
+ ReadResourceRequestSchema,
13
+ ListPromptsRequestSchema,
14
+ GetPromptRequestSchema,
15
+ ToolListChangedNotificationSchema,
16
+ } from '@modelcontextprotocol/sdk/types.js';
17
+ import { decide, fingerprint } from './policy.js';
18
+
19
+ export const VERSION = '0.2.0';
20
+ const DETAILS_MAX = 4000;
21
+
22
+ export class Gate {
23
+ /**
24
+ * @param {object} opts
25
+ * @param {import('@modelcontextprotocol/sdk/client/index.js').Client} opts.upstream connected client
26
+ * @param {import('./hibira.js').ApprovalsClient} opts.approvals
27
+ * @param {string} [opts.label] the database's name on the approval page
28
+ * @param {'writes'|'all'|'none'} [opts.mode]
29
+ * @param {string[]} [opts.allowTools]
30
+ * @param {string[]} [opts.gateTools]
31
+ * @param {number} [opts.waitSeconds] how long a call waits for the answer before it returns "pending"
32
+ * @param {number} [opts.expiresMinutes]
33
+ * @param {string[]} [opts.pushInterests]
34
+ * @param {string[]} [opts.pushUsers]
35
+ * @param {string} [opts.channel]
36
+ * @param {string[]} [opts.options]
37
+ * @param {number} [opts.upstreamTimeoutMs]
38
+ * @param {(msg: string) => void} [opts.log]
39
+ */
40
+ constructor(opts) {
41
+ this.upstream = opts.upstream;
42
+ this.approvals = opts.approvals;
43
+ this.label = opts.label || 'database';
44
+ this.mode = opts.mode ?? 'writes';
45
+ this.allowTools = opts.allowTools ?? [];
46
+ this.gateTools = opts.gateTools ?? [];
47
+ this.waitSeconds = opts.waitSeconds ?? 50;
48
+ this.expiresMinutes = opts.expiresMinutes ?? 60;
49
+ this.pushInterests = opts.pushInterests ?? [];
50
+ this.pushUsers = opts.pushUsers ?? [];
51
+ this.channel = opts.channel;
52
+ this.options = opts.options;
53
+ this.upstreamTimeoutMs = opts.upstreamTimeoutMs ?? 300_000;
54
+ this.showLink = opts.showLink ?? 'auto';
55
+ this.log = opts.log ?? (() => {});
56
+ /** fingerprint -> pending call */
57
+ this.pending = new Map();
58
+ /** approval id -> fingerprint */
59
+ this.byId = new Map();
60
+ this.tools = undefined;
61
+ this.servers = new Set();
62
+ this.checkTool = 'check_approval';
63
+ this.upstream.setNotificationHandler(ToolListChangedNotificationSchema, () => {
64
+ this.tools = undefined;
65
+ for (const s of this.servers) s.sendToolListChanged().catch(() => {});
66
+ });
67
+ }
68
+
69
+ /** A downstream MCP server for one client session. */
70
+ createServer() {
71
+ const caps = this.upstream.getServerCapabilities() ?? {};
72
+ const server = new Server(
73
+ { name: 'hibira-mcp-approval-gate', title: 'Approval gate', version: VERSION },
74
+ {
75
+ capabilities: {
76
+ tools: { listChanged: true },
77
+ logging: {},
78
+ ...(caps.resources ? { resources: {} } : {}),
79
+ ...(caps.prompts ? { prompts: {} } : {}),
80
+ },
81
+ instructions: this.#instructions(),
82
+ },
83
+ );
84
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await this.listTools() }));
85
+ server.setRequestHandler(CallToolRequestSchema, (req, extra) => this.callTool(req.params, extra, server));
86
+ if (caps.resources) {
87
+ server.setRequestHandler(ListResourcesRequestSchema, (req) => this.upstream.listResources(req.params));
88
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, (req) => this.upstream.listResourceTemplates(req.params));
89
+ server.setRequestHandler(ReadResourceRequestSchema, (req) => this.upstream.readResource(req.params));
90
+ }
91
+ if (caps.prompts) {
92
+ server.setRequestHandler(ListPromptsRequestSchema, (req) => this.upstream.listPrompts(req.params));
93
+ server.setRequestHandler(GetPromptRequestSchema, (req) => this.upstream.getPrompt(req.params));
94
+ }
95
+ this.servers.add(server);
96
+ server.onclose = () => this.servers.delete(server);
97
+ return server;
98
+ }
99
+
100
+ #instructions() {
101
+ const up = this.upstream.getInstructions?.();
102
+ const own = `Calls that change the ${this.label} (writes, schema changes, deletes) wait for a supervisor's approval before they run. ` +
103
+ `If a call answers that it is waiting, tell the person it waits for a supervisor (share the approval link only if the answer includes one), and call ${this.checkTool} with the approval_id when they say it is decided. ` +
104
+ 'Do not rewrite a declined statement to get around the decision.';
105
+ return up ? `${up}\n\n${own}` : own;
106
+ }
107
+
108
+ /** Upstream tools, plus the gate's own check tool. */
109
+ async listTools() {
110
+ if (!this.tools) {
111
+ const tools = [];
112
+ let cursor;
113
+ do {
114
+ const page = await this.upstream.listTools(cursor ? { cursor } : {});
115
+ tools.push(...page.tools);
116
+ cursor = page.nextCursor;
117
+ } while (cursor);
118
+ this.tools = tools;
119
+ if (tools.some((t) => t.name === this.checkTool)) this.checkTool = 'approval_gate_check';
120
+ }
121
+ return [...this.tools.map((t) => this.#describe(t)), this.#checkToolDef()];
122
+ }
123
+
124
+ #describe(tool) {
125
+ const d = decide({ name: tool.name, args: {}, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
126
+ const sqlTool = Object.keys(tool.inputSchema?.properties ?? {}).some((k) => ['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
127
+ let note;
128
+ if (sqlTool && this.mode === 'writes') note = 'Read-only SQL runs right away; statements that change data or schema wait for a supervisor\'s approval.';
129
+ else if (d.gate) note = 'Waits for a supervisor\'s approval before it runs.';
130
+ if (!note) return tool;
131
+ return { ...tool, description: tool.description ? `${tool.description}\n\n${note}` : note };
132
+ }
133
+
134
+ #checkToolDef() {
135
+ return {
136
+ name: this.checkTool,
137
+ title: 'Check approval',
138
+ description: 'Checks a call that is waiting for a supervisor\'s approval. If it was approved, runs it (once) and returns its result; if it was declined or expired, says so. Waits up to 25 seconds for an answer.',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: { approval_id: { type: 'string', description: 'The approval_id from the waiting answer (apr_...)' } },
142
+ required: ['approval_id'],
143
+ },
144
+ annotations: { title: 'Check approval', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
145
+ };
146
+ }
147
+
148
+ async #toolDef(name) {
149
+ if (!this.tools) await this.listTools();
150
+ return this.tools.find((t) => t.name === name);
151
+ }
152
+
153
+ /** Handles tools/call. */
154
+ async callTool(params, extra = {}, server) {
155
+ const { name, arguments: args = {} } = params;
156
+ if (name === this.checkTool) return this.#check(String(args.approval_id ?? ''), extra);
157
+ const tool = await this.#toolDef(name);
158
+ const d = decide({ name, args, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
159
+ if (!d.gate) return this.#forward(name, args, extra);
160
+
161
+ const fp = fingerprint(name, args);
162
+ let entry = this.pending.get(fp);
163
+ if (!entry) {
164
+ let created;
165
+ try {
166
+ created = await this.approvals.create(this.#approvalBody(name, args, d, fp));
167
+ } catch (err) {
168
+ this.log(`approval request failed: ${err.message}`);
169
+ return errorResult(`Could not ask for approval, so nothing ran: ${err.message}`);
170
+ }
171
+ entry = { id: created.approval_id, url: created.url, name, args, fp, expiresAt: created.expires_at, pushError: created.push_error };
172
+ entry.showLink = this.#linkVisible(entry);
173
+ this.pending.set(fp, entry);
174
+ this.byId.set(entry.id, fp);
175
+ this.log(`approval ${entry.id} requested for ${name} (${d.reason}): ${entry.url}`);
176
+ }
177
+ await notify(server, extra, entry.showLink ? `Waiting for supervisor approval: ${entry.url}` : 'Waiting for supervisor approval');
178
+ return this.#await(entry, this.waitSeconds, extra);
179
+ }
180
+
181
+ // The link goes back to the assistant only when nothing else delivers it:
182
+ // with push or a channel, the supervisor gets it and the requester never
183
+ // sees it, so they cannot approve their own change.
184
+ #linkVisible(entry) {
185
+ if (this.showLink === 'always') return true;
186
+ if (this.showLink === 'never') return false;
187
+ const pushed = (this.pushInterests.length || this.pushUsers.length) && !entry.pushError;
188
+ return !(pushed || this.channel);
189
+ }
190
+
191
+ #approvalBody(name, args, d, fp) {
192
+ const sql = d.sql;
193
+ const what = sql?.kinds?.length ? sql.kinds.join(', ') : name;
194
+ const title = truncate(`${what} on ${this.label}`, 200);
195
+ const lines = [];
196
+ lines.push(`Database: ${this.label}`);
197
+ lines.push(`Tool: ${name}`);
198
+ if (sql?.kinds?.length) lines.push(`Changes: ${sql.kinds.join(', ')}`);
199
+ for (const w of sql?.warnings ?? []) lines.push(`⚠ ${w}`);
200
+ lines.push('');
201
+ const body = sql ? sqlText(args) : JSON.stringify(args, null, 2);
202
+ const others = sql ? otherArgs(args) : '';
203
+ const footer = `\n\nFingerprint: ${fp.slice(0, 16)}\nOnly this exact call runs after approval.`;
204
+ let text = lines.join('\n') + body + (others ? `\n\nOther arguments:\n${others}` : '');
205
+ const room = DETAILS_MAX - footer.length;
206
+ if (text.length > room) text = text.slice(0, room - 40) + '\n… (truncated; see the request log)';
207
+ const out = {
208
+ title,
209
+ details: text + footer,
210
+ expires_in_minutes: this.expiresMinutes,
211
+ agent: truncate(`Approval gate · ${this.label}`, 60),
212
+ };
213
+ if (this.options?.length) out.options = this.options;
214
+ if (this.channel) out.channel = this.channel;
215
+ if (this.pushInterests.length) out.push_interests = this.pushInterests;
216
+ else if (this.pushUsers.length) out.push_users = this.pushUsers;
217
+ return out;
218
+ }
219
+
220
+ async #await(entry, seconds, extra) {
221
+ const deadline = Date.now() + seconds * 1000;
222
+ let progress = 0;
223
+ for (;;) {
224
+ if (extra.signal?.aborted) return pendingResult(entry, this.checkTool);
225
+ const left = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
226
+ let state;
227
+ try {
228
+ state = await this.approvals.get(entry.id, Math.min(25, left), extra.signal);
229
+ } catch (err) {
230
+ if (extra.signal?.aborted) return pendingResult(entry, this.checkTool);
231
+ if (err.status === 404) {
232
+ this.#forget(entry);
233
+ return errorResult(`Approval ${entry.id} is gone (it expired more than a day ago). Nothing ran.`);
234
+ }
235
+ this.log(`approval ${entry.id} status failed: ${err.message}`);
236
+ if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
237
+ await sleep(1000);
238
+ continue;
239
+ }
240
+ if (state.status === 'approved') return this.#run(entry, state, extra);
241
+ if (state.status === 'rejected' || state.status === 'expired') {
242
+ this.#forget(entry);
243
+ const how = state.status === 'expired' ? 'Nobody answered in time' : `The supervisor chose "${state.choice}"`;
244
+ return errorResult(`${how}, so the call did not run.${state.comment ? ` Comment: ${state.comment}` : ''} Do not retry it unless the person asks.`);
245
+ }
246
+ if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
247
+ if (extra._meta?.progressToken !== undefined && extra.sendNotification) {
248
+ progress += 1;
249
+ await extra.sendNotification({
250
+ method: 'notifications/progress',
251
+ params: { progressToken: extra._meta.progressToken, progress, message: 'Waiting for supervisor approval' },
252
+ }).catch(() => {});
253
+ }
254
+ }
255
+ }
256
+
257
+ async #check(id, extra) {
258
+ const fp = this.byId.get(id);
259
+ const entry = fp && this.pending.get(fp);
260
+ if (!entry) return errorResult(`No call is waiting on approval ${id || '(none given)'}: it already ran, was declined, or this gate restarted. Make the call again to ask for a new approval.`);
261
+ return this.#await(entry, 25, extra);
262
+ }
263
+
264
+ async #run(entry, state, extra) {
265
+ // An approval runs its call once, even if the call fails or two waits
266
+ // see the answer at the same time.
267
+ if (entry.ran) return errorResult(`Approval ${entry.id} was already used; the call ran once.`);
268
+ entry.ran = true;
269
+ this.#forget(entry);
270
+ this.log(`approval ${entry.id} approved (${state.choice}); running ${entry.name}`);
271
+ const result = await this.#forward(entry.name, entry.args, extra);
272
+ const note = { type: 'text', text: `Approved by a supervisor (${state.choice}${state.comment ? `: ${state.comment}` : ''}); ran once.` };
273
+ return { ...result, content: [...(result.content ?? []), note] };
274
+ }
275
+
276
+ #forget(entry) {
277
+ this.pending.delete(entry.fp);
278
+ this.byId.delete(entry.id);
279
+ }
280
+
281
+ async #forward(name, args, extra) {
282
+ try {
283
+ return await this.upstream.callTool({ name, arguments: args }, undefined, {
284
+ signal: extra.signal,
285
+ timeout: this.upstreamTimeoutMs,
286
+ ...(extra._meta?.progressToken !== undefined && extra.sendNotification ? {
287
+ onprogress: (p) => extra.sendNotification({ method: 'notifications/progress', params: { ...p, progressToken: extra._meta.progressToken } }).catch(() => {}),
288
+ resetTimeoutOnProgress: true,
289
+ } : {}),
290
+ });
291
+ } catch (err) {
292
+ return errorResult(`The database server failed: ${err.message}`);
293
+ }
294
+ }
295
+ }
296
+
297
+ function sqlText(args) {
298
+ const parts = [];
299
+ for (const [k, v] of Object.entries(args)) {
300
+ if (!['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase())) continue;
301
+ parts.push(Array.isArray(v) ? v.join(';\n') : String(v));
302
+ }
303
+ return parts.join('\n\n').trim();
304
+ }
305
+
306
+ function otherArgs(args) {
307
+ const rest = Object.entries(args).filter(([k]) => !['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
308
+ return rest.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`).join('\n');
309
+ }
310
+
311
+ function pendingResult(entry, checkTool) {
312
+ const text = entry.showLink ? [
313
+ 'Waiting for a supervisor to approve this call. Nothing has run yet.',
314
+ `Approval link: ${entry.url}`,
315
+ `approval_id: ${entry.id}`,
316
+ entry.pushError ? `(The push notification failed: ${entry.pushError}. Share the link instead.)` : '',
317
+ `Give the link to the person who approves. When they have decided, call ${checkTool} with this approval_id; it runs the call if it was approved.`,
318
+ ].filter(Boolean).join('\n') : [
319
+ 'A supervisor has been notified and must approve this call. Nothing has run yet.',
320
+ `approval_id: ${entry.id}`,
321
+ `When the person says it is decided, call ${checkTool} with this approval_id; it runs the call if it was approved.`,
322
+ ].join('\n');
323
+ const meta = { approval_id: entry.id, status: 'pending', ...(entry.showLink ? { url: entry.url } : {}) };
324
+ return { content: [{ type: 'text', text }], _meta: { 'io.hibira/approval': meta } };
325
+ }
326
+
327
+ function errorResult(text) {
328
+ return { content: [{ type: 'text', text }], isError: true };
329
+ }
330
+
331
+ async function notify(server, extra, data) {
332
+ if (!server) return;
333
+ try {
334
+ await server.sendLoggingMessage({ level: 'notice', logger: 'approval-gate', data }, extra.sessionId);
335
+ } catch {
336
+ // Clients that did not ask for logging ignore it.
337
+ }
338
+ }
339
+
340
+ function truncate(s, n) {
341
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
342
+ }
343
+
344
+ function sleep(ms) {
345
+ return new Promise((r) => setTimeout(r, ms));
346
+ }
package/src/hibira.js ADDED
@@ -0,0 +1,54 @@
1
+ // A small client for the Hibira approvals HTTP API, signed with the app's
2
+ // key and secret like the Pusher HTTP API.
3
+
4
+ import { createHash, createHmac } from 'node:crypto';
5
+
6
+ export class ApprovalsClient {
7
+ /**
8
+ * @param {{ appId: string, key: string, secret: string, baseUrl?: string, fetch?: typeof fetch }} opts
9
+ */
10
+ constructor({ appId, key, secret, baseUrl = 'https://ws.hibira.io', fetch: f = globalThis.fetch }) {
11
+ if (!appId || !key || !secret) throw new Error('HIBIRA_APP_ID, HIBIRA_KEY and HIBIRA_SECRET are required');
12
+ this.appId = appId;
13
+ this.key = key;
14
+ this.secret = secret;
15
+ this.baseUrl = baseUrl.replace(/\/$/, '');
16
+ this.fetch = f;
17
+ }
18
+
19
+ /** Creates an approval request. Returns the API's answer (approval_id, url, status...). */
20
+ create(body) {
21
+ return this.#request('POST', `/apps/${encodeURIComponent(this.appId)}/approvals`, {}, body);
22
+ }
23
+
24
+ /** Reads one request, waiting up to waitSeconds (0-25) for an answer. */
25
+ get(id, waitSeconds = 0, signal) {
26
+ const qs = waitSeconds > 0 ? { wait: String(Math.min(25, Math.floor(waitSeconds))) } : {};
27
+ return this.#request('GET', `/apps/${encodeURIComponent(this.appId)}/approvals/${encodeURIComponent(id)}`, qs, undefined, signal);
28
+ }
29
+
30
+ async #request(method, path, query, body, signal) {
31
+ const qs = { ...query, auth_key: this.key, auth_timestamp: String(Math.floor(Date.now() / 1000)), auth_version: '1.0' };
32
+ const data = body === undefined ? undefined : JSON.stringify(body);
33
+ if (data !== undefined) qs.body_md5 = createHash('md5').update(data).digest('hex');
34
+ const canonical = Object.keys(qs).sort().map((k) => `${k}=${qs[k]}`).join('&');
35
+ qs.auth_signature = createHmac('sha256', this.secret).update(`${method}\n${new URL(this.baseUrl + path).pathname}\n${canonical}`).digest('hex');
36
+ const url = `${this.baseUrl}${path}?${new URLSearchParams(qs)}`;
37
+ const res = await this.fetch(url, {
38
+ method,
39
+ headers: data === undefined ? {} : { 'Content-Type': 'application/json' },
40
+ body: data,
41
+ signal,
42
+ });
43
+ const text = await res.text();
44
+ let json;
45
+ try { json = JSON.parse(text); } catch { json = undefined; }
46
+ if (!res.ok) {
47
+ const msg = json?.error ?? json?.message ?? text.slice(0, 200);
48
+ const err = new Error(`Hibira approvals API ${res.status}: ${msg}`);
49
+ err.status = res.status;
50
+ throw err;
51
+ }
52
+ return json;
53
+ }
54
+ }
package/src/policy.js ADDED
@@ -0,0 +1,60 @@
1
+ // Decides which tool calls wait for approval.
2
+
3
+ import { createHash } from 'node:crypto';
4
+ import { classifySql } from './sql.js';
5
+
6
+ // Argument names that carry SQL in the database MCP servers we wrap
7
+ // (DBHub and postgres-mcp: sql; Supabase: query).
8
+ const SQL_KEYS = new Set(['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script']);
9
+ // Tool name prefixes that only read.
10
+ const READ_VERBS = /^(list|get|search|describe|explain|analyze|analyse|show|read|fetch|find|inspect|count|lookup|preview|generate|confirm|check|health|ping|whoami)(_|-|$)/i;
11
+
12
+ /**
13
+ * Picks the SQL strings out of a tool call's arguments: top-level string
14
+ * (or array of strings) values under a known SQL key.
15
+ */
16
+ export function sqlArguments(args) {
17
+ if (!args || typeof args !== 'object') return [];
18
+ const out = [];
19
+ for (const [k, v] of Object.entries(args)) {
20
+ if (!SQL_KEYS.has(k.toLowerCase())) continue;
21
+ if (typeof v === 'string') out.push(v);
22
+ else if (Array.isArray(v)) out.push(...v.filter((x) => typeof x === 'string'));
23
+ }
24
+ return out;
25
+ }
26
+
27
+ function matches(list, name) {
28
+ return list.some((p) => (p.endsWith('*') ? name.startsWith(p.slice(0, -1)) : p === name));
29
+ }
30
+
31
+ /**
32
+ * Decides one call. tool is the upstream tool definition (for its
33
+ * annotations), or undefined if unknown. Returns { gate, reason, sql }
34
+ * where sql is the classification when the call carries SQL.
35
+ */
36
+ export function decide({ name, args, tool, mode = 'writes', allowTools = [], gateTools = [] }) {
37
+ if (matches(gateTools, name)) return { gate: true, reason: 'tool is always gated' };
38
+ if (matches(allowTools, name)) return { gate: false, reason: 'tool is always allowed' };
39
+ const sqls = sqlArguments(args);
40
+ const sql = sqls.length ? classifySql(sqls.join(';\n')) : undefined;
41
+ if (mode === 'all') return { gate: true, reason: 'every call is gated', sql };
42
+ if (mode === 'none') return { gate: false, reason: 'gating is off', sql };
43
+ if (sql) return { gate: sql.write, reason: sql.write ? 'SQL changes data or schema' : 'read-only SQL', sql };
44
+ if (tool?.annotations?.readOnlyHint === true) return { gate: false, reason: 'tool is marked read-only' };
45
+ if (READ_VERBS.test(name)) return { gate: false, reason: 'tool name reads' };
46
+ return { gate: true, reason: 'tool may change something' };
47
+ }
48
+
49
+ /** A stable fingerprint of one call: sha256 of tool name and canonical args. */
50
+ export function fingerprint(name, args) {
51
+ return createHash('sha256').update(JSON.stringify([name, canonical(args ?? {})])).digest('hex');
52
+ }
53
+
54
+ function canonical(v) {
55
+ if (Array.isArray(v)) return v.map(canonical);
56
+ if (v && typeof v === 'object') {
57
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical(v[k])]));
58
+ }
59
+ return v;
60
+ }
package/src/sql.js ADDED
@@ -0,0 +1,176 @@
1
+ // Tells read-only SQL from SQL that changes something. It is deliberately
2
+ // conservative: anything it does not recognise as a read counts as a write,
3
+ // so an unusual statement waits for approval instead of slipping through.
4
+
5
+ const READ_START = new Set(['SELECT', 'SHOW', 'DESCRIBE', 'DESC', 'VALUES', 'TABLE', 'WITH', 'EXPLAIN', 'PRAGMA', 'USE']);
6
+ const TX_CONTROL = new Set(['BEGIN', 'START', 'COMMIT', 'END', 'ROLLBACK', 'SAVEPOINT', 'RELEASE']);
7
+ const WRITE_WORDS = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE', 'UPSERT', 'REPLACE', 'TRUNCATE', 'DROP', 'ALTER', 'CREATE', 'GRANT', 'REVOKE', 'COPY', 'CALL', 'EXEC', 'EXECUTE', 'DO']);
8
+ // Functions that change state even inside a SELECT.
9
+ const WRITE_FUNCTIONS = new Set([
10
+ 'NEXTVAL', 'SETVAL', 'SET_CONFIG', 'PG_TERMINATE_BACKEND', 'PG_CANCEL_BACKEND', 'PG_RELOAD_CONF',
11
+ 'PG_ROTATE_LOGFILE', 'PG_ADVISORY_LOCK', 'PG_ADVISORY_XACT_LOCK', 'LO_IMPORT', 'LO_EXPORT', 'LO_UNLINK',
12
+ 'LO_CREATE', 'LO_FROM_BYTEA', 'LO_PUT', 'DBLINK_EXEC', 'DBLINK', 'PG_FILE_WRITE', 'PG_CREATE_RESTORE_POINT',
13
+ 'PG_SWITCH_WAL', 'PG_PROMOTE', 'PG_CREATE_LOGICAL_REPLICATION_SLOT', 'PG_CREATE_PHYSICAL_REPLICATION_SLOT',
14
+ 'PG_DROP_REPLICATION_SLOT', 'SLEEP', 'BENCHMARK', 'GET_LOCK', 'LOAD_FILE', 'LOAD_EXTENSION', 'XP_CMDSHELL',
15
+ ]);
16
+
17
+ /**
18
+ * Splits sql into statements of tokens. Comments are dropped; string
19
+ * literals and quoted identifiers become one opaque token each, so a keyword
20
+ * inside them never counts. Throws on an unterminated quote or comment.
21
+ */
22
+ export function tokenize(sql) {
23
+ const statements = [];
24
+ let tokens = [];
25
+ const n = sql.length;
26
+ let i = 0;
27
+ const push = (t) => tokens.push(t);
28
+ while (i < n) {
29
+ const c = sql[i];
30
+ const next = sql[i + 1];
31
+ if (c === '-' && next === '-') {
32
+ const end = sql.indexOf('\n', i);
33
+ i = end === -1 ? n : end + 1;
34
+ } else if (c === '#' && (i === 0 || /\s/.test(sql[i - 1]))) {
35
+ // MySQL line comment.
36
+ const end = sql.indexOf('\n', i);
37
+ i = end === -1 ? n : end + 1;
38
+ } else if (c === '/' && next === '*') {
39
+ let depth = 1;
40
+ i += 2;
41
+ while (i < n && depth > 0) {
42
+ if (sql[i] === '/' && sql[i + 1] === '*') { depth++; i += 2; }
43
+ else if (sql[i] === '*' && sql[i + 1] === '/') { depth--; i += 2; }
44
+ else i++;
45
+ }
46
+ if (depth > 0) throw new Error('unterminated comment');
47
+ } else if (c === "'" || c === '"' || c === '`') {
48
+ const backslash = c === "'" && i > 0 && /[eE]/.test(sql[i - 1]) && !/\w/.test(sql[i - 2] ?? '');
49
+ i++;
50
+ let closed = false;
51
+ while (i < n) {
52
+ if (backslash && sql[i] === '\\') { i += 2; continue; }
53
+ if (sql[i] === c) {
54
+ if (sql[i + 1] === c) { i += 2; continue; }
55
+ i++;
56
+ closed = true;
57
+ break;
58
+ }
59
+ i++;
60
+ }
61
+ if (!closed) throw new Error('unterminated quote');
62
+ push(c === "'" ? { type: 'string' } : { type: 'ident', value: '' });
63
+ } else if (c === '[' ) {
64
+ // SQL Server bracketed identifier.
65
+ const end = sql.indexOf(']', i);
66
+ if (end === -1) throw new Error('unterminated identifier');
67
+ i = end + 1;
68
+ push({ type: 'ident', value: '' });
69
+ } else if (c === '$' && /[A-Za-z_$]/.test(next ?? '')) {
70
+ const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
71
+ if (m) {
72
+ const tag = m[0];
73
+ const end = sql.indexOf(tag, i + tag.length);
74
+ if (end === -1) throw new Error('unterminated dollar quote');
75
+ i = end + tag.length;
76
+ push({ type: 'string' });
77
+ } else {
78
+ i++;
79
+ }
80
+ } else if (c === ';') {
81
+ if (tokens.length) statements.push(tokens);
82
+ tokens = [];
83
+ i++;
84
+ } else if (/[A-Za-z_]/.test(c)) {
85
+ let j = i + 1;
86
+ while (j < n && /[A-Za-z0-9_$]/.test(sql[j])) j++;
87
+ push({ type: 'word', value: sql.slice(i, j).toUpperCase() });
88
+ i = j;
89
+ } else if (/\s/.test(c)) {
90
+ i++;
91
+ } else {
92
+ push({ type: 'punct', value: c });
93
+ i++;
94
+ }
95
+ }
96
+ if (tokens.length) statements.push(tokens);
97
+ return statements;
98
+ }
99
+
100
+ function words(tokens) {
101
+ return tokens.filter((t) => t.type === 'word').map((t) => t.value);
102
+ }
103
+
104
+ function callsWriteFunction(tokens) {
105
+ return tokens.some((t, k) => t.type === 'word' && WRITE_FUNCTIONS.has(t.value) && tokens[k + 1]?.value === '(');
106
+ }
107
+
108
+ function statementKind(ws) {
109
+ const first = ws[0];
110
+ if (['CREATE', 'DROP', 'ALTER'].includes(first)) {
111
+ const obj = ws.slice(1).find((w) => !['OR', 'REPLACE', 'TEMP', 'TEMPORARY', 'UNIQUE', 'IF', 'NOT', 'EXISTS', 'GLOBAL', 'LOCAL', 'UNLOGGED', 'MATERIALIZED', 'CONCURRENTLY'].includes(w));
112
+ return obj ? `${first} ${obj}` : first;
113
+ }
114
+ return first;
115
+ }
116
+
117
+ /** Classifies one statement's tokens: { kind, write, warnings }. */
118
+ function classifyStatement(tokens) {
119
+ const ws = words(tokens);
120
+ const first = ws[0];
121
+ const warnings = [];
122
+ if (!first) return { kind: 'UNKNOWN', write: true, warnings };
123
+ if (TX_CONTROL.has(first)) return { kind: first, write: false, warnings };
124
+ if (READ_START.has(first)) {
125
+ let write = false;
126
+ if (first === 'EXPLAIN') {
127
+ // EXPLAIN ANALYZE runs the statement it explains.
128
+ const analyze = ws.includes('ANALYZE') || ws.includes('ANALYSE');
129
+ if (analyze) {
130
+ const innerAt = tokens.findIndex((t) => t.type === 'word' && (WRITE_WORDS.has(t.value) || READ_START.has(t.value)) && t.value !== 'EXPLAIN');
131
+ if (innerAt !== -1) {
132
+ const inner = classifyStatement(tokens.slice(innerAt));
133
+ return { kind: inner.write ? `EXPLAIN ANALYZE ${inner.kind}` : 'EXPLAIN', write: inner.write, warnings: inner.warnings };
134
+ }
135
+ }
136
+ return { kind: 'EXPLAIN', write: false, warnings };
137
+ }
138
+ if (first === 'PRAGMA') write = tokens.some((t) => t.value === '=');
139
+ if (first === 'WITH') {
140
+ const inner = ws.find((w) => ['INSERT', 'UPDATE', 'DELETE', 'MERGE', 'TRUNCATE'].includes(w));
141
+ if (inner) return { kind: `WITH … ${inner}`, write: true, warnings };
142
+ }
143
+ if (first === 'SELECT' || first === 'WITH') {
144
+ if (ws.includes('INTO')) return { kind: 'SELECT INTO', write: true, warnings };
145
+ }
146
+ if (callsWriteFunction(tokens)) return { kind: `${first} (side-effect function)`, write: true, warnings };
147
+ return { kind: first, write, warnings };
148
+ }
149
+ const kind = statementKind(ws);
150
+ if ((first === 'UPDATE' || first === 'DELETE') && !ws.includes('WHERE')) {
151
+ warnings.push(`${first} without WHERE changes every row of the table`);
152
+ }
153
+ if (first === 'DROP' || first === 'TRUNCATE') warnings.push(`${kind} cannot be undone`);
154
+ return { kind, write: true, warnings };
155
+ }
156
+
157
+ /**
158
+ * Classifies sql. Returns { write, statements: [{ kind, write }], kinds,
159
+ * warnings }. Unparseable SQL is a write.
160
+ */
161
+ export function classifySql(sql) {
162
+ let statements;
163
+ try {
164
+ statements = tokenize(String(sql ?? ''));
165
+ } catch (err) {
166
+ return { write: true, statements: [], kinds: ['UNPARSEABLE'], warnings: [`could not read the SQL (${err.message})`] };
167
+ }
168
+ const classified = statements.map(classifyStatement);
169
+ const kinds = [...new Set(classified.filter((s) => s.write).map((s) => s.kind))];
170
+ return {
171
+ write: classified.some((s) => s.write),
172
+ statements: classified.map(({ kind, write }) => ({ kind, write })),
173
+ kinds,
174
+ warnings: [...new Set(classified.flatMap((s) => s.warnings))],
175
+ };
176
+ }