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.
Files changed (102) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +41 -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 +351 -0
  24. package/dist/adopt-cli.js +1857 -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 +386 -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 +535 -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 +200 -0
  38. package/dist/client-config.js +784 -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 +49 -0
  44. package/dist/connect-client.js +249 -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/draft.d.ts +71 -0
  50. package/dist/draft.js +596 -0
  51. package/dist/exposure-cli.d.ts +28 -0
  52. package/dist/exposure-cli.js +119 -0
  53. package/dist/gateway.d.ts +756 -0
  54. package/dist/gateway.js +2106 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +26 -0
  57. package/dist/notify.d.ts +44 -0
  58. package/dist/notify.js +93 -0
  59. package/dist/oauth.d.ts +139 -0
  60. package/dist/oauth.js +641 -0
  61. package/dist/observe.d.ts +10 -0
  62. package/dist/observe.js +26 -0
  63. package/dist/open.d.ts +24 -0
  64. package/dist/open.js +31 -0
  65. package/dist/packs.d.ts +119 -0
  66. package/dist/packs.js +131 -0
  67. package/dist/pin-cli.d.ts +28 -0
  68. package/dist/pin-cli.js +103 -0
  69. package/dist/probe-upstream.d.ts +31 -0
  70. package/dist/probe-upstream.js +377 -0
  71. package/dist/registry-map.d.ts +39 -0
  72. package/dist/registry-map.js +390 -0
  73. package/dist/rule-cli.d.ts +51 -0
  74. package/dist/rule-cli.js +412 -0
  75. package/dist/serve-http.d.ts +67 -0
  76. package/dist/serve-http.js +478 -0
  77. package/dist/snippet.d.ts +20 -0
  78. package/dist/snippet.js +826 -0
  79. package/dist/status-cli.d.ts +61 -0
  80. package/dist/status-cli.js +195 -0
  81. package/dist/suggest-cli.d.ts +43 -0
  82. package/dist/suggest-cli.js +279 -0
  83. package/dist/toolname.d.ts +47 -0
  84. package/dist/toolname.js +149 -0
  85. package/dist/upstream-errors.d.ts +54 -0
  86. package/dist/upstream-errors.js +330 -0
  87. package/dist/upstream.d.ts +128 -0
  88. package/dist/upstream.js +413 -0
  89. package/dist/version.d.ts +10 -0
  90. package/dist/version.js +11 -0
  91. package/package.json +50 -6
  92. package/packs/brave-search.yaml +20 -0
  93. package/packs/context7.yaml +13 -0
  94. package/packs/fetch.yaml +14 -0
  95. package/packs/filesystem.yaml +79 -0
  96. package/packs/git.yaml +29 -0
  97. package/packs/github.yaml +47 -0
  98. package/packs/huggingface.yaml +16 -0
  99. package/packs/memory.yaml +23 -0
  100. package/packs/playwright.yaml +41 -0
  101. package/packs/sequential-thinking.yaml +13 -0
  102. package/packs/time.yaml +14 -0
