@nest-mcp/manager 0.0.0-stage → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1697 @@
1
+ import { MCP_CLIENT_LEASE_CAPACITY_EXCEEDED, MCP_CLIENT_LEASE_INVALIDATED, MCP_CLIENT_LEASE_MANAGER_CLOSED, McpClientLeaseManager, McpClientRuntime } from "@nest-mcp/client";
2
+ import { AsyncResource } from "node:async_hooks";
3
+ import { METHOD_NOT_FOUND, ProtocolError } from "@modelcontextprotocol/client";
4
+ import { randomUUID } from "node:crypto";
5
+ //#region src/errors.ts
6
+ const MCP_RUNTIME_QUEUE_FULL = "MCP_QUEUE_FULL";
7
+ const MCP_RUNTIME_ADMISSION_TIMEOUT = "MCP_ADMISSION_TIMEOUT";
8
+ const MCP_RUNTIME_CAPACITY_EXCEEDED = "MCP_CAPACITY_EXCEEDED";
9
+ const MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED = "MCP_DISCOVERY_LIMIT_EXCEEDED";
10
+ const MCP_RUNTIME_GENERATION_RETIRED = "MCP_GENERATION_RETIRED";
11
+ const MCP_RUNTIME_LEASE_MODE_CONFLICT = "MCP_LEASE_MODE_CONFLICT";
12
+ const MCP_RUNTIME_NOT_READY = "MCP_NOT_READY";
13
+ const MCP_RUNTIME_QUARANTINED = "MCP_QUARANTINED";
14
+ const MCP_RUNTIME_MANAGER_CLOSED = "MCP_RUNTIME_CLOSED";
15
+ const MCP_RUNTIME_UPSTREAM_FAILED = "MCP_UPSTREAM_FAILED";
16
+ const MCP_RUNTIME_CLEANUP_FAILED = "MCP_CLEANUP_FAILED";
17
+ const MCP_RUNTIME_CONNECTION_LOST = "MCP_CONNECTION_LOST";
18
+ /** Framework-neutral, key-free failure raised by the managed runtime lifecycle. */
19
+ var McpRuntimeManagerError = class extends Error {
20
+ code;
21
+ constructor(code, message, options) {
22
+ super(message, options);
23
+ this.name = "McpRuntimeManagerError";
24
+ this.code = code;
25
+ }
26
+ };
27
+ function mapMcpRuntimeManagerError(error) {
28
+ if (error instanceof McpRuntimeManagerError) return error;
29
+ if (error instanceof McpRuntimeGenerationResolutionError) return error.cause;
30
+ const code = safeErrorCode(error);
31
+ if (code === MCP_CLIENT_LEASE_CAPACITY_EXCEEDED) return new McpRuntimeManagerError(MCP_RUNTIME_CAPACITY_EXCEEDED, "The MCP runtime manager is at its connection capacity.", { cause: error });
32
+ if (code === MCP_CLIENT_LEASE_INVALIDATED) return new McpRuntimeGenerationRetiredError(error);
33
+ if (code === MCP_CLIENT_LEASE_MANAGER_CLOSED) return runtimeManagerClosedError(error);
34
+ return new McpRuntimeManagerError(MCP_RUNTIME_UPSTREAM_FAILED, "The upstream MCP operation failed.", { cause: error });
35
+ }
36
+ function runtimeManagerErrorCode(error) {
37
+ if (error instanceof McpRuntimeManagerError) return error.code;
38
+ if (error instanceof McpRuntimeGenerationResolutionError) return runtimeManagerErrorCode(error.cause);
39
+ const code = safeErrorCode(error);
40
+ if (isRuntimeStateErrorCode(code)) return code;
41
+ if (code === MCP_CLIENT_LEASE_CAPACITY_EXCEEDED) return MCP_RUNTIME_CAPACITY_EXCEEDED;
42
+ if (code === MCP_CLIENT_LEASE_INVALIDATED) return MCP_RUNTIME_GENERATION_RETIRED;
43
+ if (code === MCP_CLIENT_LEASE_MANAGER_CLOSED) return MCP_RUNTIME_MANAGER_CLOSED;
44
+ return "UNKNOWN";
45
+ }
46
+ function runtimeManagerClosedError(cause) {
47
+ return new McpRuntimeManagerError(MCP_RUNTIME_MANAGER_CLOSED, "The MCP runtime manager is closed.", cause === void 0 ? void 0 : { cause });
48
+ }
49
+ function runtimeQuarantinedError(cause) {
50
+ return new McpRuntimeManagerError(MCP_RUNTIME_QUARANTINED, "The MCP runtime generation is quarantined after uncertain cleanup.", cause === void 0 ? void 0 : { cause });
51
+ }
52
+ function runtimeNotReadyError() {
53
+ return new McpRuntimeManagerError(MCP_RUNTIME_NOT_READY, "The MCP connection does not have an active connected runtime generation.");
54
+ }
55
+ function runtimeLeaseModeConflictError() {
56
+ return new McpRuntimeManagerError(MCP_RUNTIME_LEASE_MODE_CONFLICT, "The MCP runtime generation already has work using a conflicting lease mode.");
57
+ }
58
+ var McpRuntimeGenerationResolutionError = class extends Error {
59
+ cause;
60
+ constructor(cause) {
61
+ super("The MCP runtime generation could not be resolved.", { cause });
62
+ this.name = "McpRuntimeGenerationResolutionError";
63
+ this.cause = cause;
64
+ }
65
+ };
66
+ var McpRuntimeGenerationRetiredError = class extends McpRuntimeManagerError {
67
+ constructor(cause) {
68
+ super(MCP_RUNTIME_GENERATION_RETIRED, "The MCP runtime generation was retired before the operation completed.", { cause });
69
+ }
70
+ };
71
+ function safeErrorCode(error) {
72
+ if (typeof error !== "object" || error === null) return "UNKNOWN";
73
+ try {
74
+ const code = Reflect.get(error, "code");
75
+ return typeof code === "string" ? code : "UNKNOWN";
76
+ } catch {
77
+ return "UNKNOWN";
78
+ }
79
+ }
80
+ function isRuntimeStateErrorCode(code) {
81
+ return RUNTIME_STATE_ERROR_CODES.has(code);
82
+ }
83
+ const RUNTIME_STATE_ERROR_CODES = /* @__PURE__ */ new Set([
84
+ MCP_RUNTIME_CAPACITY_EXCEEDED,
85
+ MCP_RUNTIME_QUEUE_FULL,
86
+ MCP_RUNTIME_ADMISSION_TIMEOUT,
87
+ MCP_RUNTIME_CLEANUP_FAILED,
88
+ MCP_RUNTIME_CONNECTION_LOST,
89
+ MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED,
90
+ MCP_RUNTIME_GENERATION_RETIRED,
91
+ MCP_RUNTIME_LEASE_MODE_CONFLICT,
92
+ MCP_RUNTIME_MANAGER_CLOSED,
93
+ MCP_RUNTIME_NOT_READY,
94
+ MCP_RUNTIME_QUARANTINED,
95
+ MCP_RUNTIME_UPSTREAM_FAILED,
96
+ "UNKNOWN"
97
+ ]);
98
+ //#endregion
99
+ //#region src/runtime-factory.ts
100
+ const DEFAULT_CLIENT_INFO = Object.freeze({
101
+ name: "@nest-mcp/manager",
102
+ version: "2.0.0-alpha.0"
103
+ });
104
+ var ManagedRuntimeFactory = class {
105
+ #generationResolver;
106
+ #states;
107
+ #requestTimeoutMs;
108
+ #shutdownTimeoutMs;
109
+ #maxDiscoveryPages;
110
+ #clientInfo;
111
+ #observer;
112
+ #now;
113
+ constructor(options) {
114
+ this.#generationResolver = options.generationResolver;
115
+ this.#states = options.states;
116
+ this.#requestTimeoutMs = options.requestTimeoutMs;
117
+ this.#shutdownTimeoutMs = options.shutdownTimeoutMs;
118
+ this.#maxDiscoveryPages = options.maxDiscoveryPages;
119
+ this.#clientInfo = options.clientInfo ?? DEFAULT_CLIENT_INFO;
120
+ this.#observer = options.observer;
121
+ this.#now = options.now;
122
+ }
123
+ async create(generationKey, context) {
124
+ this.#states.transition(generationKey, "connecting");
125
+ let admitted;
126
+ try {
127
+ admitted = withSharedClose(await this.#generationResolver.resolve(generationKey, context.signal));
128
+ } catch (error) {
129
+ this.#states.transition(generationKey, "failed", runtimeManagerErrorCode(error));
130
+ throw new McpRuntimeGenerationResolutionError(error);
131
+ }
132
+ let serverName;
133
+ let runtime;
134
+ try {
135
+ serverName = `managed-${randomUUID()}`;
136
+ runtime = new McpClientRuntime({
137
+ clientInfo: this.#clientInfo,
138
+ servers: [{
139
+ name: serverName,
140
+ transport: admitted.transport,
141
+ clientOptions: {
142
+ listMaxPages: this.#maxDiscoveryPages,
143
+ versionNegotiation: { mode: "auto" }
144
+ }
145
+ }],
146
+ shutdownTimeoutMs: this.#shutdownTimeoutMs,
147
+ now: this.#now,
148
+ ...this.#observer === void 0 ? {} : { observer: this.#observer }
149
+ });
150
+ await runtime.connect(serverName, { signal: AbortSignal.any([context.signal, AbortSignal.timeout(this.#requestTimeoutMs)]) });
151
+ const snapshot = this.#states.connected(generationKey, runtime.snapshot(serverName));
152
+ await admitted.onConnected?.(snapshot, context.signal);
153
+ context.signal.throwIfAborted();
154
+ return Object.freeze({
155
+ generationKey,
156
+ generationSignal: context.signal,
157
+ runtime,
158
+ serverName,
159
+ admitted,
160
+ quarantined: false
161
+ });
162
+ } catch (error) {
163
+ this.#states.transition(generationKey, "failed", runtimeManagerErrorCode(error));
164
+ try {
165
+ await closeRuntimeThenMaterial(runtime, admitted, this.#shutdownTimeoutMs);
166
+ } catch {
167
+ this.#states.transition(generationKey, "quarantined", MCP_RUNTIME_CLEANUP_FAILED);
168
+ return Object.freeze({
169
+ generationKey,
170
+ generationSignal: context.signal,
171
+ admitted,
172
+ ...runtime === void 0 ? {} : { runtime },
173
+ ...serverName === void 0 ? {} : { serverName },
174
+ quarantined: true
175
+ });
176
+ }
177
+ throw error;
178
+ }
179
+ }
180
+ async close(owned) {
181
+ this.#states.transition(owned.generationKey, "draining");
182
+ try {
183
+ await closeRuntimeThenMaterial(owned.runtime, owned.admitted, this.#shutdownTimeoutMs);
184
+ } catch (error) {
185
+ this.#states.transition(owned.generationKey, "quarantined", MCP_RUNTIME_CLEANUP_FAILED);
186
+ throw error;
187
+ }
188
+ this.#states.transition(owned.generationKey, "offline");
189
+ }
190
+ };
191
+ function withSharedClose(admitted) {
192
+ let closeTask;
193
+ return Object.freeze({
194
+ transport: admitted.transport,
195
+ ...admitted.onConnected === void 0 ? {} : { onConnected: admitted.onConnected.bind(admitted) },
196
+ close() {
197
+ closeTask ??= Promise.resolve().then(() => admitted.close());
198
+ return closeTask;
199
+ }
200
+ });
201
+ }
202
+ async function closeRuntimeThenMaterial(runtime, admitted, shutdownTimeoutMs) {
203
+ const failures = [];
204
+ if (runtime !== void 0) try {
205
+ await runtime.close();
206
+ } catch (error) {
207
+ failures.push(error);
208
+ }
209
+ try {
210
+ await withCleanupTimeout(admitted.close(), shutdownTimeoutMs);
211
+ } catch (error) {
212
+ failures.push(error);
213
+ }
214
+ if (failures.length > 0) throw new AggregateError(failures, "An MCP runtime generation could not be closed.");
215
+ }
216
+ function withCleanupTimeout(task, timeoutMs) {
217
+ return new Promise((resolve, reject) => {
218
+ const timer = setTimeout(() => {
219
+ reject(/* @__PURE__ */ new Error("The admitted MCP runtime material did not close before its deadline."));
220
+ }, timeoutMs);
221
+ timer.unref?.();
222
+ task.then(() => {
223
+ clearTimeout(timer);
224
+ resolve();
225
+ }, (error) => {
226
+ clearTimeout(timer);
227
+ reject(error);
228
+ });
229
+ });
230
+ }
231
+ //#endregion
232
+ //#region src/runtime-state.ts
233
+ var RuntimeStateStore = class {
234
+ #states = /* @__PURE__ */ new Map();
235
+ #listeners = /* @__PURE__ */ new Set();
236
+ #now;
237
+ #maxEntries;
238
+ #onListenerError;
239
+ constructor(options) {
240
+ this.#now = options.now;
241
+ this.#maxEntries = options.maxEntries;
242
+ this.#onListenerError = options.onListenerError;
243
+ }
244
+ get size() {
245
+ return this.#states.size;
246
+ }
247
+ read(generationKey) {
248
+ const current = this.#states.get(generationKey);
249
+ if (current !== void 0) return current;
250
+ return offlineState(readTimestamp(this.#now));
251
+ }
252
+ transition(generationKey, phase, errorCode) {
253
+ const previous = this.#states.get(generationKey);
254
+ if (previous?.phase === "quarantined") return previous;
255
+ const timestamp = readTimestamp(this.#now);
256
+ const lastTransitionAt = previous?.phase === phase && previous.errorCode === errorCode ? previous.lastTransitionAt : new Date(timestamp).toISOString();
257
+ const { errorCode: previousError, ...previousWithoutError } = previous ?? {};
258
+ const state = Object.freeze({
259
+ ...phase === "degraded" || phase === "draining" ? previousWithoutError : {},
260
+ phase,
261
+ lastTransitionAt,
262
+ ...errorCode === void 0 ? {} : { errorCode }
263
+ });
264
+ this.#set(generationKey, state);
265
+ this.#publish(previous, state, timestamp);
266
+ return state;
267
+ }
268
+ connected(generationKey, snapshot) {
269
+ const capabilities = snapshot.serverCapabilities;
270
+ const previous = this.#states.get(generationKey);
271
+ if (previous?.phase === "quarantined") return previous;
272
+ const timestamp = readTimestamp(this.#now);
273
+ const state = Object.freeze({
274
+ phase: "online",
275
+ lastTransitionAt: previous?.phase === "online" ? previous.lastTransitionAt : new Date(timestamp).toISOString(),
276
+ ...snapshot.negotiatedProtocolVersion === void 0 ? {} : { protocolVersion: snapshot.negotiatedProtocolVersion },
277
+ ...snapshot.protocolEra === void 0 ? {} : { protocolEra: snapshot.protocolEra },
278
+ ...snapshot.connectedAt === void 0 ? {} : { connectedAt: new Date(snapshot.connectedAt).toISOString() },
279
+ ...capabilities === void 0 ? {} : { capabilities: Object.freeze({
280
+ tools: capabilities.tools !== void 0,
281
+ resources: capabilities.resources !== void 0,
282
+ prompts: capabilities.prompts !== void 0,
283
+ completion: capabilities.completions !== void 0,
284
+ subscriptions: capabilities.resources?.subscribe === true
285
+ }) }
286
+ });
287
+ this.#set(generationKey, state);
288
+ this.#publish(previous, state, timestamp);
289
+ return state;
290
+ }
291
+ forget(generationKey) {
292
+ this.#states.delete(generationKey);
293
+ }
294
+ #set(generationKey, state) {
295
+ if (this.#states.delete(generationKey)) {
296
+ this.#states.set(generationKey, state);
297
+ return;
298
+ }
299
+ if (this.#states.size >= this.#maxEntries) {
300
+ for (const [candidateKey, candidate] of this.#states) {
301
+ if (candidate.phase !== "offline" && candidate.phase !== "failed") continue;
302
+ this.#states.delete(candidateKey);
303
+ break;
304
+ }
305
+ if (this.#states.size >= this.#maxEntries) return;
306
+ }
307
+ this.#states.set(generationKey, state);
308
+ }
309
+ subscribe(listener) {
310
+ if (typeof listener !== "function") throw new TypeError("MCP runtime state listener must be a function.");
311
+ this.#listeners.add(listener);
312
+ let subscribed = true;
313
+ return () => {
314
+ if (!subscribed) return;
315
+ subscribed = false;
316
+ this.#listeners.delete(listener);
317
+ };
318
+ }
319
+ #publish(previous, current, timestamp) {
320
+ if (previous?.phase === current.phase && previous.errorCode === current.errorCode) return;
321
+ const event = Object.freeze({
322
+ type: "runtime.state.changed",
323
+ timestamp,
324
+ ...previous === void 0 ? { previousPhase: "offline" } : { previousPhase: previous.phase },
325
+ phase: current.phase,
326
+ ...current.errorCode === void 0 ? {} : { errorCode: current.errorCode },
327
+ ...current.protocolEra === void 0 ? {} : { protocolEra: current.protocolEra },
328
+ ...current.capabilities === void 0 ? {} : { capabilities: current.capabilities }
329
+ });
330
+ for (const listener of Array.from(this.#listeners)) try {
331
+ const result = listener(event);
332
+ if (isPromiseLike(result)) Promise.resolve(result).catch((error) => {
333
+ this.#reportListenerError(error, event);
334
+ });
335
+ } catch (error) {
336
+ this.#reportListenerError(error, event);
337
+ }
338
+ }
339
+ #reportListenerError(error, event) {
340
+ if (this.#onListenerError === void 0) return;
341
+ try {
342
+ const result = this.#onListenerError(error, event);
343
+ if (isPromiseLike(result)) Promise.resolve(result).catch(() => void 0);
344
+ } catch {}
345
+ }
346
+ };
347
+ function offlineState(timestamp) {
348
+ return Object.freeze({
349
+ phase: "offline",
350
+ lastTransitionAt: new Date(timestamp).toISOString()
351
+ });
352
+ }
353
+ function readTimestamp(now) {
354
+ try {
355
+ const timestamp = now();
356
+ if (Number.isFinite(timestamp)) {
357
+ new Date(timestamp).toISOString();
358
+ return timestamp;
359
+ }
360
+ } catch {}
361
+ return Date.now();
362
+ }
363
+ function isPromiseLike(value) {
364
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
365
+ }
366
+ //#endregion
367
+ //#region src/operation-admission.ts
368
+ /** Atomic process-local admission; transports and their cleanup remain owned by the manager. */
369
+ var OperationAdmission = class {
370
+ maxOperations;
371
+ maxConcurrentOperations;
372
+ #active = /* @__PURE__ */ new Set();
373
+ #waiters = /* @__PURE__ */ new Set();
374
+ #quarantined = /* @__PURE__ */ new Set();
375
+ #lastGranted = /* @__PURE__ */ new Map();
376
+ #sequence = 0;
377
+ #draining = false;
378
+ constructor(maxOperations, maxConcurrentOperations) {
379
+ this.maxOperations = maxOperations;
380
+ this.maxConcurrentOperations = maxConcurrentOperations;
381
+ }
382
+ get size() {
383
+ return this.#waiters.size;
384
+ }
385
+ hasIsolatedGeneration(generationKey) {
386
+ return [...this.#active].some((active) => active.generationKey === generationKey && active.mode !== "shared");
387
+ }
388
+ async enter(generationKey, mode, key, queue, signal, limit, reserve) {
389
+ const admission = {
390
+ generationKey,
391
+ mode,
392
+ key,
393
+ limit: limit === void 0 ? this.maxConcurrentOperations : limit
394
+ };
395
+ signal.throwIfAborted();
396
+ this.#assertNotQuarantined(admission);
397
+ if ([...this.#active].filter((active) => this.#related(active, admission)).some((active) => active.mode === "shared" && mode !== "shared")) throw runtimeLeaseModeConflictError();
398
+ if (queue) this.drain();
399
+ if (this.#available(admission) && reserve()) {
400
+ this.#active.add(admission);
401
+ this.#lastGranted.set(key ?? generationKey, this.#sequence++);
402
+ } else if (queue) {
403
+ if (this.#waiters.size >= this.maxOperations) throw new McpRuntimeManagerError(MCP_RUNTIME_QUEUE_FULL, "The MCP operation admission queue is full.");
404
+ await new Promise((resolve, reject) => {
405
+ const remove = () => {
406
+ this.#waiters.delete(waiter);
407
+ signal.removeEventListener("abort", abort);
408
+ };
409
+ const waiter = {
410
+ admission,
411
+ reserve,
412
+ grant: () => {
413
+ remove();
414
+ resolve();
415
+ },
416
+ reject: (error) => {
417
+ remove();
418
+ reject(error);
419
+ }
420
+ };
421
+ const abort = () => {
422
+ waiter.reject(signal.reason);
423
+ this.drain();
424
+ };
425
+ this.#waiters.add(waiter);
426
+ signal.addEventListener("abort", abort, { once: true });
427
+ if (signal.aborted) abort();
428
+ else this.drain();
429
+ });
430
+ } else throw this.#available(admission) || mode === "concurrent" ? this.#capacityError() : runtimeLeaseModeConflictError();
431
+ let released = false;
432
+ return (quarantine) => {
433
+ if (released) return;
434
+ released = true;
435
+ if (quarantine) this.#quarantined.add(admission);
436
+ this.#active.delete(admission);
437
+ this.drain();
438
+ };
439
+ }
440
+ rejectGeneration(generationKey, reason) {
441
+ for (const waiter of this.#waiters) if (waiter.admission.generationKey === generationKey) waiter.reject(reason);
442
+ this.drain();
443
+ }
444
+ rejectAll(reason) {
445
+ for (const waiter of this.#waiters) waiter.reject(reason);
446
+ }
447
+ #related(left, right) {
448
+ return left.generationKey === right.generationKey || left.key !== void 0 && left.key === right.key;
449
+ }
450
+ #available(admission, pending) {
451
+ for (const waiter of this.#waiters) {
452
+ if (waiter === pending) break;
453
+ if (this.#related(waiter.admission, admission)) return false;
454
+ }
455
+ let count = 0;
456
+ let ceiling = admission.limit ?? Number.POSITIVE_INFINITY;
457
+ for (const active of this.#active) {
458
+ if (!this.#related(active, admission)) continue;
459
+ if (active.mode === "shared" && admission.mode === "shared") continue;
460
+ if (active.mode !== "concurrent" || admission.mode !== "concurrent" || active.key !== admission.key) return false;
461
+ count += 1;
462
+ ceiling = Math.min(ceiling, active.limit ?? Number.POSITIVE_INFINITY);
463
+ }
464
+ return count < ceiling;
465
+ }
466
+ #assertNotQuarantined(admission) {
467
+ for (const failed of this.#quarantined) if (this.#related(failed, admission)) throw runtimeQuarantinedError();
468
+ }
469
+ /** Woken only when connector admission or the authoritative transport ledger changes. */
470
+ drain() {
471
+ if (this.#draining) return;
472
+ this.#draining = true;
473
+ try {
474
+ while (this.#waiters.size > 0) {
475
+ const ordered = [...new Set([...this.#waiters].map(({ admission }) => admission.key ?? admission.generationKey))].toSorted((left, right) => (this.#lastGranted.get(left) ?? -1) - (this.#lastGranted.get(right) ?? -1));
476
+ let granted = false;
477
+ for (const key of ordered) {
478
+ const waiter = [...this.#waiters].find(({ admission }) => (admission.key ?? admission.generationKey) === key);
479
+ if (waiter === void 0) continue;
480
+ try {
481
+ this.#assertNotQuarantined(waiter.admission);
482
+ if (!this.#available(waiter.admission, waiter) || !waiter.reserve()) continue;
483
+ } catch (error) {
484
+ waiter.reject(error);
485
+ granted = true;
486
+ continue;
487
+ }
488
+ this.#active.add(waiter.admission);
489
+ this.#lastGranted.set(key, this.#sequence++);
490
+ waiter.grant();
491
+ granted = true;
492
+ }
493
+ if (!granted) break;
494
+ }
495
+ } finally {
496
+ this.#draining = false;
497
+ const retained = new Set([...this.#active, ...[...this.#waiters].map(({ admission }) => admission)].map((admission) => admission.key ?? admission.generationKey));
498
+ for (const key of this.#lastGranted.keys()) if (!retained.has(key)) this.#lastGranted.delete(key);
499
+ }
500
+ }
501
+ #capacityError() {
502
+ return new McpRuntimeManagerError(MCP_RUNTIME_CAPACITY_EXCEEDED, "The MCP runtime manager has no compatible operation capacity.");
503
+ }
504
+ };
505
+ //#endregion
506
+ //#region src/runtime-manager.ts
507
+ var ExclusiveRuntimeLeaseIdentity = class {
508
+ generationKey;
509
+ constructor(generationKey) {
510
+ this.generationKey = generationKey;
511
+ }
512
+ };
513
+ const MCP_RUNTIME_MANAGER_DEFAULTS = Object.freeze({
514
+ maxConnections: 100,
515
+ maxQueuedOperations: 100,
516
+ maxConcurrentOperationsPerAdmissionKey: 4,
517
+ maxStateEntries: 1e3,
518
+ requestTimeoutMs: 1e4,
519
+ shutdownTimeoutMs: 3e4,
520
+ maxDiscoveryPages: 16,
521
+ maxDiscoveryItems: 1e3
522
+ });
523
+ var McpRuntimeManager = class {
524
+ #leases;
525
+ #keepers = /* @__PURE__ */ new Map();
526
+ #exclusiveIdentities = /* @__PURE__ */ new Map();
527
+ #admission;
528
+ #onlineTasks = /* @__PURE__ */ new Map();
529
+ #offlineTasks = /* @__PURE__ */ new Map();
530
+ #postOfflineOnlineTasks = /* @__PURE__ */ new Map();
531
+ #states;
532
+ #requestTimeoutMs;
533
+ #maxDiscoveryItems;
534
+ #now;
535
+ #closed = false;
536
+ #closeTask;
537
+ constructor(options) {
538
+ if (typeof options?.generationResolver !== "object" || options.generationResolver === null || typeof options.generationResolver.resolve !== "function") throw new TypeError("generationResolver.resolve must be a function.");
539
+ const maxConnections = positiveInteger(options.maxConnections ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxConnections, "maxConnections");
540
+ this.#admission = new OperationAdmission(positiveInteger(options.maxQueuedOperations ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxQueuedOperations, "maxQueuedOperations"), options.maxConcurrentOperationsPerAdmissionKey === null ? null : positiveInteger(options.maxConcurrentOperationsPerAdmissionKey ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxConcurrentOperationsPerAdmissionKey, "maxConcurrentOperationsPerAdmissionKey"));
541
+ const maxStateEntries = positiveInteger(options.maxStateEntries ?? Math.max(MCP_RUNTIME_MANAGER_DEFAULTS.maxStateEntries, maxConnections), "maxStateEntries");
542
+ if (maxStateEntries < maxConnections) throw new RangeError("maxStateEntries must be greater than or equal to maxConnections.");
543
+ this.#requestTimeoutMs = positiveFinite(options.requestTimeoutMs ?? MCP_RUNTIME_MANAGER_DEFAULTS.requestTimeoutMs, "requestTimeoutMs");
544
+ const shutdownTimeoutMs = positiveFinite(options.shutdownTimeoutMs ?? MCP_RUNTIME_MANAGER_DEFAULTS.shutdownTimeoutMs, "shutdownTimeoutMs");
545
+ const maxDiscoveryPages = positiveInteger(options.maxDiscoveryPages ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxDiscoveryPages, "maxDiscoveryPages");
546
+ this.#maxDiscoveryItems = positiveInteger(options.maxDiscoveryItems ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxDiscoveryItems, "maxDiscoveryItems");
547
+ if (options.observer !== void 0 && typeof options.observer.onEvent !== "function") throw new TypeError("observer.onEvent must be a function.");
548
+ this.#now = safeClock(options.now ?? Date.now);
549
+ this.#states = new RuntimeStateStore({
550
+ now: this.#now,
551
+ maxEntries: maxStateEntries,
552
+ ...options.onListenerError === void 0 ? {} : { onListenerError: options.onListenerError }
553
+ });
554
+ const factory = new ManagedRuntimeFactory({
555
+ generationResolver: options.generationResolver,
556
+ states: this.#states,
557
+ requestTimeoutMs: this.#requestTimeoutMs,
558
+ shutdownTimeoutMs,
559
+ maxDiscoveryPages,
560
+ ...options.clientInfo === void 0 ? {} : { clientInfo: options.clientInfo },
561
+ ...options.observer === void 0 ? {} : { observer: options.observer },
562
+ now: this.#now
563
+ });
564
+ this.#leases = new McpClientLeaseManager({
565
+ maxResources: maxConnections,
566
+ onCapacityAvailable: () => this.#admission.drain(),
567
+ create: (identity, context) => factory.create(generationKeyOf(identity), context),
568
+ close: (owned) => factory.close(owned)
569
+ });
570
+ }
571
+ async ensureOnline(generationKey, signal) {
572
+ this.#assertOpen();
573
+ if (this.#offlineTasks.get(generationKey) !== void 0) {
574
+ let queued = this.#postOfflineOnlineTasks.get(generationKey);
575
+ if (queued === void 0) {
576
+ const created = this.#reconnectAfterOfflineBarriers(generationKey);
577
+ queued = created;
578
+ this.#postOfflineOnlineTasks.set(generationKey, created);
579
+ created.then(() => this.#deletePostOfflineOnlineTask(generationKey, created), () => this.#deletePostOfflineOnlineTask(generationKey, created));
580
+ }
581
+ return waitForCaller(queued, signal);
582
+ }
583
+ this.#assertSharedLeaseAvailable(generationKey);
584
+ this.#assertNotQuarantined(generationKey);
585
+ return waitForCaller(this.#getOrCreateOnlineTask(generationKey), signal);
586
+ }
587
+ async #reconnectAfterOfflineBarriers(generationKey) {
588
+ for (;;) {
589
+ const barrier = this.#offlineTasks.get(generationKey);
590
+ if (barrier === void 0) break;
591
+ await barrier;
592
+ }
593
+ this.#assertOpen();
594
+ this.#assertSharedLeaseAvailable(generationKey);
595
+ this.#assertNotQuarantined(generationKey);
596
+ return this.#getOrCreateOnlineTask(generationKey);
597
+ }
598
+ #getOrCreateOnlineTask(generationKey) {
599
+ let task = this.#onlineTasks.get(generationKey);
600
+ if (task === void 0) {
601
+ task = Promise.resolve().then(() => this.#reconcileOnline(generationKey));
602
+ this.#onlineTasks.set(generationKey, task);
603
+ task.then(() => {
604
+ if (this.#onlineTasks.get(generationKey) === task) this.#onlineTasks.delete(generationKey);
605
+ }, () => {
606
+ if (this.#onlineTasks.get(generationKey) === task) this.#onlineTasks.delete(generationKey);
607
+ });
608
+ }
609
+ return task;
610
+ }
611
+ setOffline(generationKey) {
612
+ this.#assertOpen();
613
+ this.#admission.rejectGeneration(generationKey, new McpRuntimeManagerError(MCP_RUNTIME_GENERATION_RETIRED, "The MCP runtime generation was retired before the operation started."));
614
+ let task = this.#offlineTasks.get(generationKey);
615
+ if (task !== void 0) return task;
616
+ task = Promise.resolve().then(() => this.#performSetOffline(generationKey));
617
+ this.#offlineTasks.set(generationKey, task);
618
+ task.then(() => this.#deleteOfflineTask(generationKey, task), () => this.#deleteOfflineTask(generationKey, task));
619
+ return task;
620
+ }
621
+ async #performSetOffline(generationKey) {
622
+ if (this.#states.read(generationKey).phase === "quarantined") throw runtimeQuarantinedError();
623
+ this.#states.transition(generationKey, "draining");
624
+ const exclusiveIdentities = [...this.#exclusiveIdentities.get(generationKey) ?? []];
625
+ const drains = [this.#leases.invalidate(generationKey), ...exclusiveIdentities.map((identity) => this.#leases.invalidate(identity))];
626
+ const keeper = this.#keepers.get(generationKey);
627
+ this.#keepers.delete(generationKey);
628
+ const onlineTask = this.#onlineTasks.get(generationKey);
629
+ const cleanupTasks = [...drains, ...keeper === void 0 ? [] : [keeper.release()]];
630
+ const [cleanupSettled] = await Promise.all([Promise.allSettled(cleanupTasks), Promise.allSettled(onlineTask === void 0 ? [] : [onlineTask])]);
631
+ const cleanupFailed = cleanupSettled.some((result) => result.status === "rejected" && !isRetirementError(result.reason));
632
+ if (this.#onlineTasks.get(generationKey) === onlineTask) this.#onlineTasks.delete(generationKey);
633
+ if (cleanupFailed) return this.#states.transition(generationKey, "quarantined", MCP_RUNTIME_CLEANUP_FAILED);
634
+ return this.#states.transition(generationKey, "offline");
635
+ }
636
+ #deleteOfflineTask(generationKey, task) {
637
+ if (this.#offlineTasks.get(generationKey) === task) this.#offlineTasks.delete(generationKey);
638
+ }
639
+ #deletePostOfflineOnlineTask(generationKey, task) {
640
+ if (this.#postOfflineOnlineTasks.get(generationKey) === task) this.#postOfflineOnlineTasks.delete(generationKey);
641
+ }
642
+ async retire(generationKey) {
643
+ if ((await this.setOffline(generationKey)).phase === "quarantined") throw runtimeQuarantinedError();
644
+ this.#states.forget(generationKey);
645
+ }
646
+ async probe(generationKey, options) {
647
+ const controls = normalizeOperationOptions(options, "probe");
648
+ const observation = await this.#withRuntime(generationKey, async (owned, operationSignal) => {
649
+ await this.#probeProtocolLiveness(owned, operationSignal);
650
+ const { runtime, serverName } = owned;
651
+ const connected = this.#states.connected(generationKey, runtime.snapshot(serverName));
652
+ return Object.freeze({
653
+ reachable: true,
654
+ observedAt: isoTimestamp(this.#now),
655
+ ...connected.protocolVersion === void 0 ? {} : { protocolVersion: connected.protocolVersion },
656
+ ...connected.protocolEra === void 0 ? {} : { protocolEra: connected.protocolEra },
657
+ ...connected.capabilities === void 0 ? {} : { capabilities: connected.capabilities }
658
+ });
659
+ }, controls);
660
+ return Object.freeze({
661
+ ...observation,
662
+ runtime: this.#states.read(generationKey)
663
+ });
664
+ }
665
+ refreshCatalog(generationKey, options) {
666
+ let controls;
667
+ try {
668
+ controls = normalizeOperationOptions(options, "refreshCatalog");
669
+ } catch (error) {
670
+ return Promise.reject(error);
671
+ }
672
+ return this.#withRuntime(generationKey, async (owned, operationSignal) => {
673
+ await this.#probeProtocolLiveness(owned, operationSignal);
674
+ const { runtime, serverName } = owned;
675
+ const capabilities = runtime.snapshot(serverName).serverCapabilities;
676
+ const discoverTools = () => capabilities?.tools === void 0 ? Promise.resolve([]) : runtime.listTools(serverName, void 0, {
677
+ cacheMode: "refresh",
678
+ signal: operationSignal
679
+ }).then((result) => result.tools);
680
+ const discoverResources = () => capabilities?.resources === void 0 ? Promise.resolve([]) : runtime.listResources(serverName, void 0, {
681
+ cacheMode: "refresh",
682
+ signal: operationSignal
683
+ }).then((result) => result.resources);
684
+ const discoverResourceTemplates = () => capabilities?.resources === void 0 ? Promise.resolve([]) : runtime.listResourceTemplates(serverName, void 0, {
685
+ cacheMode: "refresh",
686
+ signal: operationSignal
687
+ }).then((result) => result.resourceTemplates).catch((error) => {
688
+ if (isMethodNotFoundProtocolError(error)) return [];
689
+ throw error;
690
+ });
691
+ const discoverPrompts = () => capabilities?.prompts === void 0 ? Promise.resolve([]) : runtime.listPrompts(serverName, void 0, {
692
+ cacheMode: "refresh",
693
+ signal: operationSignal
694
+ }).then((result) => result.prompts);
695
+ const finalize = (tools, resources, resourceTemplates, prompts) => {
696
+ if (tools.length + resources.length + resourceTemplates.length + prompts.length > this.#maxDiscoveryItems) throw new McpRuntimeManagerError(MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED, "The upstream MCP catalog exceeds the configured discovery limit.");
697
+ this.#states.connected(generationKey, runtime.snapshot(serverName));
698
+ return Object.freeze({
699
+ discoveredAt: isoTimestamp(this.#now),
700
+ tools: Object.freeze([...tools]),
701
+ resources: Object.freeze([...resources]),
702
+ resourceTemplates: Object.freeze([...resourceTemplates]),
703
+ prompts: Object.freeze([...prompts])
704
+ });
705
+ };
706
+ if (controls.leaseMode === "exclusive") return finalize(await discoverTools(), await discoverResources(), await discoverResourceTemplates(), await discoverPrompts());
707
+ const [toolsResult, resourcesResult, resourceTemplatesResult, promptsResult] = await Promise.allSettled([
708
+ discoverTools(),
709
+ discoverResources(),
710
+ discoverResourceTemplates(),
711
+ discoverPrompts()
712
+ ]);
713
+ return finalize(requireDiscoveryResult(toolsResult), requireDiscoveryResult(resourcesResult), requireDiscoveryResult(resourceTemplatesResult), requireDiscoveryResult(promptsResult));
714
+ }, controls);
715
+ }
716
+ withClientRuntime(generationKey, operation, options) {
717
+ if (typeof operation !== "function") return Promise.reject(/* @__PURE__ */ new TypeError("operation must be a function."));
718
+ let controls;
719
+ try {
720
+ controls = normalizeOperationOptions(options, "withClientRuntime");
721
+ } catch (error) {
722
+ return Promise.reject(error);
723
+ }
724
+ return this.#withRuntime(generationKey, (owned, operationSignal) => operation(Object.freeze({
725
+ runtime: owned.runtime,
726
+ serverName: owned.serverName,
727
+ signal: operationSignal
728
+ })), controls, true);
729
+ }
730
+ callTool(generationKey, name, arguments_, options) {
731
+ let controls;
732
+ try {
733
+ controls = normalizeToolCallOptions(options);
734
+ } catch (error) {
735
+ return Promise.reject(error);
736
+ }
737
+ const { toolDefinition } = controls;
738
+ return this.#withRuntime(generationKey, ({ runtime, serverName }, operationSignal) => runtime.callTool(serverName, {
739
+ name,
740
+ arguments: { ...arguments_ }
741
+ }, {
742
+ signal: operationSignal,
743
+ ...toolDefinition === void 0 ? {} : { toolDefinition }
744
+ }), controls, true);
745
+ }
746
+ readResource(generationKey, uri, options) {
747
+ let controls;
748
+ try {
749
+ controls = normalizeOperationOptions(options, "readResource");
750
+ } catch (error) {
751
+ return Promise.reject(error);
752
+ }
753
+ return this.#withRuntime(generationKey, ({ runtime, serverName }, operationSignal) => runtime.readResource(serverName, { uri }, { signal: operationSignal }), controls, true);
754
+ }
755
+ getPrompt(generationKey, name, arguments_, options) {
756
+ let controls;
757
+ try {
758
+ controls = normalizeOperationOptions(options, "getPrompt");
759
+ } catch (error) {
760
+ return Promise.reject(error);
761
+ }
762
+ return this.#withRuntime(generationKey, ({ runtime, serverName }, operationSignal) => runtime.getPrompt(serverName, {
763
+ name,
764
+ ...arguments_ === void 0 ? {} : { arguments: { ...arguments_ } }
765
+ }, { signal: operationSignal }), controls, true);
766
+ }
767
+ state(generationKey) {
768
+ const keeper = this.#keepers.get(generationKey);
769
+ if (keeper === void 0) return this.#states.read(generationKey);
770
+ const owned = keeper.resource;
771
+ if (owned.quarantined) return this.#states.read(generationKey);
772
+ try {
773
+ const snapshot = owned.runtime.snapshot(owned.serverName);
774
+ if (snapshot.state === "connected") return this.#states.connected(generationKey, snapshot);
775
+ } catch {}
776
+ const current = this.#states.read(generationKey);
777
+ return current.phase === "online" ? this.#states.transition(generationKey, "degraded", MCP_RUNTIME_CONNECTION_LOST) : current;
778
+ }
779
+ snapshot() {
780
+ const snapshot = this.#leases.snapshot();
781
+ return Object.freeze({
782
+ closed: snapshot.closed,
783
+ maxConnections: snapshot.maxResources,
784
+ maxQueuedOperations: this.#admission.maxOperations,
785
+ queuedOperationCount: this.#admission.size,
786
+ connectionCount: snapshot.resourceCount,
787
+ pendingConnectionCount: snapshot.pendingResourceCount,
788
+ activeConnectionCount: snapshot.activeResourceCount,
789
+ closingConnectionCount: snapshot.closingResourceCount,
790
+ quarantinedConnectionCount: snapshot.failedResourceCount,
791
+ operationReferenceCount: snapshot.referenceCount,
792
+ onlineKeeperCount: this.#keepers.size
793
+ });
794
+ }
795
+ subscribe(listener) {
796
+ return this.#states.subscribe(listener);
797
+ }
798
+ close() {
799
+ if (this.#closeTask !== void 0) return this.#closeTask;
800
+ this.#closed = true;
801
+ this.#admission.rejectAll(runtimeManagerClosedError());
802
+ this.#closeTask = this.#performClose();
803
+ return this.#closeTask;
804
+ }
805
+ async [Symbol.asyncDispose]() {
806
+ await this.close();
807
+ }
808
+ async #performClose() {
809
+ const close = this.#leases.close();
810
+ const keepers = [...this.#keepers.values()];
811
+ this.#keepers.clear();
812
+ const settled = await Promise.allSettled([close, ...keepers.map((keeper) => keeper.release())]);
813
+ this.#exclusiveIdentities.clear();
814
+ const failures = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
815
+ if (failures.length > 0) throw new AggregateError(failures, "The MCP runtime manager failed to close.");
816
+ }
817
+ async #reconcileOnline(generationKey) {
818
+ const keeper = this.#keepers.get(generationKey);
819
+ if (keeper === void 0) return this.#bringOnline(generationKey);
820
+ const owned = requireActiveRuntime(keeper.resource);
821
+ let snapshot;
822
+ try {
823
+ snapshot = owned.runtime.snapshot(owned.serverName);
824
+ } catch (error) {
825
+ const mapped = mapMcpRuntimeManagerError(error);
826
+ this.#states.transition(generationKey, "degraded", runtimeManagerErrorCode(mapped));
827
+ throw mapped;
828
+ }
829
+ if (snapshot.state === "connected") return this.#states.connected(generationKey, snapshot);
830
+ this.#states.transition(generationKey, "connecting");
831
+ try {
832
+ await owned.runtime.connect(owned.serverName, { signal: AbortSignal.any([owned.generationSignal, AbortSignal.timeout(this.#requestTimeoutMs)]) });
833
+ return this.#states.connected(generationKey, owned.runtime.snapshot(owned.serverName));
834
+ } catch (error) {
835
+ const mapped = mapMcpRuntimeManagerError(error);
836
+ if (this.#states.read(generationKey).phase !== "quarantined") this.#states.transition(generationKey, "degraded", runtimeManagerErrorCode(mapped));
837
+ throw mapped;
838
+ }
839
+ }
840
+ async #bringOnline(generationKey) {
841
+ this.#assertNotQuarantined(generationKey);
842
+ this.#states.transition(generationKey, "queued");
843
+ try {
844
+ const lease = await this.#leases.acquire(generationKey, { releaseMode: "close" });
845
+ if (lease.resource.quarantined) {
846
+ await releaseIgnoringFailure(lease);
847
+ throw runtimeQuarantinedError();
848
+ }
849
+ if (this.#closed) {
850
+ await lease.release();
851
+ throw runtimeManagerClosedError();
852
+ }
853
+ this.#keepers.set(generationKey, lease);
854
+ return this.#states.read(generationKey);
855
+ } catch (error) {
856
+ const mapped = mapMcpRuntimeManagerError(error);
857
+ if (this.#states.read(generationKey).phase !== "quarantined") this.#states.transition(generationKey, "failed", runtimeManagerErrorCode(mapped));
858
+ throw mapped;
859
+ }
860
+ }
861
+ async #withRuntime(generationKey, operation, options, requireOnline = false) {
862
+ this.#assertOpen();
863
+ if (this.#offlineTasks.has(generationKey)) throw runtimeNotReadyError();
864
+ this.#assertNotQuarantined(generationKey);
865
+ const leaseMode = options.leaseMode ?? "shared";
866
+ if (leaseMode === "shared" && requireOnline) this.#assertOnlineKeeper(generationKey);
867
+ const callerSignal = options.signal;
868
+ const acquisitionSignal = AbortSignal.any([AbortSignal.timeout(this.#requestTimeoutMs), ...callerSignal === void 0 ? [] : [callerSignal]]);
869
+ const identity = leaseMode !== "shared" ? this.#createExclusiveIdentity(generationKey) : generationKey;
870
+ let reserved;
871
+ const startedAt = this.#now();
872
+ const observe = (outcome) => {
873
+ try {
874
+ options.onAdmission?.({
875
+ outcome,
876
+ durationMs: Math.max(0, this.#now() - startedAt),
877
+ queuedOperationCount: this.#admission.size,
878
+ activeConnectionCount: this.#leases.size
879
+ });
880
+ } catch {}
881
+ };
882
+ let releaseAdmission;
883
+ try {
884
+ acquisitionSignal.throwIfAborted();
885
+ if (leaseMode !== "shared" && (this.#keepers.has(generationKey) || this.#onlineTasks.has(generationKey))) throw runtimeLeaseModeConflictError();
886
+ releaseAdmission = await this.#admission.enter(generationKey, leaseMode, options.admissionKey, options.exclusiveContention === "queue" || options.concurrentContention === "queue", acquisitionSignal, options.maxConcurrentOperations, AsyncResource.bind(() => {
887
+ acquisitionSignal.throwIfAborted();
888
+ if (!this.#leases.canAcquire(identity)) return false;
889
+ reserved = this.#leases.acquire(identity, {
890
+ releaseMode: "close",
891
+ signal: acquisitionSignal,
892
+ awaitCleanupOnCancel: leaseMode !== "shared"
893
+ });
894
+ reserved.catch(() => void 0);
895
+ return true;
896
+ }));
897
+ } catch (error) {
898
+ this.#forgetExclusiveIdentity(identity);
899
+ if (acquisitionSignal.aborted && acquisitionSignal.reason instanceof DOMException && acquisitionSignal.reason.name === "TimeoutError") {
900
+ observe("timeout");
901
+ throw new McpRuntimeManagerError(MCP_RUNTIME_ADMISSION_TIMEOUT, "The MCP operation deadline expired while waiting for admission.", { cause: error });
902
+ }
903
+ observe(acquisitionSignal.aborted ? "cancelled" : runtimeManagerErrorCode(error) === "MCP_QUEUE_FULL" ? "queue-full" : "refused");
904
+ throwIfCallerAborted(callerSignal);
905
+ throw mapMcpRuntimeManagerError(error);
906
+ }
907
+ observe("admitted");
908
+ try {
909
+ if (reserved === void 0) throw new Error("MCP admission did not reserve a transport.");
910
+ return await this.#runOperation(generationKey, operation, reserved, acquisitionSignal, callerSignal);
911
+ } finally {
912
+ this.#forgetExclusiveIdentity(identity);
913
+ releaseAdmission(this.#states.read(generationKey).phase === "quarantined");
914
+ }
915
+ }
916
+ async #runOperation(generationKey, operation, reservation, acquisitionSignal, callerSignal) {
917
+ let lease;
918
+ try {
919
+ lease = await reservation;
920
+ } catch (error) {
921
+ throwIfCallerAborted(callerSignal);
922
+ throw mapMcpRuntimeManagerError(error);
923
+ }
924
+ let outcome;
925
+ try {
926
+ this.#assertOpen();
927
+ this.#assertNotQuarantined(generationKey);
928
+ const owned = requireActiveRuntime(lease.resource);
929
+ const operationSignal = AbortSignal.any([acquisitionSignal, owned.generationSignal]);
930
+ operationSignal.throwIfAborted();
931
+ if (this.#offlineTasks.has(generationKey)) throw new McpRuntimeManagerError(MCP_RUNTIME_GENERATION_RETIRED, "The MCP runtime generation was retired before dispatch.");
932
+ outcome = {
933
+ success: true,
934
+ value: await operation(owned, operationSignal)
935
+ };
936
+ } catch (error) {
937
+ outcome = {
938
+ success: false,
939
+ error
940
+ };
941
+ }
942
+ try {
943
+ await lease.release();
944
+ } catch (error) {
945
+ this.#states.transition(generationKey, "quarantined", MCP_RUNTIME_CLEANUP_FAILED);
946
+ throw runtimeQuarantinedError(error);
947
+ }
948
+ if (!outcome.success) {
949
+ throwIfCallerAborted(callerSignal);
950
+ throw mapMcpRuntimeManagerError(outcome.error);
951
+ }
952
+ return outcome.value;
953
+ }
954
+ async #probeProtocolLiveness(owned, signal) {
955
+ const { runtime, serverName } = owned;
956
+ const protocolEra = runtime.snapshot(serverName).protocolEra;
957
+ if (protocolEra === "legacy") {
958
+ await runtime.ping(serverName, { signal });
959
+ return;
960
+ }
961
+ if (protocolEra === "modern") {
962
+ await runtime.discover(serverName, { signal });
963
+ return;
964
+ }
965
+ throw new McpRuntimeManagerError("MCP_UPSTREAM_FAILED", "The connected MCP server did not report a protocol era.");
966
+ }
967
+ #assertOpen() {
968
+ if (this.#closed) throw runtimeManagerClosedError();
969
+ }
970
+ #assertSharedLeaseAvailable(generationKey) {
971
+ if (this.#admission.hasIsolatedGeneration(generationKey)) throw runtimeLeaseModeConflictError();
972
+ }
973
+ #createExclusiveIdentity(generationKey) {
974
+ const identity = new ExclusiveRuntimeLeaseIdentity(generationKey);
975
+ let identities = this.#exclusiveIdentities.get(generationKey);
976
+ if (identities === void 0) {
977
+ identities = /* @__PURE__ */ new Set();
978
+ this.#exclusiveIdentities.set(generationKey, identities);
979
+ }
980
+ identities.add(identity);
981
+ return identity;
982
+ }
983
+ #forgetExclusiveIdentity(identity) {
984
+ if (!(identity instanceof ExclusiveRuntimeLeaseIdentity)) return;
985
+ const identities = this.#exclusiveIdentities.get(identity.generationKey);
986
+ if (identities === void 0) return;
987
+ identities.delete(identity);
988
+ if (identities.size === 0) this.#exclusiveIdentities.delete(identity.generationKey);
989
+ }
990
+ #assertNotQuarantined(generationKey) {
991
+ if (this.#states.read(generationKey).phase === "quarantined") throw runtimeQuarantinedError();
992
+ }
993
+ #assertOnlineKeeper(generationKey) {
994
+ const keeper = this.#keepers.get(generationKey);
995
+ if (keeper === void 0) throw runtimeNotReadyError();
996
+ const owned = requireActiveRuntime(keeper.resource);
997
+ const snapshot = owned.runtime.snapshot(owned.serverName);
998
+ if (snapshot.state !== "connected") {
999
+ this.#states.transition(generationKey, "degraded", MCP_RUNTIME_CONNECTION_LOST);
1000
+ throw runtimeNotReadyError();
1001
+ }
1002
+ this.#states.connected(generationKey, snapshot);
1003
+ }
1004
+ };
1005
+ const EMPTY_OPERATION_OPTIONS = Object.freeze({});
1006
+ const EMPTY_TOOL_CALL_OPTIONS = EMPTY_OPERATION_OPTIONS;
1007
+ function normalizeOperationOptions(options, operationName) {
1008
+ if (options === void 0) return EMPTY_OPERATION_OPTIONS;
1009
+ if (typeof options !== "object" || options === null) throw new TypeError(`${operationName} options must be an AbortSignal or an operation options object.`);
1010
+ if (isAbortSignal(options)) return { signal: options };
1011
+ let signal;
1012
+ let leaseMode;
1013
+ let exclusiveContention;
1014
+ let admissionKey;
1015
+ let concurrentContention;
1016
+ let maxConcurrentOperations;
1017
+ let onAdmission;
1018
+ try {
1019
+ signal = Reflect.get(options, "signal");
1020
+ leaseMode = Reflect.get(options, "leaseMode");
1021
+ exclusiveContention = Reflect.get(options, "exclusiveContention");
1022
+ admissionKey = Reflect.get(options, "admissionKey");
1023
+ concurrentContention = Reflect.get(options, "concurrentContention");
1024
+ maxConcurrentOperations = Reflect.get(options, "maxConcurrentOperations");
1025
+ onAdmission = Reflect.get(options, "onAdmission");
1026
+ } catch {
1027
+ throw new TypeError(`${operationName} options could not be read.`);
1028
+ }
1029
+ if (signal !== void 0 && (typeof signal !== "object" || signal === null || !isAbortSignal(signal))) throw new TypeError(`${operationName} options.signal must be an AbortSignal.`);
1030
+ if (leaseMode !== void 0 && leaseMode !== "shared" && leaseMode !== "exclusive" && leaseMode !== "concurrent") throw new TypeError(`${operationName} options.leaseMode must be "shared", "exclusive", or "concurrent".`);
1031
+ if (exclusiveContention !== void 0 && exclusiveContention !== "reject" && exclusiveContention !== "queue") throw new TypeError(`${operationName} options.exclusiveContention must be "reject" or "queue".`);
1032
+ if (concurrentContention !== void 0 && concurrentContention !== "reject" && concurrentContention !== "queue") throw new TypeError(`${operationName} options.concurrentContention must be "reject" or "queue".`);
1033
+ if (concurrentContention === "queue" && leaseMode !== "concurrent") throw new TypeError(`${operationName} queued concurrent contention requires leaseMode "concurrent".`);
1034
+ if (maxConcurrentOperations !== void 0 && maxConcurrentOperations !== null) {
1035
+ if (typeof maxConcurrentOperations !== "number") throw new TypeError("maxConcurrentOperations must be a positive integer or null.");
1036
+ positiveInteger(maxConcurrentOperations, "maxConcurrentOperations");
1037
+ }
1038
+ if (onAdmission !== void 0 && !isAdmissionObserver(onAdmission)) throw new TypeError("onAdmission must be a function.");
1039
+ if (exclusiveContention === "queue" && leaseMode !== "exclusive") throw new TypeError(`${operationName} queued contention requires leaseMode "exclusive".`);
1040
+ if (admissionKey !== void 0 && (typeof admissionKey !== "string" || admissionKey.length === 0 || admissionKey.length > 1024)) throw new TypeError(`${operationName} options.admissionKey must be a nonempty bounded string.`);
1041
+ if (leaseMode === "concurrent" && admissionKey === void 0) throw new TypeError(`${operationName} concurrent execution requires an admissionKey.`);
1042
+ if (admissionKey !== void 0 && leaseMode !== "concurrent" && leaseMode !== "exclusive") throw new TypeError(`${operationName} admissionKey requires an isolated lease mode.`);
1043
+ return {
1044
+ ...signal === void 0 ? {} : { signal },
1045
+ ...leaseMode === void 0 ? {} : { leaseMode },
1046
+ ...exclusiveContention === void 0 ? {} : { exclusiveContention },
1047
+ ...admissionKey === void 0 ? {} : { admissionKey },
1048
+ ...concurrentContention === void 0 ? {} : { concurrentContention },
1049
+ ...maxConcurrentOperations === void 0 ? {} : { maxConcurrentOperations },
1050
+ ...onAdmission === void 0 ? {} : { onAdmission }
1051
+ };
1052
+ }
1053
+ /** Accepts the positional cancellation form and the richer per-call options object. */
1054
+ function normalizeToolCallOptions(options) {
1055
+ if (options === void 0) return EMPTY_TOOL_CALL_OPTIONS;
1056
+ if (typeof options !== "object" || options === null) throw new TypeError("callTool options must be an AbortSignal or a tool call options object.");
1057
+ if (isAbortSignal(options)) return { signal: options };
1058
+ return {
1059
+ ...normalizeOperationOptions(options, "callTool"),
1060
+ ...options.toolDefinition === void 0 ? {} : { toolDefinition: options.toolDefinition }
1061
+ };
1062
+ }
1063
+ function isAdmissionObserver(value) {
1064
+ return typeof value === "function";
1065
+ }
1066
+ function isAbortSignal(value) {
1067
+ if (value instanceof AbortSignal) return true;
1068
+ try {
1069
+ return typeof Reflect.get(value, "aborted") === "boolean" && typeof Reflect.get(value, "addEventListener") === "function";
1070
+ } catch {
1071
+ return false;
1072
+ }
1073
+ }
1074
+ function isMethodNotFoundProtocolError(error) {
1075
+ return ProtocolError.isInstance(error) && error.code === METHOD_NOT_FOUND;
1076
+ }
1077
+ function requireDiscoveryResult(result) {
1078
+ if (result.status === "fulfilled") return result.value;
1079
+ throw result.reason;
1080
+ }
1081
+ function generationKeyOf(identity) {
1082
+ return identity instanceof ExclusiveRuntimeLeaseIdentity ? identity.generationKey : identity;
1083
+ }
1084
+ function requireActiveRuntime(owned) {
1085
+ if (owned.quarantined) throw runtimeQuarantinedError();
1086
+ return owned;
1087
+ }
1088
+ function throwIfCallerAborted(signal) {
1089
+ if (signal?.aborted === true) throw signal.reason;
1090
+ }
1091
+ function isRetirementError(error) {
1092
+ if (typeof error !== "object" || error === null) return false;
1093
+ try {
1094
+ const code = Reflect.get(error, "code");
1095
+ return code === MCP_CLIENT_LEASE_INVALIDATED || code === "MCP_GENERATION_RETIRED";
1096
+ } catch {
1097
+ return false;
1098
+ }
1099
+ }
1100
+ async function releaseIgnoringFailure(lease) {
1101
+ try {
1102
+ await lease.release();
1103
+ } catch {}
1104
+ }
1105
+ function waitForCaller(task, signal) {
1106
+ if (signal === void 0) return task;
1107
+ if (signal.aborted) return Promise.reject(signal.reason);
1108
+ return new Promise((resolve, reject) => {
1109
+ const onAbort = () => {
1110
+ signal.removeEventListener("abort", onAbort);
1111
+ reject(signal.reason);
1112
+ };
1113
+ signal.addEventListener("abort", onAbort, { once: true });
1114
+ task.then((result) => {
1115
+ signal.removeEventListener("abort", onAbort);
1116
+ resolve(result);
1117
+ }, (error) => {
1118
+ signal.removeEventListener("abort", onAbort);
1119
+ reject(error);
1120
+ });
1121
+ });
1122
+ }
1123
+ function positiveInteger(value, name) {
1124
+ if (!Number.isInteger(value) || value <= 0) throw new RangeError(`${name} must be a positive integer.`);
1125
+ return value;
1126
+ }
1127
+ function positiveFinite(value, name) {
1128
+ if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be a positive finite number.`);
1129
+ return value;
1130
+ }
1131
+ function isoTimestamp(now) {
1132
+ try {
1133
+ const timestamp = now();
1134
+ if (Number.isFinite(timestamp)) return new Date(timestamp).toISOString();
1135
+ } catch {}
1136
+ return (/* @__PURE__ */ new Date()).toISOString();
1137
+ }
1138
+ function safeClock(now) {
1139
+ return () => {
1140
+ try {
1141
+ const timestamp = now();
1142
+ if (Number.isFinite(timestamp)) {
1143
+ new Date(timestamp).toISOString();
1144
+ return timestamp;
1145
+ }
1146
+ } catch {}
1147
+ return Date.now();
1148
+ };
1149
+ }
1150
+ //#endregion
1151
+ //#region src/runtime-ownership.ts
1152
+ const MCP_RUNTIME_OWNERSHIP_DEFAULTS = Object.freeze({
1153
+ maxOwners: 1e3,
1154
+ maxGenerations: 1e3,
1155
+ maxReferences: 1e4
1156
+ });
1157
+ const MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS = "MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS";
1158
+ const MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED = "MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED";
1159
+ const MCP_RUNTIME_OWNER_RELEASED = "MCP_RUNTIME_OWNER_RELEASED";
1160
+ const MCP_RUNTIME_GENERATION_FENCED = "MCP_RUNTIME_GENERATION_FENCED";
1161
+ const MCP_RUNTIME_RETIREMENT_FAILED = "MCP_RUNTIME_RETIREMENT_FAILED";
1162
+ /** Stable ownership failure that never retains a generation key or caught manager error. */
1163
+ var McpRuntimeOwnershipError = class extends Error {
1164
+ code;
1165
+ constructor(code, message) {
1166
+ super(message);
1167
+ this.name = "McpRuntimeOwnershipError";
1168
+ this.code = code;
1169
+ }
1170
+ };
1171
+ /**
1172
+ * Bounded, framework-neutral cooperative ownership for opaque runtime generations.
1173
+ *
1174
+ * Equal keys use `Map` identity. The final cooperative release retires the manager generation.
1175
+ * `forceRetire` immediately revokes every current reference and permanently fences every owner
1176
+ * that existed when the force began. No retain can cross an unsettled retirement barrier.
1177
+ */
1178
+ var McpRuntimeOwnership = class {
1179
+ #retireGeneration;
1180
+ #maxOwners;
1181
+ #maxGenerations;
1182
+ #maxReferences;
1183
+ #owners = /* @__PURE__ */ new Set();
1184
+ #generations = /* @__PURE__ */ new Map();
1185
+ #referenceCount = 0;
1186
+ #pendingReferenceCount = 0;
1187
+ #nextOwnerSequence = 0;
1188
+ constructor(options) {
1189
+ let manager;
1190
+ let retireGeneration;
1191
+ let maxOwners;
1192
+ let maxGenerations;
1193
+ let maxReferences;
1194
+ try {
1195
+ manager = options.manager;
1196
+ if (typeof manager !== "object" && typeof manager !== "function" || manager === null) throw invalidOptionsError();
1197
+ retireGeneration = manager.retire;
1198
+ maxOwners = options.maxOwners ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxOwners;
1199
+ maxGenerations = options.maxGenerations ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxGenerations;
1200
+ maxReferences = options.maxReferences ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxReferences;
1201
+ } catch {
1202
+ throw invalidOptionsError();
1203
+ }
1204
+ if (typeof retireGeneration !== "function" || !isPositiveSafeInteger(maxOwners) || !isPositiveSafeInteger(maxGenerations) || !isPositiveSafeInteger(maxReferences)) throw invalidOptionsError();
1205
+ this.#retireGeneration = (generationKey) => retireGeneration.call(manager, generationKey);
1206
+ this.#maxOwners = maxOwners;
1207
+ this.#maxGenerations = maxGenerations;
1208
+ this.#maxReferences = maxReferences;
1209
+ }
1210
+ createOwner() {
1211
+ if (this.#owners.size >= this.#maxOwners || this.#nextOwnerSequence >= Number.MAX_SAFE_INTEGER) throw capacityExceededError();
1212
+ this.#nextOwnerSequence += 1;
1213
+ let owner;
1214
+ owner = new ManagedMcpRuntimeOwner(this.#nextOwnerSequence, (generationKey) => this.#retain(owner, generationKey), () => this.#release(owner));
1215
+ this.#owners.add(owner);
1216
+ return Object.freeze(owner);
1217
+ }
1218
+ /**
1219
+ * Retires a generation regardless of cooperative references.
1220
+ * Repeated calls against the same generation barrier share one settlement.
1221
+ */
1222
+ forceRetire(generationKey) {
1223
+ let entry = this.#generations.get(generationKey);
1224
+ if (entry !== void 0 && entry.phase !== "active") {
1225
+ entry.forceFenceThrough = Math.max(entry.forceFenceThrough ?? 0, this.#nextOwnerSequence);
1226
+ return requireRetirementTask(entry);
1227
+ }
1228
+ if (entry === void 0) {
1229
+ this.#pruneReusableFences();
1230
+ if (this.#generations.size >= this.#maxGenerations) return Promise.reject(capacityExceededError());
1231
+ entry = this.#createGeneration(generationKey);
1232
+ }
1233
+ entry.forceFenceThrough = Math.max(entry.forceFenceThrough ?? 0, this.#nextOwnerSequence);
1234
+ for (const owner of entry.owners) {
1235
+ owner.dropRetainedGeneration(generationKey);
1236
+ this.#referenceCount -= 1;
1237
+ }
1238
+ entry.owners.clear();
1239
+ return this.#startRetirement(entry);
1240
+ }
1241
+ snapshot() {
1242
+ let retiringGenerationCount = 0;
1243
+ let fencedGenerationCount = 0;
1244
+ for (const entry of this.#generations.values()) {
1245
+ if (entry.phase === "retiring") retiringGenerationCount += 1;
1246
+ if (entry.phase === "retirement-failed" || entry.forceFenceThrough !== void 0) fencedGenerationCount += 1;
1247
+ }
1248
+ return Object.freeze({
1249
+ maxOwners: this.#maxOwners,
1250
+ maxGenerations: this.#maxGenerations,
1251
+ maxReferences: this.#maxReferences,
1252
+ ownerCount: this.#owners.size,
1253
+ generationCount: this.#generations.size,
1254
+ referenceCount: this.#referenceCount,
1255
+ pendingReferenceCount: this.#pendingReferenceCount,
1256
+ retiringGenerationCount,
1257
+ fencedGenerationCount
1258
+ });
1259
+ }
1260
+ #retain(owner, generationKey) {
1261
+ if (owner.released) return Promise.reject(ownerReleasedError());
1262
+ if (owner.hasRetainedGeneration(generationKey)) return Promise.resolve();
1263
+ if (this.#referenceCount + this.#pendingReferenceCount >= this.#maxReferences) return Promise.reject(capacityExceededError());
1264
+ const reservation = { pending: true };
1265
+ this.#pendingReferenceCount += 1;
1266
+ return this.#performRetain(owner, generationKey, reservation).catch((error) => {
1267
+ if (reservation.pending) {
1268
+ reservation.pending = false;
1269
+ this.#pendingReferenceCount -= 1;
1270
+ }
1271
+ throw error;
1272
+ });
1273
+ }
1274
+ async #performRetain(owner, generationKey, reservation) {
1275
+ for (;;) {
1276
+ if (owner.released) throw ownerReleasedError();
1277
+ let entry = this.#generations.get(generationKey);
1278
+ if (entry?.phase === "retiring") {
1279
+ await waitForRetirementBarrier(requireRetirementTask(entry), owner.releaseSignal);
1280
+ continue;
1281
+ }
1282
+ if (owner.released) throw ownerReleasedError();
1283
+ if (entry !== void 0) {
1284
+ if (entry.phase === "retirement-failed") throw generationFencedError();
1285
+ if (entry.phase === "retired") {
1286
+ const forceFenceThrough = entry.forceFenceThrough;
1287
+ if (forceFenceThrough === void 0 || owner.sequence <= forceFenceThrough) throw generationFencedError();
1288
+ entry = this.#replaceRetiredGeneration(entry);
1289
+ } else if (entry.forceFenceThrough !== void 0 && owner.sequence <= entry.forceFenceThrough) throw generationFencedError();
1290
+ } else {
1291
+ this.#pruneReusableFences();
1292
+ if (this.#generations.size >= this.#maxGenerations) throw capacityExceededError();
1293
+ entry = this.#createGeneration(generationKey);
1294
+ }
1295
+ if (owner.released) throw ownerReleasedError();
1296
+ entry.owners.add(owner);
1297
+ owner.addRetainedGeneration(generationKey);
1298
+ reservation.pending = false;
1299
+ this.#pendingReferenceCount -= 1;
1300
+ this.#referenceCount += 1;
1301
+ return;
1302
+ }
1303
+ }
1304
+ #release(owner) {
1305
+ this.#owners.delete(owner);
1306
+ const retirementTasks = [];
1307
+ for (const generationKey of owner.takeRetainedGenerations()) {
1308
+ const entry = this.#generations.get(generationKey);
1309
+ if (entry === void 0 || !entry.owners.delete(owner)) continue;
1310
+ this.#referenceCount -= 1;
1311
+ if (entry.owners.size === 0 && entry.phase === "active") retirementTasks.push(this.#startRetirement(entry));
1312
+ }
1313
+ this.#pruneReusableFences();
1314
+ return settleOwnerRelease(retirementTasks);
1315
+ }
1316
+ #createGeneration(generationKey) {
1317
+ const entry = {
1318
+ key: generationKey,
1319
+ token: Symbol("mcp-runtime-ownership-generation"),
1320
+ owners: /* @__PURE__ */ new Set(),
1321
+ phase: "active",
1322
+ forceFenceThrough: void 0,
1323
+ retirementTask: void 0
1324
+ };
1325
+ this.#generations.set(generationKey, entry);
1326
+ return entry;
1327
+ }
1328
+ #replaceRetiredGeneration(retired) {
1329
+ const replacement = {
1330
+ key: retired.key,
1331
+ token: Symbol("mcp-runtime-ownership-generation"),
1332
+ owners: /* @__PURE__ */ new Set(),
1333
+ phase: "active",
1334
+ forceFenceThrough: retired.forceFenceThrough,
1335
+ retirementTask: void 0
1336
+ };
1337
+ this.#generations.set(retired.key, replacement);
1338
+ return replacement;
1339
+ }
1340
+ #startRetirement(entry) {
1341
+ if (entry.retirementTask !== void 0) return entry.retirementTask;
1342
+ entry.phase = "retiring";
1343
+ const task = Promise.resolve().then(() => this.#retireGeneration(entry.key)).then(() => this.#settleRetirementSuccess(entry), (error) => {
1344
+ if (isManagerClosedError(error)) {
1345
+ this.#settleRetirementSuccess(entry);
1346
+ return;
1347
+ }
1348
+ entry.phase = "retirement-failed";
1349
+ throw retirementFailedError();
1350
+ });
1351
+ entry.retirementTask = task;
1352
+ return task;
1353
+ }
1354
+ #settleRetirementSuccess(entry) {
1355
+ entry.phase = "retired";
1356
+ if (this.#generations.get(entry.key)?.token !== entry.token) return;
1357
+ if (entry.forceFenceThrough === void 0 || !this.#hasFencedOwner(entry.forceFenceThrough)) this.#generations.delete(entry.key);
1358
+ }
1359
+ #pruneReusableFences() {
1360
+ for (const [generationKey, entry] of this.#generations) if (entry.phase === "retired" && entry.forceFenceThrough !== void 0 && !this.#hasFencedOwner(entry.forceFenceThrough)) this.#generations.delete(generationKey);
1361
+ }
1362
+ #hasFencedOwner(fenceThrough) {
1363
+ for (const owner of this.#owners) if (owner.sequence <= fenceThrough) return true;
1364
+ return false;
1365
+ }
1366
+ };
1367
+ var ManagedMcpRuntimeOwner = class {
1368
+ #releaseController = new AbortController();
1369
+ #retainGeneration;
1370
+ #releaseOwner;
1371
+ #retainedGenerations = /* @__PURE__ */ new Set();
1372
+ #retentionTasks = /* @__PURE__ */ new Map();
1373
+ sequence;
1374
+ #releaseStarted = false;
1375
+ #releaseTask;
1376
+ constructor(sequence, retainGeneration, releaseOwner) {
1377
+ this.sequence = sequence;
1378
+ this.#retainGeneration = retainGeneration;
1379
+ this.#releaseOwner = releaseOwner;
1380
+ }
1381
+ get released() {
1382
+ return this.#releaseStarted;
1383
+ }
1384
+ get releaseSignal() {
1385
+ return this.#releaseController.signal;
1386
+ }
1387
+ retain(generationKey) {
1388
+ if (this.#releaseStarted) return Promise.reject(ownerReleasedError());
1389
+ const existing = this.#retentionTasks.get(generationKey);
1390
+ if (existing !== void 0) return existing;
1391
+ const task = this.#retainGeneration(generationKey);
1392
+ this.#retentionTasks.set(generationKey, task);
1393
+ task.catch(() => {
1394
+ if (this.#retentionTasks.get(generationKey) === task) this.#retentionTasks.delete(generationKey);
1395
+ });
1396
+ return task;
1397
+ }
1398
+ release() {
1399
+ if (this.#releaseTask === void 0) {
1400
+ this.#releaseStarted = true;
1401
+ this.#releaseController.abort();
1402
+ try {
1403
+ this.#releaseTask = this.#releaseOwner();
1404
+ } catch (error) {
1405
+ this.#releaseTask = Promise.reject(error);
1406
+ }
1407
+ }
1408
+ return this.#releaseTask;
1409
+ }
1410
+ async [Symbol.asyncDispose]() {
1411
+ await this.release();
1412
+ }
1413
+ hasRetainedGeneration(generationKey) {
1414
+ return this.#retainedGenerations.has(generationKey);
1415
+ }
1416
+ addRetainedGeneration(generationKey) {
1417
+ this.#retainedGenerations.add(generationKey);
1418
+ }
1419
+ dropRetainedGeneration(generationKey) {
1420
+ this.#retainedGenerations.delete(generationKey);
1421
+ this.#retentionTasks.delete(generationKey);
1422
+ }
1423
+ takeRetainedGenerations() {
1424
+ const retained = [...this.#retainedGenerations];
1425
+ this.#retainedGenerations.clear();
1426
+ for (const generationKey of retained) this.#retentionTasks.delete(generationKey);
1427
+ return retained;
1428
+ }
1429
+ };
1430
+ function settleOwnerRelease(tasks) {
1431
+ if (tasks.length === 0) return Promise.resolve();
1432
+ return Promise.allSettled(tasks).then((settled) => {
1433
+ const failures = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1434
+ if (failures.length > 0) throw new AggregateError(failures, "One or more MCP runtime generations failed to retire.");
1435
+ });
1436
+ }
1437
+ function requireRetirementTask(entry) {
1438
+ if (entry.retirementTask === void 0) throw new Error("The MCP runtime ownership retirement task is missing.");
1439
+ return entry.retirementTask;
1440
+ }
1441
+ function waitForRetirementBarrier(task, releaseSignal) {
1442
+ if (releaseSignal.aborted) return Promise.reject(ownerReleasedError());
1443
+ return new Promise((resolve, reject) => {
1444
+ let settled = false;
1445
+ const finish = (released) => {
1446
+ if (settled) return;
1447
+ settled = true;
1448
+ releaseSignal.removeEventListener("abort", onRelease);
1449
+ if (released) reject(ownerReleasedError());
1450
+ else resolve();
1451
+ };
1452
+ const onRelease = () => finish(true);
1453
+ releaseSignal.addEventListener("abort", onRelease, { once: true });
1454
+ task.then(() => finish(false), () => finish(false));
1455
+ });
1456
+ }
1457
+ function isPositiveSafeInteger(value) {
1458
+ return Number.isSafeInteger(value) && value > 0;
1459
+ }
1460
+ function isManagerClosedError(error) {
1461
+ if (typeof error !== "object" || error === null) return false;
1462
+ try {
1463
+ return Reflect.get(error, "code") === MCP_RUNTIME_MANAGER_CLOSED;
1464
+ } catch {
1465
+ return false;
1466
+ }
1467
+ }
1468
+ function invalidOptionsError() {
1469
+ return new McpRuntimeOwnershipError(MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS, "The MCP runtime ownership options are invalid.");
1470
+ }
1471
+ function capacityExceededError() {
1472
+ return new McpRuntimeOwnershipError(MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED, "The MCP runtime ownership coordinator is at its configured capacity.");
1473
+ }
1474
+ function ownerReleasedError() {
1475
+ return new McpRuntimeOwnershipError(MCP_RUNTIME_OWNER_RELEASED, "The MCP runtime owner has already been released.");
1476
+ }
1477
+ function generationFencedError() {
1478
+ return new McpRuntimeOwnershipError(MCP_RUNTIME_GENERATION_FENCED, "The MCP runtime generation is fenced from this owner.");
1479
+ }
1480
+ function retirementFailedError() {
1481
+ return new McpRuntimeOwnershipError(MCP_RUNTIME_RETIREMENT_FAILED, "The MCP runtime generation failed to retire.");
1482
+ }
1483
+ //#endregion
1484
+ //#region src/runtime-snapshots.ts
1485
+ const RUNTIME_PHASE_MEMBERS = [
1486
+ "offline",
1487
+ "queued",
1488
+ "connecting",
1489
+ "online",
1490
+ "degraded",
1491
+ "draining",
1492
+ "failed",
1493
+ "quarantined"
1494
+ ];
1495
+ const PROTOCOL_ERA_MEMBERS = ["legacy", "modern"];
1496
+ const CAPABILITY_MEMBERS = [
1497
+ "tools",
1498
+ "resources",
1499
+ "prompts",
1500
+ "completion",
1501
+ "subscriptions"
1502
+ ];
1503
+ const STATE_MEMBERS = [
1504
+ "phase",
1505
+ "lastTransitionAt",
1506
+ "protocolVersion",
1507
+ "protocolEra",
1508
+ "connectedAt",
1509
+ "errorCode",
1510
+ "capabilities"
1511
+ ];
1512
+ const PROBE_MEMBERS = [
1513
+ "reachable",
1514
+ "observedAt",
1515
+ "protocolVersion",
1516
+ "protocolEra",
1517
+ "capabilities",
1518
+ "runtime"
1519
+ ];
1520
+ /** Every `McpRuntimePhase`, in lifecycle order, for hosts that persist state projections. */
1521
+ const MCP_RUNTIME_PHASES = Object.freeze(RUNTIME_PHASE_MEMBERS);
1522
+ /** Every `McpRuntimeProtocolEra` a connected managed generation can report. */
1523
+ const MCP_RUNTIME_PROTOCOL_ERAS = Object.freeze(PROTOCOL_ERA_MEMBERS);
1524
+ const RUNTIME_PHASES = new Set(MCP_RUNTIME_PHASES);
1525
+ const PROTOCOL_ERAS = new Set(MCP_RUNTIME_PROTOCOL_ERAS);
1526
+ const CAPABILITY_KEYS = new Set(CAPABILITY_MEMBERS);
1527
+ const STATE_KEYS = new Set(STATE_MEMBERS);
1528
+ const PROBE_KEYS = new Set(PROBE_MEMBERS);
1529
+ const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u;
1530
+ const SNAPSHOT_SCHEMA_VENDOR = "@nest-mcp/manager";
1531
+ /** Validates a persisted `McpRuntimeCapabilitiesSnapshot`. */
1532
+ const mcpRuntimeCapabilitiesSnapshotSchema = snapshotSchema(parseCapabilitiesSnapshot);
1533
+ /** Validates a persisted `McpRuntimeStateSnapshot`, including an optional capability projection. */
1534
+ const mcpRuntimeStateSnapshotSchema = snapshotSchema(parseStateSnapshot);
1535
+ /** Validates a persisted `McpRuntimeProbeSnapshot`, including its nested state projection. */
1536
+ const mcpRuntimeProbeSnapshotSchema = snapshotSchema(parseProbeSnapshot);
1537
+ function snapshotSchema(parse) {
1538
+ return Object.freeze({ "~standard": Object.freeze({
1539
+ version: 1,
1540
+ vendor: SNAPSHOT_SCHEMA_VENDOR,
1541
+ validate(value) {
1542
+ const issues = [];
1543
+ const snapshot = parse(value, [], issues);
1544
+ if (snapshot === void 0 || issues.length > 0) return { issues: Object.freeze(issues.length > 0 ? issues : [issue("Expected a valid snapshot.", [])]) };
1545
+ return { value: snapshot };
1546
+ }
1547
+ }) });
1548
+ }
1549
+ function parseCapabilitiesSnapshot(value, path, issues) {
1550
+ const source = readObject(value, path, issues);
1551
+ if (source === void 0) return void 0;
1552
+ rejectUnknownKeys(source, CAPABILITY_KEYS, path, issues);
1553
+ const issueCount = issues.length;
1554
+ const capabilities = Object.freeze({
1555
+ tools: readBoolean(source, "tools", path, issues),
1556
+ resources: readBoolean(source, "resources", path, issues),
1557
+ prompts: readBoolean(source, "prompts", path, issues),
1558
+ completion: readBoolean(source, "completion", path, issues),
1559
+ subscriptions: readBoolean(source, "subscriptions", path, issues)
1560
+ });
1561
+ return issues.length > issueCount ? void 0 : capabilities;
1562
+ }
1563
+ function parseStateSnapshot(value, path, issues) {
1564
+ const source = readObject(value, path, issues);
1565
+ if (source === void 0) return void 0;
1566
+ rejectUnknownKeys(source, STATE_KEYS, path, issues);
1567
+ const issueCount = issues.length;
1568
+ const phase = readPhase(source, path, issues);
1569
+ const lastTransitionAt = readRequiredTimestamp(source, "lastTransitionAt", path, issues);
1570
+ const protocolVersion = readText(source, "protocolVersion", path, issues);
1571
+ const protocolEra = readProtocolEra(source, path, issues);
1572
+ const connectedAt = readOptionalTimestamp(source, "connectedAt", path, issues);
1573
+ const errorCode = readErrorCode(source, path, issues);
1574
+ const capabilities = readCapabilities(source, path, issues);
1575
+ if (phase === void 0 || lastTransitionAt === void 0 || issues.length > issueCount) return;
1576
+ return Object.freeze({
1577
+ phase,
1578
+ lastTransitionAt,
1579
+ ...protocolVersion === void 0 ? {} : { protocolVersion },
1580
+ ...protocolEra === void 0 ? {} : { protocolEra },
1581
+ ...connectedAt === void 0 ? {} : { connectedAt },
1582
+ ...errorCode === void 0 ? {} : { errorCode },
1583
+ ...capabilities === void 0 ? {} : { capabilities }
1584
+ });
1585
+ }
1586
+ function parseProbeSnapshot(value, path, issues) {
1587
+ const source = readObject(value, path, issues);
1588
+ if (source === void 0) return void 0;
1589
+ rejectUnknownKeys(source, PROBE_KEYS, path, issues);
1590
+ const issueCount = issues.length;
1591
+ if (Reflect.get(source, "reachable") !== true) issues.push(issue("Expected the literal value true.", [...path, "reachable"]));
1592
+ const observedAt = readRequiredTimestamp(source, "observedAt", path, issues);
1593
+ const protocolVersion = readText(source, "protocolVersion", path, issues);
1594
+ const protocolEra = readProtocolEra(source, path, issues);
1595
+ const capabilities = readCapabilities(source, path, issues);
1596
+ const runtime = readRuntimeState(source, path, issues);
1597
+ if (observedAt === void 0 || runtime === void 0 || issues.length > issueCount) return;
1598
+ return Object.freeze({
1599
+ reachable: true,
1600
+ observedAt,
1601
+ ...protocolVersion === void 0 ? {} : { protocolVersion },
1602
+ ...protocolEra === void 0 ? {} : { protocolEra },
1603
+ ...capabilities === void 0 ? {} : { capabilities },
1604
+ runtime
1605
+ });
1606
+ }
1607
+ function readObject(value, path, issues) {
1608
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1609
+ issues.push(issue("Expected an object.", path));
1610
+ return;
1611
+ }
1612
+ return value;
1613
+ }
1614
+ function rejectUnknownKeys(source, known, path, issues) {
1615
+ for (const key of Object.keys(source)) {
1616
+ if (known.has(key)) continue;
1617
+ issues.push(issue("Unrecognized property.", [...path, key]));
1618
+ }
1619
+ }
1620
+ function readBoolean(source, key, path, issues) {
1621
+ const value = Reflect.get(source, key);
1622
+ if (typeof value === "boolean") return value;
1623
+ issues.push(issue("Expected a boolean.", [...path, key]));
1624
+ return false;
1625
+ }
1626
+ function readPhase(source, path, issues) {
1627
+ const value = Reflect.get(source, "phase");
1628
+ if (typeof value === "string" && isRuntimePhase(value)) return value;
1629
+ issues.push(issue(expectedOneOf(MCP_RUNTIME_PHASES), [...path, "phase"]));
1630
+ }
1631
+ function readProtocolEra(source, path, issues) {
1632
+ const value = Reflect.get(source, "protocolEra");
1633
+ if (value === void 0) return void 0;
1634
+ if (typeof value === "string" && isProtocolEra(value)) return value;
1635
+ issues.push(issue(expectedOneOf(MCP_RUNTIME_PROTOCOL_ERAS), [...path, "protocolEra"]));
1636
+ }
1637
+ function readErrorCode(source, path, issues) {
1638
+ const value = Reflect.get(source, "errorCode");
1639
+ if (value === void 0) return void 0;
1640
+ if (typeof value === "string" && isRuntimeStateErrorCode(value)) return value;
1641
+ issues.push(issue("Expected a known MCP runtime state error code.", [...path, "errorCode"]));
1642
+ }
1643
+ function readCapabilities(source, path, issues) {
1644
+ const value = Reflect.get(source, "capabilities");
1645
+ if (value === void 0) return void 0;
1646
+ return parseCapabilitiesSnapshot(value, [...path, "capabilities"], issues);
1647
+ }
1648
+ function readRuntimeState(source, path, issues) {
1649
+ const value = Reflect.get(source, "runtime");
1650
+ const runtimePath = [...path, "runtime"];
1651
+ if (value === void 0) {
1652
+ issues.push(issue("Expected a required value.", runtimePath));
1653
+ return;
1654
+ }
1655
+ return parseStateSnapshot(value, runtimePath, issues);
1656
+ }
1657
+ function readText(source, key, path, issues) {
1658
+ const value = Reflect.get(source, key);
1659
+ if (value === void 0) return void 0;
1660
+ if (typeof value === "string" && value.length > 0) return value;
1661
+ issues.push(issue("Expected a non-empty string.", [...path, key]));
1662
+ }
1663
+ function readRequiredTimestamp(source, key, path, issues) {
1664
+ if (Reflect.get(source, key) === void 0) {
1665
+ issues.push(issue("Expected a required value.", [...path, key]));
1666
+ return;
1667
+ }
1668
+ return readOptionalTimestamp(source, key, path, issues);
1669
+ }
1670
+ function readOptionalTimestamp(source, key, path, issues) {
1671
+ const value = Reflect.get(source, key);
1672
+ if (value === void 0) return void 0;
1673
+ if (typeof value === "string" && ISO_TIMESTAMP_PATTERN.test(value) && isResolvedInstant(value)) return value;
1674
+ issues.push(issue("Expected an ISO 8601 date-time string.", [...path, key]));
1675
+ }
1676
+ function issue(message, path) {
1677
+ return Object.freeze({
1678
+ message,
1679
+ path: Object.freeze([...path])
1680
+ });
1681
+ }
1682
+ function expectedOneOf(members) {
1683
+ return `Expected one of ${members.join(", ")}.`;
1684
+ }
1685
+ function isRuntimePhase(value) {
1686
+ return RUNTIME_PHASES.has(value);
1687
+ }
1688
+ function isProtocolEra(value) {
1689
+ return PROTOCOL_ERAS.has(value);
1690
+ }
1691
+ function isResolvedInstant(value) {
1692
+ return Number.isFinite(Date.parse(value));
1693
+ }
1694
+ //#endregion
1695
+ export { MCP_RUNTIME_ADMISSION_TIMEOUT, MCP_RUNTIME_CAPACITY_EXCEEDED, MCP_RUNTIME_CLEANUP_FAILED, MCP_RUNTIME_CONNECTION_LOST, MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED, MCP_RUNTIME_GENERATION_FENCED, MCP_RUNTIME_GENERATION_RETIRED, MCP_RUNTIME_LEASE_MODE_CONFLICT, MCP_RUNTIME_MANAGER_CLOSED, MCP_RUNTIME_MANAGER_DEFAULTS, MCP_RUNTIME_NOT_READY, MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED, MCP_RUNTIME_OWNERSHIP_DEFAULTS, MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS, MCP_RUNTIME_OWNER_RELEASED, MCP_RUNTIME_PHASES, MCP_RUNTIME_PROTOCOL_ERAS, MCP_RUNTIME_QUARANTINED, MCP_RUNTIME_QUEUE_FULL, MCP_RUNTIME_RETIREMENT_FAILED, MCP_RUNTIME_UPSTREAM_FAILED, McpRuntimeManager, McpRuntimeManagerError, McpRuntimeOwnership, McpRuntimeOwnershipError, mcpRuntimeCapabilitiesSnapshotSchema, mcpRuntimeProbeSnapshotSchema, mcpRuntimeStateSnapshotSchema };
1696
+
1697
+ //# sourceMappingURL=index.mjs.map