hmcp-gateway 0.0.2 → 0.2.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 (114) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +135 -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 +355 -0
  24. package/dist/adopt-cli.js +1885 -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 +501 -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 +656 -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 +263 -0
  38. package/dist/client-config.js +995 -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 +51 -0
  44. package/dist/connect-client.js +299 -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/desktop-extensions.d.ts +53 -0
  50. package/dist/desktop-extensions.js +126 -0
  51. package/dist/draft.d.ts +71 -0
  52. package/dist/draft.js +596 -0
  53. package/dist/exposure-cli.d.ts +28 -0
  54. package/dist/exposure-cli.js +119 -0
  55. package/dist/gateway.d.ts +766 -0
  56. package/dist/gateway.js +2122 -0
  57. package/dist/github-doors.d.ts +162 -0
  58. package/dist/github-doors.js +780 -0
  59. package/dist/guard-install.d.ts +109 -0
  60. package/dist/guard-install.js +396 -0
  61. package/dist/guard.d.ts +265 -0
  62. package/dist/guard.js +975 -0
  63. package/dist/import-client.d.ts +184 -0
  64. package/dist/import-client.js +578 -0
  65. package/dist/index.d.ts +31 -0
  66. package/dist/index.js +31 -0
  67. package/dist/notify.d.ts +44 -0
  68. package/dist/notify.js +93 -0
  69. package/dist/oauth.d.ts +139 -0
  70. package/dist/oauth.js +641 -0
  71. package/dist/observe.d.ts +10 -0
  72. package/dist/observe.js +26 -0
  73. package/dist/open.d.ts +24 -0
  74. package/dist/open.js +31 -0
  75. package/dist/packs.d.ts +119 -0
  76. package/dist/packs.js +131 -0
  77. package/dist/pin-cli.d.ts +28 -0
  78. package/dist/pin-cli.js +103 -0
  79. package/dist/probe-upstream.d.ts +31 -0
  80. package/dist/probe-upstream.js +377 -0
  81. package/dist/registry-map.d.ts +39 -0
  82. package/dist/registry-map.js +390 -0
  83. package/dist/rule-cli.d.ts +51 -0
  84. package/dist/rule-cli.js +412 -0
  85. package/dist/serve-http.d.ts +67 -0
  86. package/dist/serve-http.js +478 -0
  87. package/dist/snippet.d.ts +20 -0
  88. package/dist/snippet.js +826 -0
  89. package/dist/status-cli.d.ts +61 -0
  90. package/dist/status-cli.js +195 -0
  91. package/dist/suggest-cli.d.ts +43 -0
  92. package/dist/suggest-cli.js +279 -0
  93. package/dist/toml-edit.d.ts +43 -0
  94. package/dist/toml-edit.js +363 -0
  95. package/dist/toolname.d.ts +47 -0
  96. package/dist/toolname.js +149 -0
  97. package/dist/upstream-errors.d.ts +54 -0
  98. package/dist/upstream-errors.js +330 -0
  99. package/dist/upstream.d.ts +128 -0
  100. package/dist/upstream.js +413 -0
  101. package/dist/version.d.ts +10 -0
  102. package/dist/version.js +11 -0
  103. package/package.json +51 -6
  104. package/packs/brave-search.yaml +20 -0
  105. package/packs/context7.yaml +13 -0
  106. package/packs/fetch.yaml +14 -0
  107. package/packs/filesystem.yaml +79 -0
  108. package/packs/git.yaml +29 -0
  109. package/packs/github.yaml +47 -0
  110. package/packs/huggingface.yaml +16 -0
  111. package/packs/memory.yaml +23 -0
  112. package/packs/playwright.yaml +41 -0
  113. package/packs/sequential-thinking.yaml +13 -0
  114. package/packs/time.yaml +14 -0
