hmcp-gateway 0.0.2 → 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.
Files changed (102) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +41 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +351 -0
  24. package/dist/adopt-cli.js +1857 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +386 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +535 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +200 -0
  38. package/dist/client-config.js +784 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +49 -0
  44. package/dist/connect-client.js +249 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/draft.d.ts +71 -0
  50. package/dist/draft.js +596 -0
  51. package/dist/exposure-cli.d.ts +28 -0
  52. package/dist/exposure-cli.js +119 -0
  53. package/dist/gateway.d.ts +756 -0
  54. package/dist/gateway.js +2106 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +26 -0
  57. package/dist/notify.d.ts +44 -0
  58. package/dist/notify.js +93 -0
  59. package/dist/oauth.d.ts +139 -0
  60. package/dist/oauth.js +641 -0
  61. package/dist/observe.d.ts +10 -0
  62. package/dist/observe.js +26 -0
  63. package/dist/open.d.ts +24 -0
  64. package/dist/open.js +31 -0
  65. package/dist/packs.d.ts +119 -0
  66. package/dist/packs.js +131 -0
  67. package/dist/pin-cli.d.ts +28 -0
  68. package/dist/pin-cli.js +103 -0
  69. package/dist/probe-upstream.d.ts +31 -0
  70. package/dist/probe-upstream.js +377 -0
  71. package/dist/registry-map.d.ts +39 -0
  72. package/dist/registry-map.js +390 -0
  73. package/dist/rule-cli.d.ts +51 -0
  74. package/dist/rule-cli.js +412 -0
  75. package/dist/serve-http.d.ts +67 -0
  76. package/dist/serve-http.js +478 -0
  77. package/dist/snippet.d.ts +20 -0
  78. package/dist/snippet.js +826 -0
  79. package/dist/status-cli.d.ts +61 -0
  80. package/dist/status-cli.js +195 -0
  81. package/dist/suggest-cli.d.ts +43 -0
  82. package/dist/suggest-cli.js +279 -0
  83. package/dist/toolname.d.ts +47 -0
  84. package/dist/toolname.js +149 -0
  85. package/dist/upstream-errors.d.ts +54 -0
  86. package/dist/upstream-errors.js +330 -0
  87. package/dist/upstream.d.ts +128 -0
  88. package/dist/upstream.js +413 -0
  89. package/dist/version.d.ts +10 -0
  90. package/dist/version.js +11 -0
  91. package/package.json +50 -6
  92. package/packs/brave-search.yaml +20 -0
  93. package/packs/context7.yaml +13 -0
  94. package/packs/fetch.yaml +14 -0
  95. package/packs/filesystem.yaml +79 -0
  96. package/packs/git.yaml +29 -0
  97. package/packs/github.yaml +47 -0
  98. package/packs/huggingface.yaml +16 -0
  99. package/packs/memory.yaml +23 -0
  100. package/packs/playwright.yaml +41 -0
  101. package/packs/sequential-thinking.yaml +13 -0
  102. package/packs/time.yaml +14 -0
