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
@@ -0,0 +1,766 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { AuditLog, EgressGuard, type ToolContract, type PolicyReload, type Policy, type Scope, type ScopedApprovals, type ToolInventoryInput, SecretStore, type LiveConfigStateRow, type LiveRequest, type UpstreamLiveState, type UpstreamLiveStateName, type UpstreamProblem } from "hmcp-core";
3
+ import { classify } from "./classify.js";
4
+ import { type UpstreamCredential } from "./credential.js";
5
+ import { UpstreamConnection, type UpstreamTool } from "./upstream.js";
6
+ import type { GatewayConfig, Upstream } from "./config.js";
7
+ import { type ConfigChange } from "./config-source.js";
8
+ import type { UpstreamTokenSource } from "./contracts.js";
9
+ import type { ParkedNotice } from "./notify.js";
10
+ export interface GatewayTool {
11
+ readonly localName: string;
12
+ readonly upstream: UpstreamConnection;
13
+ readonly tool: UpstreamTool;
14
+ readonly effect: ReturnType<typeof classify>["effect"];
15
+ readonly effectSource: ReturnType<typeof classify>["source"];
16
+ readonly description: string;
17
+ /**
18
+ * The input schema the model is advertised. The upstream's own, verbatim,
19
+ * unless an annotation inside it carried injected text and `on_injection`
20
+ * removed that annotation; `tool.inputSchema` is always the original.
21
+ */
22
+ readonly inputSchema: unknown;
23
+ /** The display title the model is advertised, if the upstream gave a usable one. */
24
+ readonly title: string | undefined;
25
+ /** Injection findings in the upstream's own text, and what we did about them. */
26
+ readonly injection: {
27
+ readonly patternIds: readonly string[];
28
+ readonly action: "strip" | "deny" | "annotate" | "accept";
29
+ } | null;
30
+ readonly hidden: boolean;
31
+ }
32
+ /**
33
+ * A resource or a prompt as this gateway advertises it.
34
+ *
35
+ * Both are relayed rather than policed: a resource read and a prompt are
36
+ * reads of text the upstream already decided to publish, and the posture that
37
+ * governs tools has no vocabulary for either. What does apply is everything
38
+ * about *untrusted text*, because that is what they are. The description a
39
+ * resource advertises and the description and argument list a prompt
40
+ * advertises are written by the server being gated and read by the model, so
41
+ * they go through the same scan, the same `on_injection` choice and the same
42
+ * audit record as a tool's description.
43
+ */
44
+ export interface GatewayRelayed {
45
+ /** The name the model uses: namespaced for a prompt, the upstream's own URI for a resource. */
46
+ readonly localName: string;
47
+ readonly upstream: UpstreamConnection;
48
+ /** The name as the upstream knows it, which is what is sent back to it. */
49
+ readonly remoteName: string;
50
+ readonly description: string;
51
+ readonly injection: GatewayTool["injection"];
52
+ readonly hidden: boolean;
53
+ }
54
+ export interface GatewayResource extends GatewayRelayed {
55
+ readonly name: string;
56
+ readonly mimeType: string | undefined;
57
+ readonly template: boolean;
58
+ }
59
+ export interface GatewayPrompt extends GatewayRelayed {
60
+ readonly arguments: readonly {
61
+ name: string;
62
+ description?: string;
63
+ required?: boolean;
64
+ }[];
65
+ }
66
+ /** A tool this gateway would not register, and why. */
67
+ /** A tool whose advertised contract differs from its pin, as `checkPins` found it. */
68
+ export interface ChangedTool {
69
+ readonly localName: string;
70
+ readonly digest: string;
71
+ readonly was: string;
72
+ readonly pinnedAt: number;
73
+ readonly pinnedBy: string;
74
+ readonly contract: ToolContract;
75
+ readonly wasContract: ToolContract | undefined;
76
+ /** Taken off the menu because `on_tool_change` is deny. */
77
+ readonly withheld: boolean;
78
+ }
79
+ export interface WithheldTool {
80
+ readonly localName: string;
81
+ readonly upstream: string;
82
+ readonly reason: string;
83
+ }
84
+ export interface GatewayOptions {
85
+ readonly config: GatewayConfig;
86
+ readonly policy: Policy;
87
+ readonly cwd?: string;
88
+ /**
89
+ * Where the config this gateway parsed was read from, reported so a reader
90
+ * can name the file in a warning. A gateway's policy may be inline in its
91
+ * config, so this is the config path rather than a policy path.
92
+ */
93
+ readonly policyPath?: string;
94
+ /**
95
+ * Called when a call is newly parked for a person to approve. Supplied by
96
+ * whatever is serving, because only it knows whether there is a desktop to
97
+ * notify; absent, parking is silent.
98
+ */
99
+ readonly notify?: ((notice: ParkedNotice) => void) | undefined;
100
+ /**
101
+ * The gateway.yaml this config was read from, watched for server changes
102
+ * when `upstream_reload` is on. Defaults to `policyPath`, which every
103
+ * caller already sets to the config path.
104
+ */
105
+ readonly configPath?: string;
106
+ /** Where `{ secret: name }` values are resolved from. Defaults to `~/.hmcp/secrets.json`. */
107
+ readonly secrets?: SecretStore;
108
+ /**
109
+ * Where a stdio server's stderr lines go, without the `[name]` prefix and
110
+ * with secret values already removed. Defaults to the gateway's own stderr.
111
+ * The console's "Test it" passes one to show what a failing server said.
112
+ */
113
+ readonly onUpstreamStderr?: (upstream: string, line: string) => void;
114
+ /**
115
+ * Where an `oauth:` upstream's Authorization header comes from. Defaults to
116
+ * the sign-in token source in `oauth.ts`; tests pass a fake.
117
+ */
118
+ readonly tokenSource?: (spec: Extract<Upstream, {
119
+ transport: "http";
120
+ }>) => UpstreamTokenSource;
121
+ /**
122
+ * Where each server's state is published for the console, and where the
123
+ * console's "Try again" requests are read from. Defaults to the approvals
124
+ * database; `null` publishes nothing.
125
+ */
126
+ readonly liveState?: LiveStateSink | null;
127
+ /** Retry backoff for a server that failed: first wait, and the cap. 5s and 5 minutes. */
128
+ readonly retry?: {
129
+ readonly baseMs?: number;
130
+ readonly maxMs?: number;
131
+ };
132
+ /** The liveness beat, which also publishes state and picks up requests. 2s. */
133
+ readonly heartbeatMs?: number;
134
+ }
135
+ /**
136
+ * Where live state goes. The approvals database implements this (workstream
137
+ * A's `writeLiveState` / `takeLiveRequests` / `clearLiveState`); the shape is
138
+ * restated here so the gateway can run against a store that does not have
139
+ * them yet, and so a test can watch what is published.
140
+ */
141
+ export interface LiveStateSink {
142
+ writeLiveState(row: LiveConfigStateRow): void;
143
+ /** This process's unseen requests; every live process sees each one. */
144
+ takeLiveRequests(component: string, pid: number): LiveRequest[];
145
+ clearLiveState(component: string, pid: number): void;
146
+ }
147
+ /**
148
+ * One configured server and what is happening with it.
149
+ *
150
+ * A slot exists for every entry in `upstreams` whether or not it connected:
151
+ * a server that failed is still the person's server, and the console needs
152
+ * to say why it is not working and when it will be tried again.
153
+ */
154
+ export interface UpstreamSlot {
155
+ readonly spec: Upstream;
156
+ state: UpstreamLiveStateName;
157
+ connection: UpstreamConnection | undefined;
158
+ problem: UpstreamProblem | undefined;
159
+ /** Epoch ms of the last state change. */
160
+ since: number;
161
+ /** Connect attempts since the last success. */
162
+ attempts: number;
163
+ nextRetryAt: number | undefined;
164
+ timer: NodeJS.Timeout | undefined;
165
+ /**
166
+ * For a missing key or an expired sign-in: the locked-keys file's stamp
167
+ * when it failed. Retrying on a timer cannot fix either, so the slot waits
168
+ * for the file to change -- which is what saving a key or signing in does.
169
+ */
170
+ waitingOnStamp: string | undefined;
171
+ connecting: Promise<void> | undefined;
172
+ }
173
+ /**
174
+ * An MCP server that fronts other MCP servers.
175
+ *
176
+ * Upstream tool text is untrusted input: it is scanned for injection before
177
+ * being advertised, and an upstream tool with no classification is not
178
+ * reachable at all.
179
+ */
180
+ /**
181
+ * What one call knows about who is making it.
182
+ *
183
+ * Over stdio there is one client for the life of the process and this is
184
+ * constant. Over HTTP there is one per MCP session, and a hosted gateway
185
+ * resolves the tenant per request — so everything that was read off the
186
+ * instance is passed in instead, and the two transports share one code path
187
+ * rather than growing a second.
188
+ */
189
+ /**
190
+ * What the HTTP layer leaves on `AuthInfo.extra` for the handlers to read.
191
+ *
192
+ * Declared once and shared by producer and consumer. Both sides used to
193
+ * describe this shape inline and happened to agree; one structural guess is
194
+ * one too many for a value that decides which tenant a row is filed under.
195
+ */
196
+ export interface GatewayAuthExtra {
197
+ readonly tenant: string;
198
+ readonly actor: string;
199
+ }
200
+ export interface CallContext {
201
+ /** Whose rows in the approvals database this call reads and writes. */
202
+ readonly scope: Scope;
203
+ /** The tenant as policy sees it; `undefined` when none is configured. */
204
+ readonly tenantValue: string | undefined;
205
+ /** Audit `session`: one MCP session, not one process. */
206
+ readonly session: string;
207
+ /** The `Server` this call arrived on, for elicitation back to that client. */
208
+ readonly server: Server;
209
+ /**
210
+ * Who the audit record names.
211
+ *
212
+ * `token:<sub>` when a verified token identified the caller, and the bare
213
+ * literal `"agent"` over stdio, where there is one client and no identity
214
+ * on offer. The gateway used to write `"agent"` for everyone, which made
215
+ * every caller on a shared deployment look like the same one.
216
+ */
217
+ readonly actor: string;
218
+ /**
219
+ * The caller's own upstream credential, when they presented one.
220
+ *
221
+ * Carried, never stored: it lives for the duration of one call and reaches
222
+ * the upstream through an AsyncLocalStorage the transport's `fetch` reads.
223
+ * Nothing writes it to disk, and it is absent from the audit record for the
224
+ * same reason the upstream credential always has been.
225
+ */
226
+ readonly credential: UpstreamCredential | undefined;
227
+ }
228
+ /**
229
+ * What the gateway tells the AI app about itself when a session starts.
230
+ *
231
+ * With a GitHub server behind it, one more sentence: an AI app that also has
232
+ * a terminal or its own GitHub connection would otherwise use whichever it
233
+ * finds first, and a change made with `git push` or `gh` never reaches the
234
+ * policy that would have asked the person. This only asks; the console's
235
+ * "Make hmcp the only way to change GitHub" card is what closes those ways.
236
+ */
237
+ export declare function gatewayInstructions(upstreams: readonly Upstream[], mode: string): string;
238
+ /**
239
+ * The tenant a single-tenant gateway runs as, in the form every other reader
240
+ * and writer of its rows uses.
241
+ *
242
+ * Normalised here, once, because the value is half of a storage key. The CLI
243
+ * and the console both pass a tenant through `normalizeTenantKey` before they
244
+ * write a kill switch; this process used the raw string from its environment,
245
+ * so a value with a trailing newline put the gateway and the operator's
246
+ * switch under two different keys, and `exposure off` reported success while
247
+ * the tool stayed live. A value the normaliser refuses stops the gateway
248
+ * starting: it is one no switch could ever be written for.
249
+ */
250
+ export declare function resolveProcessTenant(policy: Policy): string | undefined;
251
+ export declare class Gateway {
252
+ readonly server: Server;
253
+ private config;
254
+ /**
255
+ * The policy in force, which `policySource.current()` may replace between
256
+ * calls. Everything built from policy at construction time -- the egress
257
+ * guard, the audit log, the approvals database, the resolved tenant -- is
258
+ * pinned, and `PolicySource` refuses a reload that would change any of it,
259
+ * so those and the rules below can never be enforcing different policies.
260
+ */
261
+ private readonly policySource;
262
+ private readonly egress;
263
+ private readonly audit;
264
+ private readonly approvalStore;
265
+ private readonly session;
266
+ /** Every configured server, in config order, connected or not. */
267
+ private slots;
268
+ private readonly tools;
269
+ /** Keyed by the URI the model sends back, which is the upstream's own. */
270
+ private readonly resources;
271
+ private readonly prompts;
272
+ private readonly withheldTools;
273
+ /** Every session server currently connected, so a list change reaches them all. */
274
+ private readonly live;
275
+ /** Tools whose advertised contract changed since this gateway last looked. */
276
+ private readonly changed;
277
+ private tenantValue;
278
+ /** Shared by every per-session `Server` this gateway mints. */
279
+ private readonly instructions;
280
+ private readonly cwd;
281
+ private readonly policyPath;
282
+ /** The policy file, absolute, when the policy is a file rather than inline. */
283
+ private readonly policyFile;
284
+ /** The audit `component`, which is also half of every storage scope. */
285
+ private readonly component;
286
+ /** The liveness beat, running only while this process is actually serving. */
287
+ private heartbeat;
288
+ private readonly notify;
289
+ /** The mode last announced, so a reload that changes it can say so loudly. */
290
+ private lastEnforcement;
291
+ private readonly secrets;
292
+ private readonly tokenSourceFor;
293
+ private readonly onUpstreamStderr;
294
+ private readonly liveSink;
295
+ private readonly retryBaseMs;
296
+ private readonly retryMaxMs;
297
+ private readonly heartbeatMs;
298
+ /** Failed servers are retried and crashes noticed. Off for one-shot commands (`tools`, `scan`, adopt's probe). */
299
+ private supervise;
300
+ /** Published state is only written by a process that is actually serving. */
301
+ private serving;
302
+ private closed;
303
+ private log;
304
+ /** gateway.yaml, absolute, when there is one to watch. */
305
+ private readonly configFile;
306
+ private configSource;
307
+ /** Digest of the gateway.yaml text this process has applied, and when. */
308
+ private appliedDigest;
309
+ private appliedAt;
310
+ /** Why the last change to gateway.yaml was not applied, until one is. */
311
+ private refusal;
312
+ /** Reconciles run one at a time, in the order the changes were seen. */
313
+ private reconciling;
314
+ constructor(options: GatewayOptions);
315
+ /** The servers that are connected right now, in config order. */
316
+ private get connections();
317
+ private newSlot;
318
+ private setState;
319
+ /**
320
+ * Connects every upstream and classifies its tools, all or nothing.
321
+ *
322
+ * Kept strict for the commands that inspect rather than serve -- `tools`,
323
+ * `scan`, and adopt's probe -- where a server that will not connect is the
324
+ * answer the person asked for, and for `startup: strict`.
325
+ */
326
+ connectUpstreams(): Promise<void>;
327
+ /**
328
+ * Connects every upstream at once and serves whichever made it.
329
+ *
330
+ * The default for `serve`. A person with six servers whose GitHub key
331
+ * expired used to lose all six; now they lose GitHub, the other five keep
332
+ * working, and the console says what is wrong with the sixth. Each failure
333
+ * is one plain line on stderr -- for an AI app's log, which is where
334
+ * someone without the console will look -- and is retried with backoff,
335
+ * except a missing key or an expired sign-in, which wait for the
336
+ * locked-keys file to change.
337
+ */
338
+ connectUpstreamsDegraded(log?: (line: string) => void): Promise<void>;
339
+ /**
340
+ * One connect attempt for one slot. Concurrent calls share the attempt in
341
+ * flight. An attempt whose slot was replaced or removed meanwhile -- the
342
+ * server was edited or deleted while it was connecting -- closes what it
343
+ * opened and changes nothing.
344
+ */
345
+ private attempt;
346
+ /** Records why a server is not working, says so, and decides when to try again. */
347
+ private fail;
348
+ /** A comparable stamp of the locked-keys file; a constant while the store cannot say. */
349
+ private secretsStamp;
350
+ /**
351
+ * Watches a connected server for the two things it can do on its own:
352
+ * change its tool list, and go away. A stdio server that exits while
353
+ * serving is marked failed with its last words and retried, rather than
354
+ * leaving tools on the menu that fail with "connection closed".
355
+ */
356
+ private watchConnection;
357
+ /**
358
+ * A tool call found that a server's sign-in is gone. The server is taken
359
+ * off the menu and waits for someone to sign in again, rather than
360
+ * failing every call the model makes with the same 401.
361
+ */
362
+ private noticeCallFailure;
363
+ /** Rebuilds every served map from the connected servers. */
364
+ private rebuildSurface;
365
+ /**
366
+ * The served surface changed -- a server connected, failed, or was added
367
+ * or removed. Rebuild, publish, and tell every connected AI app to fetch
368
+ * its lists again.
369
+ */
370
+ private refreshSurface;
371
+ /**
372
+ * Applies a new `upstreams` list to the running gateway.
373
+ *
374
+ * In order, because each step depends on the last:
375
+ * 1. The policy is re-read first. The console writes egress and rules for
376
+ * a new server to policy.yaml *before* it writes gateway.yaml, and a
377
+ * server connected before its host is allowed would fail for no reason
378
+ * the person could see.
379
+ * 2. Removed and changed servers are closed.
380
+ * 3. Added and changed servers are connected, in parallel, degraded.
381
+ * 4. The maps are rebuilt, published, and every session told.
382
+ */
383
+ reconcile(next: GatewayConfig): Promise<void>;
384
+ private applyUpstreams;
385
+ /** Stops a slot for good: no retry, connection closed. */
386
+ private retire;
387
+ /**
388
+ * Starts watching gateway.yaml for server changes, when `upstream_reload`
389
+ * is on and there is a file to watch. From the serving paths only.
390
+ */
391
+ watchConfig(log?: (line: string) => void): void;
392
+ /**
393
+ * Reads gateway.yaml once, now, and applies what it can. The watcher's
394
+ * path, reachable without waiting for a poll.
395
+ */
396
+ reloadConfig(): Promise<ConfigChange>;
397
+ private applyConfigChange;
398
+ /** Each server's state, as the console shows it. */
399
+ upstreamStates(): UpstreamLiveState[];
400
+ /** The row this process publishes for the console. */
401
+ liveStateRow(): LiveConfigStateRow;
402
+ private publishLiveState;
403
+ /**
404
+ * The console's "Try again", and the waits on the locked-keys file. Run
405
+ * on the heartbeat, so a click is acted on within a beat.
406
+ */
407
+ private serviceRequests;
408
+ /**
409
+ * Connects one upstream, with a deadline and an error that names it.
410
+ *
411
+ * Everything about this is for the person reading the failure. Startup is
412
+ * all-or-nothing, so one server that starts and never speaks takes the
413
+ * whole gateway with it -- and the SDK's own error says a request timed out
414
+ * without saying whose, which for someone with six servers wrapped is the
415
+ * difference between a one-line fix and an afternoon.
416
+ *
417
+ * The timeout is this gateway's rather than the transport's so that it
418
+ * covers the whole of connecting: spawning, the initialize handshake, and
419
+ * the first `tools/list`. A server can get past the handshake and then
420
+ * never answer a request, which is the shape a credential prompt takes.
421
+ */
422
+ private connectOne;
423
+ /**
424
+ * The connect itself, with the deadline. On timeout the attempt is
425
+ * aborted, which closes the client and so kills a stdio child that was
426
+ * never going to answer -- with retries, a leaked child per attempt would
427
+ * add up.
428
+ */
429
+ private connectRaw;
430
+ /**
431
+ * An upstream that gains or loses a tool says so, and the list this gateway
432
+ * serves has to follow or it is quietly wrong until someone restarts it.
433
+ *
434
+ * The whole map is rebuilt rather than patched: which tool wins a name
435
+ * collision, and which is withheld for being indistinguishable from
436
+ * another, are answers about the whole set, and a new tool can change them.
437
+ * Then whoever is connected is told, so their own cached list is refreshed.
438
+ */
439
+ private watchUpstreamTools;
440
+ /**
441
+ * Builds the served tool map from what every upstream currently advertises.
442
+ *
443
+ * Re-runnable: called at startup and again whenever an upstream's list
444
+ * changes. A tool arriving this way is classified, name-checked and scanned
445
+ * exactly like one present at startup -- an upstream must not be able to
446
+ * introduce a tool on a quieter path than the one it was wrapped on.
447
+ */
448
+ private registerTools;
449
+ /**
450
+ * Compares each tool against what this gateway last saw it advertise.
451
+ *
452
+ * The injection scan reads text and decides whether it looks like an
453
+ * instruction. It cannot tell that the text is *new*, so a server that was
454
+ * harmless when it was adopted and changed its mind a week later passed
455
+ * every check this gateway had. That is the rug pull, and noticing it needs
456
+ * yesterday's listing rather than a cleverer reading of today's.
457
+ *
458
+ * Recorded once. The pin moves to what the tool says now whether or not the
459
+ * change was wanted, because the finding belongs in the audit log -- which
460
+ * cannot be overwritten -- and a warning repeated on every start forever is
461
+ * a warning nobody reads.
462
+ */
463
+ private checkPins;
464
+ /**
465
+ * What a tool returned, after looking at it.
466
+ *
467
+ * The scan on a tool's description protects against the server. This
468
+ * protects against whatever the server was asked to fetch -- an issue body,
469
+ * a web page, a row someone else can write to -- which the server will hand
470
+ * over while behaving perfectly. It is the half of prompt injection that
471
+ * needs no compromised upstream at all.
472
+ *
473
+ * Pattern-based, and so this is a floor rather than a guarantee: it catches
474
+ * what is written in the open. The finding is recorded either way, which is
475
+ * the part that does not depend on catching everything.
476
+ */
477
+ private screenResult;
478
+ /** Tools whose advertised contract changed at the last look. */
479
+ changedTools(): readonly ChangedTool[];
480
+ /**
481
+ * The pending changes, in the shape the store publishes them. Written at
482
+ * every point the inventory is, so the console never sees a tool list from
483
+ * one moment and a change list from another.
484
+ */
485
+ private publishToolChanges;
486
+ /**
487
+ * Registers this upstream's resources and prompts.
488
+ *
489
+ * A prompt's name is namespaced like a tool's, because it is a plain
490
+ * identifier two servers can both use. A resource's URI is not: the model
491
+ * sends it back exactly as advertised, and a gateway that rewrote it would
492
+ * have to translate it back on every read and would break any URI an
493
+ * upstream hands out by other means. So URIs are carried verbatim, and the
494
+ * collision case -- two servers publishing the same URI -- is settled the
495
+ * way two indistinguishable tool names are: the first keeps it, the second
496
+ * is withheld and said out loud.
497
+ */
498
+ private adoptRelayed;
499
+ /**
500
+ * The injection scan for text that is advertised rather than called.
501
+ *
502
+ * The same four actions a tool's description gets, for the same reason: the
503
+ * model reads this text as instructions. `strip` replaces rather than edits,
504
+ * because a partial clean-up leaves an attacker room to work in whatever
505
+ * survived.
506
+ */
507
+ private scanRelayed;
508
+ /**
509
+ * Records a tool withheld because of its name, and leaves it unregistered.
510
+ *
511
+ * Unregistered means it never reaches `tools/list` and `tools/call` refuses
512
+ * it as unknown -- identically to a tool that does not exist, so probing
513
+ * cannot tell the two apart. Audited at startup like the injection findings,
514
+ * because the operator needs to know their upstream advertised something
515
+ * this gateway would not pass on.
516
+ */
517
+ private refuseName;
518
+ /**
519
+ * Publishes what this process is serving, and starts saying it is alive.
520
+ *
521
+ * Called only from the paths that actually serve, never from `tools` or
522
+ * `scan`: those connect upstreams too, and a short-lived command announcing
523
+ * itself would briefly claim a running gateway that is about to exit.
524
+ *
525
+ * Everything here is advisory. A console uses it to decide whether it may
526
+ * believe a tool list, and enforcement reads none of it, so a failure must
527
+ * cost the announcement and not the gateway.
528
+ */
529
+ announceServing(): void;
530
+ /**
531
+ * Connects the upstreams, installs the handlers, and serves - over stdio by
532
+ * default, or over a supplied transport (used by tests).
533
+ */
534
+ start(transport?: Parameters<Server["connect"]>[0]): Promise<void>;
535
+ /** Installs the handlers without connecting, for an already-connected upstream set. */
536
+ serveOn(transport: Parameters<Server["connect"]>[0]): Promise<void>;
537
+ /**
538
+ * What this gateway tells a client it can do.
539
+ *
540
+ * Resources and prompts are always announced, with `listChanged`. They used
541
+ * to be announced only when a connected upstream had them, so a client was
542
+ * never offered a list that could only be empty -- but capabilities are
543
+ * fixed when a session starts, and servers now come and go while it runs.
544
+ * A server added from the console that has resources would otherwise be
545
+ * invisible until the AI app restarted, which is the restart live apply
546
+ * exists to remove. An empty list is the honest cost.
547
+ */
548
+ private capabilities;
549
+ /**
550
+ * A `Server` for one MCP session, sharing this gateway's upstreams, policy,
551
+ * audit log and approvals store.
552
+ *
553
+ * An HTTP transport needs one of these per session rather than one per
554
+ * process: a `Server` connects to exactly one transport, and a stateful
555
+ * Streamable HTTP transport has exactly one session id, so sharing a single
556
+ * instance across clients is not a trade-off but a mistake. Everything
557
+ * expensive — the upstream connections, the tool map, the database handle —
558
+ * stays on the gateway and is shared; only the protocol object is per
559
+ * session.
560
+ *
561
+ * It also fixes something that was wrong even over stdio: `session` on an
562
+ * audit record is supposed to identify one conversation, and a single
563
+ * process-wide id made every call look like the same one.
564
+ */
565
+ newSessionServer(): {
566
+ server: Server;
567
+ session: string;
568
+ };
569
+ /**
570
+ * tools/list and tools/call are handled directly rather than through the
571
+ * higher-level helper, so each upstream's own JSON Schema is advertised
572
+ * verbatim. Converting it would mean either losing constraints or widening
573
+ * what is accepted, and a gateway must not quietly do either.
574
+ */
575
+ private installHandlers;
576
+ /**
577
+ * The four handlers for what is relayed rather than policed.
578
+ *
579
+ * Always registered, like the capabilities that announce them: a server
580
+ * added while a session is open may bring resources or prompts with it.
581
+ *
582
+ * Each read and each prompt is written to the audit log. The point of this
583
+ * gateway is that a call can be reconstructed afterwards, and a resource
584
+ * read is a call: it is how an agent gets at a file, and "which documents
585
+ * did it read" is exactly the question an auditor asks.
586
+ */
587
+ private installRelayHandlers;
588
+ /**
589
+ * The template a concrete URI came from, if one was advertised.
590
+ *
591
+ * Only the scheme and the literal text around the placeholders are matched:
592
+ * enough to know which upstream owns the URI, without this gateway trying
593
+ * to be an RFC 6570 implementation.
594
+ */
595
+ private resourceForTemplate;
596
+ /**
597
+ * Scans one upstream tool's advertised text and decides how to surface it.
598
+ *
599
+ * "Advertised text" is everything the model will read that the upstream
600
+ * wrote: the description, every annotation in the input schema at any depth,
601
+ * and the display title. Scanning the description alone meant an upstream
602
+ * only had to move its instructions one field over.
603
+ */
604
+ private prepare;
605
+ /**
606
+ * What to do about injected text in this particular tool's description.
607
+ *
608
+ * Most specific wins: a per-tool override, then the upstream's own setting,
609
+ * then the gateway default. Granularity exists because `strip` is lossy --
610
+ * it replaces a description wholesale, and the patterns include fuzzy ones
611
+ * like `urgency`, so a legitimate tool saying "call this immediately" loses
612
+ * the text the model needs and gets misused rather than failing. Without a
613
+ * narrower lever the only fix was to weaken the setting for every upstream
614
+ * at once, which is the wrong trade to be forced into.
615
+ *
616
+ * `accept` can only arrive from the per-tool map; the gateway and upstream
617
+ * settings do not offer it, so there is no way to switch injection handling
618
+ * off across a surface.
619
+ */
620
+ private injectionAction;
621
+ private elicitFn;
622
+ /**
623
+ * The scope one call's rows belong to.
624
+ *
625
+ * Takes the tenant rather than reading `this.tenantValue`, because a hosted
626
+ * gateway resolves the tenant per request while a stdio one resolves it once
627
+ * at startup. Passing it in is what lets both share this code.
628
+ */
629
+ private scopeFor;
630
+ /**
631
+ * The console's override for one tool, or undefined.
632
+ *
633
+ * A store that cannot be read is treated as "switched off", matching the
634
+ * generated runtime: an override can only ever refuse, so failing closed
635
+ * here costs availability and never reachability.
636
+ */
637
+ /** What the switched-off tools were at the last beat, so a change is noticed once. */
638
+ private exposureSeen;
639
+ /**
640
+ * A tool switched off (or back on) in the console is a change to the tool
641
+ * list every connected app shows. The call was already refused; now the
642
+ * app is told, so the tool also leaves its list (UT5).
643
+ */
644
+ private noticeExposureChange;
645
+ /** The tools switched off for this toolbox (no customer), for `tools` to mark (R3). */
646
+ switchedOffTools(): ReadonlySet<string>;
647
+ private disabledTools;
648
+ private exposureBlock;
649
+ /**
650
+ * Who is calling, for one request.
651
+ *
652
+ * `extra` is the SDK's per-request envelope. Stage 2a reads nothing from it
653
+ * yet — the tenant still comes from policy, resolved once at construction —
654
+ * but the plumbing is here so that resolving it per request later is a
655
+ * change to this one method rather than to every call path.
656
+ */
657
+ private contextFor;
658
+ /** Whether the policy in force is applied to calls or only recorded against them. */
659
+ get enforcement(): Policy["enforcement"];
660
+ /**
661
+ * Anything an operator must not be able to miss about how this gateway is
662
+ * running, as lines to print. Empty when there is nothing of the kind.
663
+ */
664
+ notices(): string[];
665
+ /** The tenant configuration this gateway runs under, for the HTTP layer. */
666
+ get tenantConfig(): Policy["tenant"];
667
+ /** Who may administer this gateway, if anyone. Absent means no surface. */
668
+ get adminConfig(): Policy["admin"];
669
+ /** This gateway's component, for records an admin action writes. */
670
+ get auditComponent(): string;
671
+ /** A scoped view for one tenant, for the admin surface. */
672
+ scopedFor(tenant: string): ScopedApprovals;
673
+ /** An audit log for an administrative act, attributed to the actor. */
674
+ adminAudit(actor: string, session: string): AuditLog;
675
+ /**
676
+ * The policy in force right now.
677
+ *
678
+ * A getter rather than a field because a reload can replace it between
679
+ * calls. Anything deciding a single call snapshots it once -- see
680
+ * `dispatch` -- so one call is never decided against two policies.
681
+ */
682
+ private get policy();
683
+ /**
684
+ * Starts watching the policy file, if there is one to watch.
685
+ *
686
+ * Called from the paths that serve, alongside `announceServing`, and never
687
+ * from `tools` or `scan`: a command that prints a listing and exits has
688
+ * nothing to reload into.
689
+ */
690
+ watchPolicy(log?: (line: string) => void): void;
691
+ /**
692
+ * Re-reads the policy once, now, and reports what happened.
693
+ *
694
+ * The same path the watcher takes, reachable without waiting for a poll —
695
+ * which is what makes the behaviour testable, and what a signal handler
696
+ * would call if one is ever wanted.
697
+ */
698
+ reloadPolicy(log?: (line: string) => void): PolicyReload;
699
+ private applyReload;
700
+ /**
701
+ * Re-run classification against the policy that was just adopted, and
702
+ * republish the surface.
703
+ *
704
+ * A tool's effect is computed once, in `prepare()`, at discovery -- and a
705
+ * policy rule's `effect` is one of the four things that can produce it. So
706
+ * without this, adopting a rule that classifies a tool left the process in a
707
+ * split state that was hard to argue was correct:
708
+ *
709
+ * - `decide()` was right, because `resolveEffect` reads the matching rule's
710
+ * own `effect` per call and never consults the cached value;
711
+ * - but `tools/list` went on advertising `readOnlyHint` and
712
+ * `destructiveHint` from the stale effect, and the published inventory went
713
+ * on saying `unclassified`, so the console, `hmcp-gateway tools` and the
714
+ * Findings view all described a tool that had just been classified as
715
+ * unclassified until the process restarted.
716
+ *
717
+ * That split is worst for exactly the case the reload exists to serve: a
718
+ * reviewer classifies a tool, the call starts working, and every screen keeps
719
+ * saying it cannot. So classification is recomputed here.
720
+ *
721
+ * Only the classification is recomputed. Injection scanning, the description
722
+ * the model is told, and `hidden` all derive from the upstream's own text,
723
+ * which a policy reload does not change -- and re-running that would write a
724
+ * second HMCP005 audit record per reload for a finding already recorded.
725
+ */
726
+ private reclassifyTools;
727
+ /**
728
+ * Hands the adopted policy's egress rules to the guard. `reconfigure`
729
+ * keeps open connections and event streams alive and retires the old
730
+ * dispatchers after they have had time to finish.
731
+ */
732
+ private reconfigureEgress;
733
+ stopWatchingPolicy(): void;
734
+ /** Advisory, like the rest of `runtime_state`: never worth failing a call over. */
735
+ private republishPolicyDigest;
736
+ /** The egress guard, so a JWKS fetch goes through the same checks. */
737
+ get egressGuard(): EgressGuard;
738
+ /** `policy` is passed in so one call's broker and decision share a snapshot. */
739
+ private broker;
740
+ /** Runs one upstream call through the shared enforcement pipeline. */
741
+ private dispatch;
742
+ /**
743
+ * Each upstream tool in the shape a reader consumes, which is the one shape
744
+ * `toolSurfaceOf` joins against exposure.
745
+ *
746
+ * The only place a `GatewayTool` becomes that, so this gateway answering for
747
+ * itself and a console reading what it published describe the same tool
748
+ * identically. `description` is what the model is told, after `on_injection`
749
+ * has had its say; `rawDescription` is the upstream's own text, kept so a
750
+ * reader can see that the two differ.
751
+ */
752
+ inventoryInputs(): ToolInventoryInput[];
753
+ /** What the gateway decided about each upstream tool, for `hmcp-gateway tools`. */
754
+ inventory(): readonly GatewayTool[];
755
+ /**
756
+ * Tools an upstream advertised that this gateway would not register.
757
+ *
758
+ * Empty until `connectUpstreams()` has run. These are absent from
759
+ * `inventory()` by design -- they were never registered -- so anything
760
+ * reporting on a tool surface has to ask for them separately.
761
+ */
762
+ withheld(): readonly WithheldTool[];
763
+ /** Scans every upstream's advertised surface, without connecting as a server. */
764
+ scanUpstreams(): import("hmcp-scanner").ScanResult;
765
+ close(): Promise<void>;
766
+ }