@hibira-io/mcp-approval-gate 0.2.0 → 0.4.1
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 +35 -0
- package/README.md +179 -34
- package/bin.js +8 -3
- package/package.json +10 -3
- package/src/cli.js +61 -11
- package/src/connect.js +230 -0
- package/src/gate.js +25 -8
- package/src/hook.js +359 -0
- package/src/policy.js +12 -3
- package/src/presets.js +85 -0
- package/src/shell.js +748 -0
package/src/connect.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Connecting the gate to a Hibira Approvals workspace without keys: a device
|
|
2
|
+
// sign-in (like `gh auth login`) gives the gate a workspace token that can
|
|
3
|
+
// only ask for and read approvals. The token is kept in a local file.
|
|
4
|
+
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
|
|
6
|
+
import { homedir, hostname } from 'node:os';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_URL = 'https://api.hibira.io/approvals';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The gate's API under a base URL: https://api.hibira.io/approvals/gate, or
|
|
13
|
+
* /api/v1/gate on a bare host such as https://approvals.hibira.io (older
|
|
14
|
+
* settings and saved tokens, which keep working).
|
|
15
|
+
*/
|
|
16
|
+
export function gateUrl(baseUrl) {
|
|
17
|
+
const base = String(baseUrl).replace(/\/+$/, '');
|
|
18
|
+
return new URL(base).pathname.replace(/\/+$/, '') ? `${base}/gate` : `${base}/api/v1/gate`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Where tokens are kept: $HIBIRA_CONFIG_DIR, $XDG_CONFIG_HOME/hibira or ~/.config/hibira. */
|
|
22
|
+
export function configPath(env = process.env) {
|
|
23
|
+
const dir = env.HIBIRA_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'hibira');
|
|
24
|
+
return join(dir, 'approval-gate.json');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class TokenStore {
|
|
28
|
+
constructor(path) {
|
|
29
|
+
this.path = path;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
#all() {
|
|
33
|
+
try {
|
|
34
|
+
const data = JSON.parse(readFileSync(this.path, 'utf8'));
|
|
35
|
+
return data && typeof data === 'object' && data.profiles ? data : { profiles: {} };
|
|
36
|
+
} catch {
|
|
37
|
+
return { profiles: {} };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
get(profile) {
|
|
42
|
+
return this.#all().profiles[profile];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
set(profile, value) {
|
|
46
|
+
const all = this.#all();
|
|
47
|
+
if (value) all.profiles[profile] = value;
|
|
48
|
+
else delete all.profiles[profile];
|
|
49
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
50
|
+
writeFileSync(this.path, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
|
|
51
|
+
chmodSync(this.path, 0o600);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function call(f, url, { method = 'GET', token, body, signal } = {}) {
|
|
56
|
+
const headers = { Accept: 'application/json' };
|
|
57
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
58
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
59
|
+
const res = await f(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
|
|
60
|
+
const text = await res.text();
|
|
61
|
+
let json;
|
|
62
|
+
try { json = JSON.parse(text); } catch { json = undefined; }
|
|
63
|
+
if (!res.ok) {
|
|
64
|
+
const code = json?.error ?? json?.message ?? text.slice(0, 200);
|
|
65
|
+
const err = new Error(`Hibira approvals API ${res.status}: ${json?.error_description ?? json?.message ?? code}`);
|
|
66
|
+
err.status = res.status;
|
|
67
|
+
err.code = json?.error;
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
return json;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Approvals client for a connected workspace (bearer token). Same shape as ApprovalsClient. */
|
|
74
|
+
export class WorkspaceClient {
|
|
75
|
+
constructor({ token, baseUrl = DEFAULT_URL, fetch: f = globalThis.fetch }) {
|
|
76
|
+
if (!token) throw new Error('a workspace token is required');
|
|
77
|
+
this.token = token;
|
|
78
|
+
this.notifiesMembers = true;
|
|
79
|
+
this.baseUrl = baseUrl.replace(/\/$/, '');
|
|
80
|
+
this.fetch = f;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
create(body) {
|
|
84
|
+
return call(this.fetch, `${gateUrl(this.baseUrl)}/requests`, { method: 'POST', token: this.token, body });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get(id, waitSeconds = 0, signal) {
|
|
88
|
+
const qs = waitSeconds > 0 ? `?wait=${Math.min(25, Math.floor(waitSeconds))}` : '';
|
|
89
|
+
return call(this.fetch, `${gateUrl(this.baseUrl)}/requests/${encodeURIComponent(id)}${qs}`, { token: this.token, signal });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The device sign-in: start() gives a code and link, wait() polls until it is connected. */
|
|
94
|
+
export class DeviceLogin {
|
|
95
|
+
constructor({ baseUrl = DEFAULT_URL, label, fetch: f = globalThis.fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
|
|
96
|
+
this.baseUrl = baseUrl.replace(/\/$/, '');
|
|
97
|
+
this.label = label;
|
|
98
|
+
this.fetch = f;
|
|
99
|
+
this.sleep = sleep;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
start() {
|
|
103
|
+
return call(this.fetch, `${gateUrl(this.baseUrl)}/device`, {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
body: { client: 'mcp-approval-gate', label: this.label || 'database', host: hostname().slice(0, 100) },
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Polls until the person connects a workspace. Resolves { access_token, workspace }. */
|
|
110
|
+
async wait(start, signal) {
|
|
111
|
+
let interval = Math.max(1, Number(start.interval) || 5) * 1000;
|
|
112
|
+
const deadline = Date.now() + (Number(start.expires_in) || 900) * 1000;
|
|
113
|
+
while (Date.now() < deadline) {
|
|
114
|
+
if (signal?.aborted) throw new Error('cancelled');
|
|
115
|
+
await this.sleep(interval);
|
|
116
|
+
try {
|
|
117
|
+
return await call(this.fetch, `${gateUrl(this.baseUrl)}/token`, {
|
|
118
|
+
method: 'POST', body: { device_code: start.device_code }, signal,
|
|
119
|
+
});
|
|
120
|
+
} catch (err) {
|
|
121
|
+
if (err.code === 'authorization_pending') continue;
|
|
122
|
+
if (err.code === 'slow_down') { interval += 5000; continue; }
|
|
123
|
+
if (err.code === 'access_denied') throw new Error('the sign-in was cancelled');
|
|
124
|
+
if (err.code === 'expired_token') break;
|
|
125
|
+
if (err.status && err.status < 500) throw err;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
throw new Error('the sign-in code expired');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class NotConnectedError extends Error {
|
|
133
|
+
constructor(login) {
|
|
134
|
+
super('not connected to a Hibira Approvals workspace');
|
|
135
|
+
this.login = login;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Approvals that connect on first use. With a stored token it is a
|
|
141
|
+
* WorkspaceClient; without one, create() starts a device sign-in (once),
|
|
142
|
+
* throws NotConnectedError with its link, and finishes in the background.
|
|
143
|
+
*/
|
|
144
|
+
export class ConnectingApprovals {
|
|
145
|
+
constructor({ store, profile = 'default', baseUrl = DEFAULT_URL, label, fetch: f = globalThis.fetch, log = () => {}, sleep }) {
|
|
146
|
+
this.store = store;
|
|
147
|
+
this.profile = profile;
|
|
148
|
+
this.notifiesMembers = true;
|
|
149
|
+
this.baseUrl = baseUrl;
|
|
150
|
+
this.label = label;
|
|
151
|
+
this.fetch = f;
|
|
152
|
+
this.log = log;
|
|
153
|
+
this.sleep = sleep;
|
|
154
|
+
this.client = undefined;
|
|
155
|
+
this.login = undefined;
|
|
156
|
+
const saved = store.get(profile);
|
|
157
|
+
if (saved?.token) this.#use(saved);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
get connected() {
|
|
161
|
+
return Boolean(this.client);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
get workspace() {
|
|
165
|
+
return this.saved?.workspace;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
#use(saved) {
|
|
169
|
+
this.saved = saved;
|
|
170
|
+
this.client = new WorkspaceClient({ token: saved.token, baseUrl: saved.url || this.baseUrl, fetch: this.fetch });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Starts (or reuses) a device sign-in and returns its code and link. */
|
|
174
|
+
async connect() {
|
|
175
|
+
if (this.client) return undefined;
|
|
176
|
+
const now = Date.now();
|
|
177
|
+
if (this.login && this.login.expiresAt > now) return this.login;
|
|
178
|
+
const flow = new DeviceLogin({ baseUrl: this.baseUrl, label: this.label, fetch: this.fetch, sleep: this.sleep });
|
|
179
|
+
const start = await flow.start();
|
|
180
|
+
const login = {
|
|
181
|
+
code: start.user_code,
|
|
182
|
+
url: start.verification_uri_complete || start.verification_uri,
|
|
183
|
+
verificationUri: start.verification_uri,
|
|
184
|
+
expiresAt: now + (Number(start.expires_in) || 900) * 1000,
|
|
185
|
+
};
|
|
186
|
+
this.login = login;
|
|
187
|
+
this.log(`connect this gate: open ${login.url} and enter ${login.code}`);
|
|
188
|
+
login.done = flow.wait(start).then((res) => {
|
|
189
|
+
const saved = { token: res.access_token, workspace: res.workspace, url: this.baseUrl, connected_at: new Date().toISOString() };
|
|
190
|
+
this.store.set(this.profile, saved);
|
|
191
|
+
this.#use(saved);
|
|
192
|
+
this.login = undefined;
|
|
193
|
+
this.log(`connected to workspace ${res.workspace?.name ?? res.workspace?.id ?? ''}`.trim());
|
|
194
|
+
return saved;
|
|
195
|
+
}, (err) => {
|
|
196
|
+
if (this.login === login) this.login = undefined;
|
|
197
|
+
this.log(`connecting failed: ${err.message}`);
|
|
198
|
+
throw err;
|
|
199
|
+
});
|
|
200
|
+
login.done.catch(() => {});
|
|
201
|
+
return login;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async create(body) {
|
|
205
|
+
if (!this.client) throw new NotConnectedError(await this.connect());
|
|
206
|
+
try {
|
|
207
|
+
return await this.client.create(body);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
if (err.status === 401) this.#revoked();
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async get(id, waitSeconds, signal) {
|
|
215
|
+
if (!this.client) throw new NotConnectedError(await this.connect());
|
|
216
|
+
try {
|
|
217
|
+
return await this.client.get(id, waitSeconds, signal);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
if (err.status === 401) this.#revoked();
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
#revoked() {
|
|
225
|
+
this.log('the workspace token was revoked; the next change will ask to connect again');
|
|
226
|
+
this.store.set(this.profile, undefined);
|
|
227
|
+
this.client = undefined;
|
|
228
|
+
this.saved = undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
package/src/gate.js
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
} from '@modelcontextprotocol/sdk/types.js';
|
|
17
17
|
import { decide, fingerprint } from './policy.js';
|
|
18
18
|
|
|
19
|
-
export const VERSION = '0.
|
|
19
|
+
export const VERSION = '0.4.0';
|
|
20
20
|
const DETAILS_MAX = 4000;
|
|
21
21
|
|
|
22
22
|
export class Gate {
|
|
@@ -40,12 +40,14 @@ export class Gate {
|
|
|
40
40
|
constructor(opts) {
|
|
41
41
|
this.upstream = opts.upstream;
|
|
42
42
|
this.approvals = opts.approvals;
|
|
43
|
-
this.
|
|
43
|
+
this.preset = opts.preset;
|
|
44
|
+
this.label = opts.label || opts.preset?.label || 'database';
|
|
44
45
|
this.mode = opts.mode ?? 'writes';
|
|
45
46
|
this.allowTools = opts.allowTools ?? [];
|
|
46
47
|
this.gateTools = opts.gateTools ?? [];
|
|
47
48
|
this.waitSeconds = opts.waitSeconds ?? 50;
|
|
48
49
|
this.expiresMinutes = opts.expiresMinutes ?? 60;
|
|
50
|
+
this.approvers = opts.approvers ?? [];
|
|
49
51
|
this.pushInterests = opts.pushInterests ?? [];
|
|
50
52
|
this.pushUsers = opts.pushUsers ?? [];
|
|
51
53
|
this.channel = opts.channel;
|
|
@@ -122,7 +124,7 @@ export class Gate {
|
|
|
122
124
|
}
|
|
123
125
|
|
|
124
126
|
#describe(tool) {
|
|
125
|
-
const d = decide({ name: tool.name, args: {}, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
|
|
127
|
+
const d = decide({ name: tool.name, args: {}, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools, preset: this.preset });
|
|
126
128
|
const sqlTool = Object.keys(tool.inputSchema?.properties ?? {}).some((k) => ['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
|
|
127
129
|
let note;
|
|
128
130
|
if (sqlTool && this.mode === 'writes') note = 'Read-only SQL runs right away; statements that change data or schema wait for a supervisor\'s approval.';
|
|
@@ -155,7 +157,7 @@ export class Gate {
|
|
|
155
157
|
const { name, arguments: args = {} } = params;
|
|
156
158
|
if (name === this.checkTool) return this.#check(String(args.approval_id ?? ''), extra);
|
|
157
159
|
const tool = await this.#toolDef(name);
|
|
158
|
-
const d = decide({ name, args, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools });
|
|
160
|
+
const d = decide({ name, args, tool, mode: this.mode, allowTools: this.allowTools, gateTools: this.gateTools, preset: this.preset });
|
|
159
161
|
if (!d.gate) return this.#forward(name, args, extra);
|
|
160
162
|
|
|
161
163
|
const fp = fingerprint(name, args);
|
|
@@ -165,6 +167,7 @@ export class Gate {
|
|
|
165
167
|
try {
|
|
166
168
|
created = await this.approvals.create(this.#approvalBody(name, args, d, fp));
|
|
167
169
|
} catch (err) {
|
|
170
|
+
if (err.login) return connectResult(err.login);
|
|
168
171
|
this.log(`approval request failed: ${err.message}`);
|
|
169
172
|
return errorResult(`Could not ask for approval, so nothing ran: ${err.message}`);
|
|
170
173
|
}
|
|
@@ -184,6 +187,8 @@ export class Gate {
|
|
|
184
187
|
#linkVisible(entry) {
|
|
185
188
|
if (this.showLink === 'always') return true;
|
|
186
189
|
if (this.showLink === 'never') return false;
|
|
190
|
+
// A workspace notifies its members itself, and they answer signed in.
|
|
191
|
+
if (this.approvals.notifiesMembers) return false;
|
|
187
192
|
const pushed = (this.pushInterests.length || this.pushUsers.length) && !entry.pushError;
|
|
188
193
|
return !(pushed || this.channel);
|
|
189
194
|
}
|
|
@@ -191,9 +196,10 @@ export class Gate {
|
|
|
191
196
|
#approvalBody(name, args, d, fp) {
|
|
192
197
|
const sql = d.sql;
|
|
193
198
|
const what = sql?.kinds?.length ? sql.kinds.join(', ') : name;
|
|
194
|
-
const
|
|
199
|
+
const custom = !sql && this.preset?.title ? this.preset.title(name, args) : undefined;
|
|
200
|
+
const title = truncate(custom || `${what} on ${this.label}`, 200);
|
|
195
201
|
const lines = [];
|
|
196
|
-
lines.push(
|
|
202
|
+
lines.push(`${sql ? 'Database' : 'Service'}: ${this.label}`);
|
|
197
203
|
lines.push(`Tool: ${name}`);
|
|
198
204
|
if (sql?.kinds?.length) lines.push(`Changes: ${sql.kinds.join(', ')}`);
|
|
199
205
|
for (const w of sql?.warnings ?? []) lines.push(`⚠ ${w}`);
|
|
@@ -211,6 +217,7 @@ export class Gate {
|
|
|
211
217
|
agent: truncate(`Approval gate · ${this.label}`, 60),
|
|
212
218
|
};
|
|
213
219
|
if (this.options?.length) out.options = this.options;
|
|
220
|
+
if (this.approvers.length) out.approvers = this.approvers;
|
|
214
221
|
if (this.channel) out.channel = this.channel;
|
|
215
222
|
if (this.pushInterests.length) out.push_interests = this.pushInterests;
|
|
216
223
|
else if (this.pushUsers.length) out.push_users = this.pushUsers;
|
|
@@ -240,7 +247,7 @@ export class Gate {
|
|
|
240
247
|
if (state.status === 'approved') return this.#run(entry, state, extra);
|
|
241
248
|
if (state.status === 'rejected' || state.status === 'expired') {
|
|
242
249
|
this.#forget(entry);
|
|
243
|
-
const how = state.status === 'expired' ? 'Nobody answered in time' :
|
|
250
|
+
const how = state.status === 'expired' ? 'Nobody answered in time' : `${state.answered_by?.name || state.answered_by?.email || 'The supervisor'} chose "${state.choice}"`;
|
|
244
251
|
return errorResult(`${how}, so the call did not run.${state.comment ? ` Comment: ${state.comment}` : ''} Do not retry it unless the person asks.`);
|
|
245
252
|
}
|
|
246
253
|
if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
|
|
@@ -269,7 +276,8 @@ export class Gate {
|
|
|
269
276
|
this.#forget(entry);
|
|
270
277
|
this.log(`approval ${entry.id} approved (${state.choice}); running ${entry.name}`);
|
|
271
278
|
const result = await this.#forward(entry.name, entry.args, extra);
|
|
272
|
-
const
|
|
279
|
+
const who = state.answered_by?.name || state.answered_by?.email || 'a supervisor';
|
|
280
|
+
const note = { type: 'text', text: `Approved by ${who} (${state.choice}${state.comment ? `: ${state.comment}` : ''}); ran once.` };
|
|
273
281
|
return { ...result, content: [...(result.content ?? []), note] };
|
|
274
282
|
}
|
|
275
283
|
|
|
@@ -324,6 +332,15 @@ function pendingResult(entry, checkTool) {
|
|
|
324
332
|
return { content: [{ type: 'text', text }], _meta: { 'io.hibira/approval': meta } };
|
|
325
333
|
}
|
|
326
334
|
|
|
335
|
+
function connectResult(login) {
|
|
336
|
+
const text = [
|
|
337
|
+
'This approval gate is not connected to a Hibira Approvals workspace yet, so nothing ran.',
|
|
338
|
+
`Ask the person to open ${login.url} and confirm the code ${login.code}, then pick the workspace whose members approve changes.`,
|
|
339
|
+
'Once they say it is connected, make the same call again.',
|
|
340
|
+
].join('\n');
|
|
341
|
+
return { content: [{ type: 'text', text }], isError: true, _meta: { 'io.hibira/approval': { status: 'not_connected', url: login.url, code: login.code } } };
|
|
342
|
+
}
|
|
343
|
+
|
|
327
344
|
function errorResult(text) {
|
|
328
345
|
return { content: [{ type: 'text', text }], isError: true };
|
|
329
346
|
}
|