package/dist/cli.js ADDED
@@ -0,0 +1,535 @@
1
+ #!/usr/bin/env node
2
+ import { writeFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { Command } from "commander";
5
+ import { PolicyError, TenantError } from "hmcp-core";
6
+ import { escapeForDisplay, toSarif, toText } from "hmcp-scanner";
7
+ import { loadGatewayConfig } from "./config.js";
8
+ import { Gateway } from "./gateway.js";
9
+ import { serveHttp } from "./serve-http.js";
10
+ import { RuleCommandError, runRuleCommand } from "./rule-cli.js";
11
+ import { ExposureCommandError, runExposureCommand } from "./exposure-cli.js";
12
+ import { PinCommandError, runPinCommand } from "./pin-cli.js";
13
+ import { AdoptCommandError, runAdoptCommand, runRevertCommand } from "./adopt-cli.js";
14
+ import { VERSION } from "./version.js";
15
+ import { openGateway } from "./open.js";
16
+ import { runStatusCommand } from "./status-cli.js";
17
+ import { runSuggestCommand } from "./suggest-cli.js";
18
+ import { createInterface } from "node:readline/promises";
19
+ import { createNotifier } from "./notify.js";
20
+ const program = new Command();
21
+ /** Commander's accumulator for a repeatable option. */
22
+ function collect(value, previous) {
23
+ return [...previous, value];
24
+ }
25
+ program
26
+ .name("hmcp-gateway")
27
+ .description("Policy gateway between an agent and the MCP servers it uses.")
28
+ .version(VERSION);
29
+ program
30
+ .command("serve", { isDefault: true })
31
+ .description("Run the gateway over stdio, or over HTTP with --http.")
32
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
33
+ .option("--http [port]", "serve over Streamable HTTP on this port instead of stdio")
34
+ .option("--host <address>", "interface to bind when serving over HTTP", "127.0.0.1")
35
+ .option("--allow-host <name>", "a Host header this gateway will answer to; repeatable", (value, previous) => [...previous, value], [])
36
+ .option("--allow-origin <origin>", "a web origin allowed to connect over HTTP, e.g. http://localhost:6274; repeatable", (value, previous) => [...previous, value], [])
37
+ .action(async (options) => {
38
+ await run(async () => {
39
+ const { gateway, config, policy } = openGateway(options.config, {
40
+ notify: notifierFor(options.config, options.http !== undefined)
41
+ });
42
+ // Before anything else can scroll it away.
43
+ for (const line of gateway.notices())
44
+ warn(line);
45
+ let serving;
46
+ let stopping = false;
47
+ const shutdown = async () => {
48
+ if (stopping)
49
+ return;
50
+ stopping = true;
51
+ if (serving)
52
+ await serving.close();
53
+ await gateway.close();
54
+ process.exit(0);
55
+ };
56
+ process.on("SIGINT", shutdown);
57
+ process.on("SIGTERM", shutdown);
58
+ if (options.http !== undefined) {
59
+ /*
60
+ * One process, many clients. Everything the gateway enforces is the
61
+ * same -- these are the handlers the stdio path installs -- but the
62
+ * posture around it is not: stdio is reachable only by whoever
63
+ * spawned it, while this is a socket. It binds to loopback unless
64
+ * told otherwise, and answers only to the host names it was given.
65
+ */
66
+ const port = options.http === true ? 7878 : Number(options.http);
67
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
68
+ throw new Error(`--http needs a port number, not ${JSON.stringify(options.http)}`);
69
+ }
70
+ /*
71
+ * Degraded unless the config asks for strict: a server that will not
72
+ * connect is reported and retried, and the rest are served.
73
+ */
74
+ if (config.startup === "strict")
75
+ await gateway.connectUpstreams();
76
+ else
77
+ await gateway.connectUpstreamsDegraded(warn);
78
+ gateway.announceServing();
79
+ gateway.watchPolicy(warn);
80
+ gateway.watchConfig(warn);
81
+ const allowHosts = options.allowHost;
82
+ const allowOrigins = options.allowOrigin;
83
+ /*
84
+ * From the environment and never from a flag: a flag is visible in
85
+ * the process list and ends up in shell history.
86
+ */
87
+ const token = process.env["HMCP_GATEWAY_TOKEN"];
88
+ serving = await serveHttp(gateway, {
89
+ port,
90
+ host: options.host,
91
+ ...(allowHosts.length > 0 ? { allowedHosts: allowHosts } : {}),
92
+ ...(allowOrigins.length > 0 ? { allowedOrigins: allowOrigins } : {}),
93
+ ...(token ? { bearerToken: token } : {})
94
+ });
95
+ warn(`[hmcp-gateway] listening on http://${options.host}:${serving.port}/mcp`);
96
+ if (policy.tenant?.source.kind === "jwt-verified") {
97
+ warn(`[hmcp-gateway] callers are authenticated by a verified token (tenant.source)`);
98
+ }
99
+ else if (token) {
100
+ warn(`[hmcp-gateway] callers must present HMCP_GATEWAY_TOKEN as a bearer token`);
101
+ }
102
+ else {
103
+ warn(`[hmcp-gateway] no authentication: any process on this machine can call the tools this policy ` +
104
+ `allows. Set HMCP_GATEWAY_TOKEN to require a bearer token.`);
105
+ }
106
+ if (options.host !== "127.0.0.1" && allowHosts.length === 0) {
107
+ warn(`[hmcp-gateway] bound to ${options.host} but no --allow-host was given, so only ` +
108
+ `requests addressed to localhost will be answered. Pass --allow-host <name> for the ` +
109
+ `name clients will actually use.`);
110
+ }
111
+ }
112
+ else {
113
+ await gateway.start();
114
+ /*
115
+ * Over stdio the app is the only client, and when it goes -- quit, or
116
+ * killed outright -- its end of the pipe closes. The SDK's transport
117
+ * doesn't notice, so the toolbox and every server under it went on
118
+ * running with no one to serve (UT5). Its parent changing (to init)
119
+ * says the same thing on a platform where the pipe lingers.
120
+ */
121
+ const parent = process.ppid;
122
+ process.stdin.once("end", () => void shutdown());
123
+ process.stdin.once("close", () => void shutdown());
124
+ const orphanCheck = setInterval(() => {
125
+ if (process.ppid !== parent)
126
+ void shutdown();
127
+ }, 2_000);
128
+ orphanCheck.unref();
129
+ }
130
+ // stdio carries the protocol, so the startup summary goes to stderr.
131
+ const inventory = gateway.inventory();
132
+ const visible = inventory.filter((t) => !t.hidden);
133
+ const states = gateway.upstreamStates();
134
+ const working = states.filter((u) => u.state === "connected").length;
135
+ warn(`[hmcp-gateway] ${visible.length} of ${inventory.length} upstream tools exposed ` +
136
+ `across ${working} of ${config.upstreams.length} server(s); posture ${policy.defaults.mode}` +
137
+ (gateway.enforcement === "observe" ? " (OBSERVE MODE: not enforced)" : ""));
138
+ const unclassified = visible.filter((t) => t.effect === undefined);
139
+ if (unclassified.length > 0) {
140
+ const fate = policy.defaults.on_unclassified === "deny" ? "refused" : "held for approval";
141
+ warn(`[hmcp-gateway] ${unclassified.length} tool(s) are unclassified and ` +
142
+ // In observe mode they run like everything else; say what would happen instead.
143
+ `${gateway.enforcement === "observe" ? `would be ${fate} under enforcement` : `will be ${fate}`}: ` +
144
+ unclassified.map((t) => t.localName).join(", "));
145
+ }
146
+ for (const entry of inventory) {
147
+ if (!entry.injection)
148
+ continue;
149
+ warn(`[hmcp-gateway] ${entry.localName}: injection in the upstream's advertised text ` +
150
+ `(${entry.injection.patternIds.join(", ")}) - ${entry.injection.action}`);
151
+ }
152
+ });
153
+ });
154
+ program
155
+ .command("tools")
156
+ .description("List what the gateway would expose, and how it classified each tool.")
157
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
158
+ .option("--json", "emit JSON", false)
159
+ .action(async (options) => {
160
+ await run(async () => {
161
+ const { gateway, config, policy } = openGateway(options.config);
162
+ try {
163
+ // Inspection needs the connect-and-classify phases only, not a stdio
164
+ // session, so the inventory is built and then torn down.
165
+ await gateway.connectUpstreams();
166
+ const inventory = gateway.inventory();
167
+ const off = gateway.switchedOffTools();
168
+ if (options.json) {
169
+ log(JSON.stringify(inventory.map((t) => ({
170
+ name: t.localName,
171
+ server: t.upstream.spec.name,
172
+ upstreamName: t.tool.name,
173
+ effect: t.effect ?? null,
174
+ effectSource: t.effectSource,
175
+ hidden: t.hidden,
176
+ switchedOff: off.has(t.localName),
177
+ injection: t.injection
178
+ })), null, 2));
179
+ return;
180
+ }
181
+ log(`${inventory.length} upstream tool(s):`);
182
+ log("");
183
+ for (const entry of inventory) {
184
+ const effect = entry.effect ?? "unclassified";
185
+ const flags = [
186
+ off.has(entry.localName) ? "switched off" : null,
187
+ entry.hidden ? "hidden" : null,
188
+ entry.injection ? `injection:${entry.injection.action}` : null
189
+ ].filter(Boolean);
190
+ log(` ${entry.localName.padEnd(40)} ${effect.padEnd(13)} (${entry.effectSource})` +
191
+ (flags.length > 0 ? ` [${flags.join(", ")}]` : ""));
192
+ }
193
+ }
194
+ finally {
195
+ await gateway.close();
196
+ }
197
+ });
198
+ });
199
+ program
200
+ .command("status")
201
+ .description("Whether this gateway is running, which mode it is in, and what is waiting.")
202
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
203
+ .option("--json", "emit JSON", false)
204
+ .action(async (options) => {
205
+ await run(async () => {
206
+ await runStatusCommand({ config: options.config, json: options.json, write: log });
207
+ });
208
+ });
209
+ program
210
+ .command("suggest")
211
+ .description("What enforcing would have done to the calls observed so far, and rules that fit them.")
212
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
213
+ .option("--since <timestamp>", "only calls at or after this ISO 8601 time")
214
+ .option("--json", "emit JSON", false)
215
+ .action(async (options) => {
216
+ await run(async () => {
217
+ await runSuggestCommand({
218
+ config: options.config,
219
+ ...(options.since ? { since: options.since } : {}),
220
+ json: options.json,
221
+ write: log
222
+ });
223
+ });
224
+ });
225
+ const pin = program
226
+ .command("pin")
227
+ .description("What each upstream advertised when it was last looked at, and accepting a change to it.");
228
+ pin
229
+ .command("list")
230
+ .description("Show any tool that advertises something different from what was pinned.")
231
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
232
+ .option("--json", "emit JSON", false)
233
+ .action(async (options) => {
234
+ await run(async () => {
235
+ await runPinCommand({
236
+ config: options["config"],
237
+ action: "list",
238
+ ...(options["json"] !== undefined ? { json: options["json"] } : {}),
239
+ write: log
240
+ });
241
+ });
242
+ });
243
+ pin
244
+ .command("accept")
245
+ .argument("[tool]", "the tool whose current contract becomes the pin")
246
+ .description("Record what a tool advertises now as what this gateway expects.")
247
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
248
+ .option("--all", "accept every tool's current contract", false)
249
+ .option("--by <name>", "who reviewed it, for the record")
250
+ .action(async (tool, options) => {
251
+ await run(async () => {
252
+ await runPinCommand({
253
+ config: options["config"],
254
+ action: "accept",
255
+ ...(tool !== undefined ? { tool } : {}),
256
+ ...(options["all"] !== undefined ? { all: options["all"] } : {}),
257
+ ...(options["by"] !== undefined ? { by: options["by"] } : {}),
258
+ write: log
259
+ });
260
+ });
261
+ });
262
+ const exposure = program
263
+ .command("exposure")
264
+ .description("Switch one of this gateway's tools off, or hand it back to policy.");
265
+ /*
266
+ * Commander passes `(options, command)` for a command with no argument and
267
+ * `(arg, options, command)` for one with. Telling them apart by position is
268
+ * how `list` came to read the Command object as its options; the argument's
269
+ * type is the thing that actually distinguishes them.
270
+ */
271
+ function exposureAction(action) {
272
+ return async (first, second) => {
273
+ const tool = typeof first === "string" ? first : undefined;
274
+ const options = ((tool === undefined ? first : second) ?? {});
275
+ await run(async () => {
276
+ await runExposureCommand({
277
+ config: options["config"],
278
+ action,
279
+ ...(tool !== undefined ? { tool } : {}),
280
+ ...(options["tenant"] !== undefined ? { tenant: options["tenant"] } : {}),
281
+ ...(options["reason"] !== undefined ? { reason: options["reason"] } : {}),
282
+ ...(options["force"] !== undefined ? { force: options["force"] } : {}),
283
+ ...(options["json"] !== undefined ? { json: options["json"] } : {}),
284
+ write: log
285
+ });
286
+ });
287
+ };
288
+ }
289
+ exposure
290
+ .command("list")
291
+ .description("Show which tools are switched off.")
292
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
293
+ .option("--tenant <id>", "whose switches to show")
294
+ .option("--json", "emit JSON", false)
295
+ .action(exposureAction("list"));
296
+ exposure
297
+ .command("off <tool>")
298
+ .description("Withdraw a tool from the model and refuse every call to it.")
299
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
300
+ .option("--tenant <id>", "whose switch to flip")
301
+ .option("--reason <text>", "recorded in the audit log")
302
+ .option("--force", "do not connect upstreams to check the tool name", false)
303
+ .action(exposureAction("off"));
304
+ exposure
305
+ .command("on <tool>")
306
+ .description("Clear the override and let policy decide again.")
307
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
308
+ .option("--tenant <id>", "whose switch to flip")
309
+ .option("--force", "do not connect upstreams to check the tool name", false)
310
+ .action(exposureAction("on"));
311
+ /*
312
+ * The terminal half of the console's per-tool rule dialog.
313
+ *
314
+ * `[tool]` is optional so the bare command lists what is unclassified and what
315
+ * has been set — the question someone has before they have a tool name.
316
+ *
317
+ * `classify` stays as an alias, and not out of politeness: the refusal handed
318
+ * to the *model* for an unclassified tool names it, so an agent reports that
319
+ * string to a human who then types it.
320
+ */
321
+ function ruleAction(forcedClear = false) {
322
+ return async (tool, options) => {
323
+ await run(async () => {
324
+ await runRuleCommand({
325
+ config: options["config"],
326
+ ...(tool !== undefined ? { tool } : {}),
327
+ ...(options["effect"] !== undefined ? { effect: options["effect"] } : {}),
328
+ ...(options["decision"] !== undefined ? { decision: options["decision"] } : {}),
329
+ ...(options["reason"] !== undefined ? { reason: options["reason"] } : {}),
330
+ ...(options["bound"] !== undefined ? { bound: options["bound"] } : {}),
331
+ ...(options["onViolation"] !== undefined ? { onViolation: options["onViolation"] } : {}),
332
+ ...(options["unknownArgs"] !== undefined ? { unknownArgs: options["unknownArgs"] } : {}),
333
+ ...(options["keepBounds"] !== undefined ? { keepBounds: options["keepBounds"] } : {}),
334
+ ...(options["dropBounds"] !== undefined ? { dropBounds: options["dropBounds"] } : {}),
335
+ ...(options["overrideDeny"] !== undefined ? { overrideDeny: options["overrideDeny"] } : {}),
336
+ ...(forcedClear || options["clear"] ? { clear: true } : {}),
337
+ ...(options["list"] !== undefined ? { list: options["list"] } : {}),
338
+ ...(options["dryRun"] !== undefined ? { dryRun: options["dryRun"] } : {}),
339
+ ...(options["yesReally"] !== undefined ? { yesReally: options["yesReally"] } : {}),
340
+ ...(options["json"] !== undefined ? { json: options["json"] } : {}),
341
+ write: log
342
+ });
343
+ });
344
+ };
345
+ }
346
+ function withRuleOptions(command) {
347
+ return command
348
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
349
+ .option("--effect <kind>", "read | write | destructive")
350
+ .option("--decision <kind>", "allow | approve | deny")
351
+ .option("--reason <text>", "recorded in the rule, the log, and told to the model on a refusal")
352
+ .option("--bound <path.key=value>", "argument bound, repeatable", collect, [])
353
+ .option("--on-violation <kind>", "what a call outside the bounds gets: deny | approve")
354
+ .option("--unknown-args <kind>", "an argument no bound claims: allow | deny | approve")
355
+ .option("--keep-bounds", "carry the bounds the governing rule sets", false)
356
+ .option("--drop-bounds", "write a rule with no bounds, even where bounds exist today", false)
357
+ .option("--override-deny <rule-id>", "name the rule whose decision this reverses")
358
+ .option("--clear", "remove the rule set from here and hand the tool back to policy", false)
359
+ .option("--list", "show what is unclassified and what has been set", false)
360
+ .option("--dry-run", "print the rule and the outcome, write nothing", false)
361
+ .option("--yes-really", "required to let a destructive tool run with nobody asked", false)
362
+ .option("--json", "emit JSON", false);
363
+ }
364
+ withRuleOptions(program.command("rule [tool]").description("Set what a tool may do, or hand it back to policy.")).action(ruleAction());
365
+ withRuleOptions(program
366
+ .command("classify [tool]")
367
+ .description("Say what an unclassified tool does. An alias for `rule`.")).action(ruleAction());
368
+ program
369
+ .command("adopt")
370
+ .description("Put this gateway in front of the MCP servers a client already has configured.")
371
+ .option("--apply", "write the files and edit the client config; without it, only report", false)
372
+ .option("--revert", "restore the servers this command replaced", false)
373
+ .option("--scope <scope>", "project | local | user; detected when there is only one")
374
+ .option("--name <pair>", "rename an upstream: <original>=<name>; repeatable", collect, [])
375
+ .option("--gateway-name <name>", "the gateway's name, which names it in the audit log", "claude-code")
376
+ .option("--entry-name <name>", "what to call the gateway in the client's config", "hmcp")
377
+ .option("--posture <mode>", "read-only | approve-writes | locked", "approve-writes")
378
+ .option("--mode <mode>", "observe | enforce; asked for when applying at a terminal, otherwise observe")
379
+ .option("--on-unclassified <kind>", "what a tool nothing classified gets: approve (default) | deny")
380
+ .option("--no-packs", "do not write the ready-made classification for a server adopt recognises")
381
+ .option("--client-allow", "allow the gateway's tools in the client's own settings, so you are not asked twice")
382
+ .option("--no-client-allow", "leave the client's own permission settings alone, without asking")
383
+ .option("--copy-env", "resolve ${VAR} now and write literal values into gateway.yaml", false)
384
+ .option("--allow-local-http", "adopt HTTP upstreams on loopback, relaxing the SSRF guard", false)
385
+ .option("--strict-egress", "pin seeded egress entries to the upstream's port", false)
386
+ .option("--local", "point the client at this build on disk instead of a published version")
387
+ .option("--pin <version>", "the published version to pin in the client's config")
388
+ .option("--relative-config", "write a relative -c path, for a config meant to be shared", false)
389
+ .option("--out-dir <dir>", "where to write gateway.yaml and policy.yaml")
390
+ .option("--no-register", "do not add this gateway to the console's registry")
391
+ .option("--id <id>", "the registry id to use")
392
+ .option("--registry <file>", "the console's server registry")
393
+ .option("--purge", "with --revert, also delete the generated files", false)
394
+ .action(async (options) => {
395
+ await run(async () => {
396
+ const shared = {
397
+ scope: options.scope,
398
+ registry: options.registry,
399
+ write: log
400
+ };
401
+ if (options.revert) {
402
+ await runRevertCommand({ ...shared, purge: options.purge });
403
+ return;
404
+ }
405
+ const mode = options.mode;
406
+ if (mode !== undefined && mode !== "observe" && mode !== "enforce") {
407
+ throw new Error(`--mode must be observe or enforce, not ${JSON.stringify(mode)}`);
408
+ }
409
+ const onUnclassified = options.onUnclassified;
410
+ if (onUnclassified !== undefined && onUnclassified !== "approve" && onUnclassified !== "deny") {
411
+ throw new Error(`--on-unclassified must be approve or deny, not ${JSON.stringify(onUnclassified)}`);
412
+ }
413
+ await runAdoptCommand({
414
+ ...shared,
415
+ ...(mode ? { mode } : {}),
416
+ ...(onUnclassified ? { onUnclassified } : {}),
417
+ ...(options.clientAllow !== undefined ? { clientAllow: options.clientAllow } : {}),
418
+ // Only when a person is at both ends of the terminal. Piped or
419
+ // scripted, there is nobody to answer, and the default is used.
420
+ ...(process.stdin.isTTY && process.stdout.isTTY ? { ask: askOnTerminal } : {}),
421
+ apply: options.apply,
422
+ name: options.gatewayName,
423
+ entryName: options.entryName,
424
+ posture: options.posture,
425
+ // Commander gives `packs: false` for --no-packs.
426
+ ...(options.packs === false ? { noPacks: true } : {}),
427
+ copyEnv: options.copyEnv,
428
+ allowLocalHttp: options.allowLocalHttp,
429
+ strictEgress: options.strictEgress,
430
+ names: options.name,
431
+ local: options.local,
432
+ pinVersion: options.pin,
433
+ relativeConfig: options.relativeConfig,
434
+ outDir: options.outDir,
435
+ register: options.register,
436
+ id: options.id
437
+ });
438
+ });
439
+ });
440
+ program
441
+ .command("scan")
442
+ .description("Scan every upstream server's advertised tool surface.")
443
+ .option("-c, --config <file>", "gateway config", "gateway.yaml")
444
+ .option("--sarif <file>", "also write SARIF")
445
+ .option("--allow-high", "exit 0 even when a high-severity finding is reported", false)
446
+ .action(async (options) => {
447
+ await run(async () => {
448
+ const { gateway, config, policy } = openGateway(options.config);
449
+ try {
450
+ await gateway.connectUpstreams();
451
+ const result = gateway.scanUpstreams();
452
+ process.stdout.write(toText(result, "upstream MCP servers"));
453
+ if (options.sarif) {
454
+ writeFileSync(resolve(options.sarif), toSarif(result, "upstream MCP servers"), "utf8");
455
+ log(`SARIF written to ${options.sarif}`);
456
+ }
457
+ if (!result.ok && !options.allowHigh)
458
+ process.exitCode = 1;
459
+ }
460
+ finally {
461
+ await gateway.close();
462
+ }
463
+ });
464
+ });
465
+ /*
466
+ * Every line this command prints passes through here, and some of it is text a
467
+ * server we do not control chose: a tool name, an upstream's own description,
468
+ * an actor from a token. A control sequence in any of those rewrites the
469
+ * terminal -- `ESC[2J ESC[1;1H` clears the screen and homes the cursor, so an
470
+ * upstream could print a clean-looking report over the real one. JSON escapes
471
+ * these on the way to disk, so the log file is safe to `cat`; it is parsing it
472
+ * back and printing it that is not.
473
+ *
474
+ * Done at the one place everything funnels through rather than at each call
475
+ * site, because a new line of output should not be able to reintroduce this by
476
+ * forgetting. Nothing here prints colour, so there is no legitimate escape to
477
+ * preserve.
478
+ */
479
+ /**
480
+ * The desktop notifier for a serving gateway, or undefined for none.
481
+ *
482
+ * `HMCP_NOTIFY` decides if it is set, then the config's `notify`, then the
483
+ * transport: over stdio the gateway is on someone's own machine, and over
484
+ * HTTP it usually is not.
485
+ */
486
+ function notifierFor(configPath, overHttp) {
487
+ const env = process.env["HMCP_NOTIFY"];
488
+ let enabled = env === undefined ? undefined : !["0", "false", "off", "no", ""].includes(env.toLowerCase());
489
+ if (enabled === undefined) {
490
+ try {
491
+ enabled = loadGatewayConfig(configPath).config.notify;
492
+ }
493
+ catch {
494
+ /* the real load, a line later, reports a config that does not parse */
495
+ }
496
+ }
497
+ return (enabled ?? !overHttp) ? createNotifier() : undefined;
498
+ }
499
+ /** Asks one question on the terminal and returns the line typed. */
500
+ async function askOnTerminal(question) {
501
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
502
+ try {
503
+ return await rl.question(question);
504
+ }
505
+ finally {
506
+ rl.close();
507
+ }
508
+ }
509
+ function log(message) {
510
+ process.stdout.write(`${escapeForDisplay(message)}\n`);
511
+ }
512
+ function warn(message) {
513
+ process.stderr.write(`${escapeForDisplay(message)}\n`);
514
+ }
515
+ async function run(fn) {
516
+ try {
517
+ await fn();
518
+ }
519
+ catch (err) {
520
+ if (err instanceof ExposureCommandError ||
521
+ err instanceof AdoptCommandError ||
522
+ err instanceof RuleCommandError ||
523
+ err instanceof PinCommandError) {
524
+ warn(`error: ${err.message}`);
525
+ process.exit(1);
526
+ }
527
+ if (err instanceof PolicyError || err instanceof TenantError || err?.name === "EgressDenied") {
528
+ warn(`\nerror: ${err.message}`);
529
+ process.exit(1);
530
+ }
531
+ warn(`\nerror: ${err?.message ?? String(err)}`);
532
+ process.exit(1);
533
+ }
534
+ }
535
+ await program.parseAsync(process.argv);
@@ -0,0 +1,42 @@
1
+ import { type ScopeOptions, type ScopeTarget } from "./client-config.js";
2
+ /**
3
+ * The client's own permission to call the gateway's tools.
4
+ *
5
+ * Claude Code asks before it calls an MCP tool it has not been told to allow.
6
+ * Behind an enforcing gateway that question is redundant for every tool the
7
+ * gateway fronts: the gateway decides each call, and holds the ones a person
8
+ * should see. Being asked twice about one write is how people learn to click
9
+ * through, so `adopt` can add one allow rule covering the gateway's tools.
10
+ *
11
+ * It is a change to the *client's* settings, which is why it is offered and
12
+ * explained rather than done, why it is refused while the gateway is only
13
+ * observing -- the client's prompt is then the only thing asking -- and why
14
+ * `adopt --revert` takes it back out.
15
+ */
16
+ /**
17
+ * Where the rule goes for the scope that was adopted.
18
+ *
19
+ * A project's `.mcp.json` and the per-project block in `~/.claude.json` both
20
+ * get the project's *local* settings file, which Claude Code keeps out of
21
+ * version control: an allow rule is one person's choice about their own
22
+ * prompts, not something to commit for a team. User-wide servers get the
23
+ * user-wide settings.
24
+ */
25
+ export declare function clientSettingsPath(target: ScopeTarget, options?: ScopeOptions): string;
26
+ /**
27
+ * The rule that allows every tool the gateway's entry serves.
28
+ *
29
+ * The bare `mcp__<server>` form rather than `mcp__<server>__*`: both are
30
+ * documented, and the bare one is the one that has matched consistently.
31
+ */
32
+ export declare function allowRuleFor(entryName: string): string;
33
+ type Settings = Record<string, unknown> & {
34
+ permissions?: Record<string, unknown>;
35
+ };
36
+ /** The settings file as an object, `{}` if it does not exist. Throws rather than guess at a file it cannot read. */
37
+ export declare function readClientSettings(path: string): Settings;
38
+ /** Adds the rule. False, and nothing written, when it was already there. */
39
+ export declare function addAllowRule(path: string, rule: string): boolean;
40
+ /** Removes the rule. False when it was not there. */
41
+ export declare function removeAllowRule(path: string, rule: string): boolean;
42
+ export {};
@@ -0,0 +1,95 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { ClientConfigError } from "./client-config.js";
5
+ /**
6
+ * The client's own permission to call the gateway's tools.
7
+ *
8
+ * Claude Code asks before it calls an MCP tool it has not been told to allow.
9
+ * Behind an enforcing gateway that question is redundant for every tool the
10
+ * gateway fronts: the gateway decides each call, and holds the ones a person
11
+ * should see. Being asked twice about one write is how people learn to click
12
+ * through, so `adopt` can add one allow rule covering the gateway's tools.
13
+ *
14
+ * It is a change to the *client's* settings, which is why it is offered and
15
+ * explained rather than done, why it is refused while the gateway is only
16
+ * observing -- the client's prompt is then the only thing asking -- and why
17
+ * `adopt --revert` takes it back out.
18
+ */
19
+ /**
20
+ * Where the rule goes for the scope that was adopted.
21
+ *
22
+ * A project's `.mcp.json` and the per-project block in `~/.claude.json` both
23
+ * get the project's *local* settings file, which Claude Code keeps out of
24
+ * version control: an allow rule is one person's choice about their own
25
+ * prompts, not something to commit for a team. User-wide servers get the
26
+ * user-wide settings.
27
+ */
28
+ export function clientSettingsPath(target, options = {}) {
29
+ const home = resolve(options.home ?? homedir());
30
+ const cwd = resolve(options.cwd ?? process.cwd());
31
+ return target.scope === "user"
32
+ ? join(home, ".claude", "settings.json")
33
+ : join(cwd, ".claude", "settings.local.json");
34
+ }
35
+ /**
36
+ * The rule that allows every tool the gateway's entry serves.
37
+ *
38
+ * The bare `mcp__<server>` form rather than `mcp__<server>__*`: both are
39
+ * documented, and the bare one is the one that has matched consistently.
40
+ */
41
+ export function allowRuleFor(entryName) {
42
+ return `mcp__${entryName}`;
43
+ }
44
+ /** The settings file as an object, `{}` if it does not exist. Throws rather than guess at a file it cannot read. */
45
+ export function readClientSettings(path) {
46
+ if (!existsSync(path))
47
+ return {};
48
+ let parsed;
49
+ try {
50
+ parsed = JSON.parse(readFileSync(path, "utf8"));
51
+ }
52
+ catch (err) {
53
+ throw new ClientConfigError(`${path} is not valid JSON (${err.message}), so the allow rule cannot be added to it. ` +
54
+ `Fix that file, or leave the rule out and add it by hand.`);
55
+ }
56
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
57
+ throw new ClientConfigError(`${path} does not hold a JSON object, so the allow rule cannot be added to it.`);
58
+ }
59
+ const permissions = parsed.permissions;
60
+ if (permissions !== undefined && (typeof permissions !== "object" || permissions === null || Array.isArray(permissions))) {
61
+ throw new ClientConfigError(`"permissions" in ${path} is not an object, so the allow rule cannot be added to it.`);
62
+ }
63
+ const allow = permissions?.["allow"];
64
+ if (allow !== undefined && !Array.isArray(allow)) {
65
+ throw new ClientConfigError(`"permissions.allow" in ${path} is not a list, so the allow rule cannot be added to it.`);
66
+ }
67
+ return parsed;
68
+ }
69
+ function writeSettings(path, settings) {
70
+ mkdirSync(dirname(path), { recursive: true });
71
+ writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
72
+ }
73
+ /** Adds the rule. False, and nothing written, when it was already there. */
74
+ export function addAllowRule(path, rule) {
75
+ const settings = readClientSettings(path);
76
+ const allow = settings.permissions?.["allow"] ?? [];
77
+ if (allow.includes(rule))
78
+ return false;
79
+ writeSettings(path, { ...settings, permissions: { ...(settings.permissions ?? {}), allow: [...allow, rule] } });
80
+ return true;
81
+ }
82
+ /** Removes the rule. False when it was not there. */
83
+ export function removeAllowRule(path, rule) {
84
+ if (!existsSync(path))
85
+ return false;
86
+ const settings = readClientSettings(path);
87
+ const allow = settings.permissions?.["allow"] ?? [];
88
+ if (!allow.includes(rule))
89
+ return false;
90
+ writeSettings(path, {
91
+ ...settings,
92
+ permissions: { ...(settings.permissions ?? {}), allow: allow.filter((r) => r !== rule) }
93
+ });
94
+ return true;
95
+ }