hmcp-gateway 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +77 -0
- package/README.md +41 -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 +351 -0
- package/dist/adopt-cli.js +1857 -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 +386 -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 +535 -0
- package/dist/client-allow.d.ts +42 -0
- package/dist/client-allow.js +95 -0
- package/dist/client-config.d.ts +200 -0
- package/dist/client-config.js +784 -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 +49 -0
- package/dist/connect-client.js +249 -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/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 +756 -0
- package/dist/gateway.js +2106 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +26 -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/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 +50 -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/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,49 @@
|
|
|
1
|
+
import { ClientConfigError, type Scope as ClientScope } 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;
|
|
@@ -0,0 +1,249 @@
|
|
|
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, ClientConfigError, 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 restartHint = restartHintFor(target, platform);
|
|
36
|
+
// Already pointing at this gateway, under whatever name: nothing to do.
|
|
37
|
+
const existing = Object.entries(file.servers).find(([, entry]) => pointsAt(entry, gatewayConfig, target));
|
|
38
|
+
if (existing) {
|
|
39
|
+
return { configPath: target.path, entryName: existing[0], backupPath: backupPath(target), alreadyConnected: true, restartHint };
|
|
40
|
+
}
|
|
41
|
+
/*
|
|
42
|
+
* One undo record per folder, and it may belong to an earlier connection
|
|
43
|
+
* or an adoption (Claude Code's `user` and `local` share one file). Writing
|
|
44
|
+
* over it would lose what that Undo needs -- for an adoption, the servers
|
|
45
|
+
* it replaced -- so this stops and says which Undo to use first.
|
|
46
|
+
*/
|
|
47
|
+
const earlier = readBackup(target);
|
|
48
|
+
if (earlier) {
|
|
49
|
+
throw new ConnectClientError(`${target.client} already has a connection made by hardened-mcp ("${earlier.gateway_entry_name}"), ` +
|
|
50
|
+
`and its undo record is in ${backupPath(target)}. Undo that connection first, then connect this toolbox.`);
|
|
51
|
+
}
|
|
52
|
+
const entryName = freeName(options.entryName ?? DEFAULT_ENTRY, file.servers, target);
|
|
53
|
+
const node = stableNodePath({ execPath: options.execPath ?? process.execPath, pathDirs: options.pathDirs ?? [], platform });
|
|
54
|
+
const launch = launchCommand(platform, node);
|
|
55
|
+
const empty = {
|
|
56
|
+
upstreams: [],
|
|
57
|
+
skipped: [],
|
|
58
|
+
gatewayEnv: {},
|
|
59
|
+
egressAllow: [],
|
|
60
|
+
egressNeedsLocalHttp: false,
|
|
61
|
+
secretsOnDisk: false,
|
|
62
|
+
nameMap: new Map(),
|
|
63
|
+
malformed: []
|
|
64
|
+
};
|
|
65
|
+
const entry = {
|
|
66
|
+
// VS Code's file names the transport; the others infer it from `command`.
|
|
67
|
+
...(target.key === "servers" ? { type: "stdio" } : {}),
|
|
68
|
+
...emitClientEntry(empty, { configPath: gatewayConfig, command: launch.command, args: launch.args }),
|
|
69
|
+
/*
|
|
70
|
+
* An app started from the Dock or Start menu gets a minimal PATH, so a
|
|
71
|
+
* server launched with `npx` or `uvx` that passed "Test it" would fail
|
|
72
|
+
* with "not found" the moment the app started it. The folders the machine
|
|
73
|
+
* check found go first, then the folder of the node running this, then
|
|
74
|
+
* the system's own.
|
|
75
|
+
*/
|
|
76
|
+
env: {
|
|
77
|
+
PATH: pathWith(options.pathDirs ?? [], node, platform),
|
|
78
|
+
/*
|
|
79
|
+
* The console may be using a keys file or registry somewhere other than
|
|
80
|
+
* the default; the gateway the app starts must read the same ones, or a
|
|
81
|
+
* key saved in the console is never seen. Defaults stay out of the entry.
|
|
82
|
+
*/
|
|
83
|
+
...carriedEnv()
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
writeWholeFileBackup(file);
|
|
87
|
+
writeClientConfig(file, { ...file.servers, [entryName]: entry });
|
|
88
|
+
writeBackup(target, {
|
|
89
|
+
version: 1,
|
|
90
|
+
created_at: new Date().toISOString(),
|
|
91
|
+
scope: target.scope,
|
|
92
|
+
config_path: target.path,
|
|
93
|
+
gateway_entry_name: entryName,
|
|
94
|
+
replaced: {},
|
|
95
|
+
generated: [],
|
|
96
|
+
...(options.registryId ? { registry_id: options.registryId } : {})
|
|
97
|
+
});
|
|
98
|
+
return { configPath: target.path, entryName, backupPath: backupPath(target), alreadyConnected: false, restartHint };
|
|
99
|
+
}
|
|
100
|
+
/** Whether an app entry runs `serve -c <this gateway's config>`. */
|
|
101
|
+
function pointsAt(entry, gatewayConfig, target) {
|
|
102
|
+
if (typeof entry !== "object" || entry === null)
|
|
103
|
+
return false;
|
|
104
|
+
const args = entry.args;
|
|
105
|
+
if (!Array.isArray(args))
|
|
106
|
+
return false;
|
|
107
|
+
const at = args.indexOf("-c");
|
|
108
|
+
const value = at >= 0 ? args[at + 1] : undefined;
|
|
109
|
+
return typeof value === "string" && resolve(dirname(target.path), value) === gatewayConfig;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The entry name, or the first free numbered one. A name already taken by
|
|
113
|
+
* something else is that person's server and is never overwritten.
|
|
114
|
+
*/
|
|
115
|
+
function freeName(base, servers, target) {
|
|
116
|
+
if (servers[base] === undefined)
|
|
117
|
+
return base;
|
|
118
|
+
for (let n = 2; n <= MAX_SUFFIX; n++) {
|
|
119
|
+
const candidate = `${base}-${n}`;
|
|
120
|
+
if (servers[candidate] === undefined)
|
|
121
|
+
return candidate;
|
|
122
|
+
}
|
|
123
|
+
throw new ConnectClientError(`${target.client} already has servers called "${base}" through "${base}-${MAX_SUFFIX}". ` +
|
|
124
|
+
`Rename or remove one of them in ${target.path}, then connect again.`);
|
|
125
|
+
}
|
|
126
|
+
/** This build's own `cli.js`, which sits beside this file in `dist`. */
|
|
127
|
+
function cliPath() {
|
|
128
|
+
return stableBrewPath(fileURLToPath(new URL("./cli.js", import.meta.url)));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* What the app runs, with absolute paths.
|
|
132
|
+
*
|
|
133
|
+
* A copy on disk that will stay put -- a checkout, or a normal install --
|
|
134
|
+
* is run directly by this node: no PATH lookup at all, which is what makes
|
|
135
|
+
* it work from an app with a minimal PATH. A copy npx unpacked into its
|
|
136
|
+
* cache can be cleaned away at any time, so that case runs the published
|
|
137
|
+
* package through the npx beside this node instead.
|
|
138
|
+
*/
|
|
139
|
+
function launchCommand(platform, node) {
|
|
140
|
+
const cli = cliPath();
|
|
141
|
+
if (existsSync(cli) && !cli.includes(`${sep}_npx${sep}`))
|
|
142
|
+
return { command: node, args: [cli] };
|
|
143
|
+
const { command, args } = clientCommand({ local: false, pinVersion: VERSION });
|
|
144
|
+
const npx = join(dirname(node), platform === "win32" ? "npx.cmd" : "npx");
|
|
145
|
+
return { command: existsSync(npx) ? npx : command, args };
|
|
146
|
+
}
|
|
147
|
+
const ENV_CARRIED = ["HMCP_SECRETS_FILE", "HMCP_REGISTRY"];
|
|
148
|
+
/** The console's own non-default file locations, made absolute. */
|
|
149
|
+
function carriedEnv() {
|
|
150
|
+
const out = {};
|
|
151
|
+
for (const name of ENV_CARRIED) {
|
|
152
|
+
const value = process.env[name];
|
|
153
|
+
if (value)
|
|
154
|
+
out[name] = resolve(value);
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
const realpath = (p) => {
|
|
159
|
+
try {
|
|
160
|
+
return realpathSync(p);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
/** `<prefix>/Cellar/<formula>/<version>/<rest>`: a Homebrew folder that `brew upgrade` deletes. */
|
|
167
|
+
const CELLAR = /^(.*)[\\/]Cellar[\\/]([^\\/]+)[\\/][^\\/]+[\\/](.*)$/;
|
|
168
|
+
/**
|
|
169
|
+
* Homebrew's version-free link for a file under a versioned Cellar folder
|
|
170
|
+
* (`<prefix>/opt/<formula>/<rest>`), when it exists and is the same file.
|
|
171
|
+
* Anything else comes back unchanged.
|
|
172
|
+
*/
|
|
173
|
+
function stableBrewPath(path) {
|
|
174
|
+
const m = CELLAR.exec(path);
|
|
175
|
+
if (!m)
|
|
176
|
+
return path;
|
|
177
|
+
const opt = join(m[1], "opt", m[2], m[3]);
|
|
178
|
+
const real = realpath(path);
|
|
179
|
+
return real !== undefined && realpath(opt) === real ? opt : path;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* A path to the running node that survives an upgrade.
|
|
183
|
+
*
|
|
184
|
+
* `process.execPath` is the resolved file, which for Homebrew is
|
|
185
|
+
* `/opt/homebrew/Cellar/node/26.4.0/bin/node`. That folder is deleted by
|
|
186
|
+
* `brew upgrade` and cleanup, and an app entry naming it can no longer start
|
|
187
|
+
* the gateway at all. So look for a `node` on the found folders, then on
|
|
188
|
+
* PATH, that is the same file (by realpath) through a path that is not
|
|
189
|
+
* itself versioned -- `/opt/homebrew/bin/node`, an nvm or volta shim -- then
|
|
190
|
+
* Homebrew's `opt` link, and only then the running path.
|
|
191
|
+
*/
|
|
192
|
+
export function stableNodePath(options = {}) {
|
|
193
|
+
const execPath = options.execPath ?? process.execPath;
|
|
194
|
+
const platform = options.platform ?? process.platform;
|
|
195
|
+
const real = realpath(execPath);
|
|
196
|
+
if (real === undefined)
|
|
197
|
+
return execPath;
|
|
198
|
+
const separator = platform === "win32" ? ";" : platform === process.platform ? delimiter : ":";
|
|
199
|
+
const envDirs = (options.envPath ?? process.env["PATH"] ?? "").split(separator);
|
|
200
|
+
const exe = platform === "win32" ? "node.exe" : "node";
|
|
201
|
+
for (const dir of [...(options.pathDirs ?? []), ...envDirs]) {
|
|
202
|
+
if (!dir)
|
|
203
|
+
continue;
|
|
204
|
+
const candidate = join(dir, exe);
|
|
205
|
+
if (CELLAR.test(candidate))
|
|
206
|
+
continue;
|
|
207
|
+
if (realpath(candidate) === real)
|
|
208
|
+
return candidate;
|
|
209
|
+
}
|
|
210
|
+
return stableBrewPath(execPath);
|
|
211
|
+
}
|
|
212
|
+
const SYSTEM_PATH = {
|
|
213
|
+
darwin: ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"],
|
|
214
|
+
linux: ["/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"],
|
|
215
|
+
win32: ["C:\\Windows\\system32", "C:\\Windows", "C:\\Windows\\System32\\Wbem"]
|
|
216
|
+
};
|
|
217
|
+
/** The PATH the app gives the gateway: found folders, node's folder, then the system's. */
|
|
218
|
+
export function pathFor(pathDirs, platform = process.platform) {
|
|
219
|
+
return pathWith(pathDirs, stableNodePath({ pathDirs, platform }), platform);
|
|
220
|
+
}
|
|
221
|
+
function pathWith(pathDirs, node, platform) {
|
|
222
|
+
const system = SYSTEM_PATH[platform] ?? SYSTEM_PATH["linux"];
|
|
223
|
+
const dirs = [...pathDirs, dirname(node), ...system].filter((d) => d.length > 0);
|
|
224
|
+
return [...new Set(dirs)].join(platform === "win32" ? ";" : ":");
|
|
225
|
+
}
|
|
226
|
+
/** What a person does next in each app, in plain words. */
|
|
227
|
+
function restartHintFor(target, platform) {
|
|
228
|
+
switch (target.scope) {
|
|
229
|
+
case "claude-desktop":
|
|
230
|
+
return platform === "darwin"
|
|
231
|
+
? "Quit Claude Desktop completely (Claude menu, then Quit) and open it again. You only need to do this once."
|
|
232
|
+
: "Close Claude Desktop completely (including from the system tray) and open it again. You only need to do this once.";
|
|
233
|
+
case "user":
|
|
234
|
+
case "local":
|
|
235
|
+
return "Start a new Claude Code session so it picks this up. Sessions already open will not see it.";
|
|
236
|
+
case "project":
|
|
237
|
+
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.";
|
|
238
|
+
case "cursor-project":
|
|
239
|
+
case "cursor-user":
|
|
240
|
+
return "In Cursor, open Settings, then MCP, and make sure the new entry is switched on. If it does not appear, restart Cursor once.";
|
|
241
|
+
case "vscode-project":
|
|
242
|
+
case "vscode-user":
|
|
243
|
+
return "In VS Code, open the Command Palette, run \"MCP: List Servers\" and start the new entry. Reloading the window works too.";
|
|
244
|
+
case "windsurf":
|
|
245
|
+
return "In Windsurf, open the MCP servers list in the Cascade panel and press refresh, or restart Windsurf once.";
|
|
246
|
+
default:
|
|
247
|
+
return `Restart ${target.client} once so it picks this up.`;
|
|
248
|
+
}
|
|
249
|
+
}
|