@@ -0,0 +1,412 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { ApprovalStore, AuditLog, TOOL_RULE_CLEAR, TOOL_RULE_SET, TOOL_RULE_UPDATE, clearToolRule, parseToolRuleDraft, policyDigest, previewClearToolRule, previewToolRule, ruleToYaml, runtimeStateIsLive, writeToolRule } from "hmcp-core";
5
+ import { loadGatewayConfig } from "./config.js";
6
+ export class RuleCommandError extends Error {
7
+ }
8
+ /**
9
+ * `--bound body.maxLength=120` into a constraint.
10
+ *
11
+ * Only the handful of keys the console's editor offers. `pattern` and `coerce`
12
+ * are refused by the writer itself, with a reason; naming them here would just
13
+ * produce a worse error message than the one it gives.
14
+ */
15
+ const BOUND_KEYS = ["max", "min", "maxLength", "maxItems", "sum_max", "count_max", "enum", "optional"];
16
+ export function parseBound(spec, into) {
17
+ const eq = spec.indexOf("=");
18
+ if (eq === -1)
19
+ throw new RuleCommandError(`--bound wants path.key=value, got ${JSON.stringify(spec)}`);
20
+ const lhs = spec.slice(0, eq);
21
+ const raw = spec.slice(eq + 1);
22
+ const dot = lhs.lastIndexOf(".");
23
+ if (dot === -1)
24
+ throw new RuleCommandError(`--bound wants path.key=value, got ${JSON.stringify(spec)}`);
25
+ const path = lhs.slice(0, dot);
26
+ const key = lhs.slice(dot + 1);
27
+ if (!BOUND_KEYS.includes(key)) {
28
+ throw new RuleCommandError(`"${key}" is not a bound this writes. Try one of: ${BOUND_KEYS.join(", ")}.`);
29
+ }
30
+ const value = key === "enum"
31
+ ? raw.split(",").map((v) => v.trim())
32
+ : key === "optional"
33
+ ? raw !== "false"
34
+ : Number(raw);
35
+ if (typeof value === "number" && !Number.isFinite(value)) {
36
+ throw new RuleCommandError(`"${raw}" is not a number, and ${key} wants one`);
37
+ }
38
+ into[path] = { ...(into[path] ?? {}), [key]: value };
39
+ }
40
+ function operator() {
41
+ return process.env["HMCP_ACTOR"] ?? process.env["USER"] ?? "operator";
42
+ }
43
+ const EFFECTS = [
44
+ { key: "1", value: "read", label: "Only reads or looks things up — nothing it does changes anything." },
45
+ { key: "2", value: "write", label: "Changes or creates something — it writes, sends, updates or adds." },
46
+ { key: "3", value: "destructive", label: "Deletes or removes something, or cannot be undone." }
47
+ ];
48
+ const DECISIONS = [
49
+ { key: "1", value: "allow", label: "Run it — nobody is asked." },
50
+ { key: "2", value: "approve", label: "Ask a human first — every call waits in the approval queue." },
51
+ { key: "3", value: "deny", label: "Never allow it — refused, under a rule you named." }
52
+ ];
53
+ /**
54
+ * What the gateway is serving right now, by the same test the console applies:
55
+ * rows are trusted only when a live runtime row names the pid that wrote them.
56
+ */
57
+ function liveSurface(store, component) {
58
+ const rows = store.inventory(component);
59
+ if (rows.length === 0) {
60
+ throw new RuleCommandError(`no gateway has published a tool surface for "${component}" yet. Start it once, so it can report ` +
61
+ `what its upstreams offer, and a rule written here can name a tool that exists.`);
62
+ }
63
+ const announced = store.runtimeState(component);
64
+ const live = announced !== undefined && runtimeStateIsLive(announced) && announced.pid === rows[0].pid;
65
+ if (!live) {
66
+ throw new RuleCommandError(`no running gateway is announcing itself for "${component}", so the last published tool list cannot ` +
67
+ `be confirmed as current. A rule naming a tool nobody serves reads as a decision and governs nothing.`);
68
+ }
69
+ return rows;
70
+ }
71
+ async function choose(ask, write, heading, options) {
72
+ write("");
73
+ write(heading);
74
+ for (const o of options)
75
+ write(` ${o.key}) ${o.label}`);
76
+ for (;;) {
77
+ const answer = (await ask("> ")).trim();
78
+ const found = options.find((o) => o.key === answer);
79
+ if (found)
80
+ return found;
81
+ write(` ${JSON.stringify(answer)} is not one of ${options.map((o) => o.key).join(", ")}.`);
82
+ }
83
+ }
84
+ export async function runRuleCommand(options) {
85
+ const write = options.write ?? ((line) => process.stdout.write(`${line}\n`));
86
+ const { config, policy } = loadGatewayConfig(options.config);
87
+ const cwd = dirname(options.config);
88
+ const component = `gateway:${config.name}`;
89
+ if (typeof config.policy !== "string") {
90
+ throw new RuleCommandError(`this gateway's policy is written inline in ${options.config}, which is deliberately not reloadable — ` +
91
+ `the rest of that file configures child processes and transports an edit cannot touch. Move the policy ` +
92
+ `into its own file (policy: ./policy.yaml) to set rules from here.`);
93
+ }
94
+ /*
95
+ * `policy: ./policy.yaml` is relative to gateway.yaml's own folder, as the
96
+ * gateway reads it, wherever this command is run from -- not to the folder
97
+ * the person happens to be in (`-c .hmcp/gateway.yaml` from the project).
98
+ */
99
+ const policyPath = resolve(cwd, config.policy);
100
+ const store = new ApprovalStore(policy.approvals.store_path, cwd);
101
+ try {
102
+ const rows = liveSurface(store, component);
103
+ const liveTools = rows.map((r) => r.tool);
104
+ if (options.list || !options.tool) {
105
+ listTools(write, component, rows, policy, options);
106
+ return;
107
+ }
108
+ const row = rows.find((r) => r.tool === options.tool);
109
+ if (!row) {
110
+ throw new RuleCommandError(`this gateway serves no tool named "${options.tool}". Run "hmcp-gateway tools" to see what it does.`);
111
+ }
112
+ const audit = () => new AuditLog({
113
+ config: policy.audit,
114
+ session: `cli:${randomUUID()}`,
115
+ component,
116
+ actor: operator(),
117
+ cwd
118
+ });
119
+ /* ---------------------------------------------------------- reverting */
120
+ if (options.clear) {
121
+ const before = previewClearToolRule({ policy, tool: row.tool });
122
+ if (!before)
123
+ throw new RuleCommandError(`nothing was set from the console for "${row.tool}"`);
124
+ write(` removing ${before.removed.id}:`);
125
+ write("");
126
+ for (const line of ruleToYaml(before.removed).split("\n"))
127
+ write(` ${line}`);
128
+ write("");
129
+ write(` after this: ${verdict(before.verdict.kind)}, under "${before.verdict.ruleId}"`);
130
+ if (before.becomesUnclassified) {
131
+ write(` note: this was the only thing classifying ${row.tool}, so it goes back to being refused.`);
132
+ }
133
+ if (options.dryRun) {
134
+ write(" --dry-run: nothing was written.");
135
+ return;
136
+ }
137
+ const cleared = clearToolRule({
138
+ policyPath,
139
+ tool: row.tool,
140
+ expectedDigest: policyDigest(policy),
141
+ liveTools,
142
+ writesAllowed: config.policy_writes
143
+ });
144
+ if (cleared.kind !== "written")
145
+ throw new RuleCommandError(cleared.why);
146
+ try {
147
+ audit().appendStrict({
148
+ tool: row.tool,
149
+ effect: cleared.previous?.effect ?? null,
150
+ decision: before.verdict.kind,
151
+ rule_id: TOOL_RULE_CLEAR,
152
+ reason: `${row.tool} handed back to policy by ${operator()} via the gateway CLI; rule ` +
153
+ `"${cleared.previous?.id}" removed from ${config.policy}`,
154
+ outcome: "completed",
155
+ args_redacted: {
156
+ op: "cleared",
157
+ tool: row.tool,
158
+ previous: cleared.previous,
159
+ becomes_unclassified: before.becomesUnclassified,
160
+ scope: "all tenants",
161
+ origin: "cli",
162
+ policy_digest_before: cleared.previousDigest,
163
+ policy_digest_after: cleared.digest
164
+ }
165
+ });
166
+ }
167
+ catch (err) {
168
+ write(`warning: the rule was removed but the audit record failed: ${err.message}`);
169
+ write(` it was: ${JSON.stringify(cleared.previous)}`);
170
+ }
171
+ write("");
172
+ write(reloadNote(config.policy_reload, `${row.tool} is back to whatever policy says`));
173
+ return;
174
+ }
175
+ /* ------------------------------------------------------- the two asks */
176
+ const rl = options.ask || (options.effect && options.decision) || !process.stdin.isTTY
177
+ ? null
178
+ : createInterface({ input: process.stdin, output: process.stdout });
179
+ const ask = options.ask ?? (rl ? (q) => rl.question(q) : null);
180
+ let effect = options.effect;
181
+ let decision = options.decision;
182
+ try {
183
+ if (!effect || !decision) {
184
+ if (!ask) {
185
+ throw new RuleCommandError(`nothing says what "${options.tool}" should do, and this is not an interactive terminal. ` +
186
+ `Pass --effect read|write|destructive and --decision allow|approve|deny.`);
187
+ }
188
+ describeTool(write, row);
189
+ if (!effect)
190
+ effect = (await choose(ask, write, `What does ${row.tool} do?`, EFFECTS)).value;
191
+ if (!decision) {
192
+ decision = (await choose(ask, write, "What should happen when it is called?", DECISIONS)).value;
193
+ }
194
+ }
195
+ /* Bounds: carried unless told otherwise. */
196
+ const explicitBounds = {};
197
+ for (const spec of options.bound ?? [])
198
+ parseBound(spec, explicitBounds);
199
+ const hasExplicit = Object.keys(explicitBounds).length > 0;
200
+ let drop = options.dropBounds === true;
201
+ if (!hasExplicit && !options.keepBounds && !drop) {
202
+ /*
203
+ * The one extra question, and only when there is something to lose.
204
+ * `decide()` takes the bounds from the same rule it takes the decision
205
+ * from, so a rule written above a bounding one unbounds the tool
206
+ * unless its bounds come along. Guessing here is the one thing this
207
+ * must not do.
208
+ */
209
+ const probe = previewToolRule({
210
+ policy,
211
+ draft: { tool: row.tool, effect, decision, actor: operator() },
212
+ liveTools
213
+ });
214
+ if (probe.carriedFrom) {
215
+ if (ask) {
216
+ const keep = (await ask(`\n"${probe.carriedFrom}" bounds this tool's arguments ` +
217
+ `(${describeBounds(probe.bounds)}).\nKeep those bounds? [Y/n] `))
218
+ .trim()
219
+ .toLowerCase();
220
+ drop = keep === "n" || keep === "no";
221
+ }
222
+ else if (options.keepBounds === undefined) {
223
+ throw new RuleCommandError(`"${probe.carriedFrom}" bounds this tool's arguments (${describeBounds(probe.bounds)}), and ` +
224
+ `this is not an interactive terminal. Pass --keep-bounds to carry them, or --drop-bounds ` +
225
+ `to write a rule without them.`);
226
+ }
227
+ }
228
+ }
229
+ const draft = parseToolRuleDraft({
230
+ tool: row.tool,
231
+ effect,
232
+ decision,
233
+ ...(hasExplicit ? { args: explicitBounds } : drop ? { args: {} } : {}),
234
+ ...(options.onViolation ? { on_violation: options.onViolation } : {}),
235
+ ...(options.unknownArgs ? { unknown_args: options.unknownArgs } : {}),
236
+ ...(options.reason ? { reason: options.reason } : {}),
237
+ actor: operator(),
238
+ acknowledged: {
239
+ ...(drop ? { dropBounds: true } : {}),
240
+ ...(options.overrideDeny ? { overrideDeny: options.overrideDeny } : {}),
241
+ ...(options.yesReally ? { destructiveAllow: true } : {})
242
+ }
243
+ });
244
+ const preview = previewToolRule({ policy, draft, liveTools });
245
+ write("");
246
+ write(` now: ${describeNow(preview)}`);
247
+ write(` after this: ${row.tool} is a ${draft.effect} tool and ${verdict(preview.verdict.kind)}`);
248
+ if (preview.bounds)
249
+ write(` within bounds: ${describeBounds(preview.bounds)}`);
250
+ if (preview.carriedFrom)
251
+ write(` bounds carried from "${preview.carriedFrom}"`);
252
+ if (preview.strandedRule) {
253
+ write(` note: no tool this gateway serves reaches "${preview.strandedRule}" any more.`);
254
+ }
255
+ if (preview.nameContradiction)
256
+ write(` warning: ${preview.nameContradiction}`);
257
+ write("");
258
+ for (const line of ruleToYaml(preview.rule).split("\n"))
259
+ write(` ${line}`);
260
+ write("");
261
+ write(` to be written to ${policyPath}`);
262
+ if (options.dryRun) {
263
+ write(" --dry-run: nothing was written.");
264
+ return;
265
+ }
266
+ const result = writeToolRule({
267
+ policyPath,
268
+ draft,
269
+ expectedDigest: policyDigest(policy),
270
+ knownToLiveSurface: true,
271
+ liveTools,
272
+ writesAllowed: config.policy_writes,
273
+ overridesAllowed: config.policy_overrides
274
+ });
275
+ if (result.kind !== "written") {
276
+ throw new RuleCommandError(result.kind === "stale"
277
+ ? result.why
278
+ : result.why +
279
+ (result.needs === "overrideDeny"
280
+ ? ` Pass --override-deny ${preview.overriddenReason?.ruleId ?? "<rule-id>"} if you meant it.`
281
+ : result.needs === "dropBounds"
282
+ ? " Pass --drop-bounds if you meant it."
283
+ : result.needs === "destructiveAllow"
284
+ ? " Pass --yes-really if you meant it."
285
+ : ""));
286
+ }
287
+ try {
288
+ audit().appendStrict({
289
+ tool: draft.tool,
290
+ effect: draft.effect,
291
+ decision: preview.verdict.kind,
292
+ rule_id: result.action === "update" ? TOOL_RULE_UPDATE : TOOL_RULE_SET,
293
+ reason: `${draft.tool} set to ${draft.effect}/${draft.decision} via the gateway CLI by ${operator()}` +
294
+ (draft.reason ? `: ${draft.reason}` : "") +
295
+ `; rule "${result.rule.id}" written to ${config.policy}` +
296
+ (preview.carriedFrom ? `, carrying the bounds from "${preview.carriedFrom}"` : ""),
297
+ outcome: "completed",
298
+ args_redacted: {
299
+ op: result.action,
300
+ tool: draft.tool,
301
+ effect: draft.effect,
302
+ decision: draft.decision,
303
+ rule_id: result.rule.id,
304
+ args: result.rule.args ?? null,
305
+ on_violation: result.rule.on_violation,
306
+ unknown_args: result.rule.unknown_args,
307
+ bounds_carried_from: preview.carriedFrom,
308
+ previous: result.previous,
309
+ overrode: preview.overriddenReason,
310
+ acknowledged: draft.acknowledged ?? null,
311
+ stranded: preview.strandedRule,
312
+ loosens: preview.loosens,
313
+ scope: "all tenants",
314
+ origin: "cli",
315
+ policy_digest_before: result.previousDigest,
316
+ policy_digest_after: result.digest
317
+ }
318
+ });
319
+ }
320
+ catch (err) {
321
+ write(`warning: the rule was written but the audit record failed: ${err.message}`);
322
+ }
323
+ write(` written to ${policyPath}`);
324
+ write("");
325
+ write(reloadNote(config.policy_reload, `${draft.tool} is set`));
326
+ }
327
+ finally {
328
+ rl?.close();
329
+ }
330
+ }
331
+ finally {
332
+ store.close();
333
+ }
334
+ }
335
+ function reloadNote(reloads, what) {
336
+ return reloads
337
+ ? `${what}. A running gateway adopts it within about a second — no restart.`
338
+ : `${what}. This gateway has policy_reload off, so it applies at its next restart.`;
339
+ }
340
+ /**
341
+ * The upstream's description, shown but never as advice.
342
+ *
343
+ * It is written by the server being gated, it is the text the gateway refused
344
+ * to read as a classification, and on a tool whose description was flagged it
345
+ * is the last thing to put in front of the one reader it could still reach.
346
+ */
347
+ function describeTool(write, row) {
348
+ write(`${row.tool} (${row.upstream})`);
349
+ if (row.injection) {
350
+ write(` its description matched ${row.injection}, so it is not printed here.`);
351
+ write(` Judge it by its name, its schema and its upstream. "hmcp-gateway tools" shows the rest.`);
352
+ }
353
+ else if (row.raw_description) {
354
+ write(` its upstream says: ${JSON.stringify(row.raw_description)}`);
355
+ write(` (a description is not a classification — the server being gated wrote it)`);
356
+ }
357
+ }
358
+ function describeNow(preview) {
359
+ if (preview.current.ruleId === "defaults.on_unclassified") {
360
+ return "refused, because nothing classified it";
361
+ }
362
+ if (preview.current.ruleId.startsWith("defaults.")) {
363
+ return `${verdict(preview.current.kind)}, by the posture (no rule matches)`;
364
+ }
365
+ return `${verdict(preview.current.kind)}, under "${preview.current.ruleId}"`;
366
+ }
367
+ function describeBounds(bounds) {
368
+ if (!bounds)
369
+ return "none";
370
+ const parts = [];
371
+ if (bounds.paths.length > 0)
372
+ parts.push(bounds.paths.join(", "));
373
+ if (bounds.unknownArgs !== "allow")
374
+ parts.push(`an unclaimed argument is ${bounds.unknownArgs}`);
375
+ return parts.join("; ") || "none";
376
+ }
377
+ function listTools(write, component, rows, policy, options) {
378
+ const unclassified = rows.filter((r) => r.effect === null);
379
+ const set = rows.filter((r) => policy.rules.some((rule) => rule.id === `console-${r.tool}`));
380
+ if (options.json) {
381
+ write(JSON.stringify({ component, unclassified: unclassified.map((r) => r.tool), set: set.map((r) => r.tool) }, null, 2));
382
+ return;
383
+ }
384
+ write(`${component}`);
385
+ if (unclassified.length > 0) {
386
+ write(` ${unclassified.length} tool(s) nothing has classified, so every call to them is refused:`);
387
+ for (const row of unclassified)
388
+ write(` ${row.tool} (${row.upstream})`);
389
+ }
390
+ else {
391
+ write(" every tool this gateway serves is classified.");
392
+ }
393
+ if (set.length > 0) {
394
+ write("");
395
+ write(` ${set.length} tool(s) set from the console or this command:`);
396
+ for (const row of set) {
397
+ const rule = policy.rules.find((r) => r.id === `console-${row.tool}`);
398
+ write(` ${row.tool} ${rule.effect} / ${rule.decision}`);
399
+ }
400
+ }
401
+ write("");
402
+ const example = unclassified[0]?.tool ?? rows[0]?.tool;
403
+ if (example)
404
+ write(` Set one: hmcp-gateway rule ${example} -c ${options.config}`);
405
+ }
406
+ function verdict(kind) {
407
+ return kind === "allow"
408
+ ? "every call runs"
409
+ : kind === "approve"
410
+ ? "every call waits for a person"
411
+ : "every call is refused";
412
+ }
@@ -0,0 +1,67 @@
1
+ import { type Server as HttpServer } from "node:http";
2
+ import type { Gateway } from "./gateway.js";
3
+ /**
4
+ * Serving the gateway over HTTP instead of stdio.
5
+ *
6
+ * A stdio gateway is one process for one client, started by that client. This
7
+ * is the other shape: one long-lived process that many clients connect to,
8
+ * which is what a vendor hosting a gateway for its customers actually runs.
9
+ *
10
+ * The console's HTTP layer is not reused, and the reasons are worth stating
11
+ * because the overlap looks larger than it is. Three of its four gates would
12
+ * reject every MCP client outright: it refuses anything not from loopback, it
13
+ * requires an `Origin` header on any mutating request, and it demands a
14
+ * session cookie plus a double-submit CSRF token. All three are correct for a
15
+ * privileged browser surface on a developer's machine. An MCP client is not a
16
+ * browser — it sends no Origin, holds no cookie, and every one of its calls is
17
+ * a POST. The one gate that does transfer is the Host allowlist, and it is
18
+ * reimplemented here rather than shared, because the console derives it from
19
+ * its own fixed loopback binding and this does not.
20
+ */
21
+ export interface ServeHttpOptions {
22
+ readonly port: number;
23
+ /** Interface to bind. Defaults to loopback: widening it is a decision. */
24
+ readonly host?: string;
25
+ /**
26
+ * Hosts this server will answer to, as they appear in the `Host` header.
27
+ *
28
+ * The Streamable HTTP spec requires this check, and not for politeness:
29
+ * without it any web page can point a script at `http://localhost:<port>`
30
+ * and, because DNS rebinding makes the browser believe it is same-origin,
31
+ * drive an MCP server running on the visitor's machine. The allowlist is
32
+ * what makes the server refuse to answer to a name it was not deployed
33
+ * under.
34
+ */
35
+ readonly allowedHosts?: readonly string[];
36
+ /** How long a session may sit idle before it is dropped. */
37
+ readonly sessionIdleMs?: number;
38
+ /**
39
+ * A shared secret every request must present as `Authorization: Bearer …`.
40
+ *
41
+ * The authentication a gateway has when it has no identity provider: one
42
+ * token, held by the operator, handed to the agents that may connect. It
43
+ * says a caller is allowed in and nothing about who they are, so every call
44
+ * is still recorded as `agent`. Ignored when the policy verifies a token of
45
+ * its own (`tenant.source.kind: "jwt-verified"`), which is strictly more.
46
+ */
47
+ readonly bearerToken?: string;
48
+ /**
49
+ * `Origin` values this server will answer, exactly as a browser sends them.
50
+ *
51
+ * An MCP client that is not a browser sends no `Origin` and is unaffected.
52
+ * A request that does carry one is a web page talking to this gateway, and
53
+ * it is refused unless the operator named that page here.
54
+ */
55
+ readonly allowedOrigins?: readonly string[];
56
+ /** The most sessions held open at once. */
57
+ readonly maxSessions?: number;
58
+ /** Where this server writes its own log lines. Defaults to stderr. */
59
+ readonly log?: (line: string) => void;
60
+ }
61
+ export interface ServingHttp {
62
+ readonly http: HttpServer;
63
+ readonly port: number;
64
+ readonly sessionCount: () => number;
65
+ close(): Promise<void>;
66
+ }
67
+ export declare function serveHttp(gateway: Gateway, options: ServeHttpOptions): Promise<ServingHttp>;