@hibira-io/mcp-approval-gate 0.2.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.2.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.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;
@@ -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 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);
195
201
  const lines = [];
196
- lines.push(`Database: ${this.label}`);
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' : `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}"`;
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 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.` };
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
  }