hmcp-gateway 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,6 +35,100 @@ hmcp-gateway scan -c gateway.yaml # scan every upstream's advertised sur
35
35
  hmcp-gateway exposure off <tool> # withdraw one tool and refuse every call to it
36
36
  ```
37
37
 
38
+ ## Guarding every tool Claude Code uses
39
+
40
+ The gateway sees only the MCP servers it fronts. Claude Code also has a terminal,
41
+ file edits, web fetches, plugins and claude.ai connectors. The guard is a Claude Code
42
+ hook that checks each of those calls against the same policy before it runs:
43
+
44
+ ```sh
45
+ hmcp-gateway guard install --config ~/.hmcp/gateways/mine/gateway.yaml # all projects
46
+ hmcp-gateway guard install --config gateway.yaml --scope project # .claude/settings.local.json here
47
+ hmcp-gateway guard uninstall # takes out only its own hooks
48
+ ```
49
+
50
+ A project install writes `.claude/settings.local.json`, Claude Code's file for one
51
+ person's own settings, not the `settings.json` a team commits; if the project's
52
+ `.gitignore` does not list it, `install` says so.
53
+
54
+ In policy a Claude Code tool is called `claude-code__<tool>` (`claude-code__Bash`,
55
+ `claude-code__mcp__github__create_issue`), so a rule can match it. Reads (`Read`,
56
+ `Grep`, `WebFetch`…) and Claude Code's own session tools (plan mode, asking you a
57
+ question, its task list) are reads. File edits, scheduled tasks and every `Bash`
58
+ command are writes, and an MCP tool is classified by its name. A call that needs
59
+ approval waits in the console's "Waiting for you"; if nobody answers in time, Claude
60
+ Code is told to try the same call again once it is approved.
61
+
62
+ The toolbox's own tools (`mcp__hmcp__<server>__<tool>`) are left to the gateway, which
63
+ already decides them, but only when the `hmcp` server is in your own `~/.claude.json`
64
+ and is exactly the entry `adopt` or the console writes: `npx -y hmcp-gateway@<version>
65
+ serve -c <absolute path to this gateway.yaml>`, or this build's own `cli.js` run by an
66
+ absolute `node`. If any project (a `.mcp.json` here or in a parent folder, or a
67
+ per-project entry) defines a server called `hmcp`, whatever it says, nothing is
68
+ exempt. Those calls are checked like any other, and the log notes why
69
+ (`guard.lookalike-toolbox`).
70
+
71
+ A call that would switch the guard off is held for you whatever the policy says, in
72
+ observe mode too (`guard.protect-self`). That covers an edit to Claude Code's settings
73
+ files or `~/.claude.json`, or to the guard's config, policy, approvals database, audit
74
+ log or anything in `~/.hmcp`. It also covers a terminal command that names one of
75
+ those or runs `guard uninstall`.
76
+
77
+ A call the policy permits gets no answer from the guard, so Claude Code's own permission
78
+ prompts still apply. Restart Claude Code after installing.
79
+
80
+ **WebFetch can send information out.** Fetching a page counts as reading, so it runs
81
+ without asking, and anything Claude puts in the address goes to that site. The guard
82
+ does not stop that unless a rule names it. To be asked first:
83
+
84
+ ```yaml
85
+ - { id: webfetch-asks, match: "claude-code__WebFetch", decision: approve }
86
+ ```
87
+
88
+ ### If Claude Code refuses every tool
89
+
90
+ A guard that cannot start (its config was moved or broken, or the program it runs was
91
+ deleted) refuses every call, including the terminal and file edits, and its refusal
92
+ says how to switch it off: the exact command for the copy the hook runs. From a terminal
93
+ outside Claude Code, run that command; with a published version it is:
94
+
95
+ ```sh
96
+ npx -y hmcp-gateway@latest guard uninstall --scope user
97
+ npx -y hmcp-gateway@latest guard uninstall --scope project --project-dir /path/to/project
98
+ ```
99
+
100
+ Or open `~/.claude/settings.json` (or the project's `.claude/settings.local.json`) and
101
+ delete the entries under `"hooks"` whose command runs `hmcp-gateway … guard`. Then
102
+ restart Claude Code. `install` refuses to point the hook at anything inside a
103
+ `.claude/worktrees` folder, which Claude Code deletes, for this reason.
104
+
105
+ ### Agent SDK
106
+
107
+ For an agent you run yourself with the Claude Agent SDK, the same check runs in-process
108
+ (the SDK runs hooks even under `bypassPermissions`):
109
+
110
+ ```ts
111
+ import { query } from "@anthropic-ai/claude-agent-sdk";
112
+ import { hmcpGuardHooks } from "hmcp-gateway";
113
+
114
+ // Pinned and absolute, exactly as here: only this form is taken as the toolbox.
115
+ const mcpServers = { hmcp: { command: "npx", args: ["-y", "hmcp-gateway@0.2.0", "serve", "-c", "/srv/agent/gateway.yaml"] } };
116
+ const hooks = hmcpGuardHooks({ config: "/srv/agent/gateway.yaml", mcpServers });
117
+
118
+ for await (const message of query({
119
+ prompt: "Tidy up the release notes",
120
+ options: { hooks, mcpServers }
121
+ })) {
122
+ console.log(message);
123
+ }
124
+ ```
125
+
126
+ Each matcher comes with a `timeout` 30 seconds longer than the approval wait, and
127
+ `onFailure: "block"`. The hook timeout has to stay longer than the wait: if you set
128
+ your own, keep it above the wait (`approvals.wait_seconds`, or 120). If the SDK gives
129
+ up anyway, the guard stops waiting at once and refuses the call, and an approval
130
+ given afterwards is kept for the retry.
131
+
38
132
  Full documentation, including the policy schema and what the gateway does and
39
133
  does not protect against, is in the [repository README](https://github.com/aoutix/hardened-mcp#readme).
40
134
 
@@ -1,4 +1,4 @@
1
- import { type Effect, type Posture } from "hmcp-core";
1
+ import { SecretStore, type Effect, type Posture } from "hmcp-core";
2
2
  import { type Scope } from "./client-config.js";
3
3
  import { type SkippedServer } from "./adopt-plan.js";
4
4
  import { type ProbedTool } from "./adopt-emit.js";
@@ -118,6 +118,10 @@ export interface AppliedPackReport extends AppliedPack {
118
118
  readonly packLabel: string;
119
119
  readonly upstreamName: string;
120
120
  }
121
+ /** A locked-key name for one header or env setting of one server, unused or already holding this value. */
122
+ export declare function headerSecretName(store: SecretStore, upstream: string, header: string, value: string): string;
123
+ /** True when an env value is a key written out: a literal (not `${VAR}`) whose name or shape says so. */
124
+ export declare function isLiteralKey(name: string, value: string | undefined): value is string;
121
125
  /**
122
126
  * What enforcement would do with one probed tool, in the order `decide()`
123
127
  * asks: a hidden tool is never served, an unclassified one falls to
package/dist/adopt-cli.js CHANGED
@@ -7,7 +7,7 @@ import { defaultRegistryPath, defaultSecretsPath, SECRET_VALUE_PATTERNS, SecretS
7
7
  import { toText } from "hmcp-scanner";
8
8
  import { loadGatewayConfig } from "./config.js";
9
9
  import { Gateway } from "./gateway.js";
10
- import { backupPath, ClientConfigError, isRemote, parseServers, readBackup, readClientConfig, resolveScope, scopeTargets, tidyProjectBackups, wholeFileBackupPath, writeBackup, writeClientConfig, restoreClientConfig, writeWholeFileBackup } from "./client-config.js";
10
+ import { backupPath, clientEditProblem, ClientConfigError, codexHomeNote, isRemote, parseServers, readBackup, readClientConfig, resolveScope, scopeTargets, tidyProjectBackups, wholeFileBackupPath, writeBackup, writeClientConfig, restoreClientConfig, sameJson, writeWholeFileBackup } from "./client-config.js";
11
11
  import { planAdoption } from "./adopt-plan.js";
12
12
  import { emitClientEntry, emitGatewayYaml, emitPolicyYaml } from "./adopt-emit.js";
13
13
  import { applyPack, packFor } from "./packs.js";
@@ -45,14 +45,22 @@ function out(options) {
45
45
  function defaultNameFor(scope) {
46
46
  if (scope === "project" || scope === "local" || scope === "user")
47
47
  return DEFAULT_GATEWAY_NAME;
48
- if (scope.startsWith("cursor"))
49
- return "cursor";
50
- if (scope.startsWith("vscode"))
51
- return "vscode";
52
- return scope;
48
+ // "cursor-project" and "cursor-user" are both "cursor"; "copilot-cli" stays as it is.
49
+ return scope.replace(/-(project|user)$/, "");
53
50
  }
54
51
  /** Scopes that belong to the person rather than to one project folder. */
55
- const USER_WIDE = new Set(["user", "claude-desktop", "cursor-user", "vscode-user", "windsurf"]);
52
+ const USER_WIDE = new Set([
53
+ "user",
54
+ "claude-desktop",
55
+ "cursor-user",
56
+ "vscode-user",
57
+ "windsurf",
58
+ "copilot-cli",
59
+ "antigravity",
60
+ "devin",
61
+ "junie",
62
+ "codex"
63
+ ]);
56
64
  /** Where the generated pair lives for this scope. */
57
65
  function generatedDir(target, options) {
58
66
  if (options.outDir)
@@ -603,7 +611,7 @@ function secretsPathFor(options) {
603
611
  return options.home !== undefined ? join(options.home, ".hmcp", "secrets.json") : defaultSecretsPath();
604
612
  }
605
613
  /** A locked-key name for one header or env setting of one server, unused or already holding this value. */
606
- function headerSecretName(store, upstream, header, value) {
614
+ export function headerSecretName(store, upstream, header, value) {
607
615
  const base = `${upstream}.${header.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`.slice(0, 60);
608
616
  for (let n = 1;; n++) {
609
617
  const name = n === 1 ? base : `${base}-${n}`;
@@ -613,7 +621,7 @@ function headerSecretName(store, upstream, header, value) {
613
621
  }
614
622
  }
615
623
  /** True when an env value is a key written out: a literal (not `${VAR}`) whose name or shape says so. */
616
- function isLiteralKey(name, value) {
624
+ export function isLiteralKey(name, value) {
617
625
  if (typeof value !== "string" || value === "" || /\$\{[^}]*\}/.test(value))
618
626
  return false;
619
627
  return KEYISH_NAME.test(name) || SECRET_VALUE_PATTERNS.some((p) => p.regex.test(value));
@@ -937,13 +945,23 @@ async function adoptEngine(options, write, library) {
937
945
  throw err instanceof ClientConfigError ? new AdoptCommandError(err.message) : err;
938
946
  }
939
947
  const file = readClientConfig(target.scope, scopeOptions);
940
- const parsed = parseServers(file.servers);
948
+ const parsed = parseServers(file.servers, { httpOnly: target.httpOnly });
941
949
  const { malformed } = parsed;
942
950
  // Copied because an already-adopted scope has its gateway entry removed from
943
951
  // the set before planning.
944
952
  const servers = new Map(parsed.servers);
945
953
  write(`Client config: ${target.path}`);
946
954
  write(`Scope: ${target.scope} (${target.where})`);
955
+ const codexNote = codexHomeNote(target, options.home ?? homedir());
956
+ if (codexNote)
957
+ write(`Note: Codex is ${codexNote}.`);
958
+ // A file whose servers are in a form that cannot be changed safely: listed, never edited.
959
+ const editProblem = clientEditProblem(file);
960
+ if (editProblem) {
961
+ if (options.apply)
962
+ throw new AdoptCommandError(editProblem);
963
+ write(`Note: ${editProblem}`);
964
+ }
947
965
  /*
948
966
  * An existing gateway entry means this scope has been adopted before, and
949
967
  * the right behaviour depends on whether anything new has appeared beside
@@ -1004,8 +1022,8 @@ async function adoptEngine(options, write, library) {
1004
1022
  */
1005
1023
  if (backup.generated.length === 0 && servers.size > 1) {
1006
1024
  throw new AdoptCommandError(`"${existing[0]}" in ${target.path} is a toolbox connected from the console, not one adopt wrote, so ` +
1007
- `adopt will not rewrite it. Add the other servers to that toolbox from the console, or undo the ` +
1008
- `connection first and adopt then.`);
1025
+ `adopt will not rewrite it. To move the app's other servers into that toolbox, open the console, go to ` +
1026
+ `Connections and press "Bring in servers" for this app; or undo the connection first and adopt then.`);
1009
1027
  }
