@hibira-io/mcp-approval-gate 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/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/bin.js +4 -0
- package/package.json +64 -4
- package/src/cli.js +268 -0
- package/src/gate.js +329 -0
- package/src/hibira.js +54 -0
- package/src/policy.js +60 -0
- package/src/sql.js +176 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
- First release: an MCP proxy that puts supervisor approval in front of any
|
|
6
|
+
database MCP server. Reads pass through; writes, schema changes and other
|
|
7
|
+
changing tools wait for approval on a Hibira-hosted page (with push), then
|
|
8
|
+
run once with exactly the approved arguments.
|
|
9
|
+
- SQL classifier (Postgres, MySQL, SQLite, SQL Server dialects) that skips
|
|
10
|
+
comments, strings and dollar quotes and fails closed.
|
|
11
|
+
- `check_approval` tool for answers that take longer than the client waits.
|
|
12
|
+
- stdio and Streamable HTTP (with `GATE_TOKEN`) downstream; stdio command or
|
|
13
|
+
Streamable HTTP URL upstream.
|
|
14
|
+
- 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,246 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Approval gate for database MCP servers
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+

|
|
10
|
+
|
|
11
|
+
<sub>A real session: Claude Code asks to mark order 1042 as refunded through DBHub. The `UPDATE` waits, the supervisor approves it on the Hibira page, 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/approval-page.png" width="260" alt="The approval page on a phone: UPDATE on shop-production, with the statement, fingerprint and Approve / Reject buttons">
|
|
52
|
+
<img src="https://raw.githubusercontent.com/hibira-io/mcp-approval-gate/main/docs/approval-approved.png" width="260" alt="The same request after the supervisor approved it">
|
|
53
|
+
</p>
|
|
54
|
+
|
|
55
|
+
## Setup
|
|
56
|
+
|
|
57
|
+
1. Sign in at [hibira.io](https://hibira.io), create an app (Free works), and
|
|
58
|
+
copy its **App ID, Key and Secret**.
|
|
59
|
+
2. Optional: turn on Push for the app and subscribe the supervisors' devices to
|
|
60
|
+
an interest such as `db-approvals`, so requests reach their phones. Without
|
|
61
|
+
push, the assistant shows the approval link and you share it.
|
|
62
|
+
3. Put the gate in front of your database MCP server in your client's config
|
|
63
|
+
(below). Everything after `--` is the database server's usual command.
|
|
64
|
+
|
|
65
|
+
The Hibira credentials are read from the environment only, and they are not
|
|
66
|
+
passed on to the database server.
|
|
67
|
+
|
|
68
|
+
### Claude Code
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
claude mcp add shop-db \
|
|
72
|
+
-e HIBIRA_APP_ID=app_... -e HIBIRA_KEY=... -e HIBIRA_SECRET=... \
|
|
73
|
+
-e GATE_LABEL=shop-production -e GATE_PUSH_INTERESTS=db-approvals \
|
|
74
|
+
-- npx -y @hibira-io/mcp-approval-gate \
|
|
75
|
+
-- npx -y @bytebase/dbhub --transport stdio --dsn "postgres://user:pass@host:5432/shop"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Claude Desktop, Cursor, Windsurf, VS Code
|
|
79
|
+
|
|
80
|
+
`claude_desktop_config.json`, `.cursor/mcp.json` and the others take the same
|
|
81
|
+
shape:
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"mcpServers": {
|
|
86
|
+
"shop-db": {
|
|
87
|
+
"command": "npx",
|
|
88
|
+
"args": [
|
|
89
|
+
"-y", "@hibira-io/mcp-approval-gate",
|
|
90
|
+
"--label", "shop-production",
|
|
91
|
+
"--push-interests", "db-approvals",
|
|
92
|
+
"--",
|
|
93
|
+
"npx", "-y", "@bytebase/dbhub", "--transport", "stdio",
|
|
94
|
+
"--dsn", "postgres://user:pass@host:5432/shop"
|
|
95
|
+
],
|
|
96
|
+
"env": {
|
|
97
|
+
"HIBIRA_APP_ID": "app_...",
|
|
98
|
+
"HIBIRA_KEY": "...",
|
|
99
|
+
"HIBIRA_SECRET": "..."
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**postgres-mcp:**
|
|
107
|
+
|
|
108
|
+
```json
|
|
109
|
+
"args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "analytics", "--",
|
|
110
|
+
"uvx", "postgres-mcp", "--access-mode=unrestricted"],
|
|
111
|
+
"env": { "DATABASE_URI": "postgresql://...", "HIBIRA_APP_ID": "...", "HIBIRA_KEY": "...", "HIBIRA_SECRET": "..." }
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`--access-mode=unrestricted` is fine here: the gate is what holds writes back.
|
|
115
|
+
|
|
116
|
+
**Supabase (local server):**
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
"args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "supabase-prod", "--",
|
|
120
|
+
"npx", "-y", "@supabase/mcp-server-supabase@latest", "--project-ref=<project-ref>"],
|
|
121
|
+
"env": { "SUPABASE_ACCESS_TOKEN": "sbp_...", "HIBIRA_APP_ID": "...", "HIBIRA_KEY": "...", "HIBIRA_SECRET": "..." }
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`execute_sql` with a `SELECT` runs right away; writes, `apply_migration`,
|
|
125
|
+
`deploy_edge_function`, branch merges and project pauses wait for approval.
|
|
126
|
+
|
|
127
|
+
**Supabase (hosted server):**
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
"args": ["-y", "@hibira-io/mcp-approval-gate", "--label", "supabase-prod",
|
|
131
|
+
"--upstream-url", "https://mcp.supabase.com/mcp?project_ref=<project-ref>",
|
|
132
|
+
"--header", "Authorization: Bearer ${SUPABASE_ACCESS_TOKEN}"],
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### ChatGPT and claude.ai (remote)
|
|
136
|
+
|
|
137
|
+
Web clients need an HTTPS URL, so run the gate as a small server next to your
|
|
138
|
+
database and put HTTPS in front of it (your reverse proxy, a tunnel, or a
|
|
139
|
+
platform such as Fly.io or Railway):
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
export HIBIRA_APP_ID=app_... HIBIRA_KEY=... HIBIRA_SECRET=...
|
|
143
|
+
export GATE_TOKEN="$(openssl rand -hex 24)" # keep it secret
|
|
144
|
+
npx -y @hibira-io/mcp-approval-gate --http --host 0.0.0.0 --port 8787 \
|
|
145
|
+
--label shop-production --push-interests db-approvals \
|
|
146
|
+
-- npx -y @bytebase/dbhub --transport stdio --dsn "$DATABASE_URL"
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
The endpoint is `https://your-host/mcp/<GATE_TOKEN>`; clients that can send
|
|
150
|
+
headers may use `https://your-host/mcp` with `Authorization: Bearer <GATE_TOKEN>`.
|
|
151
|
+
|
|
152
|
+
- **ChatGPT:** Settings → Apps & Connectors → Advanced → Developer mode, then
|
|
153
|
+
Create: paste the URL with the token, authentication "No authentication".
|
|
154
|
+
- **claude.ai:** Settings → Connectors → Add custom connector, paste the URL
|
|
155
|
+
with the token.
|
|
156
|
+
|
|
157
|
+
The gate refuses to listen on a non-local address without `GATE_TOKEN`.
|
|
158
|
+
A [Dockerfile](Dockerfile) is included.
|
|
159
|
+
|
|
160
|
+
## What the assistant sees
|
|
161
|
+
|
|
162
|
+
A write call waits up to 50 seconds (`--wait`) for the decision, sending
|
|
163
|
+
progress updates so the client does not give up early:
|
|
164
|
+
|
|
165
|
+
- **Approved:** the call runs and its normal result comes back, with a line
|
|
166
|
+
saying it was approved.
|
|
167
|
+
- **Rejected or expired:** an error saying it did not run, with the
|
|
168
|
+
supervisor's comment if they left one.
|
|
169
|
+
- **Still waiting:** a short answer with the approval link and `approval_id`.
|
|
170
|
+
The gate adds one tool, `check_approval`: when the person says it is
|
|
171
|
+
decided, the assistant calls it with that `approval_id`, and the call runs if
|
|
172
|
+
it was approved. Asking for the same call again reuses the same request.
|
|
173
|
+
|
|
174
|
+
## What waits for approval
|
|
175
|
+
|
|
176
|
+
With the default `--mode writes`:
|
|
177
|
+
|
|
178
|
+
1. Tools listed in `--gate` always wait; tools in `--allow` never do (a
|
|
179
|
+
trailing `*` matches a prefix).
|
|
180
|
+
2. Calls with SQL (an argument named `sql`, `query`, `statement`, `queries`,
|
|
181
|
+
...) wait if any statement changes something: `INSERT`, `UPDATE`,
|
|
182
|
+
`DELETE`, `MERGE`, `CREATE`, `ALTER`, `DROP`, `TRUNCATE`, `GRANT`, `COPY`,
|
|
183
|
+
`CALL`, `DO`, `SET`, `VACUUM`, data-changing `WITH`, `SELECT ... INTO`,
|
|
184
|
+
`EXPLAIN ANALYZE` of a write, `SELECT` of functions such as `setval` or
|
|
185
|
+
`pg_terminate_backend`, and anything it cannot parse. Comments, strings and
|
|
186
|
+
dollar-quoted bodies are skipped, so `SELECT 'DROP TABLE x'` is a read.
|
|
187
|
+
3. Other tools pass if they are marked `readOnlyHint` or named like a read
|
|
188
|
+
(`list_`, `get_`, `search_`, `describe_`, `explain_`, `analyze_`, ...).
|
|
189
|
+
Everything else waits.
|
|
190
|
+
|
|
191
|
+
`--mode all` sends every call for approval, reads included. `--mode none` turns
|
|
192
|
+
the gate off (useful while testing).
|
|
193
|
+
|
|
194
|
+
The gate is a second pair of eyes, not a permission system. Give the database
|
|
195
|
+
user only the rights it needs too.
|
|
196
|
+
|
|
197
|
+
## Options
|
|
198
|
+
|
|
199
|
+
| Flag | Env | Default | |
|
|
200
|
+
| --- | --- | --- | --- |
|
|
201
|
+
| | `HIBIRA_APP_ID`, `HIBIRA_KEY`, `HIBIRA_SECRET` | required | your Hibira app |
|
|
202
|
+
| | `HIBIRA_API_URL` | `https://ws.hibira.io` | |
|
|
203
|
+
| `--label` | `GATE_LABEL` | `database` | the database's name on the approval page |
|
|
204
|
+
| `--mode` | `GATE_MODE` | `writes` | `writes`, `all` or `none` |
|
|
205
|
+
| `--allow` | `GATE_ALLOW_TOOLS` | | tools that never wait |
|
|
206
|
+
| `--gate` | `GATE_TOOLS` | | tools that always wait |
|
|
207
|
+
| `--push-interests` | `GATE_PUSH_INTERESTS` | | push the request to these interests |
|
|
208
|
+
| `--push-users` | `GATE_PUSH_USERS` | | ...or to these user ids |
|
|
209
|
+
| `--channel` | `GATE_CHANNEL` | | also announce requests on this channel, e.g. for an [approvals inbox](https://github.com/hibira-io/approvals) |
|
|
210
|
+
| `--options` | `GATE_OPTIONS` | `Approve,Reject` | answer buttons; the first one approves |
|
|
211
|
+
| `--wait` | `GATE_WAIT_SECONDS` | `50` | how long a call waits before answering "still waiting" |
|
|
212
|
+
| `--expires` | `GATE_EXPIRES_MINUTES` | `60` | how long a request stays open (up to 7 days) |
|
|
213
|
+
| `-- <command>` | `GATE_COMMAND` | | the database MCP server to start |
|
|
214
|
+
| `--upstream-url` | `GATE_UPSTREAM_URL` | | ...or a remote one (Streamable HTTP) |
|
|
215
|
+
| `--header` | `GATE_UPSTREAM_HEADERS` | | headers for the remote server; `${VAR}` reads the environment |
|
|
216
|
+
| `--http` | | off | serve Streamable HTTP instead of stdio |
|
|
217
|
+
| `--host`, `--port` | `GATE_HOST`, `PORT` | `127.0.0.1`, `8787` | |
|
|
218
|
+
| | `GATE_TOKEN` | | required for `--http` on a non-local address |
|
|
219
|
+
|
|
220
|
+
Pending calls live in the gate's memory. If the gate restarts, a waiting call
|
|
221
|
+
is forgotten (nothing runs) and the assistant simply asks again.
|
|
222
|
+
|
|
223
|
+
## Development
|
|
224
|
+
|
|
225
|
+
```sh
|
|
226
|
+
npm install
|
|
227
|
+
npm test
|
|
228
|
+
# against real servers and a local Postgres:
|
|
229
|
+
DATABASE_URL=postgres://... node --test test/real-servers.e2e.js
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
MIT
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
## 中文摘要
|
|
239
|
+
|
|
240
|
+
`@hibira-io/mcp-approval-gate` 套在任何数据库 MCP server(DBHub、postgres-mcp、Supabase MCP 等)外面:**读取直接通过;写入、改表、删除会先停下,等另一个人(主管)在 Hibira 托管的审批页或手机推播上核准**,核准后只按原样执行一次。
|
|
241
|
+
|
|
242
|
+
- 审批绑定这一次调用的完整参数(附指纹),SQL 改了就要重新审批。
|
|
243
|
+
- 看不懂的 SQL、不确定是否只读的工具一律要审批;审批服务连不上就不执行。
|
|
244
|
+
- Gate 跑在你自己的环境,Hibira 只经手审批内容,不碰数据库密码,也看不到查询结果。
|
|
245
|
+
- Claude(Desktop / Code / claude.ai)、Cursor、ChatGPT 都能用;网页端用 `--http` 加 `GATE_TOKEN`。
|
|
246
|
+
- 设定:在 hibira.io 建 app,把 App ID / Key / Secret 放进环境变量,在 `--` 后面接原本的数据库 MCP 指令。
|
package/bin.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hibira-io/mcp-approval-gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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,268 @@
|
|
|
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
|
+
--wait <seconds> how long a call waits before answering "pending" (default 50) [GATE_WAIT_SECONDS]
|
|
38
|
+
--expires <minutes> how long a request stays open (default 60) [GATE_EXPIRES_MINUTES]
|
|
39
|
+
--upstream-url <url> remote MCP server to wrap [GATE_UPSTREAM_URL]
|
|
40
|
+
--header "Name: value" header for the remote server, repeatable; \${VAR} reads the environment [GATE_UPSTREAM_HEADERS, one per line]
|
|
41
|
+
--http serve Streamable HTTP instead of stdio (for ChatGPT and remote clients)
|
|
42
|
+
--port <n> HTTP port (default 8787) [PORT]
|
|
43
|
+
--host <addr> HTTP bind address (default 127.0.0.1) [GATE_HOST]
|
|
44
|
+
GATE_TOKEN HTTP access token: Authorization: Bearer <token>, or the URL /mcp/<token>
|
|
45
|
+
--version, --help
|
|
46
|
+
`;
|
|
47
|
+
|
|
48
|
+
function list(v) {
|
|
49
|
+
return (v ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Splits a command line on spaces, honouring '...' and "..." quotes (no shell). */
|
|
53
|
+
export function splitCommand(line) {
|
|
54
|
+
const out = [];
|
|
55
|
+
let cur = '';
|
|
56
|
+
let quote = '';
|
|
57
|
+
let has = false;
|
|
58
|
+
for (const ch of line) {
|
|
59
|
+
if (quote) {
|
|
60
|
+
if (ch === quote) quote = '';
|
|
61
|
+
else cur += ch;
|
|
62
|
+
} else if (ch === '"' || ch === "'") {
|
|
63
|
+
quote = ch;
|
|
64
|
+
has = true;
|
|
65
|
+
} else if (/\s/.test(ch)) {
|
|
66
|
+
if (has || cur) out.push(cur);
|
|
67
|
+
cur = '';
|
|
68
|
+
has = false;
|
|
69
|
+
} else {
|
|
70
|
+
cur += ch;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (quote) throw new Error('GATE_COMMAND has an unclosed quote');
|
|
74
|
+
if (has || cur) out.push(cur);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function fail(msg) {
|
|
79
|
+
process.stderr.write(`mcp-approval-gate: ${msg}\n`);
|
|
80
|
+
process.exit(2);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function parse(argv, env) {
|
|
84
|
+
const dash = argv.indexOf('--');
|
|
85
|
+
const own = dash === -1 ? argv : argv.slice(0, dash);
|
|
86
|
+
const command = dash === -1 ? splitCommand(env.GATE_COMMAND ?? '') : argv.slice(dash + 1);
|
|
87
|
+
const { values } = parseArgs({
|
|
88
|
+
args: own,
|
|
89
|
+
options: {
|
|
90
|
+
label: { type: 'string' }, mode: { type: 'string' }, allow: { type: 'string' }, gate: { type: 'string' },
|
|
91
|
+
'push-interests': { type: 'string' }, 'push-users': { type: 'string' }, channel: { type: 'string' },
|
|
92
|
+
options: { type: 'string' }, wait: { type: 'string' }, expires: { type: 'string' },
|
|
93
|
+
'upstream-url': { type: 'string' }, header: { type: 'string', multiple: true },
|
|
94
|
+
http: { type: 'boolean' }, port: { type: 'string' }, host: { type: 'string' },
|
|
95
|
+
version: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
|
|
96
|
+
},
|
|
97
|
+
strict: true,
|
|
98
|
+
});
|
|
99
|
+
const mode = values.mode ?? env.GATE_MODE ?? 'writes';
|
|
100
|
+
if (!['writes', 'all', 'none'].includes(mode)) throw new Error('--mode must be writes, all or none');
|
|
101
|
+
const headerLines = values.header ?? (env.GATE_UPSTREAM_HEADERS ? env.GATE_UPSTREAM_HEADERS.split('\n') : []);
|
|
102
|
+
const headers = {};
|
|
103
|
+
for (const h of headerLines) {
|
|
104
|
+
const i = h.indexOf(':');
|
|
105
|
+
if (i < 1) throw new Error(`bad header "${h}", expected "Name: value"`);
|
|
106
|
+
// ${NAME} reads an environment variable, so tokens stay out of configs.
|
|
107
|
+
headers[h.slice(0, i).trim()] = h.slice(i + 1).trim().replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, k) => env[k] ?? '');
|
|
108
|
+
}
|
|
109
|
+
const num = (v, d, name, lo, hi) => {
|
|
110
|
+
if (v === undefined || v === '') return d;
|
|
111
|
+
const n = Number(v);
|
|
112
|
+
if (!Number.isInteger(n) || n < lo || n > hi) throw new Error(`${name} must be a whole number from ${lo} to ${hi}`);
|
|
113
|
+
return n;
|
|
114
|
+
};
|
|
115
|
+
const opts = {
|
|
116
|
+
help: values.help, version: values.version,
|
|
117
|
+
command,
|
|
118
|
+
upstreamUrl: values['upstream-url'] ?? env.GATE_UPSTREAM_URL,
|
|
119
|
+
headers,
|
|
120
|
+
label: values.label ?? env.GATE_LABEL,
|
|
121
|
+
mode,
|
|
122
|
+
allowTools: list(values.allow ?? env.GATE_ALLOW_TOOLS),
|
|
123
|
+
gateTools: list(values.gate ?? env.GATE_TOOLS),
|
|
124
|
+
pushInterests: list(values['push-interests'] ?? env.GATE_PUSH_INTERESTS),
|
|
125
|
+
pushUsers: list(values['push-users'] ?? env.GATE_PUSH_USERS),
|
|
126
|
+
channel: values.channel ?? env.GATE_CHANNEL,
|
|
127
|
+
options: list(values.options ?? env.GATE_OPTIONS),
|
|
128
|
+
waitSeconds: num(values.wait ?? env.GATE_WAIT_SECONDS, 50, '--wait', 0, 3600),
|
|
129
|
+
expiresMinutes: num(values.expires ?? env.GATE_EXPIRES_MINUTES, 60, '--expires', 1, 10080),
|
|
130
|
+
http: values.http ?? false,
|
|
131
|
+
port: num(values.port ?? env.PORT, 8787, '--port', 1, 65535),
|
|
132
|
+
host: values.host ?? env.GATE_HOST ?? '127.0.0.1',
|
|
133
|
+
token: env.GATE_TOKEN,
|
|
134
|
+
};
|
|
135
|
+
if (opts.pushInterests.length && opts.pushUsers.length) throw new Error('give --push-interests or --push-users, not both');
|
|
136
|
+
if (!opts.help && !opts.version && !opts.command.length && !opts.upstreamUrl) {
|
|
137
|
+
throw new Error('give the database MCP server to wrap after -- (or in GATE_COMMAND), or --upstream-url');
|
|
138
|
+
}
|
|
139
|
+
if (opts.command.length && opts.upstreamUrl) throw new Error('give a command after -- or --upstream-url, not both');
|
|
140
|
+
return opts;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The environment for the wrapped server: everything but the Hibira credentials. */
|
|
144
|
+
export function childEnv(env) {
|
|
145
|
+
return Object.fromEntries(Object.entries(env).filter(([k, v]) => v !== undefined && !k.startsWith('HIBIRA_') && k !== 'GATE_TOKEN'));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function connectUpstream(opts) {
|
|
149
|
+
const client = new Client({ name: 'hibira-mcp-approval-gate', version: VERSION }, { capabilities: {} });
|
|
150
|
+
const transport = opts.upstreamUrl
|
|
151
|
+
? new StreamableHTTPClientTransport(new URL(opts.upstreamUrl), { requestInit: { headers: opts.headers } })
|
|
152
|
+
: new StdioClientTransport({ command: opts.command[0], args: opts.command.slice(1), env: childEnv(process.env), stderr: 'inherit' });
|
|
153
|
+
await client.connect(transport);
|
|
154
|
+
return client;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function tokenOk(given, want) {
|
|
158
|
+
if (!given) return false;
|
|
159
|
+
const a = Buffer.from(given);
|
|
160
|
+
const b = Buffer.from(want);
|
|
161
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function serveHttp(gate, opts, log) {
|
|
165
|
+
const loopback = ['127.0.0.1', '::1', 'localhost'].includes(opts.host);
|
|
166
|
+
if (!opts.token && !loopback) fail('set GATE_TOKEN before serving HTTP on a non-local address');
|
|
167
|
+
const sessions = new Map();
|
|
168
|
+
const http = createHttpServer(async (req, res) => {
|
|
169
|
+
const url = new URL(req.url, 'http://localhost');
|
|
170
|
+
if (url.pathname === '/healthz') {
|
|
171
|
+
res.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const m = /^\/mcp(?:\/([^/]+))?\/?$/.exec(url.pathname);
|
|
175
|
+
if (!m) {
|
|
176
|
+
res.writeHead(404).end();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (opts.token) {
|
|
180
|
+
const bearer = /^Bearer (.+)$/i.exec(req.headers.authorization ?? '')?.[1];
|
|
181
|
+
if (!tokenOk(m[1] ?? bearer, opts.token)) {
|
|
182
|
+
res.writeHead(401, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'unauthorized' }));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
let body;
|
|
187
|
+
if (req.method === 'POST') {
|
|
188
|
+
const chunks = [];
|
|
189
|
+
for await (const c of req) chunks.push(c);
|
|
190
|
+
try {
|
|
191
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
192
|
+
} catch {
|
|
193
|
+
res.writeHead(400).end('bad JSON');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const sid = req.headers['mcp-session-id'];
|
|
198
|
+
let transport = sid && sessions.get(sid);
|
|
199
|
+
if (!transport) {
|
|
200
|
+
if (req.method !== 'POST' || !isInitializeRequest(body)) {
|
|
201
|
+
res.writeHead(sid ? 404 : 400, { 'Content-Type': 'application/json' })
|
|
202
|
+
.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: sid ? 'unknown session' : 'initialize first' }, id: null }));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
transport = new StreamableHTTPServerTransport({
|
|
206
|
+
sessionIdGenerator: () => randomUUID(),
|
|
207
|
+
onsessioninitialized: (id) => sessions.set(id, transport),
|
|
208
|
+
});
|
|
209
|
+
transport.onclose = () => transport.sessionId && sessions.delete(transport.sessionId);
|
|
210
|
+
await gate.createServer().connect(transport);
|
|
211
|
+
}
|
|
212
|
+
await transport.handleRequest(req, res, body);
|
|
213
|
+
});
|
|
214
|
+
http.listen(opts.port, opts.host, () => log(`serving MCP on http://${opts.host}:${opts.port}/mcp`));
|
|
215
|
+
return http;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export async function main() {
|
|
219
|
+
let opts;
|
|
220
|
+
try {
|
|
221
|
+
opts = parse(process.argv.slice(2), process.env);
|
|
222
|
+
} catch (err) {
|
|
223
|
+
fail(`${err.message}\n\n${HELP}`);
|
|
224
|
+
}
|
|
225
|
+
if (opts.help) {
|
|
226
|
+
process.stdout.write(HELP);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (opts.version) {
|
|
230
|
+
process.stdout.write(`${VERSION}\n`);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const log = (msg) => process.stderr.write(`[approval-gate] ${msg}\n`);
|
|
234
|
+
let approvals;
|
|
235
|
+
try {
|
|
236
|
+
approvals = new ApprovalsClient({
|
|
237
|
+
appId: process.env.HIBIRA_APP_ID, key: process.env.HIBIRA_KEY, secret: process.env.HIBIRA_SECRET,
|
|
238
|
+
baseUrl: process.env.HIBIRA_API_URL || undefined,
|
|
239
|
+
});
|
|
240
|
+
} catch (err) {
|
|
241
|
+
fail(err.message);
|
|
242
|
+
}
|
|
243
|
+
let upstream;
|
|
244
|
+
try {
|
|
245
|
+
upstream = await connectUpstream(opts);
|
|
246
|
+
} catch (err) {
|
|
247
|
+
fail(`could not start the database MCP server: ${err.message}`);
|
|
248
|
+
}
|
|
249
|
+
const gate = new Gate({ ...opts, upstream, approvals, log });
|
|
250
|
+
if (opts.http) {
|
|
251
|
+
serveHttp(gate, opts, log);
|
|
252
|
+
} else {
|
|
253
|
+
const server = gate.createServer();
|
|
254
|
+
await server.connect(new StdioServerTransport());
|
|
255
|
+
process.stdin.on('end', () => stop());
|
|
256
|
+
}
|
|
257
|
+
async function stop() {
|
|
258
|
+
await upstream.close().catch(() => {});
|
|
259
|
+
process.exit(0);
|
|
260
|
+
}
|
|
261
|
+
process.on('SIGINT', stop);
|
|
262
|
+
process.on('SIGTERM', stop);
|
|
263
|
+
upstream.onclose = () => {
|
|
264
|
+
log('the database MCP server exited');
|
|
265
|
+
process.exit(1);
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
package/src/gate.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
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.1.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.log = opts.log ?? (() => {});
|
|
55
|
+
/** fingerprint -> pending call */
|
|
56
|
+
this.pending = new Map();
|
|
57
|
+
/** approval id -> fingerprint */
|
|
58
|
+
this.byId = new Map();
|
|
59
|
+
this.tools = undefined;
|
|
60
|
+
this.servers = new Set();
|
|
61
|
+
this.checkTool = 'check_approval';
|
|
62
|
+
this.upstream.setNotificationHandler(ToolListChangedNotificationSchema, () => {
|
|
63
|
+
this.tools = undefined;
|
|
64
|
+
for (const s of this.servers) s.sendToolListChanged().catch(() => {});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A downstream MCP server for one client session. */
|
|
69
|
+
createServer() {
|
|
70
|
+
const caps = this.upstream.getServerCapabilities() ?? {};
|
|
71
|
+
const server = new Server(
|
|
72
|
+
{ name: 'hibira-mcp-approval-gate', title: 'Approval gate', version: VERSION },
|
|
73
|
+
{
|
|
74
|
+
capabilities: {
|
|
75
|
+
tools: { listChanged: true },
|
|
76
|
+
logging: {},
|
|
77
|
+
...(caps.resources ? { resources: {} } : {}),
|
|
78
|
+
...(caps.prompts ? { prompts: {} } : {}),
|
|
79
|
+
},
|
|
80
|
+
instructions: this.#instructions(),
|
|
81
|
+
},
|
|
82
|
+
);
|
|
83
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await this.listTools() }));
|
|
84
|
+
server.setRequestHandler(CallToolRequestSchema, (req, extra) => this.callTool(req.params, extra, server));
|
|
85
|
+
if (caps.resources) {
|
|
86
|
+
server.setRequestHandler(ListResourcesRequestSchema, (req) => this.upstream.listResources(req.params));
|
|
87
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, (req) => this.upstream.listResourceTemplates(req.params));
|
|
88
|
+
server.setRequestHandler(ReadResourceRequestSchema, (req) => this.upstream.readResource(req.params));
|
|
89
|
+
}
|
|
90
|
+
if (caps.prompts) {
|
|
91
|
+
server.setRequestHandler(ListPromptsRequestSchema, (req) => this.upstream.listPrompts(req.params));
|
|
92
|
+
server.setRequestHandler(GetPromptRequestSchema, (req) => this.upstream.getPrompt(req.params));
|
|
93
|
+
}
|
|
94
|
+
this.servers.add(server);
|
|
95
|
+
server.onclose = () => this.servers.delete(server);
|
|
96
|
+
return server;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
#instructions() {
|
|
100
|
+
const up = this.upstream.getInstructions?.();
|
|
101
|
+
const own = `Calls that change the ${this.label} (writes, schema changes, deletes) wait for a supervisor's approval before they run. ` +
|
|
102
|
+
`If a call answers that it is waiting, give the person the approval link, and call ${this.checkTool} with the approval_id when they say it is decided. ` +
|
|
103
|
+
'Do not rewrite a declined statement to get around the decision.';
|
|
104
|
+
return up ? `${up}\n\n${own}` : own;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Upstream tools, plus the gate's own check tool. */
|
|
108
|
+
async listTools() {
|
|
109
|
+
if (!this.tools) {
|
|
110
|
+
const tools = [];
|
|
111
|
+
let cursor;
|
|
112
|
+
do {
|
|
113
|
+
const page = await this.upstream.listTools(cursor ? { cursor } : {});
|
|
114
|
+
tools.push(...page.tools);
|
|
115
|
+
cursor = page.nextCursor;
|
|
116
|
+
} while (cursor);
|
|
117
|
+
this.tools = tools;
|
|
118
|
+
if (tools.some((t) => t.name === this.checkTool)) this.checkTool = 'approval_gate_check';
|
|
119
|
+
}
|
|
120
|
+
return [...this.tools.map((t) => this.#describe(t)), this.#checkToolDef()];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
#describe(tool) {
|
|
124
|
+
const d = decide({ name: tool.name, args: {}, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
|
|
125
|
+
const sqlTool = Object.keys(tool.inputSchema?.properties ?? {}).some((k) => ['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
|
|
126
|
+
let note;
|
|
127
|
+
if (sqlTool && this.mode === 'writes') note = 'Read-only SQL runs right away; statements that change data or schema wait for a supervisor\'s approval.';
|
|
128
|
+
else if (d.gate) note = 'Waits for a supervisor\'s approval before it runs.';
|
|
129
|
+
if (!note) return tool;
|
|
130
|
+
return { ...tool, description: tool.description ? `${tool.description}\n\n${note}` : note };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
#checkToolDef() {
|
|
134
|
+
return {
|
|
135
|
+
name: this.checkTool,
|
|
136
|
+
title: 'Check approval',
|
|
137
|
+
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.',
|
|
138
|
+
inputSchema: {
|
|
139
|
+
type: 'object',
|
|
140
|
+
properties: { approval_id: { type: 'string', description: 'The approval_id from the waiting answer (apr_...)' } },
|
|
141
|
+
required: ['approval_id'],
|
|
142
|
+
},
|
|
143
|
+
annotations: { title: 'Check approval', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async #toolDef(name) {
|
|
148
|
+
if (!this.tools) await this.listTools();
|
|
149
|
+
return this.tools.find((t) => t.name === name);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Handles tools/call. */
|
|
153
|
+
async callTool(params, extra = {}, server) {
|
|
154
|
+
const { name, arguments: args = {} } = params;
|
|
155
|
+
if (name === this.checkTool) return this.#check(String(args.approval_id ?? ''), extra);
|
|
156
|
+
const tool = await this.#toolDef(name);
|
|
157
|
+
const d = decide({ name, args, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
|
|
158
|
+
if (!d.gate) return this.#forward(name, args, extra);
|
|
159
|
+
|
|
160
|
+
const fp = fingerprint(name, args);
|
|
161
|
+
let entry = this.pending.get(fp);
|
|
162
|
+
if (!entry) {
|
|
163
|
+
let created;
|
|
164
|
+
try {
|
|
165
|
+
created = await this.approvals.create(this.#approvalBody(name, args, d, fp));
|
|
166
|
+
} catch (err) {
|
|
167
|
+
this.log(`approval request failed: ${err.message}`);
|
|
168
|
+
return errorResult(`Could not ask for approval, so nothing ran: ${err.message}`);
|
|
169
|
+
}
|
|
170
|
+
entry = { id: created.approval_id, url: created.url, name, args, fp, expiresAt: created.expires_at, pushError: created.push_error };
|
|
171
|
+
this.pending.set(fp, entry);
|
|
172
|
+
this.byId.set(entry.id, fp);
|
|
173
|
+
this.log(`approval ${entry.id} requested for ${name} (${d.reason}): ${entry.url}`);
|
|
174
|
+
}
|
|
175
|
+
await notify(server, extra, `Waiting for supervisor approval: ${entry.url}`);
|
|
176
|
+
return this.#await(entry, this.waitSeconds, extra);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
#approvalBody(name, args, d, fp) {
|
|
180
|
+
const sql = d.sql;
|
|
181
|
+
const what = sql?.kinds?.length ? sql.kinds.join(', ') : name;
|
|
182
|
+
const title = truncate(`${what} on ${this.label}`, 200);
|
|
183
|
+
const lines = [];
|
|
184
|
+
lines.push(`Database: ${this.label}`);
|
|
185
|
+
lines.push(`Tool: ${name}`);
|
|
186
|
+
if (sql?.kinds?.length) lines.push(`Changes: ${sql.kinds.join(', ')}`);
|
|
187
|
+
for (const w of sql?.warnings ?? []) lines.push(`⚠ ${w}`);
|
|
188
|
+
lines.push('');
|
|
189
|
+
const body = sql ? sqlText(args) : JSON.stringify(args, null, 2);
|
|
190
|
+
const others = sql ? otherArgs(args) : '';
|
|
191
|
+
const footer = `\n\nFingerprint: ${fp.slice(0, 16)}\nOnly this exact call runs after approval.`;
|
|
192
|
+
let text = lines.join('\n') + body + (others ? `\n\nOther arguments:\n${others}` : '');
|
|
193
|
+
const room = DETAILS_MAX - footer.length;
|
|
194
|
+
if (text.length > room) text = text.slice(0, room - 40) + '\n… (truncated; see the request log)';
|
|
195
|
+
const out = {
|
|
196
|
+
title,
|
|
197
|
+
details: text + footer,
|
|
198
|
+
expires_in_minutes: this.expiresMinutes,
|
|
199
|
+
agent: truncate(`Approval gate · ${this.label}`, 60),
|
|
200
|
+
};
|
|
201
|
+
if (this.options?.length) out.options = this.options;
|
|
202
|
+
if (this.channel) out.channel = this.channel;
|
|
203
|
+
if (this.pushInterests.length) out.push_interests = this.pushInterests;
|
|
204
|
+
else if (this.pushUsers.length) out.push_users = this.pushUsers;
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async #await(entry, seconds, extra) {
|
|
209
|
+
const deadline = Date.now() + seconds * 1000;
|
|
210
|
+
let progress = 0;
|
|
211
|
+
for (;;) {
|
|
212
|
+
if (extra.signal?.aborted) return pendingResult(entry, this.checkTool);
|
|
213
|
+
const left = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
|
214
|
+
let state;
|
|
215
|
+
try {
|
|
216
|
+
state = await this.approvals.get(entry.id, Math.min(25, left), extra.signal);
|
|
217
|
+
} catch (err) {
|
|
218
|
+
if (extra.signal?.aborted) return pendingResult(entry, this.checkTool);
|
|
219
|
+
if (err.status === 404) {
|
|
220
|
+
this.#forget(entry);
|
|
221
|
+
return errorResult(`Approval ${entry.id} is gone (it expired more than a day ago). Nothing ran.`);
|
|
222
|
+
}
|
|
223
|
+
this.log(`approval ${entry.id} status failed: ${err.message}`);
|
|
224
|
+
if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
|
|
225
|
+
await sleep(1000);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (state.status === 'approved') return this.#run(entry, state, extra);
|
|
229
|
+
if (state.status === 'rejected' || state.status === 'expired') {
|
|
230
|
+
this.#forget(entry);
|
|
231
|
+
const how = state.status === 'expired' ? 'Nobody answered in time' : `The supervisor chose "${state.choice}"`;
|
|
232
|
+
return errorResult(`${how}, so the call did not run.${state.comment ? ` Comment: ${state.comment}` : ''} Do not retry it unless the person asks.`);
|
|
233
|
+
}
|
|
234
|
+
if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
|
|
235
|
+
if (extra._meta?.progressToken !== undefined && extra.sendNotification) {
|
|
236
|
+
progress += 1;
|
|
237
|
+
await extra.sendNotification({
|
|
238
|
+
method: 'notifications/progress',
|
|
239
|
+
params: { progressToken: extra._meta.progressToken, progress, message: 'Waiting for supervisor approval' },
|
|
240
|
+
}).catch(() => {});
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async #check(id, extra) {
|
|
246
|
+
const fp = this.byId.get(id);
|
|
247
|
+
const entry = fp && this.pending.get(fp);
|
|
248
|
+
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.`);
|
|
249
|
+
return this.#await(entry, 25, extra);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async #run(entry, state, extra) {
|
|
253
|
+
// An approval runs its call once, even if the call fails or two waits
|
|
254
|
+
// see the answer at the same time.
|
|
255
|
+
if (entry.ran) return errorResult(`Approval ${entry.id} was already used; the call ran once.`);
|
|
256
|
+
entry.ran = true;
|
|
257
|
+
this.#forget(entry);
|
|
258
|
+
this.log(`approval ${entry.id} approved (${state.choice}); running ${entry.name}`);
|
|
259
|
+
const result = await this.#forward(entry.name, entry.args, extra);
|
|
260
|
+
const note = { type: 'text', text: `Approved by a supervisor (${state.choice}${state.comment ? `: ${state.comment}` : ''}); ran once.` };
|
|
261
|
+
return { ...result, content: [...(result.content ?? []), note] };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
#forget(entry) {
|
|
265
|
+
this.pending.delete(entry.fp);
|
|
266
|
+
this.byId.delete(entry.id);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async #forward(name, args, extra) {
|
|
270
|
+
try {
|
|
271
|
+
return await this.upstream.callTool({ name, arguments: args }, undefined, {
|
|
272
|
+
signal: extra.signal,
|
|
273
|
+
timeout: this.upstreamTimeoutMs,
|
|
274
|
+
...(extra._meta?.progressToken !== undefined && extra.sendNotification ? {
|
|
275
|
+
onprogress: (p) => extra.sendNotification({ method: 'notifications/progress', params: { ...p, progressToken: extra._meta.progressToken } }).catch(() => {}),
|
|
276
|
+
resetTimeoutOnProgress: true,
|
|
277
|
+
} : {}),
|
|
278
|
+
});
|
|
279
|
+
} catch (err) {
|
|
280
|
+
return errorResult(`The database server failed: ${err.message}`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function sqlText(args) {
|
|
286
|
+
const parts = [];
|
|
287
|
+
for (const [k, v] of Object.entries(args)) {
|
|
288
|
+
if (!['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase())) continue;
|
|
289
|
+
parts.push(Array.isArray(v) ? v.join(';\n') : String(v));
|
|
290
|
+
}
|
|
291
|
+
return parts.join('\n\n').trim();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function otherArgs(args) {
|
|
295
|
+
const rest = Object.entries(args).filter(([k]) => !['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
|
|
296
|
+
return rest.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`).join('\n');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function pendingResult(entry, checkTool) {
|
|
300
|
+
const text = [
|
|
301
|
+
'Waiting for a supervisor to approve this call. Nothing has run yet.',
|
|
302
|
+
`Approval link: ${entry.url}`,
|
|
303
|
+
`approval_id: ${entry.id}`,
|
|
304
|
+
entry.pushError ? `(The push notification failed: ${entry.pushError}. Share the link instead.)` : '',
|
|
305
|
+
`Give the person the link. When they say it is decided, call ${checkTool} with this approval_id; it runs the call if it was approved.`,
|
|
306
|
+
].filter(Boolean).join('\n');
|
|
307
|
+
return { content: [{ type: 'text', text }], _meta: { 'io.hibira/approval': { approval_id: entry.id, url: entry.url, status: 'pending' } } };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function errorResult(text) {
|
|
311
|
+
return { content: [{ type: 'text', text }], isError: true };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function notify(server, extra, data) {
|
|
315
|
+
if (!server) return;
|
|
316
|
+
try {
|
|
317
|
+
await server.sendLoggingMessage({ level: 'notice', logger: 'approval-gate', data }, extra.sessionId);
|
|
318
|
+
} catch {
|
|
319
|
+
// Clients that did not ask for logging ignore it.
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function truncate(s, n) {
|
|
324
|
+
return s.length > n ? s.slice(0, n - 1) + '…' : s;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function sleep(ms) {
|
|
328
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
329
|
+
}
|
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
|
+
}
|