@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/src/hook.js ADDED
@@ -0,0 +1,359 @@
1
+ // mcp-approval-gate hook: a command hook for coding agents (Claude Code
2
+ // PreToolUse, Codex PreToolUse, Cursor beforeShellExecution, Hermes Agent
3
+ // pre_tool_call). Risky shell
4
+ // commands wait until a second person approves them in a Hibira Approvals
5
+ // workspace; everything else runs as usual.
6
+
7
+ import { execFileSync } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { homedir, hostname } from 'node:os';
11
+ import { dirname, join } from 'node:path';
12
+ import { classifyShell } from './shell.js';
13
+ import { ApprovalsClient } from './hibira.js';
14
+ import { TokenStore, WorkspaceClient, configPath, DEFAULT_URL } from './connect.js';
15
+
16
+ export const AGENTS = { claude: 'Claude Code', codex: 'Codex', cursor: 'Cursor', hermes: 'Hermes Agent' };
17
+ const LOGIN = 'npx -y @hibira-io/mcp-approval-gate login --label "coding agent"';
18
+ const REJECT_MEMORY_MS = 15 * 60 * 1000;
19
+ const HERMES_MAX_WAIT = 280;
20
+
21
+ const HELP = `Usage:
22
+ mcp-approval-gate hook [claude|codex|cursor|hermes] run as the agent's hook (reads the hook JSON on stdin)
23
+ mcp-approval-gate hook check -- <command...> show whether a command would wait for approval
24
+
25
+ Shell commands that delete files, force-push, deploy, change infrastructure,
26
+ publish packages or write to a database wait for a second person to approve
27
+ them in your Hibira Approvals workspace. Connect once with:
28
+ ${LOGIN}
29
+
30
+ Settings (env, or ~/.config/hibira/approval-hook.json with the keys in brackets):
31
+ GATE_HOOK=off turn the hook off [enabled: false]
32
+ GATE_HOOK_ALWAYS regexes, one per line: also ask for these [always]
33
+ GATE_HOOK_NEVER regexes, one per line: never ask for these [never]
34
+ GATE_APPROVERS comma-separated approver emails or groups [approvers]
35
+ GATE_HOOK_WAIT seconds to wait for an answer, default 600 [wait]
36
+ GATE_EXPIRES_MINUTES how long a request stays open, default 30 [expires]
37
+ GATE_PROFILE which connected workspace to use, default "default" [profile]
38
+ GATE_LOGIN_COMMAND the connect command the agent tells the user to run (containers)
39
+ A project can add rules (never remove them) in .hibira/approval-hook.json: { "always": [...], "approvers": [...] }.
40
+ `;
41
+
42
+ /** Reads settings from the user's config file, the project's file and the environment. */
43
+ export function loadSettings(env = process.env, cwd = process.cwd()) {
44
+ const readJson = (p) => {
45
+ try {
46
+ const v = JSON.parse(readFileSync(p, 'utf8'));
47
+ return v && typeof v === 'object' ? v : {};
48
+ } catch {
49
+ return {};
50
+ }
51
+ };
52
+ const user = readJson(join(dirname(configPath(env)), 'approval-hook.json'));
53
+ const project = readJson(join(cwd, '.hibira', 'approval-hook.json'));
54
+ const lines = (v) => (v ?? '').split('\n').map((s) => s.trim()).filter(Boolean);
55
+ const arr = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
56
+ const num = (v, d, lo, hi) => {
57
+ const n = Number(v);
58
+ return v !== undefined && v !== '' && Number.isFinite(n) ? Math.min(hi, Math.max(lo, Math.floor(n))) : d;
59
+ };
60
+ return {
61
+ enabled: env.GATE_HOOK ? !/^(off|0|false|no)$/i.test(env.GATE_HOOK) : user.enabled !== false,
62
+ always: [...arr(user.always), ...arr(project.always), ...lines(env.GATE_HOOK_ALWAYS)],
63
+ never: [...arr(user.never), ...lines(env.GATE_HOOK_NEVER)],
64
+ approvers: env.GATE_APPROVERS ? env.GATE_APPROVERS.split(',').map((s) => s.trim()).filter(Boolean)
65
+ : arr(project.approvers).length ? arr(project.approvers) : arr(user.approvers),
66
+ waitSeconds: num(env.GATE_HOOK_WAIT ?? user.wait, 600, 0, 3600),
67
+ expiresMinutes: num(env.GATE_EXPIRES_MINUTES ?? user.expires, 30, 1, 10080),
68
+ profile: env.GATE_PROFILE || user.profile || 'default',
69
+ pushInterests: (env.GATE_PUSH_INTERESTS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
70
+ pushUsers: (env.GATE_PUSH_USERS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
71
+ channel: env.GATE_CHANNEL || undefined,
72
+ login: env.GATE_LOGIN_COMMAND || LOGIN,
73
+ };
74
+ }
75
+
76
+ /** Picks how to ask: app keys, a token from the environment, or the connected workspace. */
77
+ export function approvalsFromEnv(env, settings) {
78
+ if (env.HIBIRA_APP_ID || env.HIBIRA_KEY || env.HIBIRA_SECRET) {
79
+ return new ApprovalsClient({ appId: env.HIBIRA_APP_ID, key: env.HIBIRA_KEY, secret: env.HIBIRA_SECRET, baseUrl: env.HIBIRA_API_URL || undefined });
80
+ }
81
+ const baseUrl = env.HIBIRA_APPROVALS_URL || DEFAULT_URL;
82
+ if (env.HIBIRA_APPROVALS_TOKEN) return new WorkspaceClient({ token: env.HIBIRA_APPROVALS_TOKEN, baseUrl });
83
+ const saved = new TokenStore(configPath(env)).get(settings.profile);
84
+ if (saved?.token) return new WorkspaceClient({ token: saved.token, baseUrl: saved.url || baseUrl });
85
+ return undefined;
86
+ }
87
+
88
+ /** Which agent sent this input, and the shell command in it (undefined for other tools). */
89
+ export function readInput(input, client) {
90
+ if (!input || typeof input !== 'object') return {};
91
+ let agent = client;
92
+ if (!agent) {
93
+ if (input.hook_event_name === 'pre_tool_call') agent = 'hermes';
94
+ else if (input.hook_event_name === 'beforeShellExecution' || (typeof input.command === 'string' && !input.tool_name)) agent = 'cursor';
95
+ else if ('turn_id' in input) agent = 'codex';
96
+ else agent = 'claude';
97
+ }
98
+ if (agent === 'cursor') {
99
+ return { agent, command: typeof input.command === 'string' ? input.command : undefined, cwd: input.cwd || process.cwd() };
100
+ }
101
+ const shellTool = /^(Bash|Shell|shell|exec_command|local_shell|run_terminal_cmd|terminal)$/.test(input.tool_name ?? '');
102
+ let command = input.tool_input?.command;
103
+ if (Array.isArray(command)) command = command.join(' ');
104
+ return {
105
+ agent,
106
+ command: shellTool && typeof command === 'string' ? command : undefined,
107
+ cwd: input.cwd || process.cwd(),
108
+ };
109
+ }
110
+
111
+ /** What the agent is told. kind: pass | approved | deny. */
112
+ export function render(agent, { kind, reason, userMessage }) {
113
+ if (agent === 'cursor') {
114
+ if (kind === 'deny') return { permission: 'deny', user_message: userMessage ?? reason, agent_message: reason };
115
+ return kind === 'approved' ? { permission: 'allow', user_message: userMessage } : { permission: 'allow' };
116
+ }
117
+ if (agent === 'hermes') return kind === 'deny' ? { action: 'block', message: reason } : undefined;
118
+ if (kind === 'pass') return undefined;
119
+ if (kind === 'approved') return userMessage ? { systemMessage: userMessage } : undefined;
120
+ const out = { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } };
121
+ if (userMessage && agent === 'claude') out.systemMessage = userMessage;
122
+ return out;
123
+ }
124
+
125
+ class State {
126
+ constructor(path) {
127
+ this.path = path;
128
+ }
129
+
130
+ #read() {
131
+ try {
132
+ return JSON.parse(readFileSync(this.path, 'utf8')) ?? {};
133
+ } catch {
134
+ return {};
135
+ }
136
+ }
137
+
138
+ get(fp) {
139
+ return this.#read()[fp];
140
+ }
141
+
142
+ set(fp, value) {
143
+ const all = this.#read();
144
+ const now = Date.now();
145
+ for (const [k, v] of Object.entries(all)) if (!v?.at || now - v.at > 24 * 3600 * 1000) delete all[k];
146
+ if (value) all[fp] = { ...value, at: now };
147
+ else delete all[fp];
148
+ try {
149
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
150
+ writeFileSync(this.path, JSON.stringify(all), { mode: 0o600 });
151
+ } catch {
152
+ // A read-only home only costs a new request on the next try.
153
+ }
154
+ }
155
+ }
156
+
157
+ export function statePath(env = process.env) {
158
+ const dir = env.HIBIRA_STATE_DIR || join(env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'hibira');
159
+ return join(dir, 'approval-hook.json');
160
+ }
161
+
162
+ function gitInfo(cwd) {
163
+ const git = (...args) => {
164
+ try {
165
+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
166
+ } catch {
167
+ return '';
168
+ }
169
+ };
170
+ const remote = git('remote', 'get-url', 'origin').replace(/\/\/[^@/]*@/, '//');
171
+ const branch = git('rev-parse', '--abbrev-ref', 'HEAD');
172
+ return { remote, branch };
173
+ }
174
+
175
+ function shorten(s, n) {
176
+ const one = s.replace(/\s+/g, ' ').trim();
177
+ return one.length > n ? `${one.slice(0, n - 1)}…` : one;
178
+ }
179
+
180
+ /** The request a person sees in the Approvals inbox. */
181
+ export function requestBody({ agent, command, cwd, verdict, settings, git = gitInfo(cwd) }) {
182
+ const name = AGENTS[agent] ?? agent;
183
+ const lines = [`${name} wants to run:`, '', command.length > 4000 ? `${command.slice(0, 4000)}\n…` : command, ''];
184
+ const why = [...new Set(verdict.reasons.map((r) => (r.remote ? `${r.label} (on a remote machine)` : r.label)))];
185
+ lines.push(`Why it asks: ${why.join('; ')}`);
186
+ for (const w of verdict.warnings) lines.push(`⚠ ${w}`);
187
+ lines.push(`Folder: ${cwd}`);
188
+ if (git.remote) lines.push(`Repository: ${git.remote}${git.branch ? ` (${git.branch})` : ''}`);
189
+ lines.push(`Computer: ${hostname()}`);
190
+ const body = {
191
+ title: shorten(`${name}: ${command}`, 200),
192
+ details: lines.join('\n'),
193
+ expires_in_minutes: settings.expiresMinutes,
194
+ agent: name,
195
+ };
196
+ if (settings.approvers.length) body.approvers = settings.approvers;
197
+ if (settings.channel) body.channel = settings.channel;
198
+ if (settings.pushInterests.length) body.push_interests = settings.pushInterests;
199
+ else if (settings.pushUsers.length) body.push_users = settings.pushUsers;
200
+ return body;
201
+ }
202
+
203
+ function answeredBy(res) {
204
+ const by = res?.answered_by;
205
+ if (!by) return '';
206
+ return typeof by === 'string' ? by : by.name || by.email || '';
207
+ }
208
+
209
+ /**
210
+ * Decides one hook call. Returns { kind, reason, userMessage }.
211
+ * deps: { approvals, state, settings, now, sleep } for tests.
212
+ */
213
+ export async function decideHook({ agent, command, cwd }, deps) {
214
+ const { settings } = deps;
215
+ if (!command || !settings.enabled) return { kind: 'pass' };
216
+ const login = settings.login ?? LOGIN;
217
+ const verdict = classifyShell(command, settings);
218
+ if (!verdict.gate) return { kind: 'pass' };
219
+ const what = shorten(verdict.reasons.map((r) => r.label).join('; '), 160);
220
+ const approvals = deps.approvals;
221
+ if (!approvals) {
222
+ return {
223
+ kind: 'deny',
224
+ reason: `This command needs a second person's approval (${what}), but this computer is not connected to a Hibira Approvals workspace yet. ` +
225
+ `Ask the user to run \`${login}\` in a terminal, or run it yourself in the background and show the user the link and code it prints. ` +
226
+ 'Once it says connected, run the same command again. Do not try another way to do the same thing.',
227
+ userMessage: `Hibira Approvals: "${shorten(command, 80)}" needs approval. Connect this computer first: ${login}`,
228
+ };
229
+ }
230
+ const fp = createHash('sha256').update(JSON.stringify([cwd, command])).digest('hex');
231
+ const state = deps.state;
232
+ let entry = state.get(fp);
233
+ const now = deps.now?.() ?? Date.now();
234
+ if (entry?.status === 'rejected' && now - entry.at < REJECT_MEMORY_MS) return rejected(entry);
235
+ if (entry?.status === 'pending' && entry.expiresAt && Date.parse(entry.expiresAt) <= now) entry = undefined;
236
+ if (entry?.status !== 'pending') entry = undefined;
237
+
238
+ let created;
239
+ if (!entry) {
240
+ try {
241
+ created = await approvals.create(requestBody({ agent, command, cwd, verdict, settings, git: deps.git }));
242
+ } catch (err) {
243
+ if (err.status === 401) {
244
+ return { kind: 'deny', reason: `Hibira Approvals refused this computer's sign-in (it may have been disconnected). Ask the user to run \`${login}\` again, then retry the same command.` };
245
+ }
246
+ if (err.status === 402) {
247
+ return {
248
+ kind: 'deny',
249
+ reason: 'The Hibira Approvals workspace has used up its approval requests for this month, so this command was not run. Tell the user; do not try another way to do the same thing.',
250
+ userMessage: 'Hibira Approvals: this workspace is out of approval requests for the month. A workspace admin can upgrade the plan, or add safe commands to the "never" list in ~/.config/hibira/approval-hook.json.',
251
+ };
252
+ }
253
+ return { kind: 'deny', reason: `Could not ask for approval (${err.message}), so the command was not run. Tell the user; do not try another way.` };
254
+ }
255
+ entry = { status: 'pending', id: created.approval_id, url: created.url, expiresAt: created.expires_at };
256
+ state.set(fp, entry);
257
+ }
258
+
259
+ // Without a workspace or a push/channel, nobody else hears about the
260
+ // request: hand the link to the person at the keyboard and stop waiting.
261
+ const delivered = approvals.notifiesMembers || settings.channel || ((settings.pushInterests.length || settings.pushUsers.length) && !created?.push_error);
262
+ if (!delivered && entry.url) {
263
+ return {
264
+ kind: 'deny',
265
+ reason: `This command waits for approval (${what}). ${agent === 'claude' || agent === 'cursor' ? 'The user was shown the approval link.' : `Give the user this approval link to pass to whoever approves: ${entry.url}`} ` +
266
+ 'Do not try another way to do the same thing. When the user says it was approved, run exactly the same command again.',
267
+ userMessage: `Hibira Approvals: "${shorten(command, 80)}" waits for approval. Send this link to whoever approves: ${entry.url}`,
268
+ };
269
+ }
270
+
271
+ const deadline = now + settings.waitSeconds * 1000;
272
+ for (;;) {
273
+ let res;
274
+ const left = Math.ceil((deadline - (deps.now?.() ?? Date.now())) / 1000);
275
+ try {
276
+ res = await approvals.get(entry.id, Math.max(0, Math.min(25, left)));
277
+ } catch (err) {
278
+ if (err.status === 404) {
279
+ state.set(fp, undefined);
280
+ return { kind: 'deny', reason: 'The approval request is gone. Run the same command again to ask again.' };
281
+ }
282
+ if ((deps.now?.() ?? Date.now()) >= deadline) break;
283
+ await (deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(2000);
284
+ continue;
285
+ }
286
+ const status = res?.status;
287
+ if (status === 'approved') {
288
+ state.set(fp, undefined);
289
+ const by = answeredBy(res);
290
+ return { kind: 'approved', userMessage: `Hibira Approvals: approved${by ? ` by ${by}` : ''}.` };
291
+ }
292
+ if (status === 'rejected') {
293
+ const r = { status: 'rejected', by: answeredBy(res), comment: res.comment, choice: res.choice };
294
+ state.set(fp, r);
295
+ return rejected(r);
296
+ }
297
+ if (status === 'expired' || status === 'cancelled') {
298
+ state.set(fp, undefined);
299
+ return { kind: 'deny', reason: 'Nobody approved this command before the request expired, so it was not run. Tell the user; run it again only if they ask.' };
300
+ }
301
+ if ((deps.now?.() ?? Date.now()) >= deadline) break;
302
+ }
303
+ return {
304
+ kind: 'deny',
305
+ reason: `This command is waiting for a second person to approve it in Hibira Approvals (${what}); nobody has answered yet. ` +
306
+ 'Do not try another way to do the same thing. Tell the user it is waiting; when they say it was approved, run exactly the same command again.',
307
+ userMessage: `Hibira Approvals: still waiting for someone to approve "${shorten(command, 80)}".`,
308
+ };
309
+ }
310
+
311
+ function rejected(r) {
312
+ const by = r.by ? ` (${r.by})` : '';
313
+ const comment = r.comment ? `: "${r.comment}"` : '';
314
+ return {
315
+ kind: 'deny',
316
+ reason: `A supervisor${by} rejected this command in Hibira Approvals${comment}. Do not run it, or anything that does the same thing another way. Stop and tell the user.`,
317
+ userMessage: `Hibira Approvals: rejected${by}${comment}.`,
318
+ };
319
+ }
320
+
321
+ async function readStdin() {
322
+ const chunks = [];
323
+ for await (const c of process.stdin) chunks.push(c);
324
+ return Buffer.concat(chunks).toString('utf8');
325
+ }
326
+
327
+ export async function runHook(argv, env = process.env) {
328
+ if (argv[0] === '--help' || argv[0] === '-h') {
329
+ process.stdout.write(HELP);
330
+ return;
331
+ }
332
+ if (argv[0] === 'check') {
333
+ const rest = argv.slice(1);
334
+ const command = rest[0] === '--' ? rest.slice(1).join(' ') : rest.join(' ');
335
+ const settings = loadSettings(env);
336
+ const v = classifyShell(command, settings);
337
+ process.stdout.write(v.gate ? `asks for approval: ${v.reasons.map((r) => r.label).join('; ')}\n` : 'runs without asking\n');
338
+ return;
339
+ }
340
+ const client = argv[0] && argv[0] in AGENTS ? argv[0] : undefined;
341
+ let agent = client ?? 'claude';
342
+ let out;
343
+ try {
344
+ const input = readInput(JSON.parse(await readStdin()), client);
345
+ agent = input.agent ?? agent;
346
+ const settings = loadSettings(env, input.cwd);
347
+ // Hermes stops a hook after 300 seconds at most; answer before that.
348
+ if (agent === 'hermes') settings.waitSeconds = Math.min(settings.waitSeconds, HERMES_MAX_WAIT);
349
+ const needs = input.command && settings.enabled && classifyShell(input.command, settings).gate;
350
+ const decision = needs
351
+ ? await decideHook(input, { settings, approvals: approvalsFromEnv(env, settings), state: new State(statePath(env)) })
352
+ : { kind: 'pass' };
353
+ out = render(agent, decision);
354
+ } catch (err) {
355
+ // Fail closed: a broken hook must not let a risky command through.
356
+ out = render(agent, { kind: 'deny', reason: `The Hibira approval hook failed (${err.message}). Tell the user.` });
357
+ }
358
+ if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
359
+ }
package/src/policy.js CHANGED
@@ -24,8 +24,13 @@ export function sqlArguments(args) {
24
24
  return out;
25
25
  }
26
26
 
27
- function matches(list, name) {
28
- return list.some((p) => (p.endsWith('*') ? name.startsWith(p.slice(0, -1)) : p === name));
27
+ // A pattern is a tool name, a prefix ending in * or a suffix starting with *.
28
+ export function matches(list, name) {
29
+ return list.some((p) => {
30
+ if (p.endsWith('*')) return name.startsWith(p.slice(0, -1));
31
+ if (p.startsWith('*')) return name.endsWith(p.slice(1));
32
+ return p === name;
33
+ });
29
34
  }
30
35
 
31
36
  /**
@@ -33,9 +38,13 @@ function matches(list, name) {
33
38
  * annotations), or undefined if unknown. Returns { gate, reason, sql }
34
39
  * where sql is the classification when the call carries SQL.
35
40
  */
36
- export function decide({ name, args, tool, mode = 'writes', allowTools = [], gateTools = [] }) {
41
+ export function decide({ name, args, tool, mode = 'writes', allowTools = [], gateTools = [], preset }) {
37
42
  if (matches(gateTools, name)) return { gate: true, reason: 'tool is always gated' };
38
43
  if (matches(allowTools, name)) return { gate: false, reason: 'tool is always allowed' };
44
+ if (preset && mode === 'writes') {
45
+ if (matches(preset.gate ?? [], name)) return { gate: true, reason: `${preset.label} tool that changes something` };
46
+ if (matches(preset.allow ?? [], name)) return { gate: false, reason: `${preset.label} tool that only reads` };
47
+ }
39
48
  const sqls = sqlArguments(args);
40
49
  const sql = sqls.length ? classifySql(sqls.join(';\n')) : undefined;
41
50
  if (mode === 'all') return { gate: true, reason: 'every call is gated', sql };
package/src/presets.js ADDED
@@ -0,0 +1,85 @@
1
+ // Presets for well-known MCP servers that are not databases: which tools only
2
+ // read (so they never wait), which always wait, and a plain title for the
3
+ // approval page. Anything a preset does not name falls back to the usual
4
+ // rules (readOnlyHint, read-like names, otherwise it waits).
5
+
6
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
7
+ const first = (args, ...keys) => {
8
+ for (const k of keys) {
9
+ const v = args?.[k];
10
+ if (Array.isArray(v) && v.length) return v.map(String).join(', ');
11
+ if (str(v)) return str(v);
12
+ if (typeof v === 'number') return String(v);
13
+ }
14
+ return undefined;
15
+ };
16
+ const repo = (a) => (a?.owner && a?.repo ? `${a.owner}/${a.repo}` : first(a, 'repository', 'repo'));
17
+ const words = (name) => name.replace(/[_-]+/g, ' ');
18
+
19
+ export const PRESETS = {
20
+ // Stripe's hosted server (https://mcp.stripe.com): one generic write tool
21
+ // plus Treasury money movement.
22
+ stripe: {
23
+ label: 'Stripe',
24
+ allow: ['stripe_api_read', 'stripe_api_search', 'stripe_api_details', 'search_stripe_documentation',
25
+ 'stripe_analytics', 'stripe_implementation_planner', 'get_*'],
26
+ gate: ['stripe_api_write', 'send_money', 'transfer_money', 'convert_currency', 'setup_recipient', 'atlas_company_formation'],
27
+ title(name, a) {
28
+ if (name === 'stripe_api_write') {
29
+ const what = first(a, 'method', 'operation', 'api_method', 'name');
30
+ const path = first(a, 'path', 'endpoint', 'url', 'resource');
31
+ return `Stripe: ${[what, path].filter(Boolean).join(' ') || 'write'}`;
32
+ }
33
+ const amount = first(a, 'amount');
34
+ const currency = first(a, 'currency');
35
+ return `Stripe: ${words(name)}${amount ? ` ${amount}${currency ? ` ${currency.toUpperCase()}` : ''}` : ''}`;
36
+ },
37
+ },
38
+ // GitHub's MCP server (github/github-mcp-server).
39
+ github: {
40
+ label: 'GitHub',
41
+ allow: ['get_*', 'list_*', 'search_*', '*_read', 'actions_get', 'actions_list'],
42
+ gate: ['merge_pull_request', 'delete_file', 'push_files', 'create_or_update_file', 'create_repository',
43
+ 'fork_repository', 'actions_run_trigger', 'update_pull_request_branch', 'enable_pr_auto_merge'],
44
+ title(name, a) {
45
+ const r = repo(a);
46
+ const n = first(a, 'pullNumber', 'pull_number', 'issue_number', 'issueNumber');
47
+ const ref = first(a, 'branch', 'path', 'name');
48
+ return `GitHub: ${words(name)}${r ? ` ${r}` : ''}${n ? `#${n}` : ''}${!n && ref ? ` (${ref})` : ''}`;
49
+ },
50
+ },
51
+ // Google's Gmail MCP server: drafts are fine, anything that sends, deletes
52
+ // or changes filters waits.
53
+ gmail: {
54
+ label: 'Gmail',
55
+ allow: ['get_*', 'list_*', 'search_*', 'create_draft', 'update_draft'],
56
+ gate: ['send_message', 'send_draft', 'reply', 'forward', 'delete_*', 'trash_*', 'create_filter', 'update_label', 'delete_label'],
57
+ title(name, a) {
58
+ const to = first(a, 'to', 'recipients', 'recipient');
59
+ const subject = first(a, 'subject');
60
+ if (['send_message', 'send_draft', 'reply', 'forward'].includes(name)) {
61
+ return `Gmail: ${words(name)}${to ? ` to ${to}` : ''}${subject ? `: ${subject}` : ''}`;
62
+ }
63
+ return `Gmail: ${words(name)}`;
64
+ },
65
+ },
66
+ // Shopify store tools (product, discount, inventory and GraphQL Admin).
67
+ shopify: {
68
+ label: 'Shopify',
69
+ allow: ['get-*', 'get_*', 'list-*', 'search*', 'find-*', 'graphql_query', 'graphql_schema', 'run-analytics-query',
70
+ 'validate_graphql_codeblocks', 'search_docs_chunks'],
71
+ gate: ['graphql_mutation', 'create-*', 'update-*', 'bulk-*', 'set-*', 'add-to-*', 'delete-*', 'publish-*', 'upload*', 'import-*'],
72
+ title(name, a) {
73
+ const what = first(a, 'title', 'name', 'code', 'productId', 'id');
74
+ return `Shopify: ${words(name)}${what ? ` (${what})` : ''}`;
75
+ },
76
+ },
77
+ };
78
+
79
+ /** The preset called name, or throws listing the ones there are. */
80
+ export function preset(name) {
81
+ if (!name) return undefined;
82
+ const p = PRESETS[name.toLowerCase()];
83
+ if (!p) throw new Error(`unknown --preset "${name}"; one of ${Object.keys(PRESETS).join(', ')}`);
84
+ return p;
85
+ }