mcpose 2.0.2 → 3.0.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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +494 -37
  3. package/dist/backendClient.d.ts +5 -0
  4. package/dist/backendClient.d.ts.map +1 -1
  5. package/dist/backendClient.js +17 -9
  6. package/dist/backendClient.js.map +1 -1
  7. package/dist/core.d.ts +293 -28
  8. package/dist/core.d.ts.map +1 -1
  9. package/dist/core.js +969 -175
  10. package/dist/core.js.map +1 -1
  11. package/dist/delegation.d.ts +89 -0
  12. package/dist/delegation.d.ts.map +1 -0
  13. package/dist/delegation.js +175 -0
  14. package/dist/delegation.js.map +1 -0
  15. package/dist/eventStore.d.ts +12 -0
  16. package/dist/eventStore.d.ts.map +1 -1
  17. package/dist/eventStore.js +43 -5
  18. package/dist/eventStore.js.map +1 -1
  19. package/dist/hiddenTools.d.ts +42 -0
  20. package/dist/hiddenTools.d.ts.map +1 -0
  21. package/dist/hiddenTools.js +53 -0
  22. package/dist/hiddenTools.js.map +1 -0
  23. package/dist/index.d.ts +15 -6
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +7 -3
  26. package/dist/index.js.map +1 -1
  27. package/dist/mesh.d.ts +82 -0
  28. package/dist/mesh.d.ts.map +1 -0
  29. package/dist/mesh.js +141 -0
  30. package/dist/mesh.js.map +1 -0
  31. package/dist/middleware.d.ts +13 -0
  32. package/dist/middleware.d.ts.map +1 -1
  33. package/dist/middleware.js +27 -3
  34. package/dist/middleware.js.map +1 -1
  35. package/dist/proxyContext.d.ts +65 -5
  36. package/dist/proxyContext.d.ts.map +1 -1
  37. package/dist/proxyContext.js +39 -4
  38. package/dist/proxyContext.js.map +1 -1
  39. package/dist/rejection.d.ts +1 -1
  40. package/dist/rejection.d.ts.map +1 -1
  41. package/dist/rejection.js +1 -1
  42. package/dist/rejection.js.map +1 -1
  43. package/dist/sanitizeCatalog.d.ts +37 -0
  44. package/dist/sanitizeCatalog.d.ts.map +1 -0
  45. package/dist/sanitizeCatalog.js +86 -0
  46. package/dist/sanitizeCatalog.js.map +1 -0
  47. package/dist/sessionRegistry.d.ts +79 -0
  48. package/dist/sessionRegistry.d.ts.map +1 -0
  49. package/dist/sessionRegistry.js +83 -0
  50. package/dist/sessionRegistry.js.map +1 -0
  51. package/dist/telemetry.d.ts +29 -1
  52. package/dist/telemetry.d.ts.map +1 -1
  53. package/dist/testing.d.ts +18 -2
  54. package/dist/testing.d.ts.map +1 -1
  55. package/dist/testing.js +30 -8
  56. package/dist/testing.js.map +1 -1
  57. package/dist/version.d.ts +7 -0
  58. package/dist/version.d.ts.map +1 -0
  59. package/dist/version.js +7 -0
  60. package/dist/version.js.map +1 -0
  61. package/package.json +30 -14
  62. package/src/__tests__/_helpers.ts +64 -0
  63. package/src/__tests__/backendClient.test.ts +198 -0
  64. package/src/__tests__/core.delegation.test.ts +964 -0
  65. package/src/__tests__/core.edge.test.ts +314 -0
  66. package/src/__tests__/core.hiddenTools.predicate.test.ts +236 -0
  67. package/src/__tests__/core.localTools.test.ts +314 -0
  68. package/src/__tests__/core.mesh.test.ts +1182 -0
  69. package/src/__tests__/core.stripRequestMeta.test.ts +226 -0
  70. package/src/__tests__/core.stripResultMeta.test.ts +217 -0
  71. package/src/__tests__/core.test.ts +1019 -0
  72. package/src/__tests__/eventStore.test.ts +141 -0
  73. package/src/__tests__/mapToolResult.test.ts +101 -0
  74. package/src/__tests__/middleware.edge.test.ts +126 -0
  75. package/src/__tests__/middleware.test.ts +233 -0
  76. package/src/__tests__/proxyContext.test.ts +140 -0
  77. package/src/__tests__/sanitizeCatalog.test.ts +359 -0
  78. package/src/__tests__/startHttpProxy.lifecycle.test.ts +638 -0
  79. package/src/__tests__/startHttpProxy.registry.test.ts +409 -0
  80. package/src/__tests__/startHttpProxy.replay.test.ts +116 -0
  81. package/src/__tests__/startHttpProxy.security.test.ts +288 -0
  82. package/src/__tests__/startHttpProxy.test.ts +985 -0
  83. package/src/__tests__/testing.test.ts +250 -0
  84. package/src/__tests__/version.test.ts +12 -0
  85. package/src/backendClient.ts +83 -0
  86. package/src/core.ts +2042 -0
  87. package/src/delegation.ts +224 -0
  88. package/src/eventStore.ts +106 -0
  89. package/src/hiddenTools.ts +84 -0
  90. package/src/identity.ts +15 -0
  91. package/src/index.ts +63 -0
  92. package/src/mesh.ts +204 -0
  93. package/src/middleware.ts +101 -0
  94. package/src/proxyContext.ts +108 -0
  95. package/src/rejection.ts +37 -0
  96. package/src/sanitizeCatalog.ts +120 -0
  97. package/src/sessionRegistry.ts +142 -0
  98. package/src/telemetry.ts +46 -0
  99. package/src/testing.ts +174 -0
  100. package/src/version.ts +6 -0
