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
package/dist/config.js ADDED
@@ -0,0 +1,330 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { z } from "zod";
5
+ import { expandPath, parsePolicy, SecretNameSchema, SecretValueSchema } from "hmcp-core";
6
+ /** One MCP server the gateway sits in front of. */
7
+ /**
8
+ * Relaying the caller's own credential to this upstream instead of holding
9
+ * one for it.
10
+ *
11
+ * Off by default: forwarding a credential somewhere is a decision, and an
12
+ * upstream that was configured with a static header should keep behaving the
13
+ * way it does until someone says otherwise.
14
+ */
15
+ export const CredentialPassthroughSchema = z
16
+ .object({
17
+ enabled: z.boolean().default(false),
18
+ /** Where the caller's token is placed on the upstream request. */
19
+ header: z.string().min(1).default("authorization"),
20
+ /** Refuse the call rather than fall back to the static headers. */
21
+ required: z.boolean().default(false),
22
+ /**
23
+ * `shared` keeps one upstream connection for the process and varies only
24
+ * the credential, which is what nearly every HTTP API wants. `per-tenant`
25
+ * is reserved for an upstream that binds its MCP session to whichever
26
+ * token initialized it; it is not implemented yet and is rejected rather
27
+ * than silently behaving like `shared`.
28
+ */
29
+ session: z.enum(["shared", "per-tenant"]).default("shared")
30
+ })
31
+ .strict()
32
+ .refine((v) => v.session === "shared", {
33
+ message: 'credential_passthrough.session "per-tenant" is not implemented yet'
34
+ });
35
+ export const UpstreamSchema = z.discriminatedUnion("transport", [
36
+ z
37
+ .object({
38
+ name: z
39
+ .string()
40
+ .min(1)
41
+ .regex(/^[a-z0-9_]+$/, "an upstream name must be lowercase letters, digits and underscores"),
42
+ transport: z.literal("stdio"),
43
+ /** Overrides the gateway-wide `on_injection` for this upstream alone. */
44
+ on_injection: z.enum(["strip", "deny", "annotate"]).optional(),
45
+ command: z.string().min(1),
46
+ args: z.array(z.string()).default([]),
47
+ /**
48
+ * Environment for the child process. Nothing else is inherited. A value
49
+ * is a literal string or `{ secret: name }`, resolved from the
50
+ * locked-keys file (~/.hmcp/secrets.json) when the server starts.
51
+ */
52
+ env: z.record(z.string(), SecretValueSchema).default({}),
53
+ /** Names to pass through from the gateway's own environment. */
54
+ pass_env: z.array(z.string()).default([]),
55
+ cwd: z.string().optional()
56
+ })
57
+ .strict(),
58
+ z
59
+ .object({
60
+ name: z
61
+ .string()
62
+ .min(1)
63
+ .regex(/^[a-z0-9_]+$/, "an upstream name must be lowercase letters, digits and underscores"),
64
+ transport: z.literal("http"),
65
+ /** Overrides the gateway-wide `on_injection` for this upstream alone. */
66
+ on_injection: z.enum(["strip", "deny", "annotate"]).optional(),
67
+ url: z.string().url(),
68
+ /*
69
+ * Static headers, sent on every request to this upstream. Note there is
70
+ * no `${VAR}` expansion and deliberately none: a literal `${...}` here
71
+ * used to be sent verbatim, so a config that looked like it was
72
+ * interpolating a secret was actually shipping the word. It is rejected
73
+ * rather than quietly honoured, and a per-caller credential belongs in
74
+ * credential_passthrough anyway.
75
+ */
76
+ headers: z
77
+ .record(z.string(), SecretValueSchema)
78
+ .refine((h) => !Object.values(h).some((v) => typeof v === "string" && /\$\{[^}]*\}/.test(v)), {
79
+ message: "a header value contains ${...}, which is not expanded. Use credential_passthrough for a " +
80
+ "per-caller token, or put the literal value here."
81
+ })
82
+ .default({}),
83
+ credential_passthrough: CredentialPassthroughSchema.default(() => CredentialPassthroughSchema.parse({})),
84
+ /**
85
+ * Sign in to this server (OAuth). The tokens live in the locked-keys
86
+ * file under this name and the gateway refreshes them itself. Cannot be
87
+ * combined with credential_passthrough or a hand-set authorization
88
+ * header: a request carries one credential, and which one must be
89
+ * obvious from the file.
90
+ */
91
+ oauth: z.object({ secret: SecretNameSchema }).strict().optional()
92
+ })
93
+ .strict()
94
+ .superRefine((u, ctx) => {
95
+ if (!u.oauth)
96
+ return;
97
+ if (u.credential_passthrough.enabled) {
98
+ ctx.addIssue({ code: "custom", path: ["oauth"], message: "oauth cannot be combined with credential_passthrough" });
99
+ }
100
+ if (Object.keys(u.headers).some((h) => h.toLowerCase() === "authorization")) {
101
+ ctx.addIssue({ code: "custom", path: ["oauth"], message: "oauth cannot be combined with an authorization header" });
102
+ }
103
+ })
104
+ ]);
105
+ export const GatewayConfigSchema = z
106
+ .object({
107
+ version: z.literal(1),
108
+ name: z.string().default("hmcp-gateway"),
109
+ /** Inline policy, or a path to one. */
110
+ policy: z.union([z.string(), z.record(z.string(), z.unknown())]),
111
+ upstreams: z.array(UpstreamSchema).min(1),
112
+ /**
113
+ * How long one upstream has to finish connecting and answer the first
114
+ * request.
115
+ *
116
+ * Startup is all-or-nothing -- every upstream is connected before
117
+ * anything is served -- so a server that starts and never speaks took the
118
+ * whole gateway with it for as long as the SDK's own request timeout, and
119
+ * then failed with a message that did not name it. Waiting is
120
+ * defensible; not knowing which server to go and look at is not.
121
+ *
122
+ * 20 seconds, because the slow cases are real and legitimate: a container
123
+ * image being pulled, a cold interpreter, a server that reads a large
124
+ * index at startup. Set it higher for an upstream known to be slow, or
125
+ * lower on a machine where a hang should fail fast.
126
+ */
127
+ connect_timeout_ms: z.number().int().positive().default(20_000),
128
+ /**
129
+ * `degraded` (the default): serve with whichever servers connected, keep
130
+ * retrying the rest, and report each one's state to the console. One
131
+ * broken server no longer takes every other server's tools with it.
132
+ * `strict`: the old behaviour -- every server connects, or nothing is
133
+ * served.
134
+ */
135
+ startup: z.enum(["degraded", "strict"]).default("degraded"),
136
+ /**
137
+ * Apply changes to `upstreams` in this file while running: connect what
138
+ * was added, disconnect what was removed, and tell the AI app its tool
139
+ * list changed. Any other change to this file still needs a restart.
140
+ */
141
+ upstream_reload: z.boolean().default(true),
142
+ /**
143
+ * What to do with a tool whose description contains an injection attempt.
144
+ * `strip` replaces the description and keeps the tool usable; `deny` hides
145
+ * the tool; `annotate` leaves the text but prefixes a warning.
146
+ *
147
+ * The default for every upstream, overridable per upstream and then per
148
+ * tool. One setting for a whole gateway made a false positive expensive:
149
+ * `strip` replaces a description wholesale, so a legitimate tool caught by
150
+ * a fuzzy pattern loses the text the model needs and gets misused rather
151
+ * than failing — and the only escape was to weaken the setting everywhere.
152
+ */
153
+ on_injection: z.enum(["strip", "deny", "annotate"]).default("strip"),
154
+ /**
155
+ * Per-tool overrides, keyed by the name the gateway exposes — so
156
+ * `<server>__<tool>` when `namespace` is on.
157
+ *
158
+ * For the reviewed false positive. Written in the config and read in a
159
+ * diff, which is the point: a decision to treat a specific finding on a
160
+ * specific tool as noise should be as visible as any other policy edit.
161
+ *
162
+ * `accept` is available here and *only* here — not as the gateway default
163
+ * and not per upstream. It keeps the upstream's text exactly as written,
164
+ * which is the honest answer for a pattern that fired on a legitimate
165
+ * description: `annotate` would tell the model to treat a real instruction
166
+ * as data, which makes it distrust a tool it should be using.
167
+ *
168
+ * It is safe to offer because a description cannot reach a decision —
169
+ * nothing in `decide()` or `classify()` reads one — so accepting text
170
+ * widens no permission. What it must never do is make the finding
171
+ * disappear, and it does not: the audit record is written either way and
172
+ * the console still shows which patterns matched. The reason it is
173
+ * per-tool only is that a blanket `accept` would simply be injection
174
+ * handling switched off, and then nobody reviewed anything.
175
+ */
176
+ injection_overrides: z.record(z.string(), z.enum(["strip", "deny", "annotate", "accept"])).default({}),
177
+ /** Prefix upstream tool names with `<server>__`. */
178
+ namespace: z.boolean().default(true),
179
+ /**
180
+ * Adopt a change to `policy.yaml` without a restart.
181
+ *
182
+ * On by default, and only for a policy kept in its own file. The
183
+ * asymmetry it removes: the console's exposure switch took effect on the
184
+ * next call because it is a database row both processes read, while
185
+ * tightening an argument bound meant an edit and a restart. The fastest
186
+ * control was the blunt one and the precise one was the slow one, which is
187
+ * backwards for anyone reacting to something in production.
188
+ *
189
+ * It is safe to default on because it is all-or-nothing and fails closed:
190
+ * a file that does not parse or does not validate leaves the previous
191
+ * policy enforcing, and a change to anything this process consumed at
192
+ * startup -- `audit`, `tenant`, `approvals.store_path` -- is refused in
193
+ * full rather than partly applied. `egress` is live: the guard is
194
+ * reconfigured in place, so adding a server's address needs no restart. Every outcome is logged and
195
+ * written to the audit log, adopted or not. See `PolicySource`.
196
+ *
197
+ * Set `false` where policy must only ever change with a deployment.
198
+ */
199
+ policy_reload: z.boolean().default(true),
200
+ /**
201
+ * Whether a reviewer may set a tool's rule from the console or the CLI,
202
+ * which writes one per-tool rule into `policy.yaml`.
203
+ *
204
+ * On by default, because the thing it replaces was a dead end: an upstream
205
+ * that added a tool got it refused, and the only remedy was hand-writing
206
+ * YAML with a trap in it (a rule with no `effect:` silently classifies
207
+ * nothing). A control that has to be found and switched on first would
208
+ * leave that dead end in place for everyone who did not find it.
209
+ *
210
+ * What it opens is bounded in `policy-write.ts` rather than described
211
+ * here: one rule per tool, naming that tool literally, carrying an effect,
212
+ * a decision and argument bounds — and nothing else in the file changes,
213
+ * including the position of every other rule. See `policy_overrides` below
214
+ * for the narrower setting.
215
+ *
216
+ * Set `false` where policy must only ever change with a deployment -- the
217
+ * same reason to set `policy_reload: false`, and usually set together with
218
+ * it. An inline policy is never writable regardless, because this file
219
+ * configures child processes and transports that an edit cannot touch.
220
+ */
221
+ policy_writes: z.boolean().default(true),
222
+ /**
223
+ * The longest agent-facing tool name this gateway will serve. A tool whose
224
+ * name is longer is withheld, like one whose name cannot be read.
225
+ *
226
+ * A model API rejects a request carrying any tool name over 64 characters,
227
+ * which takes down every tool rather than the one. The client adds its own
228
+ * prefix on top of the name served here, so the room left depends on what
229
+ * the gateway's entry is called in that client; `adopt` works it out and
230
+ * writes it here. Unset means no limit, for a client that adds no prefix.
231
+ */
232
+ max_tool_name_length: z.number().int().positive().optional(),
233
+ /**
234
+ * Show a desktop notification when a call is parked for approval.
235
+ *
236
+ * Unset, a gateway serving one client over stdio does and one serving many
237
+ * over HTTP does not: the first is on someone's own machine, the second
238
+ * usually is not. The `HMCP_NOTIFY` environment variable (`0` or `1`)
239
+ * overrides either.
240
+ */
241
+ notify: z.boolean().optional(),
242
+ /**
243
+ * Whether the console and the CLI may *reverse* a decision the policy
244
+ * already makes, as against classifying a tool nothing classified.
245
+ *
246
+ * The distinction is the whole safety story of this feature. Classifying
247
+ * an unclassified tool is additive but uncontroversial: nobody had decided
248
+ * anything, and the gateway was refusing by default. Turning a
249
+ * human-written `deny` — with a reason somebody typed — into `allow` is a
250
+ * different act, and it is the one that ends this product's "the console
251
+ * can only narrow" posture.
252
+ *
253
+ * On by default, because the owner's requirement is that every function be
254
+ * settable from the console, and a capability nobody can find is the thing
255
+ * being fixed. Set `false` to keep the narrower behaviour: the console then
256
+ * still classifies unclassified tools and still tightens anything, but
257
+ * explains rather than offering the control when a change would reverse an
258
+ * existing decision.
259
+ *
260
+ * `policy_writes: false` is the stronger setting and overrides this one —
261
+ * it stops all policy writing, including classification.
262
+ */
263
+ policy_overrides: z.boolean().default(true)
264
+ })
265
+ .strict()
266
+ .superRefine((config, ctx) => {
267
+ const seen = new Set();
268
+ config.upstreams.forEach((upstream, i) => {
269
+ if (seen.has(upstream.name)) {
270
+ ctx.addIssue({
271
+ code: "custom",
272
+ path: ["upstreams", i, "name"],
273
+ message: `duplicate upstream name "${upstream.name}"`
274
+ });
275
+ }
276
+ seen.add(upstream.name);
277
+ });
278
+ });
279
+ /**
280
+ * The path every command falls back to when `-c` is not given. Compared
281
+ * against so a missing config can tell "there is nothing here yet" from "the
282
+ * path you typed is wrong" -- two mistakes with different remedies, which both
283
+ * arrived as the same `ENOENT`.
284
+ */
285
+ export const DEFAULT_CONFIG_PATH = "gateway.yaml";
286
+ /** A config or policy file that is not there. Reported as a message. */
287
+ export class ConfigNotFound extends Error {
288
+ }
289
+ /**
290
+ * Turns a failure to read a config file into something that says what to do.
291
+ *
292
+ * `ENOENT: no such file or directory, open '/some/dir/gateway.yaml'` is the
293
+ * first thing a new user sees, and it mentions neither `adopt`, which writes
294
+ * that file, nor `-c`, which points at one elsewhere.
295
+ */
296
+ function readConfigFile(full, what, typed) {
297
+ try {
298
+ return readFileSync(full, "utf8");
299
+ }
300
+ catch (err) {
301
+ if (err.code !== "ENOENT")
302
+ throw err;
303
+ if (what === "policy") {
304
+ throw new ConfigNotFound(`the policy file ${full} does not exist. The gateway config points at it, so either ` +
305
+ `create it or correct the \`policy:\` path in the config.`);
306
+ }
307
+ if (typed) {
308
+ throw new ConfigNotFound(`the gateway config ${full} does not exist. Check the path given to -c.`);
309
+ }
310
+ throw new ConfigNotFound(`no gateway config here: ${full} does not exist. Run \`hmcp-gateway adopt\` to write one for ` +
311
+ `the servers a client is already using, or pass -c with the path to a config you have.`);
312
+ }
313
+ }
314
+ export function loadGatewayConfig(path, options = {}) {
315
+ const full = expandPath(path);
316
+ const typed = options.typed ?? path !== DEFAULT_CONFIG_PATH;
317
+ const raw = parseYaml(readConfigFile(full, "gateway config", typed));
318
+ const result = GatewayConfigSchema.safeParse(raw);
319
+ if (!result.success) {
320
+ const detail = result.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
321
+ throw new Error(`invalid gateway config ${full}:\n${detail}`);
322
+ }
323
+ const config = result.data;
324
+ // A relative policy path is relative to the config file's directory, which is
325
+ // what someone writing `policy: ./policy.yaml` means.
326
+ const policy = typeof config.policy === "string"
327
+ ? parsePolicy(parseYaml(readConfigFile(expandPath(config.policy, dirname(full)), "policy", true)), config.policy)
328
+ : parsePolicy(config.policy, `${full}#/policy`);
329
+ return { config, policy };
330
+ }
@@ -0,0 +1,51 @@
1
+ import { ClientConfigError, type Scope as ClientScope, type ScopeTarget } from "./client-config.js";
2
+ export interface ConnectClientOptions {
3
+ scope: ClientScope;
4
+ cwd: string;
5
+ home: string;
6
+ gatewayConfigPath: string;
7
+ /** Entry name in the app's config. Default "hmcp". */
8
+ entryName?: string;
9
+ /** Folders of node/uv/docker found by the machine check, for env.PATH. */
10
+ pathDirs?: string[];
11
+ /** Registry id the backup records, so Undo can find it. */
12
+ registryId?: string;
13
+ /** Overridable so per-platform paths and PATH defaults can be tested on one machine. */
14
+ platform?: string;
15
+ /** The node to find a stable path for. Default `process.execPath`; overridable for tests. */
16
+ execPath?: string;
17
+ }
18
+ export interface ConnectClientResult {
19
+ configPath: string;
20
+ entryName: string;
21
+ backupPath: string;
22
+ /** True when the entry was already there and pointed at this gateway. */
23
+ alreadyConnected: boolean;
24
+ /** Plain words: "Restart Claude Desktop once so it picks this up." */
25
+ restartHint: string;
26
+ }
27
+ /** A refusal with nothing written, in words a person can act on. */
28
+ export declare class ConnectClientError extends ClientConfigError {
29
+ }
30
+ export declare function connectClient(options: ConnectClientOptions): Promise<ConnectClientResult>;
31
+ /**
32
+ * A path to the running node that survives an upgrade.
33
+ *
34
+ * `process.execPath` is the resolved file, which for Homebrew is
35
+ * `/opt/homebrew/Cellar/node/26.4.0/bin/node`. That folder is deleted by
36
+ * `brew upgrade` and cleanup, and an app entry naming it can no longer start
37
+ * the gateway at all. So look for a `node` on the found folders, then on
38
+ * PATH, that is the same file (by realpath) through a path that is not
39
+ * itself versioned -- `/opt/homebrew/bin/node`, an nvm or volta shim -- then
40
+ * Homebrew's `opt` link, and only then the running path.
41
+ */
42
+ export declare function stableNodePath(options?: {
43
+ execPath?: string;
44
+ pathDirs?: readonly string[];
45
+ envPath?: string;
46
+ platform?: string;
47
+ }): string;
48
+ /** The PATH the app gives the gateway: found folders, node's folder, then the system's. */
49
+ export declare function pathFor(pathDirs: readonly string[], platform?: string): string;
50
+ /** What a person does next in each app, in plain words. */
51
+ export declare function restartHintFor(target: ScopeTarget, platform: string): string;
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Put an existing gateway into an AI app's config -- for a gateway built in
3
+ * the console rather than adopted from the app. CONTRACT (phase 0);
4
+ * implemented by workstream F with client-config.ts's helpers.
5
+ *
6
+ * Unlike `adopt`, this replaces nothing: the app's own servers stay exactly
7
+ * where they are and one entry is added beside them. The undo record says so
8
+ * -- nothing replaced, nothing generated -- so Undo removes the entry and
9
+ * never touches the gateway's files, which the console made and still owns.
10
+ */
11
+ import { existsSync, realpathSync } from "node:fs";
12
+ import { delimiter, dirname, join, resolve, sep } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import { emitClientEntry } from "./adopt-emit.js";
15
+ import { clientCommand } from "./adopt-cli.js";
16
+ import { backupPath, clientEditProblem, ClientConfigError, codexHomeNote, readBackup, readClientConfig, scopeTargets, writeBackup, writeClientConfig, writeWholeFileBackup } from "./client-config.js";
17
+ import { VERSION } from "./version.js";
18
+ /** A refusal with nothing written, in words a person can act on. */
19
+ export class ConnectClientError extends ClientConfigError {
20
+ }
21
+ const DEFAULT_ENTRY = "hmcp";
22
+ /** How many numbered names to try before saying so. */
23
+ const MAX_SUFFIX = 9;
24
+ export async function connectClient(options) {
25
+ const platform = options.platform ?? process.platform;
26
+ const scopeOptions = { cwd: options.cwd, home: options.home, platform };
27
+ const target = scopeTargets(scopeOptions).find((t) => t.scope === options.scope);
28
+ if (!target)
29
+ throw new ConnectClientError(`"${options.scope}" is not an app this version knows how to connect`);
30
+ const gatewayConfig = resolve(options.gatewayConfigPath);
31
+ if (!existsSync(gatewayConfig)) {
32
+ throw new ConnectClientError(`the toolbox's settings file ${gatewayConfig} is not there, so there is nothing to connect`);
33
+ }
34
+ const file = readClientConfig(target.scope, scopeOptions);
35
+ const codexNote = codexHomeNote(target, options.home);
36
+ const restartHint = [
37
+ restartHintFor(target, platform),
38
+ sharedWithVsCode(target, scopeOptions, gatewayConfig),
39
+ codexNote ? `Codex is ${codexNote}.` : ""
40
+ ]
41
+ .filter(Boolean)
42
+ .join(" ");
43
+ // Already pointing at this gateway, under whatever name: nothing to do.
44
+ const existing = Object.entries(file.servers).find(([, entry]) => pointsAt(entry, gatewayConfig, target));
45
+ if (existing) {
46
+ return { configPath: target.path, entryName: existing[0], backupPath: backupPath(target), alreadyConnected: true, restartHint };
47
+ }
48
+ /*
49
+ * One undo record per folder, and it may belong to an earlier connection
50
+ * or an adoption (Claude Code's `user` and `local` share one file). Writing
51
+ * over it would lose what that Undo needs -- for an adoption, the servers
52
+ * it replaced -- so this stops and says which Undo to use first.
53
+ */
54
+ const earlier = readBackup(target);
55
+ if (earlier) {
56
+ throw new ConnectClientError(`${target.client} already has a connection made by hardened-mcp ("${earlier.gateway_entry_name}"), ` +
57
+ `and its undo record is in ${backupPath(target)}. Undo that connection first, then connect this toolbox.`);
58
+ }
59
+ // Codex's TOML in a form that cannot be changed safely: refused before anything, the backup included, is written.
60
+ const editProblem = clientEditProblem(file);
61
+ if (editProblem)
62
+ throw new ConnectClientError(editProblem);
63
+ const entryName = freeName(options.entryName ?? DEFAULT_ENTRY, file.servers, target);
64
+ const node = stableNodePath({ execPath: options.execPath ?? process.execPath, pathDirs: options.pathDirs ?? [], platform });
65
+ const launch = launchCommand(platform, node);
66
+ const empty = {
67
+ upstreams: [],
68
+ skipped: [],
69
+ gatewayEnv: {},
70
+ egressAllow: [],
71
+ egressNeedsLocalHttp: false,
72
+ secretsOnDisk: false,
73
+ nameMap: new Map(),
74
+ malformed: []
75
+ };
76
+ const entry = {
77
+ // VS Code and Copilot CLI name the transport; the others infer it from `command`.
78
+ ...target.stdioFields,
79
+ ...emitClientEntry(empty, { configPath: gatewayConfig, command: launch.command, args: launch.args }),
80
+ /*
81
+ * An app started from the Dock or Start menu gets a minimal PATH, so a
82
+ * server launched with `npx` or `uvx` that passed "Test it" would fail
83
+ * with "not found" the moment the app started it. The folders the machine
84
+ * check found go first, then the folder of the node running this, then
85
+ * the system's own.
86
+ */
87
+ env: {
88
+ PATH: pathWith(options.pathDirs ?? [], node, platform),
89
+ /*
90
+ * The console may be using a keys file or registry somewhere other than
91
+ * the default; the gateway the app starts must read the same ones, or a
92
+ * key saved in the console is never seen. Defaults stay out of the entry.
93
+ */
94
+ ...carriedEnv()
95
+ }
96
+ };
97
+ writeWholeFileBackup(file);
98
+ writeClientConfig(file, { ...file.servers, [entryName]: entry });
99
+ writeBackup(target, {
100
+ version: 1,
101
+ created_at: new Date().toISOString(),
102
+ scope: target.scope,
103
+ config_path: target.path,
104
+ gateway_entry_name: entryName,
105
+ replaced: {},
106
+ generated: [],
107
+ ...(options.registryId ? { registry_id: options.registryId } : {})
108
+ });
109
+ return { configPath: target.path, entryName, backupPath: backupPath(target), alreadyConnected: false, restartHint };
110
+ }
111
+ /**
112
+ * Copilot in VS Code may read Copilot CLI's file as well as its own
113
+ * (unverified against a real install), so with both connected the toolbox
114
+ * can show up twice there. Said when the other one is already connected by
115
+ * hardened-mcp: it has an undo record, or an entry pointing at this toolbox.
116
+ */
117
+ function sharedWithVsCode(target, scopeOptions, gatewayConfig) {
118
+ const other = target.scope === "copilot-cli" ? "vscode-user" : target.scope === "vscode-user" ? "copilot-cli" : undefined;
119
+ if (!other)
120
+ return "";
121
+ try {
122
+ const otherTarget = scopeTargets(scopeOptions).find((t) => t.scope === other);
123
+ const connected = readBackup(otherTarget) !== undefined ||
124
+ Object.values(readClientConfig(other, scopeOptions).servers).some((entry) => pointsAt(entry, gatewayConfig, otherTarget));
125
+ if (!connected)
126
+ return "";
127
+ }
128
+ catch {
129
+ return "";
130
+ }
131
+ return "GitHub Copilot CLI and VS Code are both connected, so the two entries may both appear in VS Code; that is harmless, and you can switch one off there.";
132
+ }
133
+ /** Whether an app entry runs `serve -c <this gateway's config>`. */
134
+ function pointsAt(entry, gatewayConfig, target) {
135
+ if (typeof entry !== "object" || entry === null)
136
+ return false;
137
+ const args = entry.args;
138
+ if (!Array.isArray(args))
139
+ return false;
140
+ const at = args.indexOf("-c");
141
+ const value = at >= 0 ? args[at + 1] : undefined;
142
+ return typeof value === "string" && resolve(dirname(target.path), value) === gatewayConfig;
143
+ }
144
+ /**
145
+ * The entry name, or the first free numbered one. A name already taken by
146
+ * something else is that person's server and is never overwritten.
147
+ */
148
+ function freeName(base, servers, target) {
149
+ if (servers[base] === undefined)
150
+ return base;
151
+ for (let n = 2; n <= MAX_SUFFIX; n++) {
152
+ const candidate = `${base}-${n}`;
153
+ if (servers[candidate] === undefined)
154
+ return candidate;
155
+ }
156
+ throw new ConnectClientError(`${target.client} already has servers called "${base}" through "${base}-${MAX_SUFFIX}". ` +
157
+ `Rename or remove one of them in ${target.path}, then connect again.`);
158
+ }
159
+ /** This build's own `cli.js`, which sits beside this file in `dist`. */
160
+ function cliPath() {
161
+ return stableBrewPath(fileURLToPath(new URL("./cli.js", import.meta.url)));
162
+ }
163
+ /**
164
+ * What the app runs, with absolute paths.
165
+ *
166
+ * A copy on disk that will stay put -- a checkout, or a normal install --
167
+ * is run directly by this node: no PATH lookup at all, which is what makes
168
+ * it work from an app with a minimal PATH. A copy npx unpacked into its
169
+ * cache can be cleaned away at any time, so that case runs the published
170
+ * package through the npx beside this node instead.
171
+ */
172
+ function launchCommand(platform, node) {
173
+ const cli = cliPath();
174
+ if (existsSync(cli) && !cli.includes(`${sep}_npx${sep}`))
175
+ return { command: node, args: [cli] };
176
+ const { command, args } = clientCommand({ local: false, pinVersion: VERSION });
177
+ const npx = join(dirname(node), platform === "win32" ? "npx.cmd" : "npx");
178
+ return { command: existsSync(npx) ? npx : command, args };
179
+ }
180
+ const ENV_CARRIED = ["HMCP_SECRETS_FILE", "HMCP_REGISTRY"];
181
+ /** The console's own non-default file locations, made absolute. */
182
+ function carriedEnv() {
183
+ const out = {};
184
+ for (const name of ENV_CARRIED) {
185
+ const value = process.env[name];
186
+ if (value)
187
+ out[name] = resolve(value);
188
+ }
189
+ return out;
190
+ }
191
+ const realpath = (p) => {
192
+ try {
193
+ return realpathSync(p);
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ };
199
+ /** `<prefix>/Cellar/<formula>/<version>/<rest>`: a Homebrew folder that `brew upgrade` deletes. */
200
+ const CELLAR = /^(.*)[\\/]Cellar[\\/]([^\\/]+)[\\/][^\\/]+[\\/](.*)$/;
201
+ /**
202
+ * Homebrew's version-free link for a file under a versioned Cellar folder
203
+ * (`<prefix>/opt/<formula>/<rest>`), when it exists and is the same file.
204
+ * Anything else comes back unchanged.
205
+ */
206
+ function stableBrewPath(path) {
207
+ const m = CELLAR.exec(path);
208
+ if (!m)
209
+ return path;
210
+ const opt = join(m[1], "opt", m[2], m[3]);
211
+ const real = realpath(path);
212
+ return real !== undefined && realpath(opt) === real ? opt : path;
213
+ }
214
+ /**
215
+ * A path to the running node that survives an upgrade.
216
+ *
217
+ * `process.execPath` is the resolved file, which for Homebrew is
218
+ * `/opt/homebrew/Cellar/node/26.4.0/bin/node`. That folder is deleted by
219
+ * `brew upgrade` and cleanup, and an app entry naming it can no longer start
220
+ * the gateway at all. So look for a `node` on the found folders, then on
221
+ * PATH, that is the same file (by realpath) through a path that is not
222
+ * itself versioned -- `/opt/homebrew/bin/node`, an nvm or volta shim -- then
223
+ * Homebrew's `opt` link, and only then the running path.
224
+ */
225
+ export function stableNodePath(options = {}) {
226
+ const execPath = options.execPath ?? process.execPath;
227
+ const platform = options.platform ?? process.platform;
228
+ const real = realpath(execPath);
229
+ if (real === undefined)
230
+ return execPath;
231
+ const separator = platform === "win32" ? ";" : platform === process.platform ? delimiter : ":";
232
+ const envDirs = (options.envPath ?? process.env["PATH"] ?? "").split(separator);
233
+ const exe = platform === "win32" ? "node.exe" : "node";
234
+ for (const dir of [...(options.pathDirs ?? []), ...envDirs]) {
235
+ if (!dir)
236
+ continue;
237
+ const candidate = join(dir, exe);
238
+ if (CELLAR.test(candidate))
239
+ continue;
240
+ if (realpath(candidate) === real)
241
+ return candidate;
242
+ }
243
+ return stableBrewPath(execPath);
244
+ }
245
+ const SYSTEM_PATH = {
246
+ darwin: ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"],
247
+ linux: ["/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"],
248
+ win32: ["C:\\Windows\\system32", "C:\\Windows", "C:\\Windows\\System32\\Wbem"]
249
+ };
250
+ /** The PATH the app gives the gateway: found folders, node's folder, then the system's. */
251
+ export function pathFor(pathDirs, platform = process.platform) {
252
+ return pathWith(pathDirs, stableNodePath({ pathDirs, platform }), platform);
253
+ }
254
+ function pathWith(pathDirs, node, platform) {
255
+ const system = SYSTEM_PATH[platform] ?? SYSTEM_PATH["linux"];
256
+ const dirs = [...pathDirs, dirname(node), ...system].filter((d) => d.length > 0);
257
+ return [...new Set(dirs)].join(platform === "win32" ? ";" : ":");
258
+ }
259
+ /** What a person does next in each app, in plain words. */
260
+ export function restartHintFor(target, platform) {
261
+ switch (target.scope) {
262
+ case "claude-desktop":
263
+ return platform === "darwin"
264
+ ? "Quit Claude Desktop completely (Claude menu, then Quit) and open it again. You only need to do this once."
265
+ : "Close Claude Desktop completely (including from the system tray) and open it again. You only need to do this once.";
266
+ case "user":
267
+ case "local":
268
+ return "Start a new Claude Code session so it picks this up. Sessions already open will not see it.";
269
+ case "project":
270
+ return "Start a new Claude Code session in this project. The first time, Claude Code asks whether to use the servers in this project's .mcp.json: say yes.";
271
+ case "cursor-project":
272
+ case "cursor-user":
273
+ return "In Cursor, open Settings, then MCP, and make sure the new entry is switched on. If it does not appear, restart Cursor once.";
274
+ case "vscode-project":
275
+ case "vscode-user":
276
+ return "In VS Code, open the Command Palette, run \"MCP: List Servers\" and start the new entry. Reloading the window works too.";
277
+ case "windsurf":
278
+ return "In Windsurf, open the MCP servers list in the Cascade panel and press refresh, or restart Windsurf once.";
279
+ case "copilot-cli":
280
+ return "Restart GitHub Copilot CLI (or start a new session) so it picks up the change.";
281
+ case "antigravity":
282
+ case "antigravity-project":
283
+ return "Restart Antigravity CLI (or start a new session) so it picks up the change.";
284
+ case "devin":
285
+ case "devin-project":
286
+ return "Restart Devin Desktop (or start a new session) so it picks up the change.";
287
+ case "junie":
288
+ case "junie-project":
289
+ return "Restart Junie or your JetBrains IDE (or start a new session) so it picks up the change.";
290
+ case "codex":
291
+ return "Restart Codex or the ChatGPT desktop app so it picks up the change.";
292
+ case "codex-project":
293
+ return "Restart Codex so it picks up the change. Codex reads a project's own settings only when you have marked the project as trusted.";
294
+ case "roo-project":
295
+ return "Restart Roo Code by reloading the VS Code window (or start a new session) so it picks up the change.";
296
+ default:
297
+ return `Restart ${target.client} once so it picks this up.`;
298
+ }
299
+ }