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