@@ -0,0 +1,478 @@
1
+ import { createServer } from "node:http";
2
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { ADMIN_DENIED_RULE, ExposureAuditFailed, HttpError, TenantError, TenantVerifier, applyExposureChange, bearerToken, constantTimeEquals, parseExposureChange, readBody, tokenActor, toolSurfaceOf, unprocessable } from "hmcp-core";
5
+ /**
6
+ * The whole of what a caller learns when their token does not establish a
7
+ * tenant here.
8
+ *
9
+ * One sentence for every cause. Which check failed -- expiry, audience,
10
+ * signature, a key set that could not be fetched, a key this deployment has
11
+ * misconfigured -- is useful to someone probing and, for the last two, is a
12
+ * fact about the deployment rather than about the token. The operator gets
13
+ * the specific reason in the gateway's log.
14
+ */
15
+ const TOKEN_REFUSED = "this token does not establish a tenant on this gateway";
16
+ const DEFAULT_MAX_SESSIONS = 256;
17
+ /** True for an interface only this machine can reach. */
18
+ function isLoopback(host) {
19
+ return host === "127.0.0.1" || host === "::1" || host === "localhost";
20
+ }
21
+ /** One string for "this tenant, this caller". The separator cannot occur in either. */
22
+ function ownerOf(auth) {
23
+ const extra = auth?.extra;
24
+ return extra?.tenant === undefined ? undefined : `${extra.tenant}\u0000${extra.actor ?? ""}`;
25
+ }
26
+ const DEFAULT_IDLE_MS = 10 * 60 * 1000;
27
+ /** The most of a caller-chosen path that is copied into an audit record. */
28
+ const MAX_RECORDED_PATH = 200;
29
+ /** A decoded path segment, or undefined when it is not valid percent-encoding. */
30
+ function decodePathSegment(segment) {
31
+ try {
32
+ return decodeURIComponent(segment);
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ function securityHeaders(res) {
39
+ res.setHeader("X-Content-Type-Options", "nosniff");
40
+ res.setHeader("Cache-Control", "no-store");
41
+ res.setHeader("Referrer-Policy", "no-referrer");
42
+ }
43
+ function sendJson(res, status, body) {
44
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
45
+ res.end(JSON.stringify(body, null, 2));
46
+ }
47
+ function methodNotAllowed(res, allow) {
48
+ res.setHeader("Allow", allow);
49
+ send(res, 405, "method-not-allowed", `this route accepts ${allow}`);
50
+ }
51
+ function describeRow(row) {
52
+ return row ? { setBy: row.set_by, setAt: row.set_at, reason: row.reason } : null;
53
+ }
54
+ function send(res, status, code, message) {
55
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
56
+ res.end(JSON.stringify({ error: { code, message } }, null, 2));
57
+ }
58
+ /**
59
+ * The `Host` header without its port, lowercased.
60
+ *
61
+ * Compared without the port deliberately: the port is not a security boundary
62
+ * — anything that can reach the socket knows it — while the name is what a
63
+ * rebinding attack has to forge.
64
+ */
65
+ function hostName(raw) {
66
+ if (!raw)
67
+ return undefined;
68
+ const value = raw.trim().toLowerCase();
69
+ if (value.startsWith("["))
70
+ return value.slice(0, value.indexOf("]") + 1);
71
+ const colon = value.lastIndexOf(":");
72
+ return colon === -1 ? value : value.slice(0, colon);
73
+ }
74
+ export async function serveHttp(gateway, options) {
75
+ const host = options.host ?? "127.0.0.1";
76
+ const log = options.log ?? ((line) => void process.stderr.write(`${line}\n`));
77
+ /*
78
+ * Refuse to start rather than serve many tenants out of one scope.
79
+ *
80
+ * Over HTTP every stored row is filed under the tenant, so an unverified
81
+ * tenant means anyone can file under anyone. The dangerous outcome is not a
82
+ * crash, it is a server that comes up looking fine and quietly puts every
83
+ * customer in the same bucket -- or lets one name themselves as another.
84
+ * A policy with no tenant at all is allowed: that is a single-tenant
85
+ * deployment that happens to be reachable over a socket, and it says so.
86
+ */
87
+ const tenantConfig = gateway.tenantConfig;
88
+ if (tenantConfig && tenantConfig.source.kind !== "jwt-verified") {
89
+ throw new Error(`this gateway is configured with tenant.source.kind "${tenantConfig.source.kind}", which resolves ` +
90
+ `one tenant for the whole process. Serving over HTTP means many callers share it, so the tenant ` +
91
+ `has to come from the request: use kind "jwt-verified". Remove the tenant block if this really is ` +
92
+ `a single-tenant deployment.`);
93
+ }
94
+ const verifier = tenantConfig?.source.kind === "jwt-verified"
95
+ ? new TenantVerifier(tenantConfig.source, gateway.egressGuard)
96
+ : undefined;
97
+ /*
98
+ * An admin surface with no way to authenticate anybody is the worst thing
99
+ * this process could put on a socket, so it refuses to start rather than
100
+ * serving one. A deployment with no identity provider is not left without
101
+ * a switch: that is what `hmcp-gateway exposure` is for.
102
+ */
103
+ const admin = gateway.adminConfig;
104
+ if (admin && !verifier) {
105
+ throw new Error(`this gateway has an "admin" policy block but no verified tenant source, so there is no way to tell ` +
106
+ `an administrator from anyone else. Configure tenant.source.kind "jwt-verified", or drop the admin ` +
107
+ `block and use "hmcp-gateway exposure" instead.`);
108
+ }
109
+ /*
110
+ * A socket other machines can reach, and nothing that tells one caller from
111
+ * another: refuse to start. Whoever connects would get every tool the
112
+ * policy allows, which is the configuration nobody chooses on purpose and
113
+ * the one a `--host 0.0.0.0` typed in a hurry produces. Loopback is left
114
+ * alone -- it is reachable by the same local user stdio already trusts.
115
+ */
116
+ const staticToken = verifier ? undefined : options.bearerToken;
117
+ if (options.bearerToken !== undefined && options.bearerToken.length < 16) {
118
+ throw new Error(`the gateway's bearer token is ${options.bearerToken.length} characters; use at least 16. ` +
119
+ `Generate one with: openssl rand -base64 32`);
120
+ }
121
+ if (!isLoopback(host) && !verifier && !staticToken) {
122
+ throw new Error(`refusing to listen on ${host} with no way to authenticate callers: anyone who can reach that ` +
123
+ `address would be able to call every tool this policy allows. Set HMCP_GATEWAY_TOKEN to a secret ` +
124
+ `(openssl rand -base64 32) and have clients send it as "Authorization: Bearer <token>", ` +
125
+ `or bind to 127.0.0.1.`);
126
+ }
127
+ const allowedOrigins = new Set(options.allowedOrigins ?? []);
128
+ const maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS;
129
+ const idleMs = options.sessionIdleMs ?? DEFAULT_IDLE_MS;
130
+ const allowed = new Set((options.allowedHosts ?? ["127.0.0.1", "localhost", "[::1]"]).map((h) => h.toLowerCase()));
131
+ const sessions = new Map();
132
+ function drop(id) {
133
+ const session = sessions.get(id);
134
+ if (!session)
135
+ return;
136
+ sessions.delete(id);
137
+ void session.transport.close().catch(() => undefined);
138
+ void session.server.close().catch(() => undefined);
139
+ }
140
+ /*
141
+ * A client that goes away without a DELETE leaves its session behind, and a
142
+ * long-lived hosted process would accumulate them for ever. The sweep is
143
+ * unreferenced so it never keeps the process alive on its own.
144
+ */
145
+ const sweeper = setInterval(() => {
146
+ const cutoff = Date.now() - idleMs;
147
+ for (const [id, session] of sessions)
148
+ if (session.lastSeen < cutoff)
149
+ drop(id);
150
+ // A quarter of the TTL, so a session is dropped within 25%% of its deadline
151
+ // rather than whenever a fixed timer next happens to fire. Floored so a
152
+ // short TTL cannot turn this into a hot loop.
153
+ }, Math.max(250, Math.floor(idleMs / 4)));
154
+ sweeper.unref?.();
155
+ async function openSession(owner) {
156
+ const { server } = gateway.newSessionServer();
157
+ const transport = new StreamableHTTPServerTransport({
158
+ sessionIdGenerator: () => randomUUID(),
159
+ onsessioninitialized: (id) => {
160
+ sessions.set(id, session);
161
+ session.lastSeen = Date.now();
162
+ }
163
+ });
164
+ const session = { server, transport, owner, lastSeen: Date.now() };
165
+ await server.connect(transport);
166
+ /*
167
+ * The transport is the authority on when a session ends -- a DELETE, a
168
+ * dropped connection -- so eviction hangs off it rather than being
169
+ * inferred here. Chained *after* connect and around whatever the SDK
170
+ * installed, because `Protocol.connect` assigns `transport.onclose`
171
+ * itself: setting it beforehand looks right and is silently discarded.
172
+ */
173
+ const inner = transport.onclose;
174
+ transport.onclose = () => {
175
+ inner?.();
176
+ const id = transport.sessionId;
177
+ if (id)
178
+ sessions.delete(id);
179
+ };
180
+ return session;
181
+ }
182
+ /**
183
+ * The administrative surface: three routes, one tenant, one bit.
184
+ *
185
+ * The tenant is always the one this caller's own token proved. It is never
186
+ * a path segment and never a body field -- a "act for any tenant" mode is
187
+ * a different trust model, and cross-tenant work belongs to whoever holds
188
+ * the database file, which is the CLI.
189
+ */
190
+ async function handleAdmin(url, req, res, auth) {
191
+ // Written by the verification step above, which is the only way to
192
+ // reach here: `isAdminPath` implies `admin`, and `admin` implies a
193
+ // verifier, so `auth` is always present and always carries both.
194
+ const { tenant, actor } = auth.extra;
195
+ const scoped = gateway.scopedFor(tenant);
196
+ if (!(auth.scopes ?? []).includes(admin.scope)) {
197
+ /*
198
+ * Audited, unlike a token that fails verification. This one named a
199
+ * tenant, so there is somewhere to file it; an unverified token
200
+ * establishes nothing, and letting it append to a hash-chained log
201
+ * would make the log an amplifier.
202
+ */
203
+ // The one string here a caller without the scope chooses. Bounded, and
204
+ // left encoded if it does not decode, before it goes into the log.
205
+ const tool = (url.pathname.startsWith("/admin/v1/exposure/")
206
+ ? (decodePathSegment(url.pathname.slice("/admin/v1/exposure/".length)) ?? url.pathname)
207
+ : url.pathname).slice(0, MAX_RECORDED_PATH);
208
+ gateway.adminAudit(actor, `admin:${randomUUID()}`).append({
209
+ tool,
210
+ decision: "deny",
211
+ outcome: "denied",
212
+ tenant,
213
+ rule_id: ADMIN_DENIED_RULE,
214
+ reason: `${actor} asked to administer this gateway without the required scope`
215
+ });
216
+ send(res, 403, "forbidden", "this token does not carry the scope required to administer this gateway");
217
+ return;
218
+ }
219
+ const path = url.pathname.slice("/admin/v1/".length);
220
+ if (path === "tools") {
221
+ if (req.method !== "GET")
222
+ return methodNotAllowed(res, "GET");
223
+ /*
224
+ * The same join a console makes over the published rows, from the one
225
+ * shared implementation, so an operator asking the gateway directly and
226
+ * an operator looking at a console are told the same thing.
227
+ */
228
+ sendJson(res, 200, {
229
+ tenant,
230
+ tools: toolSurfaceOf(gateway.inventoryInputs(), scoped.listDisabledTools())
231
+ });
232
+ return;
233
+ }
234
+ if (path === "exposure") {
235
+ if (req.method !== "GET")
236
+ return methodNotAllowed(res, "GET");
237
+ sendJson(res, 200, {
238
+ tenant,
239
+ disabled: scoped.listDisabledTools().map((r) => ({ tool: r.tool, ...describeRow(r) }))
240
+ });
241
+ return;
242
+ }
243
+ if (path.startsWith("exposure/")) {
244
+ if (req.method !== "PUT")
245
+ return methodNotAllowed(res, "PUT");
246
+ const tool = decodePathSegment(path.slice("exposure/".length));
247
+ if (tool === undefined) {
248
+ send(res, 400, "bad-request", "the tool name in the path is not valid percent-encoding");
249
+ return;
250
+ }
251
+ // Validated against the live surface, so a typo cannot write an orphan
252
+ // row that looks like protection and guards nothing.
253
+ const entry = gateway.inventory().find((e) => e.localName === tool);
254
+ if (!entry) {
255
+ send(res, 404, "not-found", `this gateway exposes no tool named ${JSON.stringify(tool)}`);
256
+ return;
257
+ }
258
+ const body = ((await readBody(req)) ?? {});
259
+ let change;
260
+ try {
261
+ change = parseExposureChange({ tool, disabled: body["disabled"], reason: body["reason"] ?? "" });
262
+ }
263
+ catch (err) {
264
+ throw unprocessable(`invalid exposure change: ${err.message}`);
265
+ }
266
+ try {
267
+ const result = applyExposureChange({
268
+ scoped,
269
+ audit: gateway.adminAudit(actor, `admin:${randomUUID()}`),
270
+ change,
271
+ actor,
272
+ effect: entry.effect ?? null,
273
+ channel: "the admin API"
274
+ });
275
+ sendJson(res, 200, {
276
+ tool,
277
+ tenant,
278
+ ...result,
279
+ exposure: describeRow(scoped.toolExposure(tool))
280
+ });
281
+ }
282
+ catch (err) {
283
+ if (err instanceof ExposureAuditFailed)
284
+ throw new HttpError(500, "audit-failed", err.message);
285
+ throw err;
286
+ }
287
+ return;
288
+ }
289
+ send(res, 404, "not-found", "no such admin route");
290
+ }
291
+ const http = createServer((req, res) => {
292
+ void handle(req, res).catch((err) => {
293
+ process.stderr.write(`[hmcp-gateway] ${err.stack ?? err}\n`);
294
+ if (!res.headersSent)
295
+ send(res, 500, "internal", "the gateway failed to handle this request");
296
+ });
297
+ });
298
+ async function handle(req, res) {
299
+ securityHeaders(res);
300
+ const name = hostName(req.headers.host);
301
+ if (!name || !allowed.has(name)) {
302
+ // Before anything else, including before the session lookup: a request
303
+ // that fails this check must not be able to learn whether a session id
304
+ // exists.
305
+ send(res, 403, "forbidden", `this gateway does not answer to host ${JSON.stringify(req.headers.host ?? "")}`);
306
+ return;
307
+ }
308
+ /*
309
+ * A browser attaches `Origin` to a cross-origin request; an MCP client
310
+ * that is not a browser sends none. So a request carrying one is a web
311
+ * page driving this gateway, and the Host check above does not cover
312
+ * that: a page on any site can address `http://127.0.0.1:<port>` by its
313
+ * real name. Refused unless the operator allowed that page.
314
+ */
315
+ const origin = req.headers.origin;
316
+ if (origin !== undefined && !allowedOrigins.has(origin)) {
317
+ send(res, 403, "forbidden", `this gateway does not accept requests from the web origin ${JSON.stringify(origin)}; ` +
318
+ `start it with --allow-origin ${origin} if that page is meant to connect`);
319
+ return;
320
+ }
321
+ /*
322
+ * Two surfaces, and nothing about exposure appears on the first one.
323
+ *
324
+ * `/mcp` is what the model talks to. An exposure switch reachable there
325
+ * would be reachable through the exact channel it exists to restrain:
326
+ * upstream tool results are untrusted text this gateway already scans for
327
+ * injection, so one injected result would be one call away from the model
328
+ * clearing its own kill switch, or disabling the tenant's whole surface.
329
+ * Even a read-only "list the switches" tool would hand it a map of the
330
+ * levers. The agent learns a tool is off from the refusal, which is all
331
+ * it needs.
332
+ *
333
+ * `/admin/v1` is what a person talks to, and it exists only when an
334
+ * `admin` block is configured -- otherwise these paths are an ordinary
335
+ * 404, because a 403 would confirm the feature is there.
336
+ */
337
+ const url = new URL(req.url ?? "/", `http://${name}`);
338
+ const isAdminPath = admin !== undefined && url.pathname.startsWith("/admin/v1/");
339
+ if (url.pathname !== "/mcp" && !isAdminPath) {
340
+ send(res, 404, "not-found", "the MCP endpoint is at /mcp");
341
+ return;
342
+ }
343
+ /*
344
+ * Authenticate before anything stateful. The token is verified on every
345
+ * request rather than once per session: a session id is not a credential,
346
+ * and binding authorization to it would mean a token that has since
347
+ * expired or been revoked keeps working for as long as the client holds
348
+ * the session open.
349
+ */
350
+ let auth;
351
+ if (verifier) {
352
+ const header = tenantConfig?.source.kind === "jwt-verified" ? tenantConfig.source.header_name : "authorization";
353
+ const token = bearerToken(req.headers, header);
354
+ if (!token) {
355
+ res.setHeader("WWW-Authenticate", 'Bearer realm="hmcp-gateway"');
356
+ send(res, 401, "unauthorized", `this gateway requires a bearer token in the ${header} header`);
357
+ return;
358
+ }
359
+ try {
360
+ const claim = await verifier.verify(token);
361
+ /*
362
+ * One token must not be able to do both jobs. An agent holding a
363
+ * token that carries the admin scope could clear its own kill switch
364
+ * over this surface, which is the single thing the switch exists to
365
+ * prevent -- and "don't mint agent tokens with the admin scope" is a
366
+ * convention, not a control. This makes it a control. It breaks the
367
+ * deployment where one human's token does everything, which is
368
+ * exactly the configuration being refused.
369
+ */
370
+ if (admin && url.pathname === "/mcp" && claim.scopes.includes(admin.scope)) {
371
+ send(res, 403, "forbidden", `this token carries the ${admin.scope} scope, which administers the gateway. An agent must ` +
372
+ `present a token without it; administration happens on /admin/v1, not here.`);
373
+ return;
374
+ }
375
+ // Computed once. `clientId` carries the same value rather than a
376
+ // second, differently-formatted copy of "who is calling".
377
+ const actor = tokenActor(claim.subject);
378
+ const extra = { tenant: claim.tenant, actor };
379
+ auth = { token, clientId: actor, scopes: [...claim.scopes], extra: { ...extra } };
380
+ }
381
+ catch (err) {
382
+ if (err instanceof TenantError) {
383
+ /*
384
+ * To the log, not the audit trail: an unverified token establishes
385
+ * nothing, so there is no tenant to file a record under, and letting
386
+ * anyone who can reach the socket append to a hash-chained log would
387
+ * make the log an amplifier. The token itself is never written.
388
+ */
389
+ log(`[hmcp-gateway] refused a bearer token on ${req.method} ${url.pathname}: ${err.message}`);
390
+ send(res, 403, "forbidden", TOKEN_REFUSED);
391
+ return;
392
+ }
393
+ throw err;
394
+ }
395
+ }
396
+ if (staticToken) {
397
+ /*
398
+ * Checked on every request, like the verified token above and for the
399
+ * same reason: a session id is not a credential. One answer whether the
400
+ * token was absent or wrong, so the response says nothing about which.
401
+ */
402
+ const presented = bearerToken(req.headers, "authorization");
403
+ if (!presented || !constantTimeEquals(presented, staticToken)) {
404
+ res.setHeader("WWW-Authenticate", 'Bearer realm="hmcp-gateway"');
405
+ send(res, 401, "unauthorized", "this gateway requires its bearer token in the authorization header");
406
+ return;
407
+ }
408
+ }
409
+ const id = req.headers["mcp-session-id"];
410
+ const sessionId = Array.isArray(id) ? id[0] : id;
411
+ // The SDK reads the credential off the request object and surfaces it to
412
+ // handlers as `extra.authInfo`; this is its designated hook.
413
+ const authed = req;
414
+ if (auth)
415
+ authed.auth = auth;
416
+ try {
417
+ // Inside the try, so an HttpError it raises reaches the mapping below
418
+ // rather than escaping as a 500.
419
+ if (isAdminPath) {
420
+ await handleAdmin(url, req, res, auth);
421
+ return;
422
+ }
423
+ if (sessionId) {
424
+ const session = sessions.get(sessionId);
425
+ /*
426
+ * A session belongs to whoever opened it. The token is verified on
427
+ * every request, but that only establishes who is asking -- without
428
+ * this, a second tenant holding the id could use the first tenant's
429
+ * session, and an approval prompt for its calls would go down the
430
+ * first tenant's connection. Answered exactly like an unknown id, so
431
+ * it does not confirm that the session exists.
432
+ */
433
+ if (!session || session.owner !== ownerOf(auth)) {
434
+ // The spec's answer for a session the server no longer holds; the
435
+ // client is expected to initialize again rather than retry.
436
+ send(res, 404, "no-session", "unknown or expired MCP session; initialize again");
437
+ return;
438
+ }
439
+ session.lastSeen = Date.now();
440
+ await session.transport.handleRequest(authed, res);
441
+ return;
442
+ }
443
+ // No session id: either an initialize, or a client that has lost its
444
+ // session. The transport tells the two apart and answers accordingly.
445
+ if (sessions.size >= maxSessions) {
446
+ // Each session holds a protocol object and a transport. Without a
447
+ // ceiling, `initialize` in a loop is all it takes to exhaust the
448
+ // process; idle ones are swept, so this clears on its own.
449
+ res.setHeader("Retry-After", String(Math.ceil(idleMs / 4000)));
450
+ send(res, 503, "too-many-sessions", `this gateway already holds ${maxSessions} sessions; try again shortly`);
451
+ return;
452
+ }
453
+ const session = await openSession(ownerOf(auth));
454
+ await session.transport.handleRequest(authed, res);
455
+ }
456
+ catch (err) {
457
+ if (err instanceof HttpError) {
458
+ send(res, err.status, err.code, err.message);
459
+ return;
460
+ }
461
+ throw err;
462
+ }
463
+ }
464
+ await new Promise((resolve) => http.listen(options.port, host, resolve));
465
+ const address = http.address();
466
+ const port = typeof address === "object" && address ? address.port : options.port;
467
+ return {
468
+ http,
469
+ port,
470
+ sessionCount: () => sessions.size,
471
+ async close() {
472
+ clearInterval(sweeper);
473
+ for (const id of [...sessions.keys()])
474
+ drop(id);
475
+ await new Promise((resolve) => http.close(() => resolve()));
476
+ }
477
+ };
478
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Reading setup instructions pasted from a server's README.
3
+ *
4
+ * People copy whatever the README shows: a Claude Desktop `mcpServers` block,
5
+ * a VS Code `servers` block with `inputs`, one entry, a `claude mcp add` line,
6
+ * a bare `npx …` command, or just an address. All of them become the same
7
+ * draft the catalog gives, so the next screen is the same form and Test it.
8
+ *
9
+ * The rule that matters: a key never travels into the launch template. A
10
+ * placeholder (`<YOUR_TOKEN>`, `${input:x}`) or a setting whose name says it
11
+ * is a key becomes a secret field; a real key pasted in by mistake is lifted
12
+ * into `values`, from where it goes to the locked-keys file, and the template
13
+ * only ever refers to it.
14
+ */
15
+ import type { ParsedSnippet } from "./contracts.js";
16
+ /** Why an address can't be kept as written: a key in it would be saved as plain text. Null when it's fine. */
17
+ export declare function addressKeyProblem(url: string): "userinfo" | "query" | "path" | null;
18
+ export declare function parseSnippet(text: string): ParsedSnippet;
19
+ /** Shell-style words: quotes, backslash escapes, `\` line continuations. */
20
+ export declare function tokenize(line: string): string[];