package/src/core.ts ADDED
@@ -0,0 +1,2042 @@
1
+ /** MCP proxy core: wires server→upstream through middleware pipelines. */
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import * as http from 'node:http';
4
+ import * as https from 'node:https';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
9
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
10
+ import {
11
+ CallToolRequestSchema,
12
+ ErrorCode,
13
+ GetPromptRequestSchema,
14
+ ListPromptsRequestSchema,
15
+ ListResourcesRequestSchema,
16
+ type ListToolsRequest,
17
+ type ListToolsResult,
18
+ ListToolsRequestSchema,
19
+ PromptListChangedNotificationSchema,
20
+ ReadResourceRequestSchema,
21
+ ResourceListChangedNotificationSchema,
22
+ ToolListChangedNotificationSchema,
23
+ type CallToolRequest,
24
+ type CallToolRequestParams,
25
+ type CallToolResult,
26
+ type CompatibilityCallToolResult,
27
+ type ContentBlock,
28
+ type GetPromptRequest,
29
+ type GetPromptResult,
30
+ type TextContent,
31
+ type ReadResourceRequest,
32
+ type ReadResourceResult,
33
+ type ServerCapabilities,
34
+ type Tool,
35
+ McpError,
36
+ } from '@modelcontextprotocol/sdk/types.js';
37
+ import { pipe, isPassThroughObserver, type Middleware } from './middleware.js';
38
+ import type { HiddenToolPredicate } from './hiddenTools.js';
39
+ import type { BackendClient } from './backendClient.js';
40
+ import {
41
+ createProxyContext,
42
+ type ProxyContext,
43
+ type ProxyIdentity,
44
+ } from './proxyContext.js';
45
+ import type { Identity } from './identity.js';
46
+ import type {
47
+ BackendDegradedTelemetryEvent,
48
+ TelemetryEvent,
49
+ ToolCallTelemetryEvent,
50
+ } from './telemetry.js';
51
+ import {
52
+ listAcrossMesh,
53
+ namespaceName,
54
+ namespaceUri,
55
+ normalizeBackends,
56
+ routeNamespaced,
57
+ routeResourceUri,
58
+ type Backends,
59
+ type MeshEntry,
60
+ } from './mesh.js';
61
+ import {
62
+ attachDelegationMeta,
63
+ detectDelegationLoop,
64
+ readInboundDelegation,
65
+ } from './delegation.js';
66
+ import { createInMemoryEventStore, scopeEventStore } from './eventStore.js';
67
+ import {
68
+ initializeParamsOf,
69
+ replayInitialize,
70
+ type SessionRegistry,
71
+ } from './sessionRegistry.js';
72
+ import type { EventStore } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
73
+ import { rejectionMcpError } from './rejection.js';
74
+ import type { RejectionReason } from './rejection.js';
75
+ import { VERSION } from './version.js';
76
+
77
+ /**
78
+ * Middleware for tool calls.
79
+ * Uses `CompatibilityCallToolResult` to cover legacy `{ toolResult }` shape
80
+ * (protocol 2024-10-07). Narrow with `hasToolContent()` before accessing `.content`.
81
+ */
82
+ export type ToolMiddleware = Middleware<
83
+ CallToolRequest,
84
+ CompatibilityCallToolResult
85
+ >;
86
+
87
+ /** Middleware for resource reads. */
88
+ export type ResourceMiddleware = Middleware<
89
+ ReadResourceRequest,
90
+ ReadResourceResult
91
+ >;
92
+
93
+ /** Middleware for prompt fetches (`prompts/get`). */
94
+ export type PromptMiddleware = Middleware<GetPromptRequest, GetPromptResult>;
95
+
96
+ /** Middleware for tool-list responses. */
97
+ export type ListToolsMiddleware = Middleware<ListToolsRequest, ListToolsResult>;
98
+
99
+ /**
100
+ * The result channels of a `CallToolResult` — everything a redaction or
101
+ * transform middleware must account for:
102
+ *
103
+ * 1. `content` blocks (text, image, audio, resource link, embedded
104
+ * resource), each carrying its own block-level `_meta`,
105
+ * 2. `structuredContent`, the machine-readable mirror of the content,
106
+ * 3. result-level `_meta`,
107
+ * 4. `isError`,
108
+ * 5. unknown extra keys via the index signature.
109
+ *
110
+ * Redaction that maps only `.content` misses 2, 3, and the non-text
111
+ * members of 1. Use {@link mapToolResult} to cover every payload channel
112
+ * by construction; channel 3 is stripped at the proxy boundary by default
113
+ * via `ProxyOptions.stripResultMeta` (ADR-0009).
114
+ *
115
+ * This guard narrows `CompatibilityCallToolResult` to `CallToolResult`
116
+ * (has `.content` array). Both union members carry `[x: string]: unknown`,
117
+ * so this avoids unsafe casts.
118
+ */
119
+ export function hasToolContent(
120
+ r: CompatibilityCallToolResult,
121
+ ): r is CallToolResult {
122
+ return Array.isArray(r.content);
123
+ }
124
+
125
+ /**
126
+ * Handlers for {@link mapToolResult}, one per payload channel. All three
127
+ * are required, so forgetting a channel is a compile error rather than a
128
+ * silent leak.
129
+ */
130
+ export interface ToolResultHandlers {
131
+ /** Maps a text content block. Return `null` to drop the block. */
132
+ onText: (block: TextContent) => ContentBlock | null;
133
+ /**
134
+ * Maps a non-text content block (image, audio, resource link, embedded
135
+ * resource). Return `null` to drop the block.
136
+ */
137
+ onOther: (block: Exclude<ContentBlock, TextContent>) => ContentBlock | null;
138
+ /**
139
+ * Maps `structuredContent`. Called only when the field is present.
140
+ * Return `undefined` to remove the field entirely.
141
+ */
142
+ onStructured: (
143
+ structured: Record<string, unknown>,
144
+ ) => Record<string, unknown> | undefined;
145
+ }
146
+
147
+ /**
148
+ * Maps every payload channel of a tool result through the given handlers.
149
+ *
150
+ * The legacy `{ toolResult }` shape (protocol 2024-10-07) is returned
151
+ * untouched. `isError`, result-level `_meta`, and unknown extra keys are
152
+ * preserved by spread — result-level `_meta` needs no handler because the
153
+ * proxy strips it by default (`stripResultMeta`, ADR-0009); with
154
+ * `stripResultMeta: false` forwarding it is the consumer's explicit choice.
155
+ */
156
+ export function mapToolResult(
157
+ result: CompatibilityCallToolResult,
158
+ handlers: ToolResultHandlers,
159
+ ): CompatibilityCallToolResult {
160
+ if (!hasToolContent(result)) return result;
161
+ const content = result.content
162
+ .map((block) =>
163
+ block.type === 'text' ? handlers.onText(block) : handlers.onOther(block),
164
+ )
165
+ .filter((block): block is ContentBlock => block !== null);
166
+ const structured =
167
+ result.structuredContent === undefined
168
+ ? undefined
169
+ : handlers.onStructured(result.structuredContent);
170
+ const { structuredContent: _dropped, ...rest } = result;
171
+ return {
172
+ ...rest,
173
+ content,
174
+ ...(structured === undefined ? {} : { structuredContent: structured }),
175
+ };
176
+ }
177
+
178
+ /** HTTP transport options for {@link startHttpProxy}. */
179
+ export interface HttpProxyOptions {
180
+ /** Default: 3000 */
181
+ port?: number;
182
+ /**
183
+ * Bind address. Default: `'127.0.0.1'` (loopback).
184
+ *
185
+ * Binding a non-loopback address (e.g. `'0.0.0.0'`) exposes an
186
+ * unauthenticated MCP proxy holding an authenticated upstream session to
187
+ * the network, so it is a deliberate opt-in; doing so without
188
+ * {@link resolveIdentity} reports a startup warning through {@link onError}.
189
+ */
190
+ host?: string;
191
+ /** Default: '/mcp' */
192
+ path?: string;
193
+ /**
194
+ * Called for every incoming request before MCP handling. Return false to
195
+ * block (caller writes its own response). Throw to get a 401, with the error
196
+ * reported through {@link onError}.
197
+ */
198
+ onRequest?: (
199
+ req: http.IncomingMessage,
200
+ res: http.ServerResponse,
201
+ ) => boolean | Promise<boolean>;
202
+ /**
203
+ * Called on unhandled errors instead of console.error, and on every auth
204
+ * hook that throws: the request still fails closed, and the operator still
205
+ * sees why.
206
+ */
207
+ onError?: (err: unknown) => void;
208
+ /** Maximum request body size in bytes. Default: 4 MB. */
209
+ maxBodyBytes?: number;
210
+ /**
211
+ * Maximum number of concurrent MCP sessions. Excess requests return 503.
212
+ * Default: 1000. Set to `Infinity` to opt out of the cap.
213
+ *
214
+ * `0` is a valid value and means "reject every session", so it is not the
215
+ * opt-out.
216
+ */
217
+ maxSessions?: number;
218
+ /**
219
+ * Session TTL in milliseconds. Sessions are closed after this duration,
220
+ * which fires {@link onSessionClosed}. Default: 30 minutes. Finite values
221
+ * must not exceed Node's maximum timer delay of 2,147,483,647 ms. Set to
222
+ * `Infinity` to opt out of the TTL.
223
+ */
224
+ sessionTtlMs?: number;
225
+ /**
226
+ * Resolves caller identity from the initial session request.
227
+ * Called once per new session; the result is stamped on every
228
+ * {@link ProxyContext} within that session.
229
+ *
230
+ * Supply a JWT extractor, mTLS cert reader, API-key lookup, or any async
231
+ * function returning an {@link Identity}. Errors thrown here abort the
232
+ * session with a 401 and are reported through {@link onError}.
233
+ *
234
+ * @example
235
+ * resolveIdentity: extractJwtIdentity({ jwksUri: '...' })
236
+ */
237
+ resolveIdentity?: (req: http.IncomingMessage) => Identity | Promise<Identity>;
238
+ /**
239
+ * TLS options for mutual TLS (mTLS). When provided, the proxy listens on
240
+ * HTTPS and requires client certificates signed by the supplied CA.
241
+ *
242
+ * @example
243
+ * tlsOptions: {
244
+ * key: fs.readFileSync('server.key'),
245
+ * cert: fs.readFileSync('server.crt'),
246
+ * ca: fs.readFileSync('trusted-ca.crt'),
247
+ * requestCert: true,
248
+ * rejectUnauthorized: true,
249
+ * }
250
+ */
251
+ tlsOptions?: https.ServerOptions;
252
+ /**
253
+ * Event store for SSE reconnect replay. Defaults to an in-memory store
254
+ * (suitable for single-instance deployments). For multi-instance / HA
255
+ * deployments, supply a Redis or Postgres-backed implementation.
256
+ *
257
+ * Stream ids reach the store namespaced as `<sessionId>:<streamId>`, so
258
+ * one store serves every session without their replay histories mixing.
259
+ *
260
+ * Set to `null` to disable reconnect replay entirely.
261
+ */
262
+ eventStore?: EventStore | null;
263
+ /**
264
+ * Shared record of live sessions, so a client can resume after a proxy
265
+ * restart or on another instance behind a load balancer. Without one,
266
+ * sessions live only in this process and a resume against a fresh process
267
+ * is a 404.
268
+ *
269
+ * A record is written before the initialize response goes out and read
270
+ * only for an `mcp-session-id` this instance does not hold; the resumed
271
+ * session negotiates what the original did, keeps its identity, and dies
272
+ * at the original deadline. Client DELETE and TTL expiry delete the
273
+ * record, server shutdown keeps it. Pair it with the matching
274
+ * {@link eventStore} adapter, or a resumed session has no replay history.
275
+ *
276
+ * @example
277
+ * sessionRegistry: createRedisSessionRegistry(redis),
278
+ * eventStore: createRedisEventStore(redis),
279
+ */
280
+ sessionRegistry?: SessionRegistry;
281
+ /**
282
+ * Called when a session is closed (client DELETE, TTL expiry, or server
283
+ * shutdown). Wire {@link AuditMiddlewareHandle.closeSession} here to flush
284
+ * the ReplayManifest for the session.
285
+ *
286
+ * A returned promise is awaited: `server.close()` does not complete until
287
+ * every session's hook has settled, so a host that exits in the close
288
+ * callback never loses a final manifest. A throw or a rejection is routed
289
+ * to {@link onError} and never breaks teardown.
290
+ *
291
+ * @example
292
+ * onSessionClosed: (sessionId) => auditHandle.closeSession(sessionId)
293
+ */
294
+ onSessionClosed?: (sessionId: string) => unknown;
295
+ /**
296
+ * Re-validates an existing session on every routed request. Return `false`
297
+ * (or throw, which is reported through {@link onError}) to reject with 401.
298
+ * Use to bind sessions to their original credential — e.g. re-check the
299
+ * bearer token — so a leaked `mcp-session-id` alone cannot take over a
300
+ * session.
301
+ */
302
+ validateSession?: (
303
+ req: http.IncomingMessage,
304
+ session: { sessionId: string; identity?: Identity },
305
+ ) => boolean | Promise<boolean>;
306
+ /**
307
+ * Hosts allowed in the `Host` header when
308
+ * {@link enableDnsRebindingProtection} is on. Forwarded to the SDK
309
+ * transport, which only validates against a non-empty list.
310
+ *
311
+ * Default: for a loopback bind, derived from the effective bind address
312
+ * and the real listening port (`127.0.0.1:<port>`, `localhost:<port>`,
313
+ * `[::1]:<port>`). An explicit value is used verbatim, never merged with
314
+ * the derived list. No list is derived for a non-loopback bind.
315
+ */
316
+ allowedHosts?: string[];
317
+ /**
318
+ * Origins allowed in the `Origin` header. Forwarded to the SDK transport,
319
+ * which only validates against a non-empty list.
320
+ *
321
+ * Default: for a loopback bind, the derived {@link allowedHosts} entries
322
+ * as origins (`http://` or `https://` matching {@link tlsOptions}). An
323
+ * explicit value is used verbatim, never merged.
324
+ */
325
+ allowedOrigins?: string[];
326
+ /**
327
+ * Enables the SDK transport's DNS-rebinding protection (Host/Origin
328
+ * checks). Default: `true` when the effective bind address is loopback,
329
+ * `false` otherwise (a non-loopback bind usually sits behind a gateway
330
+ * that rewrites `Host`).
331
+ *
332
+ * Enabling this on a non-loopback bind without explicit
333
+ * {@link allowedHosts} / {@link allowedOrigins} validates nothing and
334
+ * reports a startup warning through {@link onError}.
335
+ */
336
+ enableDnsRebindingProtection?: boolean;
337
+ }
338
+
339
+ /**
340
+ * A tool the proxy implements itself, instead of forwarding to the
341
+ * upstream. See ADR-0007.
342
+ */
343
+ export interface LocalTool {
344
+ /** The tool definition advertised in `tools/list`. */
345
+ tool: Tool;
346
+ /**
347
+ * Runs instead of the upstream call, from inside the innermost `next`,
348
+ * so the whole `toolMiddleware` pipeline (audit, redaction) still
349
+ * applies.
350
+ */
351
+ handler: (
352
+ params: CallToolRequestParams,
353
+ context: ProxyContext,
354
+ ) => Promise<CallToolResult>;
355
+ }
356
+
357
+ /** Proxy server options. */
358
+ export interface ProxyOptions {
359
+ /**
360
+ * Human-readable name for this proxy instance. Required, and rejected at
361
+ * construction when empty or whitespace-only.
362
+ *
363
+ * It is stamped onto every `ProxyContext`, every audit event, and the
364
+ * `ReplayManifest` as provenance (ADR-0012), so a default would record a
365
+ * whole fleet under one name: attribution in appearance only (#122).
366
+ */
367
+ name: string;
368
+
369
+ /**
370
+ * Version of this proxy server (yours, not the mcpose library). MCP clients see
371
+ * it in the `initialize` response. Defaults to the mcpose library version when
372
+ * omitted; set it to your own release version when you ship your proxy.
373
+ */
374
+ version?: string;
375
+
376
+ /**
377
+ * Tool middleware in response-processing order (first = innermost).
378
+ * @example [piiMW, auditMW] // pii redacts first, audit logs clean data
379
+ */
380
+ toolMiddleware?: ReadonlyArray<ToolMiddleware>;
381
+
382
+ /** Resource middleware in response-processing order (first = innermost). */
383
+ resourceMiddleware?: ReadonlyArray<ResourceMiddleware>;
384
+
385
+ /**
386
+ * Prompt middleware in response-processing order (first = innermost),
387
+ * per ADR-0002. Runs around every `prompts/get`, in both 1:1 and mesh
388
+ * mode.
389
+ *
390
+ * Mesh routing and the `BACKEND_UNROUTABLE` rejection for an unroutable
391
+ * prompt name happen inside the innermost `next` (the ADR-0007 pattern),
392
+ * so an observing middleware such as audit records every prompt call
393
+ * including the rejected ones.
394
+ *
395
+ * `prompts/list` has no pipeline yet; hiding and pass-through for prompts
396
+ * are deferred with it (ADR-0014).
397
+ */
398
+ promptMiddleware?: ReadonlyArray<PromptMiddleware>;
399
+
400
+ /** Tool-list middleware in response-processing order (first = innermost). */
401
+ listToolsMiddleware?: ReadonlyArray<ListToolsMiddleware>;
402
+
403
+ /**
404
+ * Tools that skip transforming middleware — upstream response forwarded
405
+ * as-is. Middleware wrapped in `markPassThroughObserver()` (e.g. audit)
406
+ * still runs for these tools.
407
+ */
408
+ passThroughTools?: ReadonlyArray<string>;
409
+
410
+ /**
411
+ * Resources that skip middleware — upstream response forwarded as-is.
412
+ * Matched against the URI the client sees, which in mesh mode is
413
+ * `mcpose://<backendKey>/<uri>` (ADR-0022).
414
+ */
415
+ passThroughResources?: ReadonlyArray<string>;
416
+
417
+ /**
418
+ * Tools hidden from list_tools and rejected at runtime with
419
+ * MethodNotFound. Precedence: a tool listed here AND in
420
+ * `passThroughTools` stays hidden. Hidden filtering is applied both
421
+ * before and after `listToolsMiddleware`, so list middleware cannot
422
+ * re-expose a hidden tool.
423
+ *
424
+ * A name array cannot see through a dispatcher (meta-tool) that takes
425
+ * the real tool name as an argument. Pass a {@link HiddenToolPredicate}
426
+ * (e.g. {@link dispatcherAwareBlock}) to close that bypass: it receives
427
+ * `undefined` args during list filtering and always an object at call
428
+ * time. See ADR-0006.
429
+ */
430
+ hiddenTools?: ReadonlyArray<string> | HiddenToolPredicate;
431
+
432
+ /**
433
+ * Resources hidden from list_resources and rejected at runtime with
434
+ * InvalidRequest. Matched against the URI the client sees, which in mesh
435
+ * mode is `mcpose://<backendKey>/<uri>` (ADR-0022).
436
+ */
437
+ hiddenResources?: ReadonlyArray<string>;
438
+
439
+ /**
440
+ * Strips `params._meta` from every request the proxy forwards (tool
441
+ * calls, resource reads, list and prompt calls). Default: `true`.
442
+ *
443
+ * MCP clients put correlation identifiers there (VS Code sends
444
+ * `progressToken`, a W3C `traceparent`, and `vscode/conversationId`),
445
+ * and the upstream is frequently a third party. The strip happens at the
446
+ * proxy boundary, before the pipeline, so middleware sees the stripped
447
+ * request and can still add its own `_meta` deliberately. Progress relay
448
+ * is unaffected: the proxy reads the client's progress token from the
449
+ * server-side request `extra`, and the SDK client stamps its own token
450
+ * on the upstream request.
451
+ *
452
+ * Applies to `passThroughTools` too; disable only globally with `false`
453
+ * for upstreams that read other `_meta` keys. See ADR-0008.
454
+ */
455
+ stripRequestMeta?: boolean;
456
+
457
+ /**
458
+ * Strips top-level `_meta` from every result the proxy returns from the
459
+ * upstream (tool calls, resource reads, list and prompt calls).
460
+ * Default: `true`.
461
+ *
462
+ * The response-direction mirror of {@link stripRequestMeta}: upstreams
463
+ * stamp correlation identifiers there (the SDK stamps
464
+ * `io.modelcontextprotocol/related-task`), and the client is a third
465
+ * party to them. The strip happens at the upstream boundary, inside the
466
+ * innermost `next`, so middleware sees the stripped result and any
467
+ * `_meta` middleware adds deliberately still reaches the client.
468
+ *
469
+ * Local tool results are not stripped (they have no upstream), and
470
+ * nested `_meta` (per-tool in `tools[]`, per-block in `content`) is
471
+ * untouched. Applies to pass-through tools and resources too; disable
472
+ * only globally with `false`. See ADR-0009.
473
+ */
474
+ stripResultMeta?: boolean;
475
+
476
+ /**
477
+ * Tools the proxy implements itself. Local tools appear in `tools/list`
478
+ * (first page only, so pagination does not duplicate them) and route to
479
+ * their handler instead of the upstream, from inside the innermost
480
+ * `next`, so the full `toolMiddleware` pipeline still runs.
481
+ *
482
+ * Precedence: `hiddenTools` beats a local tool; a local tool beats (and
483
+ * shadows) an upstream tool of the same name; `passThroughTools` has no
484
+ * effect on a local tool, because pass-through means "forward the
485
+ * upstream response as-is" and a local tool has no upstream.
486
+ *
487
+ * The proxy advertises the `tools` capability when this is non-empty
488
+ * even if the upstream has none. A duplicate local tool name throws at
489
+ * {@link createProxyServer}. See ADR-0007.
490
+ */
491
+ localTools?: ReadonlyArray<LocalTool>;
492
+
493
+ /**
494
+ * Called after every tool call with timing and outcome data. Wire to any
495
+ * custom telemetry sink, or to `createOtelTelemetry` from `@mcpose/otel`
496
+ * for OpenTelemetry spans.
497
+ * A throwing sink is logged and never fails the tool call.
498
+ */
499
+ onTelemetry?: (event: TelemetryEvent) => void;
500
+ }
501
+
502
+ type ProgressToken = string | number;
503
+ type BackendRequestOptions = Parameters<BackendClient['listTools']>[1];
504
+ // Structural mirror of the SDK's `RequestHandlerExtra`. The SDK declares its
505
+ // optional members as `?: T | undefined`, so this type has to as well to stay
506
+ // assignable under `exactOptionalPropertyTypes`.
507
+ type ProxyRequestExtra = {
508
+ signal?: AbortSignal | undefined;
509
+ _meta?: { progressToken?: ProgressToken | undefined } | undefined;
510
+ sendNotification?: (notification: {
511
+ method: 'notifications/progress';
512
+ params: {
513
+ progressToken: ProgressToken;
514
+ progress: number;
515
+ total?: number;
516
+ message?: string;
517
+ };
518
+ }) => Promise<void>;
519
+ };
520
+
521
+ /**
522
+ * Subscribers to one backend's list-changed notifications, with the
523
+ * capabilities each proxy server advertises. The handlers are registered
524
+ * from the backend's own capabilities rather than any one subscriber's, so
525
+ * a backend shared between proxies that advertise different surfaces
526
+ * forwards every surface it has, and the fan-out filters per subscriber.
527
+ */
528
+ type ListChangedBus = {
529
+ servers: Set<Server>;
530
+ };
531
+
532
+ type ListChangedSurface = 'tools' | 'prompts' | 'resources';
533
+
534
+ const listChangedBuses = new WeakMap<BackendClient, ListChangedBus>();
535
+ const httpProxyContext = new AsyncLocalStorage<
536
+ Omit<ProxyContext, 'requestId'>
537
+ >();
538
+
539
+ /**
540
+ * Union of every backend's capabilities, plus the ADR-0007 rule that a
541
+ * non-empty `localTools` advertises `tools` on its own.
542
+ */
543
+ function createProxyCapabilities(
544
+ entries: ReadonlyArray<MeshEntry>,
545
+ hasLocalTools: boolean,
546
+ ): ServerCapabilities {
547
+ const upstreams = entries.map((entry) =>
548
+ entry.client.getServerCapabilities(),
549
+ );
550
+ const listChanged = (supported: boolean) =>
551
+ supported ? { listChanged: true } : {};
552
+
553
+ return {
554
+ ...(upstreams.some((u) => u?.tools) || hasLocalTools
555
+ ? { tools: listChanged(upstreams.some((u) => u?.tools?.listChanged)) }
556
+ : {}),
557
+ ...(upstreams.some((u) => u?.resources)
558
+ ? {
559
+ resources: listChanged(
560
+ upstreams.some((u) => u?.resources?.listChanged),
561
+ ),
562
+ }
563
+ : {}),
564
+ ...(upstreams.some((u) => u?.prompts)
565
+ ? { prompts: listChanged(upstreams.some((u) => u?.prompts?.listChanged)) }
566
+ : {}),
567
+ };
568
+ }
569
+
570
+ function createRequestOptions(
571
+ extra: ProxyRequestExtra = {},
572
+ ): BackendRequestOptions {
573
+ const progressToken = extra._meta?.progressToken;
574
+ // `0` and `''` are legitimate progress tokens — only undefined disables.
575
+ const onprogress =
576
+ progressToken !== undefined && extra.sendNotification
577
+ ? ({
578
+ progress,
579
+ total,
580
+ message,
581
+ }: {
582
+ progress: number;
583
+ total?: number | undefined;
584
+ message?: string | undefined;
585
+ }) => {
586
+ // A client that disconnected mid-call makes sendNotification
587
+ // reject; dropping the progress tick is the correct outcome.
588
+ void extra
589
+ .sendNotification?.({
590
+ method: 'notifications/progress',
591
+ params: {
592
+ progressToken,
593
+ progress,
594
+ ...(total === undefined ? {} : { total }),
595
+ ...(message === undefined ? {} : { message }),
596
+ },
597
+ })
598
+ .catch(() => {});
599
+ }
600
+ : undefined;
601
+
602
+ if (!extra.signal && !onprogress) return undefined;
603
+
604
+ return {
605
+ ...(extra.signal ? { signal: extra.signal } : {}),
606
+ ...(onprogress ? { onprogress } : {}),
607
+ };
608
+ }
609
+
610
+ /**
611
+ * Credential-bearing headers are stripped before headers reach
612
+ * `ProxyContext` (and through it, audit logs). Identity resolution reads
613
+ * the raw `http.IncomingMessage`, so `resolveIdentity` still sees them.
614
+ */
615
+ const SENSITIVE_HEADERS: ReadonlySet<string> = new Set([
616
+ 'authorization',
617
+ 'proxy-authorization',
618
+ 'cookie',
619
+ 'set-cookie',
620
+ 'x-api-key',
621
+ ]);
622
+
623
+ function normalizeHeaders(
624
+ headers: http.IncomingHttpHeaders,
625
+ ): Readonly<Record<string, string>> | undefined {
626
+ const normalized = Object.entries(headers).reduce<Record<string, string>>(
627
+ (acc, [key, value]) => {
628
+ if (SENSITIVE_HEADERS.has(key)) return acc;
629
+ if (typeof value === 'string') {
630
+ acc[key] = value;
631
+ return acc;
632
+ }
633
+ if (Array.isArray(value)) {
634
+ acc[key] = value.join(', ');
635
+ }
636
+ return acc;
637
+ },
638
+ {},
639
+ );
640
+
641
+ return Object.keys(normalized).length ? normalized : undefined;
642
+ }
643
+
644
+ function getMiddlewareContext(
645
+ proxy: ProxyIdentity,
646
+ signal?: AbortSignal,
647
+ delegatedFrom?: Identity[],
648
+ ): ProxyContext {
649
+ const store = httpProxyContext.getStore();
650
+ return createProxyContext({
651
+ ...store,
652
+ ...(signal === undefined ? {} : { signal }),
653
+ // A host-stamped chain wins; an extracted one fills the field only when
654
+ // the host left it unset, which keeps the extraction additive (ADR-0016).
655
+ delegatedFrom: store?.delegatedFrom ?? delegatedFrom,
656
+ proxy,
657
+ });
658
+ }
659
+
660
+ function getRejectionReason(err: unknown): RejectionReason | undefined {
661
+ const data = (err as { data?: { rejectionReason?: unknown } } | null)?.data;
662
+ return typeof data?.rejectionReason === 'string'
663
+ ? (data.rejectionReason as RejectionReason)
664
+ : undefined;
665
+ }
666
+
667
+ /**
668
+ * Removes `params._meta` at the proxy boundary, before the pipeline runs,
669
+ * so middleware sees the stripped request, can still add its own `_meta`
670
+ * deliberately, and audit hashes cover what is actually forwarded.
671
+ * Identity function when there is nothing to strip.
672
+ */
673
+ function stripParamsMeta<
674
+ Req extends { params?: { _meta?: unknown } | undefined },
675
+ >(req: Req): Req {
676
+ if (req.params === undefined || !('_meta' in req.params)) return req;
677
+ const { _meta: _stripped, ...params } = req.params;
678
+ return { ...req, params };
679
+ }
680
+
681
+ /**
682
+ * Removes top-level `_meta` from an upstream result at the proxy boundary,
683
+ * inside the innermost `next`, so middleware sees the stripped result and
684
+ * middleware-added `_meta` still reaches the client. Nested `_meta`
685
+ * (per-tool in `tools[]`, per-block in `content`) is untouched.
686
+ * Identity function when there is nothing to strip.
687
+ */
688
+ function stripTopLevelMeta<Res extends { _meta?: unknown }>(res: Res): Res {
689
+ if (!('_meta' in res)) return res;
690
+ const { _meta: _stripped, ...rest } = res;
691
+ // Omit<Res, '_meta'> still satisfies Res: `_meta` is optional.
692
+ return rest as Res;
693
+ }
694
+
695
+ /**
696
+ * Validates and indexes `localTools`. Throws on a duplicate name: there is
697
+ * no correct way to pick one, and silently keeping the last would route
698
+ * calls to a handler the configuration does not obviously name.
699
+ */
700
+ /**
701
+ * Rejects a blank proxy name at construction, like a duplicate local tool name.
702
+ *
703
+ * The name is recorded as provenance on every `ProxyContext`, audit event, and
704
+ * `ReplayManifest` (ADR-0012), so a blank one produces a trail that looks
705
+ * attributed and is not (#122). The negated check covers all three bad values
706
+ * at once: whitespace-only trims to `''`, and `''` and an omitted name (from a
707
+ * JS caller the type does not bind) are falsy already.
708
+ */
709
+ function assertProxyName(name: string): void {
710
+ if (!name?.trim()) {
711
+ throw new Error(
712
+ `mcpose: name must be a non-empty string, got ${JSON.stringify(name)}`,
713
+ );
714
+ }
715
+ }
716
+
717
+ function buildLocalToolMap(
718
+ localTools: ReadonlyArray<LocalTool> | undefined,
719
+ ): Map<string, LocalTool> {
720
+ const localToolMap = new Map<string, LocalTool>();
721
+ for (const localTool of localTools ?? []) {
722
+ const toolName = localTool.tool.name;
723
+ if (localToolMap.has(toolName)) {
724
+ throw new Error(`mcpose: duplicate local tool name "${toolName}"`);
725
+ }
726
+ localToolMap.set(toolName, localTool);
727
+ }
728
+ return localToolMap;
729
+ }
730
+
731
+ /**
732
+ * The backends advertising one surface, ready to list across and to route
733
+ * by backend key. Only these are queried or routed to, so an otherwise-valid
734
+ * prefix naming a backend without the surface is unroutable rather than a
735
+ * call the upstream cannot serve.
736
+ */
737
+ function surfaceBackends(
738
+ entries: ReadonlyArray<MeshEntry>,
739
+ surface: 'tools' | 'prompts' | 'resources',
740
+ ): {
741
+ entries: ReadonlyArray<MeshEntry>;
742
+ byKey: ReadonlyMap<string, BackendClient>;
743
+ } {
744
+ const selected = entries.filter(
745
+ (entry) => entry.client.getServerCapabilities()?.[surface] !== undefined,
746
+ );
747
+ return {
748
+ entries: selected,
749
+ byKey: new Map(selected.map((entry) => [entry.key, entry.client] as const)),
750
+ };
751
+ }
752
+
753
+ /** Normalizes the `hiddenTools` option to its predicate form. */
754
+ function toHiddenToolPredicate(
755
+ hiddenTools: ReadonlyArray<string> | HiddenToolPredicate | undefined,
756
+ ): HiddenToolPredicate {
757
+ if (typeof hiddenTools === 'function') return hiddenTools;
758
+ const hiddenToolSet = new Set(hiddenTools ?? []);
759
+ return (name) => hiddenToolSet.has(name);
760
+ }
761
+
762
+ function filterHiddenTools(
763
+ result: ListToolsResult,
764
+ isHiddenTool: HiddenToolPredicate,
765
+ ): ListToolsResult {
766
+ // List phase: a listed tool has no arguments, so args is undefined.
767
+ const tools = result.tools.filter(
768
+ (tool) => !isHiddenTool(tool.name, undefined),
769
+ );
770
+ return tools.length === result.tools.length ? result : { ...result, tools };
771
+ }
772
+
773
+ /**
774
+ * Subscribes `server` to every backend's list-changed notifications, so a
775
+ * mesh fans them in through the same per-backend bus a 1:1 proxy uses.
776
+ *
777
+ * Every subscriber advertises the union of its backends' surfaces, so a
778
+ * notification a bus can emit is always one its subscribers accept, and the
779
+ * fan-out needs no per-surface filter.
780
+ */
781
+ function registerListChangedForwarders(
782
+ entries: ReadonlyArray<MeshEntry>,
783
+ server: Server,
784
+ capabilities: ServerCapabilities,
785
+ ): void {
786
+ const leaveBuses: Array<() => void> = [];
787
+
788
+ for (const { client } of entries) {
789
+ const upstream = client.getServerCapabilities() ?? {};
790
+ const surfaces: ReadonlyArray<ListChangedSurface> = [
791
+ 'tools',
792
+ 'prompts',
793
+ 'resources',
794
+ ];
795
+ if (
796
+ !surfaces.some(
797
+ (surface) =>
798
+ capabilities[surface]?.listChanged === true &&
799
+ upstream[surface]?.listChanged === true,
800
+ )
801
+ ) {
802
+ continue;
803
+ }
804
+
805
+ let bus = listChangedBuses.get(client);
806
+
807
+ if (!bus) {
808
+ const servers = new Set<Server>();
809
+ const fanOut = async (
810
+ notify: (proxyServer: Server) => Promise<void>,
811
+ ): Promise<void> => {
812
+ await Promise.allSettled([...servers].map(notify));
813
+ };
814
+
815
+ if (upstream.tools?.listChanged) {
816
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () =>
817
+ fanOut((proxyServer) => proxyServer.sendToolListChanged()),
818
+ );
819
+ }
820
+
821
+ if (upstream.prompts?.listChanged) {
822
+ client.setNotificationHandler(PromptListChangedNotificationSchema, () =>
823
+ fanOut((proxyServer) => proxyServer.sendPromptListChanged()),
824
+ );
825
+ }
826
+
827
+ if (upstream.resources?.listChanged) {
828
+ client.setNotificationHandler(
829
+ ResourceListChangedNotificationSchema,
830
+ () => fanOut((proxyServer) => proxyServer.sendResourceListChanged()),
831
+ );
832
+ }
833
+
834
+ bus = { servers };
835
+ listChangedBuses.set(client, bus);
836
+ }
837
+
838
+ const joined = bus;
839
+ joined.servers.add(server);
840
+
841
+ let active = true;
842
+ leaveBuses.push(() => {
843
+ if (!active) return;
844
+ active = false;
845
+ joined.servers.delete(server);
846
+ if (!joined.servers.size) listChangedBuses.delete(client);
847
+ });
848
+ }
849
+
850
+ if (leaveBuses.length === 0) return;
851
+
852
+ // Accessor instead of plain assignment: a consumer setting `server.onclose`
853
+ // after createProxyServer() must not clobber the bus cleanup (which would
854
+ // leak this server into the fan-out set forever).
855
+ let consumerOnClose: (() => void) | undefined;
856
+ Object.defineProperty(server, 'onclose', {
857
+ configurable: true,
858
+ get: () => () => {
859
+ for (const leaveBus of leaveBuses) leaveBus();
860
+ consumerOnClose?.();
861
+ },
862
+ set: (fn: (() => void) | undefined) => {
863
+ consumerOnClose = fn;
864
+ },
865
+ });
866
+ }
867
+
868
+ /**
869
+ * Creates a proxy MCP server without connecting it to a transport.
870
+ *
871
+ * Mirrors upstream tool/resource/prompt lists and routes requests through
872
+ * middleware pipelines. `prompts/list` is forwarded as-is; `prompts/get`
873
+ * runs `promptMiddleware` (ADR-0014).
874
+ *
875
+ * Uses low-level `Server` (not `McpServer`) — transparent proxying requires
876
+ * generic list interception; `McpServer.tool()` needs names upfront.
877
+ *
878
+ * @param backends - Connected (or mock) upstream MCP client for a 1:1 proxy,
879
+ * or a record of named backends for mesh mode (ADR-0013), where every
880
+ * upstream tool and prompt is exposed as `<backendKey>__<name>`.
881
+ * @param options - Middleware stacks, hidden/passthrough sets.
882
+ * @returns Configured {@link Server} ready to connect.
883
+ */
884
+ export function createProxyServer(
885
+ backends: Backends,
886
+ options: ProxyOptions,
887
+ ): Server {
888
+ assertProxyName(options.name);
889
+ const { mesh, entries } = normalizeBackends(backends);
890
+ for (const { key, client } of entries) {
891
+ if (client.getServerCapabilities() === undefined) {
892
+ throw new Error(
893
+ `mcpose: backend${mesh ? ` "${key}"` : ''} is not connected (getServerCapabilities() returned undefined). Connect the backend before calling createProxyServer().`,
894
+ );
895
+ }
896
+ }
897
+ const backend = entries[0]!.client;
898
+
899
+ const localToolMap = buildLocalToolMap(options.localTools);
900
+ const toolBackends = surfaceBackends(entries, 'tools');
901
+ const promptBackends = surfaceBackends(entries, 'prompts');
902
+ const resourceBackends = surfaceBackends(entries, 'resources');
903
+ const upstreamHasTools = toolBackends.entries.length > 0;
904
+
905
+ const capabilities = createProxyCapabilities(entries, localToolMap.size > 0);
906
+ const toolPipeline = pipe(options.toolMiddleware ?? []);
907
+ // Pass-through tools skip transforming middleware but are still seen by
908
+ // observers (audit, telemetry) marked via markPassThroughObserver().
909
+ const passThroughToolPipeline = pipe(
910
+ (options.toolMiddleware ?? []).filter(isPassThroughObserver),
911
+ );
912
+ const resourcePipeline = pipe(options.resourceMiddleware ?? []);
913
+ const promptPipeline = pipe(options.promptMiddleware ?? []);
914
+ const listToolsPipeline = pipe(options.listToolsMiddleware ?? []);
915
+
916
+ const isHiddenTool = toHiddenToolPredicate(options.hiddenTools);
917
+ // Applied uniformly at every handler entry, pass-through included: a
918
+ // privacy control a per-tool option could silently switch off would be
919
+ // the same false-confidence failure as the dispatcher bypass (ADR-0006).
920
+ const stripMeta = options.stripRequestMeta !== false;
921
+ const stripRequest = <
922
+ Req extends { params?: { _meta?: unknown } | undefined },
923
+ >(
924
+ req: Req,
925
+ ): Req => (stripMeta ? stripParamsMeta(req) : req);
926
+ // The response-direction mirror: applied to every upstream result at the
927
+ // innermost `next`, never to local tool results (they have no upstream).
928
+ const stripResMeta = options.stripResultMeta !== false;
929
+ const stripResult = <Res extends { _meta?: unknown }>(res: Res): Res =>
930
+ stripResMeta ? stripTopLevelMeta(res) : res;
931
+ const passThroughToolSet = new Set(options.passThroughTools ?? []);
932
+ const hiddenResourceSet = new Set(options.hiddenResources ?? []);
933
+ const passThroughResourceSet = new Set(options.passThroughResources ?? []);
934
+
935
+ // Stamped onto every ProxyContext so middleware and the audit trail can
936
+ // attribute events to this proxy instance (#85, ADR-0012). Frozen because
937
+ // the one object is aliased into the SDK Server, every context, and every
938
+ // audit event: a middleware mutating it would rewrite provenance already
939
+ // recorded elsewhere.
940
+ const proxyIdentity: ProxyIdentity = Object.freeze({
941
+ name: options.name,
942
+ version: options.version ?? VERSION,
943
+ });
944
+
945
+ const server = new Server(proxyIdentity, { capabilities });
946
+
947
+ registerListChangedForwarders(entries, server, capabilities);
948
+
949
+ /**
950
+ * Reports a backend that dropped out of a mesh list. Failure isolation is
951
+ * only safe if the gap is visible, and a throwing sink must not turn a
952
+ * degraded list into a failed one.
953
+ */
954
+ const reportDegraded = (
955
+ context: ProxyContext,
956
+ backendKey: string,
957
+ method: BackendDegradedTelemetryEvent['method'],
958
+ error: unknown,
959
+ ): void => {
960
+ try {
961
+ options.onTelemetry?.({
962
+ type: 'backend_degraded',
963
+ requestId: context.requestId,
964
+ ...(context.sessionId === undefined
965
+ ? {}
966
+ : { sessionId: context.sessionId }),
967
+ backend: backendKey,
968
+ method,
969
+ error,
970
+ ...(context.identity === undefined
971
+ ? {}
972
+ : { identity: context.identity }),
973
+ ...(context.proxy === undefined ? {} : { proxy: context.proxy }),
974
+ });
975
+ } catch (err) {
976
+ console.error(err);
977
+ }
978
+ };
979
+
980
+ // ── Tool handlers ──────────────────────────────────────────────────────────
981
+
982
+ if (capabilities.tools) {
983
+ server.setRequestHandler(ListToolsRequestSchema, async (rawReq, extra) => {
984
+ // Read the chain before the strip, or it never survives a chained
985
+ // proxy (ADR-0016, the ADR-0011 boundary-ordering constraint).
986
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
987
+ const req = stripRequest(rawReq);
988
+ const requestOptions = createRequestOptions(extra);
989
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
990
+ const delegationError = wireError ?? detectDelegationLoop(context);
991
+ // Local tools are overlaid inside the innermost `next`, so
992
+ // listToolsMiddleware sees them exactly as it sees upstream tools.
993
+ // They are added to the first page only (no cursor), so a paginating
994
+ // client sees each local tool once; the shadow filter runs on every
995
+ // page, so the client sees exactly one entry per name.
996
+ const result = await listToolsPipeline(
997
+ req,
998
+ async (currentReq) => {
999
+ // Thrown inside the pipeline, so observing middleware records the
1000
+ // attempt rather than seeing a call that never happened.
1001
+ if (delegationError !== undefined) throw delegationError;
1002
+ const upstreamResult: ListToolsResult = mesh
1003
+ ? {
1004
+ // A mesh has no cursor that means "page 3 of the union", so
1005
+ // every backend is drained into one complete page.
1006
+ tools: await listAcrossMesh(
1007
+ toolBackends.entries,
1008
+ async (client, cursor) => {
1009
+ const page = stripResult(
1010
+ await client.listTools(
1011
+ attachDelegationMeta(
1012
+ cursor === undefined ? {} : { cursor },
1013
+ context,
1014
+ ),
1015
+ requestOptions,
1016
+ ),
1017
+ );
1018
+ return { items: page.tools, nextCursor: page.nextCursor };
1019
+ },
1020
+ (key, error) =>
1021
+ reportDegraded(context, key, 'tools/list', error),
1022
+ namespaceName,
1023
+ ),
1024
+ }
1025
+ : upstreamHasTools
1026
+ ? stripResult(
1027
+ await backend.listTools(
1028
+ attachDelegationMeta(currentReq.params, context),
1029
+ requestOptions,
1030
+ ),
1031
+ )
1032
+ : { tools: [] };
1033
+ if (!localToolMap.size) {
1034
+ return filterHiddenTools(upstreamResult, isHiddenTool);
1035
+ }
1036
+ const tools = [
1037
+ ...upstreamResult.tools.filter((t) => !localToolMap.has(t.name)),
1038
+ // A mesh response is always the only page, so local tools belong
1039
+ // on it whatever cursor the client sent.
1040
+ ...(mesh || currentReq.params?.cursor === undefined
1041
+ ? [...localToolMap.values()].map((lt) => lt.tool)
1042
+ : []),
1043
+ ];
1044
+ return filterHiddenTools({ ...upstreamResult, tools }, isHiddenTool);
1045
+ },
1046
+ context,
1047
+ );
1048
+
1049
+ return filterHiddenTools(result, isHiddenTool);
1050
+ });
1051
+
1052
+ server.setRequestHandler(CallToolRequestSchema, async (rawReq, extra) => {
1053
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1054
+ const req = stripRequest(rawReq);
1055
+ const name = req.params.name;
1056
+ const requestOptions = createRequestOptions(extra);
1057
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
1058
+ const delegationError = wireError ?? detectDelegationLoop(context);
1059
+ const start = performance.now();
1060
+
1061
+ const emitTelemetry = (
1062
+ outcome: ToolCallTelemetryEvent['outcome'],
1063
+ rejectionReason?: RejectionReason,
1064
+ ) => {
1065
+ try {
1066
+ options.onTelemetry?.({
1067
+ type: 'tool_call',
1068
+ requestId: context.requestId,
1069
+ ...(context.sessionId === undefined
1070
+ ? {}
1071
+ : { sessionId: context.sessionId }),
1072
+ tool: name,
1073
+ duration_ms: Math.round(performance.now() - start),
1074
+ outcome,
1075
+ ...(rejectionReason === undefined ? {} : { rejectionReason }),
1076
+ ...(context.identity === undefined
1077
+ ? {}
1078
+ : { identity: context.identity }),
1079
+ ...(context.proxy === undefined ? {} : { proxy: context.proxy }),
1080
+ });
1081
+ } catch (err) {
1082
+ // A throwing telemetry sink must never fail the tool call.
1083
+ console.error(err);
1084
+ }
1085
+ };
1086
+
1087
+ // Hidden beats pass-through. The rejection is thrown by the innermost
1088
+ // `next` INSIDE the pipeline so middleware (audit) observes it in-chain;
1089
+ // the backend is never called for hidden tools.
1090
+ // Call phase: args is always an object, empty when the client sent
1091
+ // none, so a dispatcher-aware predicate can fail closed on it.
1092
+ const isHidden = isHiddenTool(name, req.params.arguments ?? {});
1093
+ // Hidden beats local; local beats upstream; pass-through never
1094
+ // applies to a local tool (it has no upstream response to forward).
1095
+ const localTool = isHidden ? undefined : localToolMap.get(name);
1096
+ const pipeline =
1097
+ !isHidden && localTool === undefined && passThroughToolSet.has(name)
1098
+ ? passThroughToolPipeline
1099
+ : toolPipeline;
1100
+ // The return type is annotated on the binding rather than on the arrow:
1101
+ // Babel, which Stryker uses to instrument this file for mutation testing,
1102
+ // cannot parse an async arrow carrying a return type inside a conditional.
1103
+ const callBackend: (
1104
+ r: CallToolRequest,
1105
+ ) => Promise<CompatibilityCallToolResult> = isHidden
1106
+ ? async () => {
1107
+ throw rejectionMcpError(
1108
+ 'TOOL_HIDDEN',
1109
+ ErrorCode.MethodNotFound,
1110
+ `Tool not found: ${name}`,
1111
+ );
1112
+ }
1113
+ : localTool !== undefined
1114
+ ? (r) => localTool.handler(r.params, context)
1115
+ : mesh
1116
+ ? async (r) => {
1117
+ // Routed at the innermost `next` from the post-pipeline name,
1118
+ // so middleware can re-route a call deliberately.
1119
+ const routed = routeNamespaced(
1120
+ r.params.name,
1121
+ toolBackends.byKey,
1122
+ );
1123
+ if (routed === undefined) {
1124
+ throw rejectionMcpError(
1125
+ 'BACKEND_UNROUTABLE',
1126
+ ErrorCode.MethodNotFound,
1127
+ `Tool not found: ${r.params.name} — a mesh exposes tools as "<backendKey>__<tool>"`,
1128
+ );
1129
+ }
1130
+ return stripResult(
1131
+ await routed.client.callTool(
1132
+ attachDelegationMeta(
1133
+ { ...r.params, name: routed.name },
1134
+ context,
1135
+ ),
1136
+ undefined,
1137
+ requestOptions,
1138
+ ),
1139
+ );
1140
+ }
1141
+ : upstreamHasTools
1142
+ ? async (r) =>
1143
+ stripResult(
1144
+ await backend.callTool(
1145
+ attachDelegationMeta(r.params, context),
1146
+ undefined,
1147
+ requestOptions,
1148
+ ),
1149
+ )
1150
+ : async () => {
1151
+ // Tools-less upstream: reject inside the pipeline rather
1152
+ // than forwarding to an upstream that cannot serve it.
1153
+ throw new McpError(
1154
+ ErrorCode.MethodNotFound,
1155
+ `Tool not found: ${name}`,
1156
+ );
1157
+ };
1158
+
1159
+ try {
1160
+ // A malformed chain replaces the innermost `next` rather than
1161
+ // rejecting at the boundary, so the pipeline observes it, and it is
1162
+ // decided before the tool is: the answer says nothing about the tool.
1163
+ const result = await pipeline(
1164
+ req,
1165
+ delegationError === undefined
1166
+ ? callBackend
1167
+ : () => Promise.reject(delegationError),
1168
+ context,
1169
+ );
1170
+ // MCP signals tool-level failures in-band via isError, not by throwing.
1171
+ emitTelemetry(
1172
+ hasToolContent(result) && result.isError === true
1173
+ ? 'error'
1174
+ : 'success',
1175
+ );
1176
+ return result;
1177
+ } catch (err) {
1178
+ const reason = getRejectionReason(err);
1179
+ if (reason === undefined) emitTelemetry('error');
1180
+ else emitTelemetry('rejected', reason);
1181
+ throw err;
1182
+ }
1183
+ });
1184
+ }
1185
+
1186
+ // ── Resource handlers ──────────────────────────────────────────────────────
1187
+
1188
+ if (capabilities.resources) {
1189
+ server.setRequestHandler(
1190
+ ListResourcesRequestSchema,
1191
+ async (rawReq, extra) => {
1192
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1193
+ const context = getMiddlewareContext(
1194
+ proxyIdentity,
1195
+ extra.signal,
1196
+ chain,
1197
+ );
1198
+ const delegationError = wireError ?? detectDelegationLoop(context);
1199
+ // `resources/list` runs no pipeline, so there is no observer to
1200
+ // record the attempt: the rejection is thrown here instead.
1201
+ if (delegationError !== undefined) throw delegationError;
1202
+ const requestOptions = createRequestOptions(extra);
1203
+ const result = mesh
1204
+ ? {
1205
+ // Each URI is exposed as `mcpose://<key>/<uri>` (ADR-0022), so
1206
+ // two backends serving the same URI never collide.
1207
+ resources: await listAcrossMesh(
1208
+ resourceBackends.entries,
1209
+ async (client, cursor) => {
1210
+ const page = stripResult(
1211
+ await client.listResources(
1212
+ attachDelegationMeta(
1213
+ cursor === undefined ? {} : { cursor },
1214
+ context,
1215
+ ),
1216
+ requestOptions,
1217
+ ),
1218
+ );
1219
+ return { items: page.resources, nextCursor: page.nextCursor };
1220
+ },
1221
+ (key, error) =>
1222
+ reportDegraded(context, key, 'resources/list', error),
1223
+ namespaceUri,
1224
+ ),
1225
+ }
1226
+ : stripResult(
1227
+ await backend.listResources(
1228
+ attachDelegationMeta(stripRequest(rawReq).params, context),
1229
+ requestOptions,
1230
+ ),
1231
+ );
1232
+ if (!hiddenResourceSet.size) return result;
1233
+ return {
1234
+ ...result,
1235
+ resources: result.resources.filter(
1236
+ (r) => !hiddenResourceSet.has(r.uri),
1237
+ ),
1238
+ };
1239
+ },
1240
+ );
1241
+
1242
+ server.setRequestHandler(ReadResourceRequestSchema, (rawReq, extra) => {
1243
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1244
+ const req = stripRequest(rawReq);
1245
+ const uri = req.params.uri;
1246
+ const requestOptions = createRequestOptions(extra);
1247
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
1248
+ const delegationError = wireError ?? detectDelegationLoop(context);
1249
+
1250
+ if (hiddenResourceSet.has(uri)) {
1251
+ throw rejectionMcpError(
1252
+ 'RESOURCE_HIDDEN',
1253
+ ErrorCode.InvalidRequest,
1254
+ `Resource not found: ${uri}`,
1255
+ );
1256
+ }
1257
+ // In mesh mode the exposed URI is unwrapped to a backend and its own
1258
+ // URI; an unwrappable one is rejected loudly, with no lookup of which
1259
+ // backend listed it (ADR-0022). Resolved from the post-pipeline params
1260
+ // so middleware can re-route a read deliberately.
1261
+ const readUpstream = (
1262
+ params: ReadResourceRequest['params'],
1263
+ ): Promise<ReadResourceResult> => {
1264
+ if (delegationError !== undefined) throw delegationError;
1265
+ if (!mesh) {
1266
+ return backend
1267
+ .readResource(attachDelegationMeta(params, context), requestOptions)
1268
+ .then(stripResult);
1269
+ }
1270
+ const routed = routeResourceUri(params.uri, resourceBackends.byKey);
1271
+ if (routed === undefined) {
1272
+ throw rejectionMcpError(
1273
+ 'BACKEND_UNROUTABLE',
1274
+ ErrorCode.InvalidRequest,
1275
+ `Resource not found: ${params.uri} — a mesh exposes resources as "mcpose://<backendKey>/<uri>"`,
1276
+ );
1277
+ }
1278
+ return routed.client
1279
+ .readResource(
1280
+ attachDelegationMeta({ ...params, uri: routed.uri }, context),
1281
+ requestOptions,
1282
+ )
1283
+ .then(stripResult);
1284
+ };
1285
+
1286
+ if (passThroughResourceSet.has(uri)) {
1287
+ // A pass-through resource runs no pipeline at all, so as with
1288
+ // `resources/list` the rejection is thrown here.
1289
+ return readUpstream(req.params);
1290
+ }
1291
+ return resourcePipeline(req, (r) => readUpstream(r.params), context);
1292
+ });
1293
+ }
1294
+
1295
+ // ── Prompt handlers ───────────────────────────────────────────────────────
1296
+ // `prompts/get` runs the promptMiddleware pipeline; `prompts/list` is still
1297
+ // pass-through (ADR-0014).
1298
+
1299
+ if (capabilities.prompts && mesh) {
1300
+ // Prompt names are plain strings, so they namespace and route exactly
1301
+ // like tool names (ADR-0013).
1302
+ server.setRequestHandler(
1303
+ ListPromptsRequestSchema,
1304
+ async (rawReq, extra) => {
1305
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1306
+ const requestOptions = createRequestOptions(extra);
1307
+ const context = getMiddlewareContext(
1308
+ proxyIdentity,
1309
+ extra.signal,
1310
+ chain,
1311
+ );
1312
+ // No pipeline here either, so the rejection is thrown at the handler.
1313
+ const delegationError = wireError ?? detectDelegationLoop(context);
1314
+ if (delegationError !== undefined) throw delegationError;
1315
+ return {
1316
+ prompts: await listAcrossMesh(
1317
+ promptBackends.entries,
1318
+ async (client, cursor) => {
1319
+ const page = stripResult(
1320
+ await client.listPrompts(
1321
+ attachDelegationMeta(
1322
+ cursor === undefined ? {} : { cursor },
1323
+ context,
1324
+ ),
1325
+ requestOptions,
1326
+ ),
1327
+ );
1328
+ return { items: page.prompts, nextCursor: page.nextCursor };
1329
+ },
1330
+ (key, error) => reportDegraded(context, key, 'prompts/list', error),
1331
+ namespaceName,
1332
+ ),
1333
+ };
1334
+ },
1335
+ );
1336
+
1337
+ server.setRequestHandler(GetPromptRequestSchema, (rawReq, extra) => {
1338
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1339
+ const req = stripRequest(rawReq);
1340
+ const requestOptions = createRequestOptions(extra);
1341
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
1342
+ const delegationError = wireError ?? detectDelegationLoop(context);
1343
+ // Routed at the innermost `next` from the post-pipeline name, so the
1344
+ // rejection is thrown in-chain and middleware (audit) observes it.
1345
+ return promptPipeline(
1346
+ req,
1347
+ async (r) => {
1348
+ if (delegationError !== undefined) throw delegationError;
1349
+ const routed = routeNamespaced(r.params.name, promptBackends.byKey);
1350
+ if (routed === undefined) {
1351
+ throw rejectionMcpError(
1352
+ 'BACKEND_UNROUTABLE',
1353
+ ErrorCode.MethodNotFound,
1354
+ `Prompt not found: ${r.params.name} — a mesh exposes prompts as "<backendKey>__<prompt>"`,
1355
+ );
1356
+ }
1357
+ return stripResult(
1358
+ await routed.client.getPrompt(
1359
+ attachDelegationMeta({ ...r.params, name: routed.name }, context),
1360
+ requestOptions,
1361
+ ),
1362
+ );
1363
+ },
1364
+ context,
1365
+ );
1366
+ });
1367
+ } else if (capabilities.prompts) {
1368
+ server.setRequestHandler(ListPromptsRequestSchema, (rawReq, extra) => {
1369
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1370
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
1371
+ // No pipeline here either, so the rejection is thrown at the handler.
1372
+ const delegationError = wireError ?? detectDelegationLoop(context);
1373
+ if (delegationError !== undefined) throw delegationError;
1374
+ return backend
1375
+ .listPrompts(
1376
+ attachDelegationMeta(stripRequest(rawReq).params, context),
1377
+ createRequestOptions(extra),
1378
+ )
1379
+ .then(stripResult);
1380
+ });
1381
+
1382
+ server.setRequestHandler(GetPromptRequestSchema, (rawReq, extra) => {
1383
+ const { chain, error: wireError } = readInboundDelegation(rawReq);
1384
+ const requestOptions = createRequestOptions(extra);
1385
+ const context = getMiddlewareContext(proxyIdentity, extra.signal, chain);
1386
+ const delegationError = wireError ?? detectDelegationLoop(context);
1387
+ return promptPipeline(
1388
+ stripRequest(rawReq),
1389
+ async (r) => {
1390
+ if (delegationError !== undefined) throw delegationError;
1391
+ return stripResult(
1392
+ await backend.getPrompt(
1393
+ attachDelegationMeta(r.params, context),
1394
+ requestOptions,
1395
+ ),
1396
+ );
1397
+ },
1398
+ context,
1399
+ );
1400
+ });
1401
+ }
1402
+
1403
+ return server;
1404
+ }
1405
+
1406
+ /**
1407
+ * Starts the proxy on stdio.
1408
+ * Calls {@link createProxyServer} then connects to `StdioServerTransport`.
1409
+ * Use `createProxyServer` directly for testable access to the server.
1410
+ */
1411
+ export async function startProxy(
1412
+ backends: Backends,
1413
+ options: ProxyOptions,
1414
+ ): Promise<void> {
1415
+ const server = createProxyServer(backends, options);
1416
+ await server.connect(new StdioServerTransport());
1417
+ }
1418
+
1419
+ /**
1420
+ * Enforces `maxBodyBytes`.
1421
+ *
1422
+ * Fast path: a declared `Content-Length` over the limit is rejected before
1423
+ * any body is read. Chunked/streamed bodies are counted as they arrive.
1424
+ *
1425
+ * @returns `true` when the request was already rejected (caller must stop).
1426
+ */
1427
+ function applyBodySizeLimit(
1428
+ req: http.IncomingMessage,
1429
+ res: http.ServerResponse,
1430
+ maxBodyBytes: number,
1431
+ ): boolean {
1432
+ const reject413 = (): void => {
1433
+ if (!res.headersSent) {
1434
+ res.writeHead(413, { 'content-type': 'application/json' }).end(
1435
+ JSON.stringify({
1436
+ error: {
1437
+ message: 'Request body too large',
1438
+ data: { rejectionReason: 'BODY_LIMIT' },
1439
+ },
1440
+ }),
1441
+ );
1442
+ }
1443
+ };
1444
+
1445
+ const declared = Number(req.headers['content-length']);
1446
+ if (Number.isFinite(declared) && declared > maxBodyBytes) {
1447
+ reject413();
1448
+ req.destroy();
1449
+ return true;
1450
+ }
1451
+
1452
+ let total = 0;
1453
+ const originalPush = req.push.bind(req);
1454
+ (req as unknown as { push: typeof req.push }).push = (
1455
+ chunk: Buffer | string | null,
1456
+ enc?: BufferEncoding,
1457
+ ): boolean => {
1458
+ const chunkBytes =
1459
+ chunk === null
1460
+ ? 0
1461
+ : typeof chunk === 'string'
1462
+ ? Buffer.byteLength(chunk, enc)
1463
+ : chunk.length;
1464
+ if (chunk !== null && total + chunkBytes > maxBodyBytes) {
1465
+ reject413();
1466
+ if (res.headersSent) {
1467
+ // Too late for a clean 413 — sever the connection instead of
1468
+ // leaving the client on a hung socket.
1469
+ res.destroy();
1470
+ } else {
1471
+ // Mute the response for downstream writers (the SDK transport will
1472
+ // observe the destroyed request and try to send its own error).
1473
+ const muted = res as unknown as Record<string, unknown>;
1474
+ muted.writeHead = () => res;
1475
+ muted.write = () => true;
1476
+ muted.end = () => res;
1477
+ }
1478
+ req.destroy(new Error('Request body too large'));
1479
+ return false;
1480
+ }
1481
+ total += chunkBytes;
1482
+ return originalPush(chunk, enc);
1483
+ };
1484
+ return false;
1485
+ }
1486
+
1487
+ /**
1488
+ * True for bind addresses only reachable from the local machine.
1489
+ * `127.` catches the whole 127.0.0.0/8 block Node can bind.
1490
+ */
1491
+ function isLoopbackHost(host: string): boolean {
1492
+ return (
1493
+ host === 'localhost' ||
1494
+ host === '::1' ||
1495
+ host === '::ffff:127.0.0.1' ||
1496
+ host.startsWith('127.')
1497
+ );
1498
+ }
1499
+
1500
+ const MAX_NODE_TIMER_DELAY_MS = 2 ** 31 - 1;
1501
+
1502
+ /**
1503
+ * Starts the proxy over Streamable HTTP with stateful sessions.
1504
+ *
1505
+ * Sessions keyed by `mcp-session-id`. Upstream notifications fanned out to
1506
+ * all active sessions via their GET SSE stream. Dropped connections can
1507
+ * replay missed notifications via the built-in in-memory EventStore (or a
1508
+ * custom persistent store for multi-instance deployments).
1509
+ *
1510
+ * @returns Promise resolving to the listening `http.Server` (or `https.Server`
1511
+ * when `tlsOptions` is supplied).
1512
+ */
1513
+ export function startHttpProxy(
1514
+ backends: Backends,
1515
+ options: ProxyOptions,
1516
+ httpOptions: HttpProxyOptions = {},
1517
+ ): Promise<http.Server> {
1518
+ // Sessions build their proxy server lazily, so surface configuration
1519
+ // errors (a blank name, duplicate local tool names, invalid backend keys)
1520
+ // at startup, not on first initialize.
1521
+ assertProxyName(options.name);
1522
+ buildLocalToolMap(options.localTools);
1523
+ normalizeBackends(backends);
1524
+
1525
+ const mcpPath = httpOptions.path ?? '/mcp';
1526
+ const port = httpOptions.port ?? 3000;
1527
+ const host = httpOptions.host ?? '127.0.0.1';
1528
+ const loopback = isLoopbackHost(host);
1529
+ const dnsRebindingProtection =
1530
+ httpOptions.enableDnsRebindingProtection ?? loopback;
1531
+ // Bounded by default (#107): unlimited sessions that never expire are a
1532
+ // memory exhaustion path for any client that can initialize. `Infinity`
1533
+ // is the opt-out for both; `maxSessions: 0` already means "reject every
1534
+ // session", so it cannot double as one. The `!(x >= n)` form also
1535
+ // rejects NaN, which a plain `x < n` would let through.
1536
+ const maxSessions = httpOptions.maxSessions ?? 1000;
1537
+ const sessionTtlMs = httpOptions.sessionTtlMs ?? 30 * 60 * 1000;
1538
+ if (!(maxSessions >= 0)) {
1539
+ throw new Error(
1540
+ `mcpose: maxSessions must be >= 0 or Infinity, got ${String(httpOptions.maxSessions)}`,
1541
+ );
1542
+ }
1543
+ if (!(sessionTtlMs > 0)) {
1544
+ throw new Error(
1545
+ `mcpose: sessionTtlMs must be > 0 or Infinity, got ${String(httpOptions.sessionTtlMs)}`,
1546
+ );
1547
+ }
1548
+ if (Number.isFinite(sessionTtlMs) && sessionTtlMs > MAX_NODE_TIMER_DELAY_MS) {
1549
+ throw new Error(
1550
+ `mcpose: sessionTtlMs must be <= ${MAX_NODE_TIMER_DELAY_MS} or Infinity, got ${String(httpOptions.sessionTtlMs)}`,
1551
+ );
1552
+ }
1553
+ // Filled in once the server is listening (the real port is only known
1554
+ // then); sessions are only created after that. The SDK transport
1555
+ // validates Host/Origin only against a non-empty list, so an enabled flag
1556
+ // without a list would be an inert control — see #74.
1557
+ let derivedAllowedHosts: string[] | undefined;
1558
+ let derivedAllowedOrigins: string[] | undefined;
1559
+ const eventStore =
1560
+ httpOptions.eventStore === null
1561
+ ? undefined
1562
+ : (httpOptions.eventStore ?? createInMemoryEventStore());
1563
+ const registry = httpOptions.sessionRegistry;
1564
+
1565
+ interface Session {
1566
+ transport: StreamableHTTPServerTransport;
1567
+ proxyServer: Server;
1568
+ identity?: Identity;
1569
+ ttlTimer?: NodeJS.Timeout;
1570
+ }
1571
+ // session ID → live session held by this instance
1572
+ const sessions = new Map<string, Session>();
1573
+
1574
+ // Sessions being initialized or resumed (identity resolution or registry
1575
+ // lookup in flight) — counted so concurrent admissions cannot overshoot
1576
+ // maxSessions.
1577
+ let pendingSessions = 0;
1578
+
1579
+ const reportError = (err: unknown): void => {
1580
+ (httpOptions.onError ?? console.error)(err);
1581
+ };
1582
+
1583
+ /**
1584
+ * Single teardown path for every way a session can end: client DELETE,
1585
+ * TTL expiry, and server shutdown. Clears the TTL timer, drops the shared
1586
+ * record unless the session is meant to outlive this process, fires and
1587
+ * awaits `onSessionClosed` (guarded — a throwing or rejecting hook must not
1588
+ * break teardown), and closes the proxy server so it leaves the listChanged
1589
+ * fan-out bus. Idempotent: a second call for the same id is a no-op.
1590
+ */
1591
+ const destroySession = async (
1592
+ id: string,
1593
+ keepRecord = false,
1594
+ ): Promise<void> => {
1595
+ const session = sessions.get(id);
1596
+ if (!session) return;
1597
+ sessions.delete(id);
1598
+ if (session.ttlTimer !== undefined) clearTimeout(session.ttlTimer);
1599
+ if (registry && !keepRecord) await registry.delete(id).catch(reportError);
1600
+ try {
1601
+ await httpOptions.onSessionClosed?.(id);
1602
+ } catch (err) {
1603
+ reportError(err);
1604
+ }
1605
+ await session.proxyServer.close().catch(reportError);
1606
+ };
1607
+
1608
+ /**
1609
+ * Takes a session live on this instance. `expiresAt` is the session's
1610
+ * deadline fixed at creation, so a resumed session gets the remaining
1611
+ * lifetime rather than a fresh TTL; `undefined` means it never expires.
1612
+ */
1613
+ const admitSession = (
1614
+ id: string,
1615
+ transport: StreamableHTTPServerTransport,
1616
+ proxyServer: Server,
1617
+ identity: Identity | undefined,
1618
+ expiresAt: number | undefined,
1619
+ ): void => {
1620
+ let ttlTimer: NodeJS.Timeout | undefined;
1621
+ if (expiresAt !== undefined) {
1622
+ // A record from a proxy with a longer TTL may still exceed Node's
1623
+ // timer ceiling; clamping only makes that timer fire early and
1624
+ // re-check nothing, since the session is then simply closed.
1625
+ const remaining = Math.min(
1626
+ Math.max(expiresAt - Date.now(), 0),
1627
+ MAX_NODE_TIMER_DELAY_MS,
1628
+ );
1629
+ ttlTimer = setTimeout(() => {
1630
+ void destroySession(id);
1631
+ }, remaining);
1632
+ ttlTimer.unref();
1633
+ }
1634
+ sessions.set(id, {
1635
+ transport,
1636
+ proxyServer,
1637
+ ...(identity === undefined ? {} : { identity }),
1638
+ ...(ttlTimer === undefined ? {} : { ttlTimer }),
1639
+ });
1640
+ };
1641
+
1642
+ const sessionLimitBody = JSON.stringify({
1643
+ error: {
1644
+ message: 'Session limit reached',
1645
+ data: { rejectionReason: 'SESSION_LIMIT' },
1646
+ },
1647
+ });
1648
+
1649
+ // Builds the transport for one session. The id is fixed before the
1650
+ // transport exists so the event store can be scoped to it: stream ids are
1651
+ // namespaced per session (#154).
1652
+ const createTransport = (
1653
+ sessionId: string,
1654
+ onsessioninitialized: (id: string) => void | Promise<void>,
1655
+ ): StreamableHTTPServerTransport => {
1656
+ // An explicit list is used verbatim; the derived loopback list only
1657
+ // fills the gap so the default actually validates something.
1658
+ const allowedHosts = httpOptions.allowedHosts ?? derivedAllowedHosts;
1659
+ const allowedOrigins = httpOptions.allowedOrigins ?? derivedAllowedOrigins;
1660
+ return new StreamableHTTPServerTransport({
1661
+ sessionIdGenerator: () => sessionId,
1662
+ ...(eventStore
1663
+ ? { eventStore: scopeEventStore(eventStore, sessionId) }
1664
+ : {}),
1665
+ ...(allowedHosts ? { allowedHosts } : {}),
1666
+ ...(allowedOrigins ? { allowedOrigins } : {}),
1667
+ enableDnsRebindingProtection: dnsRebindingProtection,
1668
+ onsessioninitialized,
1669
+ onsessionclosed: (id) => {
1670
+ void destroySession(id);
1671
+ },
1672
+ });
1673
+ };
1674
+
1675
+ // Resumes in flight, so concurrent requests for one unknown id build one
1676
+ // session between them instead of one each.
1677
+ const resuming = new Map<
1678
+ string,
1679
+ Promise<Session | { status: number; body: string } | undefined>
1680
+ >();
1681
+
1682
+ /**
1683
+ * Rebuilds a session this instance does not hold from its shared record:
1684
+ * `undefined` when the registry has no live record for it, or the SDK's
1685
+ * own rejection when the replayed initialize did not bring the transport
1686
+ * up (a failed Host or Origin check, which the real request would fail
1687
+ * identically).
1688
+ */
1689
+ const resumeSession = (
1690
+ id: string,
1691
+ sharedRegistry: SessionRegistry,
1692
+ req: http.IncomingMessage,
1693
+ ): Promise<Session | { status: number; body: string } | undefined> => {
1694
+ const inflight = resuming.get(id);
1695
+ if (inflight) return inflight;
1696
+ pendingSessions += 1;
1697
+ const attempt = (async () => {
1698
+ const record = await sharedRegistry.get(id);
1699
+ if (
1700
+ record === undefined ||
1701
+ (record.expiresAt !== undefined && record.expiresAt <= Date.now())
1702
+ ) {
1703
+ return undefined;
1704
+ }
1705
+ // The pending slot is already counted, so this instance can be full
1706
+ // by exactly one.
1707
+ if (sessions.size + pendingSessions > maxSessions) {
1708
+ return { status: 503, body: sessionLimitBody };
1709
+ }
1710
+ const proxyServer = createProxyServer(backends, options);
1711
+ const transport = createTransport(id, (sid) => {
1712
+ admitSession(
1713
+ sid,
1714
+ transport,
1715
+ proxyServer,
1716
+ record.identity,
1717
+ record.expiresAt,
1718
+ );
1719
+ });
1720
+ try {
1721
+ await proxyServer.connect(transport as Transport);
1722
+ const answer = await replayInitialize(transport, record.initialize, {
1723
+ ...(req.headers.host === undefined ? {} : { host: req.headers.host }),
1724
+ ...(req.headers.origin === undefined
1725
+ ? {}
1726
+ : { origin: req.headers.origin }),
1727
+ });
1728
+ return sessions.get(id) ?? answer;
1729
+ } finally {
1730
+ // Not admitted, whether the SDK refused the replay or threw: close
1731
+ // the orphaned proxy server before it leaks (memory + listChanged
1732
+ // fan-out), as the fresh-session path does.
1733
+ if (!sessions.has(id)) void proxyServer.close().catch(reportError);
1734
+ }
1735
+ })().finally(() => {
1736
+ resuming.delete(id);
1737
+ pendingSessions -= 1;
1738
+ });
1739
+ resuming.set(id, attempt);
1740
+ return attempt;
1741
+ };
1742
+
1743
+ const requestHandler = (
1744
+ req: http.IncomingMessage,
1745
+ res: http.ServerResponse,
1746
+ ) => {
1747
+ const handle = async () => {
1748
+ if (httpOptions.onRequest !== undefined) {
1749
+ let allowed: boolean;
1750
+ try {
1751
+ allowed = await httpOptions.onRequest(req, res);
1752
+ } catch (err) {
1753
+ // Failing closed is the right answer for the caller; it is not an
1754
+ // answer for the operator, whose only signal would otherwise be a
1755
+ // stream of 401s. Same containment the session teardown path
1756
+ // already uses for a throwing `onSessionClosed`.
1757
+ reportError(err);
1758
+ if (!res.headersSent) res.writeHead(401).end();
1759
+ return;
1760
+ }
1761
+ if (!allowed) return;
1762
+ }
1763
+
1764
+ const url = new URL(req.url ?? '/', 'http://localhost');
1765
+ const method = req.method ?? '';
1766
+
1767
+ if (
1768
+ url.pathname !== mcpPath ||
1769
+ !['GET', 'POST', 'DELETE'].includes(method)
1770
+ ) {
1771
+ res.writeHead(404).end();
1772
+ return;
1773
+ }
1774
+
1775
+ if (method === 'POST') {
1776
+ const rejected = applyBodySizeLimit(
1777
+ req,
1778
+ res,
1779
+ httpOptions.maxBodyBytes ?? 4 * 1024 * 1024,
1780
+ );
1781
+ if (rejected) return;
1782
+ }
1783
+
1784
+ const sessionId = req.headers['mcp-session-id'];
1785
+ const headers = normalizeHeaders(req.headers);
1786
+
1787
+ if (typeof sessionId === 'string') {
1788
+ // Route to an existing session, resuming it from the shared registry
1789
+ // if another process created it — stamp its resolved identity into
1790
+ // context.
1791
+ const session =
1792
+ sessions.get(sessionId) ??
1793
+ (registry
1794
+ ? await resumeSession(sessionId, registry, req)
1795
+ : undefined);
1796
+ if (!session) {
1797
+ res.writeHead(404).end();
1798
+ return;
1799
+ }
1800
+ if ('status' in session) {
1801
+ res
1802
+ .writeHead(session.status, { 'content-type': 'application/json' })
1803
+ .end(session.body);
1804
+ return;
1805
+ }
1806
+ if (httpOptions.validateSession !== undefined) {
1807
+ let valid: boolean;
1808
+ try {
1809
+ valid = await httpOptions.validateSession(req, {
1810
+ sessionId,
1811
+ ...(session.identity === undefined
1812
+ ? {}
1813
+ : { identity: session.identity }),
1814
+ });
1815
+ } catch (err) {
1816
+ reportError(err);
1817
+ valid = false;
1818
+ }
1819
+ if (!valid) {
1820
+ if (!res.headersSent) res.writeHead(401).end();
1821
+ return;
1822
+ }
1823
+ }
1824
+ const requestContext: Omit<ProxyContext, 'requestId'> = {
1825
+ transport: 'http',
1826
+ sessionId,
1827
+ ...(headers === undefined ? {} : { headers }),
1828
+ ...(session.identity === undefined
1829
+ ? {}
1830
+ : { identity: session.identity }),
1831
+ };
1832
+ await httpProxyContext.run(requestContext, () =>
1833
+ session.transport.handleRequest(req, res),
1834
+ );
1835
+ } else {
1836
+ // New session — only an initialize POST may create one. A
1837
+ // session-less GET/DELETE can never initialize, so reject it
1838
+ // before constructing a Server/transport (which would otherwise
1839
+ // leak into the listChanged fan-out bus).
1840
+ if (method !== 'POST') {
1841
+ res.writeHead(400, { 'content-type': 'application/json' }).end(
1842
+ JSON.stringify({
1843
+ jsonrpc: '2.0',
1844
+ error: {
1845
+ code: -32000,
1846
+ message: 'Bad Request: no valid session ID provided',
1847
+ },
1848
+ id: null,
1849
+ }),
1850
+ );
1851
+ return;
1852
+ }
1853
+
1854
+ // Count this initialize as pending so concurrent initializes
1855
+ // cannot overshoot maxSessions while identity resolution awaits.
1856
+ if (sessions.size + pendingSessions >= maxSessions) {
1857
+ res
1858
+ .writeHead(503, { 'content-type': 'application/json' })
1859
+ .end(sessionLimitBody);
1860
+ return;
1861
+ }
1862
+ pendingSessions += 1;
1863
+
1864
+ // The shared record carries the client's initialize params, and the
1865
+ // SDK owns parsing the body, so tap the bytes as they arrive rather
1866
+ // than reading the stream out from under it. The same seam the body
1867
+ // limit uses.
1868
+ const bodyChunks: Buffer[] = [];
1869
+ if (registry) {
1870
+ const push = req.push.bind(req);
1871
+ (req as unknown as { push: typeof req.push }).push = (
1872
+ chunk: Buffer | string | null,
1873
+ enc?: BufferEncoding,
1874
+ ): boolean => {
1875
+ if (chunk !== null) {
1876
+ bodyChunks.push(
1877
+ typeof chunk === 'string' ? Buffer.from(chunk, enc) : chunk,
1878
+ );
1879
+ }
1880
+ return push(chunk, enc);
1881
+ };
1882
+ }
1883
+
1884
+ try {
1885
+ // Resolve identity once for the lifetime of this session
1886
+ let identity: Identity | undefined;
1887
+ if (httpOptions.resolveIdentity !== undefined) {
1888
+ try {
1889
+ identity = await httpOptions.resolveIdentity(req);
1890
+ } catch (err) {
1891
+ reportError(err);
1892
+ if (!res.headersSent) res.writeHead(401).end();
1893
+ return;
1894
+ }
1895
+ }
1896
+
1897
+ const proxyServer = createProxyServer(backends, options);
1898
+ const sessionId = randomUUID();
1899
+ const transport = createTransport(sessionId, async (id) => {
1900
+ // The deadline is fixed here and travels with the record, so a
1901
+ // resume elsewhere inherits what is left of it. Infinity opts
1902
+ // out; setTimeout would clamp it to 1ms.
1903
+ const expiresAt = Number.isFinite(sessionTtlMs)
1904
+ ? Date.now() + sessionTtlMs
1905
+ : undefined;
1906
+ // The SDK awaits this hook before it answers, so the record is
1907
+ // durable before the client can present the id anywhere. A
1908
+ // throw here becomes the SDK's 400 with the error text in the
1909
+ // body, so the real cause goes to onError and the client gets a
1910
+ // message that names nothing about the backing store.
1911
+ if (registry) {
1912
+ try {
1913
+ await registry.set(id, {
1914
+ initialize: initializeParamsOf(
1915
+ Buffer.concat(bodyChunks).toString(),
1916
+ ),
1917
+ ...(identity === undefined ? {} : { identity }),
1918
+ ...(expiresAt === undefined ? {} : { expiresAt }),
1919
+ });
1920
+ } catch (err) {
1921
+ reportError(err);
1922
+ throw new Error('mcpose: session registry unavailable');
1923
+ }
1924
+ }
1925
+ admitSession(id, transport, proxyServer, identity, expiresAt);
1926
+ });
1927
+
1928
+ const requestContext: Omit<ProxyContext, 'requestId'> = {
1929
+ transport: 'http',
1930
+ ...(headers === undefined ? {} : { headers }),
1931
+ ...(identity === undefined ? {} : { identity }),
1932
+ };
1933
+ // See backendClient.ts: the SDK's transports are not assignable to
1934
+ // its own `Transport` interface under `exactOptionalPropertyTypes`
1935
+ // (here `onclose?: () => void` vs `onclose: (() => void) | undefined`).
1936
+ await proxyServer.connect(transport as Transport);
1937
+ try {
1938
+ await httpProxyContext.run(requestContext, () =>
1939
+ transport.handleRequest(req, res),
1940
+ );
1941
+ } finally {
1942
+ // No session came up — a non-initialize body the transport
1943
+ // rejected, or a registry that refused the record — so close the
1944
+ // orphaned proxy server before it leaks (memory + listChanged
1945
+ // fan-out).
1946
+ if (!sessions.has(sessionId)) {
1947
+ void proxyServer.close().catch(reportError);
1948
+ }
1949
+ }
1950
+ } finally {
1951
+ pendingSessions -= 1;
1952
+ }
1953
+ }
1954
+ };
1955
+
1956
+ handle().catch((err) => {
1957
+ if (!res.headersSent) res.writeHead(500).end();
1958
+ (httpOptions.onError ?? console.error)(err);
1959
+ });
1960
+ };
1961
+
1962
+ const server: http.Server = httpOptions.tlsOptions
1963
+ ? https.createServer(httpOptions.tlsOptions, requestHandler)
1964
+ : http.createServer(requestHandler);
1965
+
1966
+ const rawClose = server.close.bind(server);
1967
+ let shuttingDown = false;
1968
+
1969
+ server.close = (callback?: (err?: Error) => void) => {
1970
+ if (shuttingDown) return rawClose(callback);
1971
+ shuttingDown = true;
1972
+
1973
+ // Tear down every session through the single teardown path (clears TTL
1974
+ // timers, fires and awaits onSessionClosed so audit manifests flush
1975
+ // before the close callback runs).
1976
+ // Shared records are kept: the sessions are meant to resume on the next
1977
+ // process, and their deadlines expire them on their own.
1978
+ void Promise.allSettled(
1979
+ [...sessions.keys()].map((id) => destroySession(id, true)),
1980
+ ).finally(() => {
1981
+ rawClose(callback);
1982
+ // Idle keep-alive and lingering SSE sockets would otherwise keep the
1983
+ // close callback pending indefinitely.
1984
+ server.closeAllConnections();
1985
+ });
1986
+
1987
+ return server;
1988
+ };
1989
+
1990
+ if (!loopback && httpOptions.resolveIdentity === undefined) {
1991
+ reportError(
1992
+ new Error(
1993
+ `mcpose: startHttpProxy is binding non-loopback address "${host}" without resolveIdentity — ` +
1994
+ 'anything that can route to this host can call the upstream with ' +
1995
+ "the proxy's credentials. Pass resolveIdentity, or bind 127.0.0.1.",
1996
+ ),
1997
+ );
1998
+ }
1999
+ // The SDK transport validates Host/Origin only against a non-empty list,
2000
+ // and no list is derived for a non-loopback bind, so this combination is
2001
+ // an inert flag — the false-confidence case the derived defaults exist
2002
+ // to remove.
2003
+ if (
2004
+ dnsRebindingProtection &&
2005
+ !loopback &&
2006
+ httpOptions.allowedHosts === undefined &&
2007
+ httpOptions.allowedOrigins === undefined
2008
+ ) {
2009
+ reportError(
2010
+ new Error(
2011
+ 'mcpose: enableDnsRebindingProtection is on, but no allowedHosts or ' +
2012
+ 'allowedOrigins are set and none are derived for a non-loopback ' +
2013
+ 'bind, so the transport validates nothing. Pass allowedHosts ' +
2014
+ 'and/or allowedOrigins.',
2015
+ ),
2016
+ );
2017
+ }
2018
+
2019
+ return new Promise((resolve, reject) => {
2020
+ server.once('error', reject);
2021
+ server.listen(port, host, () => {
2022
+ server.off('error', reject);
2023
+ // Route post-listen server errors (e.g. EMFILE) to onError instead of
2024
+ // crashing the process with an unhandled 'error' event.
2025
+ server.on('error', reportError);
2026
+ if (dnsRebindingProtection && loopback) {
2027
+ const addr = server.address();
2028
+ const actualPort =
2029
+ addr !== null && typeof addr === 'object' ? addr.port : port;
2030
+ const hosts = [
2031
+ `127.0.0.1:${actualPort}`,
2032
+ `localhost:${actualPort}`,
2033
+ `[::1]:${actualPort}`,
2034
+ ];
2035
+ const scheme = httpOptions.tlsOptions ? 'https' : 'http';
2036
+ derivedAllowedHosts = hosts;
2037
+ derivedAllowedOrigins = hosts.map((h) => `${scheme}://${h}`);
2038
+ }
2039
+ resolve(server);
2040
+ });
2041
+ });
2042
+ }