1010
1028
  existingConfigPath = configPathOf(existing[1]);
1011
1029
  if (existingConfigPath && existsSync(existingConfigPath)) {
@@ -1361,7 +1379,8 @@ function installEntry(args) {
1361
1379
  const configPath = options.relativeConfig
1362
1380
  ? relative(dirname(target.path), generated.configPath)
1363
1381
  : generated.configPath;
1364
- servers[entryName] = emitClientEntry(merged, { configPath, command, args: commandArgs });
1382
+ // The app's own fields first (VS Code's `type: "stdio"`), as connecting from the console writes them.
1383
+ servers[entryName] = { ...target.stdioFields, ...emitClientEntry(merged, { configPath, command, args: commandArgs }) };
1365
1384
  writeClientConfig(file, servers);
1366
1385
  write(`Rewrote ${target.path}: ${adopted.length} entr(ies) replaced by "${entryName}"`);
1367
1386
  const registryIdUsed = registration ? commitRegistration(registration, write) : undefined;
@@ -1440,7 +1459,7 @@ function literalSecretNames(replaced) {
1440
1459
  function registryLabel(target, options) {
1441
1460
  const app = target.client.replace(/ \((this|all) projects?\)$/, "");
1442
1461
  if (USER_WIDE.has(target.scope)) {
1443
- const label = target.scope === "user" || target.scope.endsWith("-user") ? `${app}, all projects` : app;
1462
+ const label = target.scope === "user" || target.client.endsWith("(all projects)") ? `${app}, all projects` : app;
1444
1463
  return { label, idHint: defaultNameFor(target.scope) };
1445
1464
  }
1446
1465
  const folder = basename(resolve(options.cwd ?? process.cwd())) || "project";
@@ -1601,7 +1620,7 @@ function appsStillUsing(backup, undoing, scopeOptions, registryPath) {
1601
1620
  if (target.scope === undoing.scope)
1602
1621
  continue;
1603
1622
  try {
1604
- const { servers } = parseServers(readClientConfig(target.scope, scopeOptions).servers);
1623
+ const { servers } = parseServers(readClientConfig(target.scope, scopeOptions).servers, { httpOnly: target.httpOnly });
1605
1624
  const uses = [...servers.values()].some((server) => {
1606
1625
  if (isRemote(server))
1607
1626
  return false;
@@ -1662,7 +1681,8 @@ async function revertEngine(options, write, guarded) {
1662
1681
  * sitting there now is something the user added on purpose, and it is not
1663
1682
  * this command's to overwrite on the way to undoing its own work.
1664
1683
  */
1665
- const collisions = Object.keys(backup.replaced).filter((name) => servers[name] !== undefined && name !== backup.gateway_entry_name);
1684
+ // The very entry being restored (the app wrote its old list back) needs nothing, and is no collision.
1685
+ const collisions = Object.keys(backup.replaced).filter((name) => servers[name] !== undefined && name !== backup.gateway_entry_name && !sameJson(servers[name], backup.replaced[name]));
1666
1686
  if (collisions.length > 0) {
1667
1687
  throw new AdoptCommandError(`these names were adopted, and ${target.path} now has a different server under each:\n` +
1668
1688
  collisions.map((n) => ` ${n}`).join("\n") +
@@ -1806,9 +1826,17 @@ function looksInstalled(target, home) {
1806
1826
  case "user":
1807
1827
  case "local":
1808
1828
  return existsSync(join(home, ".claude"));
1829
+ case "junie":
1830
+ case "junie-project":
1831
+ // Junie's file is in an `mcp` folder of its own, made only when a server is added.
1832
+ return existsSync(dirname(dirname(target.path)));
1809
1833
  case "project":
1810
1834
  case "cursor-project":
1811
1835
  case "vscode-project":
1836
+ case "antigravity-project":
1837
+ case "devin-project":
1838
+ case "roo-project":
1839
+ case "codex-project":
1812
1840
  // A project file is about the folder, not an installed app.
1813
1841
  return existsSync(dirname(target.path));
1814
1842
  default:
@@ -1839,7 +1867,7 @@ export function detectClients(options = {}) {
1839
1867
  };
1840
1868
  try {
1841
1869
  const file = readClientConfig(target.scope, scopeOptions);
1842
- const { servers } = parseServers(file.servers);
1870
+ const { servers } = parseServers(file.servers, { httpOnly: target.httpOnly });
1843
1871
  const backup = readBackup(target);
1844
1872
  return {
1845
1873
  ...base,
@@ -1,3 +1,4 @@
1
+ import { isAbsolute } from "node:path";
1
2
  import { classifyAddress, isIpLiteral } from "hmcp-core";
2
3
  import { UpstreamSchema } from "./config.js";
3
4
  import { isRemote } from "./client-config.js";
@@ -99,6 +100,113 @@ function isGatewayItself(name, server, options) {
99
100
  return true;
100
101
  return false;
101
102
  }
103
+ /** Tool names from an app's list, for a reason a person reads: names only, and not too many. */
104
+ function toolNames(list) {
105
+ const names = list.filter((t) => typeof t === "string");
106
+ const shown = names.slice(0, 5).join(", ");
107
+ return names.length > 5 ? `${shown} and ${names.length - 5} more` : shown;
108
+ }
109
+ const LEAVE_IT = "the toolbox would expose all of its tools, so it was left where it is";
110
+ const ADD_IT_THERE = "add it from the console and switch the other tools off there, or leave it configured directly in the app";
111
+ /**
112
+ * A limit the app itself puts on one server, which adopting would lose.
113
+ *
114
+ * Behind the gateway the app sees one entry, the gateway's, so a limit
115
+ * written on the original entry no longer applies: every tool the server has
116
+ * would be exposed, under a starting policy that only watches. So such a
117
+ * server is not adopted, and says why. Field names and tool names are shown;
118
+ * no other value from the entry is.
119
+ *
120
+ * - `tools` (GitHub Copilot CLI): which tools the app may use; `["*"]` is all.
121
+ * - `disabled` (Roo Code, Windsurf, Devin, others): switched off in the app.
122
+ * - `disabledTools` (Windsurf, Devin), `excludeTools` / `includeTools`
123
+ * (Gemini and Antigravity CLI): tools left out or picked.
124
+ * - `trust` (Gemini and Antigravity CLI): runs its tools without asking.
125
+ * - Codex: `enabled = false`, `enabled_tools`, `disabled_tools`, a `tools`
126
+ * table of per-tool settings, `default_tools_approval_mode`; and sign-in
127
+ * settings it cannot carry over (`bearer_token_env_var`,
128
+ * `env_http_headers`, `auth`, `env_vars`). These field names are from Codex's docs as
129
+ * known when this was written, not from the research notes.
130
+ * - `cwd` given relative to the app: the toolbox starts it from elsewhere.
131
+ */
132
+ function appLimit(server) {
133
+ const entry = server;
134
+ const tools = entry["tools"];
135
+ if (Array.isArray(tools) && !(tools.length === 1 && tools[0] === "*")) {
136
+ const which = tools.length === 0 ? "none of them" : `only ${toolNames(tools)}`;
137
+ return {
138
+ reason: `it limits which tools the app may use (${which}); the toolbox would expose all of them, so it was left where it is`,
139
+ remedy: ADD_IT_THERE
140
+ };
141
+ }
142
+ if (tools !== null && typeof tools === "object" && !Array.isArray(tools)) {
143
+ return {
144
+ reason: `it has settings for single tools in the app (tools); ${LEAVE_IT}`,
145
+ remedy: ADD_IT_THERE
146
+ };
147
+ }
148
+ for (const [field, off] of [["disabled", true], ["enabled", false]]) {
149
+ if (entry[field] === off) {
150
+ return {
151
+ reason: `it is switched off in the app (${field}); behind the toolbox it would be on again, so it was left where it is`,
152
+ remedy: "switch it on in the app first if you want it behind the toolbox, then run this again"
153
+ };
154
+ }
155
+ }
156
+ // Codex: `enabled_tools` picks tools (an empty list picks none); `disabled_tools` leaves some out.
157
+ const enabledTools = entry["enabled_tools"];
158
+ if (Array.isArray(enabledTools)) {
159
+ const which = enabledTools.length === 0 ? "none of them" : toolNames(enabledTools);
160
+ return { reason: `it limits which tools the app may use (enabled_tools: ${which}); ${LEAVE_IT}`, remedy: ADD_IT_THERE };
161
+ }
162
+ for (const field of ["disabledTools", "excludeTools", "includeTools", "disabled_tools"]) {
163
+ const list = entry[field];
164
+ if (Array.isArray(list) && list.length > 0) {
165
+ return { reason: `it limits which tools the app may use (${field}: ${toolNames(list)}); ${LEAVE_IT}`, remedy: ADD_IT_THERE };
166
+ }
167
+ }
168
+ if (entry["trust"] === true) {
169
+ return {
170
+ reason: "the app runs its tools without asking first (trust); the toolbox cannot carry that setting over, so it was left where it is",
171
+ remedy: "remove the trust setting in the app if you want it behind the toolbox, then run this again"
172
+ };
173
+ }
174
+ if (entry["default_tools_approval_mode"] !== undefined) {
175
+ return {
176
+ reason: "it sets how the app asks before its tools run (default_tools_approval_mode); the toolbox cannot carry that " +
177
+ "setting over, so it was left where it is",
178
+ remedy: ADD_IT_THERE
179
+ };
180
+ }
181
+ /*
182
+ * Codex's ways of signing in to a remote server that the toolbox cannot
183
+ * carry over: the server would be adopted without its key and quietly fail.
184
+ */
185
+ for (const field of ["bearer_token_env_var", "env_http_headers", "auth"]) {
186
+ if (entry[field] !== undefined) {
187
+ return {
188
+ reason: `it signs in in a way the toolbox can't carry over yet (${field}), so it was left where it is`,
189
+ remedy: "add it from the console and save its key there, or leave it configured directly in the app"
190
+ };
191
+ }
192
+ }
193
+ // Codex: names of its own environment variables passed on to the server, which the toolbox's process never has.
194
+ const envVars = entry["env_vars"];
195
+ if (Array.isArray(envVars) && envVars.length > 0) {
196
+ return {
197
+ reason: "it passes the server keys from Codex's own environment (env_vars), which the toolbox can't see, so it was left where it is",
198
+ remedy: "add it from the console and save its keys there, or leave it configured directly in the app"
199
+ };
200
+ }
201
+ const cwd = entry["cwd"];
202
+ if (cwd !== undefined && !(typeof cwd === "string" && isAbsolute(cwd))) {
203
+ return {
204
+ reason: "it starts in a folder given relative to the app (cwd), and the toolbox starts it from elsewhere, so it was left where it is",
205
+ remedy: "give it the full path of its folder in the app, then run this again"
206
+ };
207
+ }
208
+ return undefined;
209
+ }
102
210
  export function planAdoption(servers, options) {
103
211
  const upstreams = [];
104
212
  const skipped = [];
@@ -130,6 +238,11 @@ export function planAdoption(servers, options) {
130
238
  });
131
239
  continue;
132
240
  }
241
+ const limit = appLimit(server);
242
+ if (limit) {
243
+ skipped.push({ name: original, ...limit });
244
+ continue;
245
+ }
133
246
  if (isRemote(server)) {
134
247
  const planned = planRemote(original, name, server, options, egressAllow);
135
248
  if ("skip" in planned) {
@@ -356,7 +469,9 @@ function planStdio(original, name, server, options, gatewayEnv, envOwner) {
356
469
  command: server.command,
357
470
  args: server.args,
358
471
  env: ownEnv,
359
- pass_env: passEnv
472
+ pass_env: passEnv,
473
+ // The folder it starts in (Codex, Antigravity), when the app gave one; only a full path reaches here.
474
+ ...(typeof server["cwd"] === "string" ? { cwd: server["cwd"] } : {})
360
475
  }),
361
476
  originalName: original,
362
477
  warnings
package/dist/cli.js CHANGED
@@ -17,6 +17,9 @@ import { runStatusCommand } from "./status-cli.js";
17
17
  import { runSuggestCommand } from "./suggest-cli.js";
18
18
  import { createInterface } from "node:readline/promises";
19
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";
20
23
  const program = new Command();
21
24
  /** Commander's accumulator for a repeatable option. */
22
25
  function collect(value, previous) {
@@ -25,7 +28,13 @@ function collect(value, previous) {
25
28
  program
26
29
  .name("hmcp-gateway")
27
30
  .description("Policy gateway between an agent and the MCP servers it uses.")
28
- .version(VERSION);
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();
29
38
  program
30
39
  .command("serve", { isDefault: true })
31
40
  .description("Run the gateway over stdio, or over HTTP with --http.")
@@ -370,7 +379,10 @@ program
370
379
  .description("Put this gateway in front of the MCP servers a client already has configured.")
371
380
  .option("--apply", "write the files and edit the client config; without it, only report", false)
372
381
  .option("--revert", "restore the servers this command replaced", false)
373
- .option("--scope <scope>", "project | local | user; detected when there is only one")
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")
374
386
  .option("--name <pair>", "rename an upstream: <original>=<name>; repeatable", collect, [])
375
387
  .option("--gateway-name <name>", "the gateway's name, which names it in the audit log", "claude-code")
376
388
  .option("--entry-name <name>", "what to call the gateway in the client's config", "hmcp")
@@ -437,6 +449,114 @@ program
437
449
  });
438
450
  });
439
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
+ });
440
560
  program
441
561
  .command("scan")
442
562
  .description("Scan every upstream server's advertised tool surface.")
@@ -520,7 +640,8 @@ async function run(fn) {
520
640
  if (err instanceof ExposureCommandError ||
521
641
  err instanceof AdoptCommandError ||
522
642
  err instanceof RuleCommandError ||
523
- err instanceof PinCommandError) {
643
+ err instanceof PinCommandError ||
644
+ err instanceof GuardInstallError) {
524
645
  warn(`error: ${err.message}`);
525
646
  process.exit(1);
526
647
  }