@hibira-io/mcp-approval-gate 0.1.0 → 0.4.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/src/connect.js ADDED
@@ -0,0 +1,220 @@
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://approvals.hibira.io';
10
+
11
+ /** Where tokens are kept: $HIBIRA_CONFIG_DIR, $XDG_CONFIG_HOME/hibira or ~/.config/hibira. */
12
+ export function configPath(env = process.env) {
13
+ const dir = env.HIBIRA_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'hibira');
14
+ return join(dir, 'approval-gate.json');
15
+ }
16
+
17
+ export class TokenStore {
18
+ constructor(path) {
19
+ this.path = path;
20
+ }
21
+
22
+ #all() {
23
+ try {
24
+ const data = JSON.parse(readFileSync(this.path, 'utf8'));
25
+ return data && typeof data === 'object' && data.profiles ? data : { profiles: {} };
26
+ } catch {
27
+ return { profiles: {} };
28
+ }
29
+ }
30
+
31
+ get(profile) {
32
+ return this.#all().profiles[profile];
33
+ }
34
+
35
+ set(profile, value) {
36
+ const all = this.#all();
37
+ if (value) all.profiles[profile] = value;
38
+ else delete all.profiles[profile];
39
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
40
+ writeFileSync(this.path, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
41
+ chmodSync(this.path, 0o600);
42
+ }
43
+ }
44
+
45
+ async function call(f, url, { method = 'GET', token, body, signal } = {}) {
46
+ const headers = { Accept: 'application/json' };
47
+ if (token) headers.Authorization = `Bearer ${token}`;
48
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
49
+ const res = await f(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
50
+ const text = await res.text();
51
+ let json;
52
+ try { json = JSON.parse(text); } catch { json = undefined; }
53
+ if (!res.ok) {
54
+ const code = json?.error ?? json?.message ?? text.slice(0, 200);
55
+ const err = new Error(`Hibira approvals API ${res.status}: ${json?.error_description ?? json?.message ?? code}`);
56
+ err.status = res.status;
57
+ err.code = json?.error;
58
+ throw err;
59
+ }
60
+ return json;
61
+ }
62
+
63
+ /** Approvals client for a connected workspace (bearer token). Same shape as ApprovalsClient. */
64
+ export class WorkspaceClient {
65
+ constructor({ token, baseUrl = DEFAULT_URL, fetch: f = globalThis.fetch }) {
66
+ if (!token) throw new Error('a workspace token is required');
67
+ this.token = token;
68
+ this.notifiesMembers = true;
69
+ this.baseUrl = baseUrl.replace(/\/$/, '');
70
+ this.fetch = f;
71
+ }
72
+
73
+ create(body) {
74
+ return call(this.fetch, `${this.baseUrl}/api/v1/gate/requests`, { method: 'POST', token: this.token, body });
75
+ }
76
+
77
+ get(id, waitSeconds = 0, signal) {
78
+ const qs = waitSeconds > 0 ? `?wait=${Math.min(25, Math.floor(waitSeconds))}` : '';
79
+ return call(this.fetch, `${this.baseUrl}/api/v1/gate/requests/${encodeURIComponent(id)}${qs}`, { token: this.token, signal });
80
+ }
81
+ }
82
+
83
+ /** The device sign-in: start() gives a code and link, wait() polls until it is connected. */
84
+ export class DeviceLogin {
85
+ constructor({ baseUrl = DEFAULT_URL, label, fetch: f = globalThis.fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
86
+ this.baseUrl = baseUrl.replace(/\/$/, '');
87
+ this.label = label;
88
+ this.fetch = f;
89
+ this.sleep = sleep;
90
+ }
91
+
92
+ start() {
93
+ return call(this.fetch, `${this.baseUrl}/api/v1/gate/device`, {
94
+ method: 'POST',
95
+ body: { client: 'mcp-approval-gate', label: this.label || 'database', host: hostname().slice(0, 100) },
96
+ });
97
+ }
98
+
99
+ /** Polls until the person connects a workspace. Resolves { access_token, workspace }. */
100
+ async wait(start, signal) {
101
+ let interval = Math.max(1, Number(start.interval) || 5) * 1000;
102
+ const deadline = Date.now() + (Number(start.expires_in) || 900) * 1000;
103
+ while (Date.now() < deadline) {
104
+ if (signal?.aborted) throw new Error('cancelled');
105
+ await this.sleep(interval);
106
+ try {
107
+ return await call(this.fetch, `${this.baseUrl}/api/v1/gate/token`, {
108
+ method: 'POST', body: { device_code: start.device_code }, signal,
109
+ });
110
+ } catch (err) {
111
+ if (err.code === 'authorization_pending') continue;
112
+ if (err.code === 'slow_down') { interval += 5000; continue; }
113
+ if (err.code === 'access_denied') throw new Error('the sign-in was cancelled');
114
+ if (err.code === 'expired_token') break;
115
+ if (err.status && err.status < 500) throw err;
116
+ }
117
+ }
118
+ throw new Error('the sign-in code expired');
119
+ }
120
+ }
121
+
122
+ export class NotConnectedError extends Error {
123
+ constructor(login) {
124
+ super('not connected to a Hibira Approvals workspace');
125
+ this.login = login;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Approvals that connect on first use. With a stored token it is a
131
+ * WorkspaceClient; without one, create() starts a device sign-in (once),
132
+ * throws NotConnectedError with its link, and finishes in the background.
133
+ */
134
+ export class ConnectingApprovals {
135
+ constructor({ store, profile = 'default', baseUrl = DEFAULT_URL, label, fetch: f = globalThis.fetch, log = () => {}, sleep }) {
136
+ this.store = store;
137
+ this.profile = profile;
138
+ this.notifiesMembers = true;
139
+ this.baseUrl = baseUrl;
140
+ this.label = label;
141
+ this.fetch = f;
142
+ this.log = log;
143
+ this.sleep = sleep;
144
+ this.client = undefined;
145
+ this.login = undefined;
146
+ const saved = store.get(profile);
147
+ if (saved?.token) this.#use(saved);
148
+ }
149
+
150
+ get connected() {
151
+ return Boolean(this.client);
152
+ }
153
+
154
+ get workspace() {
155
+ return this.saved?.workspace;
156
+ }
157
+
158
+ #use(saved) {
159
+ this.saved = saved;
160
+ this.client = new WorkspaceClient({ token: saved.token, baseUrl: saved.url || this.baseUrl, fetch: this.fetch });
161
+ }
162
+
163
+ /** Starts (or reuses) a device sign-in and returns its code and link. */
164
+ async connect() {
165
+ if (this.client) return undefined;
166
+ const now = Date.now();
167
+ if (this.login && this.login.expiresAt > now) return this.login;
168
+ const flow = new DeviceLogin({ baseUrl: this.baseUrl, label: this.label, fetch: this.fetch, sleep: this.sleep });
169
+ const start = await flow.start();
170
+ const login = {
171
+ code: start.user_code,
172
+ url: start.verification_uri_complete || start.verification_uri,
173
+ verificationUri: start.verification_uri,
174
+ expiresAt: now + (Number(start.expires_in) || 900) * 1000,
175
+ };
176
+ this.login = login;
177
+ this.log(`connect this gate: open ${login.url} and enter ${login.code}`);
178
+ login.done = flow.wait(start).then((res) => {
179
+ const saved = { token: res.access_token, workspace: res.workspace, url: this.baseUrl, connected_at: new Date().toISOString() };
180
+ this.store.set(this.profile, saved);
181
+ this.#use(saved);
182
+ this.login = undefined;
183
+ this.log(`connected to workspace ${res.workspace?.name ?? res.workspace?.id ?? ''}`.trim());
184
+ return saved;
185
+ }, (err) => {
186
+ if (this.login === login) this.login = undefined;
187
+ this.log(`connecting failed: ${err.message}`);
188
+ throw err;
189
+ });
190
+ login.done.catch(() => {});
191
+ return login;
192
+ }
193
+
194
+ async create(body) {
195
+ if (!this.client) throw new NotConnectedError(await this.connect());
196
+ try {
197
+ return await this.client.create(body);
198
+ } catch (err) {
199
+ if (err.status === 401) this.#revoked();
200
+ throw err;
201
+ }
202
+ }
203
+
204
+ async get(id, waitSeconds, signal) {
205
+ if (!this.client) throw new NotConnectedError(await this.connect());
206
+ try {
207
+ return await this.client.get(id, waitSeconds, signal);
208
+ } catch (err) {
209
+ if (err.status === 401) this.#revoked();
210
+ throw err;
211
+ }
212
+ }
213
+
214
+ #revoked() {
215
+ this.log('the workspace token was revoked; the next change will ask to connect again');
216
+ this.store.set(this.profile, undefined);
217
+ this.client = undefined;
218
+ this.saved = undefined;
219
+ }
220
+ }
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.1.0';
19
+ export const VERSION = '0.4.0';
20
20
  const DETAILS_MAX = 4000;
21
21
 
22
22
  export class Gate {
@@ -40,17 +40,20 @@ export class Gate {
40
40
  constructor(opts) {
41
41
  this.upstream = opts.upstream;
42
42
  this.approvals = opts.approvals;
43
- this.label = opts.label || 'database';
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;
52
54
  this.options = opts.options;
53
55
  this.upstreamTimeoutMs = opts.upstreamTimeoutMs ?? 300_000;
56
+ this.showLink = opts.showLink ?? 'auto';
54
57
  this.log = opts.log ?? (() => {});
55
58
  /** fingerprint -> pending call */
56
59
  this.pending = new Map();
@@ -99,7 +102,7 @@ export class Gate {
99
102
  #instructions() {
100
103
  const up = this.upstream.getInstructions?.();
101
104
  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. ` +
105
+ `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. ` +
103
106
  'Do not rewrite a declined statement to get around the decision.';
104
107
  return up ? `${up}\n\n${own}` : own;
105
108
  }
@@ -121,7 +124,7 @@ export class Gate {
121
124
  }
122
125
 
123
126
  #describe(tool) {
124
- 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 });
125
128
  const sqlTool = Object.keys(tool.inputSchema?.properties ?? {}).some((k) => ['sql', 'query', 'statement', 'statements', 'sql_query', 'queries', 'script'].includes(k.toLowerCase()));
126
129
  let note;
127
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.';
@@ -154,7 +157,7 @@ export class Gate {
154
157
  const { name, arguments: args = {} } = params;
155
158
  if (name === this.checkTool) return this.#check(String(args.approval_id ?? ''), extra);
156
159
  const tool = await this.#toolDef(name);
157
- 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 });
158
161
  if (!d.gate) return this.#forward(name, args, extra);
159
162
 
160
163
  const fp = fingerprint(name, args);
@@ -164,24 +167,39 @@ export class Gate {
164
167
  try {
165
168
  created = await this.approvals.create(this.#approvalBody(name, args, d, fp));
166
169
  } catch (err) {
170
+ if (err.login) return connectResult(err.login);
167
171
  this.log(`approval request failed: ${err.message}`);
168
172
  return errorResult(`Could not ask for approval, so nothing ran: ${err.message}`);
169
173
  }
170
174
  entry = { id: created.approval_id, url: created.url, name, args, fp, expiresAt: created.expires_at, pushError: created.push_error };
175
+ entry.showLink = this.#linkVisible(entry);
171
176
  this.pending.set(fp, entry);
172
177
  this.byId.set(entry.id, fp);
173
178
  this.log(`approval ${entry.id} requested for ${name} (${d.reason}): ${entry.url}`);
174
179
  }
175
- await notify(server, extra, `Waiting for supervisor approval: ${entry.url}`);
180
+ await notify(server, extra, entry.showLink ? `Waiting for supervisor approval: ${entry.url}` : 'Waiting for supervisor approval');
176
181
  return this.#await(entry, this.waitSeconds, extra);
177
182
  }
178
183
 
184
+ // The link goes back to the assistant only when nothing else delivers it:
185
+ // with push or a channel, the supervisor gets it and the requester never
186
+ // sees it, so they cannot approve their own change.
187
+ #linkVisible(entry) {
188
+ if (this.showLink === 'always') return true;
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;
192
+ const pushed = (this.pushInterests.length || this.pushUsers.length) && !entry.pushError;
193
+ return !(pushed || this.channel);
194
+ }
195
+
179
196
  #approvalBody(name, args, d, fp) {
180
197
  const sql = d.sql;
181
198
  const what = sql?.kinds?.length ? sql.kinds.join(', ') : name;
182
- const title = truncate(`${what} on ${this.label}`, 200);
199
+ const custom = !sql && this.preset?.title ? this.preset.title(name, args) : undefined;
200
+ const title = truncate(custom || `${what} on ${this.label}`, 200);
183
201
  const lines = [];
184
- lines.push(`Database: ${this.label}`);
202
+ lines.push(`${sql ? 'Database' : 'Service'}: ${this.label}`);
185
203
  lines.push(`Tool: ${name}`);
186
204
  if (sql?.kinds?.length) lines.push(`Changes: ${sql.kinds.join(', ')}`);
187
205
  for (const w of sql?.warnings ?? []) lines.push(`⚠ ${w}`);
@@ -199,6 +217,7 @@ export class Gate {
199
217
  agent: truncate(`Approval gate · ${this.label}`, 60),
200
218
  };
201
219
  if (this.options?.length) out.options = this.options;
220
+ if (this.approvers.length) out.approvers = this.approvers;
202
221
  if (this.channel) out.channel = this.channel;
203
222
  if (this.pushInterests.length) out.push_interests = this.pushInterests;
204
223
  else if (this.pushUsers.length) out.push_users = this.pushUsers;
@@ -228,7 +247,7 @@ export class Gate {
228
247
  if (state.status === 'approved') return this.#run(entry, state, extra);
229
248
  if (state.status === 'rejected' || state.status === 'expired') {
230
249
  this.#forget(entry);
231
- const how = state.status === 'expired' ? 'Nobody answered in time' : `The supervisor chose "${state.choice}"`;
250
+ const how = state.status === 'expired' ? 'Nobody answered in time' : `${state.answered_by?.name || state.answered_by?.email || 'The supervisor'} chose "${state.choice}"`;
232
251
  return errorResult(`${how}, so the call did not run.${state.comment ? ` Comment: ${state.comment}` : ''} Do not retry it unless the person asks.`);
233
252
  }
234
253
  if (Date.now() >= deadline) return pendingResult(entry, this.checkTool);
@@ -257,7 +276,8 @@ export class Gate {
257
276
  this.#forget(entry);
258
277
  this.log(`approval ${entry.id} approved (${state.choice}); running ${entry.name}`);
259
278
  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.` };
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.` };
261
281
  return { ...result, content: [...(result.content ?? []), note] };
262
282
  }
263
283
 
@@ -297,14 +317,28 @@ function otherArgs(args) {
297
317
  }
298
318
 
299
319
  function pendingResult(entry, checkTool) {
300
- const text = [
320
+ const text = entry.showLink ? [
301
321
  'Waiting for a supervisor to approve this call. Nothing has run yet.',
302
322
  `Approval link: ${entry.url}`,
303
323
  `approval_id: ${entry.id}`,
304
324
  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' } } };
325
+ `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.`,
326
+ ].filter(Boolean).join('\n') : [
327
+ 'A supervisor has been notified and must approve this call. Nothing has run yet.',
328
+ `approval_id: ${entry.id}`,
329
+ `When the person says it is decided, call ${checkTool} with this approval_id; it runs the call if it was approved.`,
330
+ ].join('\n');
331
+ const meta = { approval_id: entry.id, status: 'pending', ...(entry.showLink ? { url: entry.url } : {}) };
332
+ return { content: [{ type: 'text', text }], _meta: { 'io.hibira/approval': meta } };
333
+ }
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 } } };
308
342
  }
309
343
 
310
344
  function errorResult(text) {