@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["packageMetadata.version","#generationResolver","#states","#requestTimeoutMs","#shutdownTimeoutMs","#maxDiscoveryPages","#clientInfo","#observer","#now","#states","#listeners","#now","#maxEntries","#onListenerError","#set","#publish","#reportListenerError","#active","#waiters","#quarantined","#lastGranted","#assertNotQuarantined","#related","#available","#sequence","#capacityError","#draining","#leases","#keepers","#exclusiveIdentities","#admission","#onlineTasks","#offlineTasks","#postOfflineOnlineTasks","#states","#requestTimeoutMs","#maxDiscoveryItems","#now","#assertOpen","#reconnectAfterOfflineBarriers","#deletePostOfflineOnlineTask","#assertSharedLeaseAvailable","#assertNotQuarantined","#getOrCreateOnlineTask","#reconcileOnline","#performSetOffline","#deleteOfflineTask","#withRuntime","#probeProtocolLiveness","#closeTask","#closed","#performClose","#bringOnline","#assertOnlineKeeper","#createExclusiveIdentity","#forgetExclusiveIdentity","#runOperation","#retireGeneration","#maxOwners","#maxGenerations","#maxReferences","#owners","#generations","#nextOwnerSequence","#retain","#release","#pruneReusableFences","#createGeneration","#referenceCount","#startRetirement","#pendingReferenceCount","#performRetain","#replaceRetiredGeneration","#settleRetirementSuccess","#hasFencedOwner","#releaseController","#retainGeneration","#releaseOwner","#retainedGenerations","#retentionTasks","#releaseStarted","#releaseTask"],"sources":["../src/errors.ts","../package.json","../src/runtime-factory.ts","../src/runtime-state.ts","../src/operation-admission.ts","../src/runtime-manager.ts","../src/runtime-ownership.ts","../src/runtime-snapshots.ts"],"sourcesContent":["import {\n\tMCP_CLIENT_LEASE_CAPACITY_EXCEEDED,\n\tMCP_CLIENT_LEASE_INVALIDATED,\n\tMCP_CLIENT_LEASE_MANAGER_CLOSED,\n} from \"@nest-mcp/client\";\n\nexport const MCP_RUNTIME_QUEUE_FULL = \"MCP_QUEUE_FULL\" as const;\nexport const MCP_RUNTIME_ADMISSION_TIMEOUT = \"MCP_ADMISSION_TIMEOUT\" as const;\n\nexport const MCP_RUNTIME_CAPACITY_EXCEEDED = \"MCP_CAPACITY_EXCEEDED\" as const;\nexport const MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED = \"MCP_DISCOVERY_LIMIT_EXCEEDED\" as const;\nexport const MCP_RUNTIME_GENERATION_RETIRED = \"MCP_GENERATION_RETIRED\" as const;\nexport const MCP_RUNTIME_LEASE_MODE_CONFLICT = \"MCP_LEASE_MODE_CONFLICT\" as const;\nexport const MCP_RUNTIME_NOT_READY = \"MCP_NOT_READY\" as const;\nexport const MCP_RUNTIME_QUARANTINED = \"MCP_QUARANTINED\" as const;\nexport const MCP_RUNTIME_MANAGER_CLOSED = \"MCP_RUNTIME_CLOSED\" as const;\nexport const MCP_RUNTIME_UPSTREAM_FAILED = \"MCP_UPSTREAM_FAILED\" as const;\n\nexport const MCP_RUNTIME_CLEANUP_FAILED = \"MCP_CLEANUP_FAILED\" as const;\nexport const MCP_RUNTIME_CONNECTION_LOST = \"MCP_CONNECTION_LOST\" as const;\n\nexport type McpRuntimeManagerErrorCode =\n\t| typeof MCP_RUNTIME_CAPACITY_EXCEEDED\n\t| typeof MCP_RUNTIME_QUEUE_FULL\n\t| typeof MCP_RUNTIME_ADMISSION_TIMEOUT\n\t| typeof MCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED\n\t| typeof MCP_RUNTIME_GENERATION_RETIRED\n\t| typeof MCP_RUNTIME_LEASE_MODE_CONFLICT\n\t| typeof MCP_RUNTIME_NOT_READY\n\t| typeof MCP_RUNTIME_QUARANTINED\n\t| typeof MCP_RUNTIME_MANAGER_CLOSED\n\t| typeof MCP_RUNTIME_UPSTREAM_FAILED;\n\nexport type McpRuntimeStateErrorCode =\n\t| McpRuntimeManagerErrorCode\n\t| typeof MCP_RUNTIME_CLEANUP_FAILED\n\t| typeof MCP_RUNTIME_CONNECTION_LOST\n\t| \"UNKNOWN\";\n\n/** Framework-neutral, key-free failure raised by the managed runtime lifecycle. */\nexport class McpRuntimeManagerError extends Error {\n\treadonly code: McpRuntimeManagerErrorCode;\n\n\tconstructor(code: McpRuntimeManagerErrorCode, message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = \"McpRuntimeManagerError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport function mapMcpRuntimeManagerError(error: unknown): unknown {\n\tif (error instanceof McpRuntimeManagerError) return error;\n\tif (error instanceof McpRuntimeGenerationResolutionError) return error.cause;\n\tconst code = safeErrorCode(error);\n\tif (code === MCP_CLIENT_LEASE_CAPACITY_EXCEEDED) {\n\t\treturn new McpRuntimeManagerError(\n\t\t\tMCP_RUNTIME_CAPACITY_EXCEEDED,\n\t\t\t\"The MCP runtime manager is at its connection capacity.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (code === MCP_CLIENT_LEASE_INVALIDATED) {\n\t\treturn new McpRuntimeGenerationRetiredError(error);\n\t}\n\tif (code === MCP_CLIENT_LEASE_MANAGER_CLOSED) return runtimeManagerClosedError(error);\n\treturn new McpRuntimeManagerError(\n\t\tMCP_RUNTIME_UPSTREAM_FAILED,\n\t\t\"The upstream MCP operation failed.\",\n\t\t{ cause: error },\n\t);\n}\n\nexport function runtimeManagerErrorCode(error: unknown): McpRuntimeStateErrorCode {\n\tif (error instanceof McpRuntimeManagerError) return error.code;\n\tif (error instanceof McpRuntimeGenerationResolutionError) {\n\t\treturn runtimeManagerErrorCode(error.cause);\n\t}\n\tconst code = safeErrorCode(error);\n\tif (isRuntimeStateErrorCode(code)) return code;\n\tif (code === MCP_CLIENT_LEASE_CAPACITY_EXCEEDED) return MCP_RUNTIME_CAPACITY_EXCEEDED;\n\tif (code === MCP_CLIENT_LEASE_INVALIDATED) return MCP_RUNTIME_GENERATION_RETIRED;\n\tif (code === MCP_CLIENT_LEASE_MANAGER_CLOSED) return MCP_RUNTIME_MANAGER_CLOSED;\n\treturn \"UNKNOWN\";\n}\n\nexport function runtimeManagerClosedError(cause?: unknown): McpRuntimeManagerError {\n\treturn new McpRuntimeManagerError(\n\t\tMCP_RUNTIME_MANAGER_CLOSED,\n\t\t\"The MCP runtime manager is closed.\",\n\t\tcause === undefined ? undefined : { cause },\n\t);\n}\n\nexport function runtimeQuarantinedError(cause?: unknown): McpRuntimeManagerError {\n\treturn new McpRuntimeManagerError(\n\t\tMCP_RUNTIME_QUARANTINED,\n\t\t\"The MCP runtime generation is quarantined after uncertain cleanup.\",\n\t\tcause === undefined ? undefined : { cause },\n\t);\n}\n\nexport function runtimeNotReadyError(): McpRuntimeManagerError {\n\treturn new McpRuntimeManagerError(\n\t\tMCP_RUNTIME_NOT_READY,\n\t\t\"The MCP connection does not have an active connected runtime generation.\",\n\t);\n}\n\nexport function runtimeLeaseModeConflictError(): McpRuntimeManagerError {\n\treturn new McpRuntimeManagerError(\n\t\tMCP_RUNTIME_LEASE_MODE_CONFLICT,\n\t\t\"The MCP runtime generation already has work using a conflicting lease mode.\",\n\t);\n}\n\nexport class McpRuntimeGenerationResolutionError extends Error {\n\toverride readonly cause: unknown;\n\n\tconstructor(cause: unknown) {\n\t\tsuper(\"The MCP runtime generation could not be resolved.\", { cause });\n\t\tthis.name = \"McpRuntimeGenerationResolutionError\";\n\t\tthis.cause = cause;\n\t}\n}\n\nclass McpRuntimeGenerationRetiredError extends McpRuntimeManagerError {\n\tconstructor(cause: unknown) {\n\t\tsuper(\n\t\t\tMCP_RUNTIME_GENERATION_RETIRED,\n\t\t\t\"The MCP runtime generation was retired before the operation completed.\",\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\nfunction safeErrorCode(error: unknown): string {\n\tif (typeof error !== \"object\" || error === null) return \"UNKNOWN\";\n\ttry {\n\t\tconst code = Reflect.get(error, \"code\");\n\t\treturn typeof code === \"string\" ? code : \"UNKNOWN\";\n\t} catch {\n\t\treturn \"UNKNOWN\";\n\t}\n}\n\nexport function isRuntimeStateErrorCode(code: string): code is McpRuntimeStateErrorCode {\n\treturn RUNTIME_STATE_ERROR_CODES.has(code);\n}\n\nconst RUNTIME_STATE_ERROR_CODES: ReadonlySet<string> = new Set([\n\tMCP_RUNTIME_CAPACITY_EXCEEDED,\n\tMCP_RUNTIME_QUEUE_FULL,\n\tMCP_RUNTIME_ADMISSION_TIMEOUT,\n\tMCP_RUNTIME_CLEANUP_FAILED,\n\tMCP_RUNTIME_CONNECTION_LOST,\n\tMCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED,\n\tMCP_RUNTIME_GENERATION_RETIRED,\n\tMCP_RUNTIME_LEASE_MODE_CONFLICT,\n\tMCP_RUNTIME_MANAGER_CLOSED,\n\tMCP_RUNTIME_NOT_READY,\n\tMCP_RUNTIME_QUARANTINED,\n\tMCP_RUNTIME_UPSTREAM_FAILED,\n\t\"UNKNOWN\",\n]);\n","","import { randomUUID } from \"node:crypto\";\n\nimport {\n\tMcpClientRuntime,\n\ttype McpClientLeaseFactoryContext,\n\ttype McpClientRuntimeOptions,\n} from \"@nest-mcp/client\";\nimport type { McpLifecycleObserver } from \"@nest-mcp/core\";\n\nimport {\n\tMCP_RUNTIME_CLEANUP_FAILED,\n\tMcpRuntimeGenerationResolutionError,\n\truntimeManagerErrorCode,\n} from \"./errors.ts\";\nimport type { RuntimeStateStore } from \"./runtime-state.ts\";\nimport type { McpAdmittedRuntimeGeneration, McpRuntimeGenerationResolver } from \"./types.ts\";\nimport packageMetadata from \"../package.json\" with { type: \"json\" };\n\ninterface OwnedMcpRuntimeBase<GenerationKey> {\n\treadonly generationKey: GenerationKey;\n\treadonly generationSignal: AbortSignal;\n\treadonly admitted: McpAdmittedRuntimeGeneration;\n}\n\nexport interface ActiveMcpRuntime<GenerationKey> extends OwnedMcpRuntimeBase<GenerationKey> {\n\treadonly runtime: McpClientRuntime;\n\treadonly serverName: string;\n\treadonly quarantined: false;\n}\n\nexport interface QuarantinedMcpRuntime<GenerationKey> extends OwnedMcpRuntimeBase<GenerationKey> {\n\treadonly runtime?: McpClientRuntime;\n\treadonly serverName?: string;\n\treadonly quarantined: true;\n}\n\nexport type OwnedMcpRuntime<GenerationKey> =\n\tActiveMcpRuntime<GenerationKey> | QuarantinedMcpRuntime<GenerationKey>;\n\ninterface ManagedRuntimeFactoryOptions<GenerationKey> {\n\treadonly generationResolver: McpRuntimeGenerationResolver<GenerationKey>;\n\treadonly states: RuntimeStateStore<GenerationKey>;\n\treadonly requestTimeoutMs: number;\n\treadonly shutdownTimeoutMs: number;\n\treadonly maxDiscoveryPages: number;\n\treadonly clientInfo?: NonNullable<McpClientRuntimeOptions[\"clientInfo\"]>;\n\treadonly observer?: McpLifecycleObserver;\n\treadonly now: () => number;\n}\n\nconst DEFAULT_CLIENT_INFO = Object.freeze({\n\tname: \"@nest-mcp/manager\",\n\tversion: packageMetadata.version,\n});\n\nexport class ManagedRuntimeFactory<GenerationKey> {\n\treadonly #generationResolver: McpRuntimeGenerationResolver<GenerationKey>;\n\treadonly #states: RuntimeStateStore<GenerationKey>;\n\treadonly #requestTimeoutMs: number;\n\treadonly #shutdownTimeoutMs: number;\n\treadonly #maxDiscoveryPages: number;\n\treadonly #clientInfo: NonNullable<McpClientRuntimeOptions[\"clientInfo\"]>;\n\treadonly #observer: McpLifecycleObserver | undefined;\n\treadonly #now: () => number;\n\n\tconstructor(options: ManagedRuntimeFactoryOptions<GenerationKey>) {\n\t\tthis.#generationResolver = options.generationResolver;\n\t\tthis.#states = options.states;\n\t\tthis.#requestTimeoutMs = options.requestTimeoutMs;\n\t\tthis.#shutdownTimeoutMs = options.shutdownTimeoutMs;\n\t\tthis.#maxDiscoveryPages = options.maxDiscoveryPages;\n\t\tthis.#clientInfo = options.clientInfo ?? DEFAULT_CLIENT_INFO;\n\t\tthis.#observer = options.observer;\n\t\tthis.#now = options.now;\n\t}\n\n\tasync create(\n\t\tgenerationKey: GenerationKey,\n\t\tcontext: McpClientLeaseFactoryContext,\n\t): Promise<OwnedMcpRuntime<GenerationKey>> {\n\t\tthis.#states.transition(generationKey, \"connecting\");\n\t\tlet admitted: McpAdmittedRuntimeGeneration;\n\t\ttry {\n\t\t\tadmitted = withSharedClose(\n\t\t\t\tawait this.#generationResolver.resolve(generationKey, context.signal),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.#states.transition(generationKey, \"failed\", runtimeManagerErrorCode(error));\n\t\t\tthrow new McpRuntimeGenerationResolutionError(error);\n\t\t}\n\t\tlet serverName: string | undefined;\n\t\tlet runtime: McpClientRuntime | undefined;\n\t\ttry {\n\t\t\tserverName = `managed-${randomUUID()}`;\n\t\t\truntime = new McpClientRuntime({\n\t\t\t\tclientInfo: this.#clientInfo,\n\t\t\t\tservers: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: serverName,\n\t\t\t\t\t\ttransport: admitted.transport,\n\t\t\t\t\t\tclientOptions: {\n\t\t\t\t\t\t\tlistMaxPages: this.#maxDiscoveryPages,\n\t\t\t\t\t\t\tversionNegotiation: { mode: \"auto\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tshutdownTimeoutMs: this.#shutdownTimeoutMs,\n\t\t\t\tnow: this.#now,\n\t\t\t\t...(this.#observer === undefined ? {} : { observer: this.#observer }),\n\t\t\t});\n\t\t\tawait runtime.connect(serverName, {\n\t\t\t\tsignal: AbortSignal.any([context.signal, AbortSignal.timeout(this.#requestTimeoutMs)]),\n\t\t\t});\n\t\t\tconst snapshot = this.#states.connected(generationKey, runtime.snapshot(serverName));\n\t\t\tawait admitted.onConnected?.(snapshot, context.signal);\n\t\t\tcontext.signal.throwIfAborted();\n\t\t\treturn Object.freeze({\n\t\t\t\tgenerationKey,\n\t\t\t\tgenerationSignal: context.signal,\n\t\t\t\truntime,\n\t\t\t\tserverName,\n\t\t\t\tadmitted,\n\t\t\t\tquarantined: false,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#states.transition(generationKey, \"failed\", runtimeManagerErrorCode(error));\n\t\t\ttry {\n\t\t\t\tawait closeRuntimeThenMaterial(runtime, admitted, this.#shutdownTimeoutMs);\n\t\t\t} catch {\n\t\t\t\tthis.#states.transition(generationKey, \"quarantined\", MCP_RUNTIME_CLEANUP_FAILED);\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tgenerationKey,\n\t\t\t\t\tgenerationSignal: context.signal,\n\t\t\t\t\tadmitted,\n\t\t\t\t\t...(runtime === undefined ? {} : { runtime }),\n\t\t\t\t\t...(serverName === undefined ? {} : { serverName }),\n\t\t\t\t\tquarantined: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync close(owned: OwnedMcpRuntime<GenerationKey>): Promise<void> {\n\t\tthis.#states.transition(owned.generationKey, \"draining\");\n\t\ttry {\n\t\t\tawait closeRuntimeThenMaterial(owned.runtime, owned.admitted, this.#shutdownTimeoutMs);\n\t\t} catch (error) {\n\t\t\tthis.#states.transition(owned.generationKey, \"quarantined\", MCP_RUNTIME_CLEANUP_FAILED);\n\t\t\tthrow error;\n\t\t}\n\t\tthis.#states.transition(owned.generationKey, \"offline\");\n\t}\n}\n\nfunction withSharedClose(admitted: McpAdmittedRuntimeGeneration): McpAdmittedRuntimeGeneration {\n\tlet closeTask: Promise<void> | undefined;\n\treturn Object.freeze({\n\t\ttransport: admitted.transport,\n\t\t...(admitted.onConnected === undefined\n\t\t\t? {}\n\t\t\t: { onConnected: admitted.onConnected.bind(admitted) }),\n\t\tclose(): Promise<void> {\n\t\t\tcloseTask ??= Promise.resolve().then(() => admitted.close());\n\t\t\treturn closeTask;\n\t\t},\n\t});\n}\n\nasync function closeRuntimeThenMaterial(\n\truntime: McpClientRuntime | undefined,\n\tadmitted: McpAdmittedRuntimeGeneration,\n\tshutdownTimeoutMs: number,\n): Promise<void> {\n\tconst failures: unknown[] = [];\n\tif (runtime !== undefined) {\n\t\ttry {\n\t\t\tawait runtime.close();\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t}\n\ttry {\n\t\tawait withCleanupTimeout(admitted.close(), shutdownTimeoutMs);\n\t} catch (error) {\n\t\tfailures.push(error);\n\t}\n\tif (failures.length > 0) {\n\t\tthrow new AggregateError(failures, \"An MCP runtime generation could not be closed.\");\n\t}\n}\n\nfunction withCleanupTimeout(task: Promise<void>, timeoutMs: number): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(new Error(\"The admitted MCP runtime material did not close before its deadline.\"));\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\t\tvoid task.then(\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n","import type { McpClientConnectionSnapshot } from \"@nest-mcp/client\";\n\nimport type { McpRuntimeStateErrorCode } from \"./errors.ts\";\nimport type {\n\tMcpRuntimePhase,\n\tMcpRuntimeStateListener,\n\tMcpRuntimeStateSnapshot,\n\tMcpRuntimeStateTransitionEvent,\n} from \"./types.ts\";\n\ninterface RuntimeStateStoreOptions {\n\treadonly now: () => number;\n\treadonly maxEntries: number;\n\treadonly onListenerError?: (\n\t\terror: unknown,\n\t\tevent: McpRuntimeStateTransitionEvent,\n\t) => void | PromiseLike<void>;\n}\n\nexport class RuntimeStateStore<GenerationKey> {\n\treadonly #states = new Map<GenerationKey, McpRuntimeStateSnapshot>();\n\treadonly #listeners = new Set<McpRuntimeStateListener>();\n\treadonly #now: () => number;\n\treadonly #maxEntries: number;\n\treadonly #onListenerError:\n\t\t| ((error: unknown, event: McpRuntimeStateTransitionEvent) => void | PromiseLike<void>)\n\t\t| undefined;\n\n\tconstructor(options: RuntimeStateStoreOptions) {\n\t\tthis.#now = options.now;\n\t\tthis.#maxEntries = options.maxEntries;\n\t\tthis.#onListenerError = options.onListenerError;\n\t}\n\n\tget size(): number {\n\t\treturn this.#states.size;\n\t}\n\n\tread(generationKey: GenerationKey): McpRuntimeStateSnapshot {\n\t\tconst current = this.#states.get(generationKey);\n\t\tif (current !== undefined) return current;\n\t\treturn offlineState(readTimestamp(this.#now));\n\t}\n\n\ttransition(\n\t\tgenerationKey: GenerationKey,\n\t\tphase: McpRuntimePhase,\n\t\terrorCode?: McpRuntimeStateErrorCode,\n\t): McpRuntimeStateSnapshot {\n\t\tconst previous = this.#states.get(generationKey);\n\t\tif (previous?.phase === \"quarantined\") return previous;\n\t\tconst timestamp = readTimestamp(this.#now);\n\t\tconst lastTransitionAt =\n\t\t\tprevious?.phase === phase && previous.errorCode === errorCode\n\t\t\t\t? previous.lastTransitionAt\n\t\t\t\t: new Date(timestamp).toISOString();\n\t\tconst { errorCode: previousError, ...previousWithoutError } = previous ?? {};\n\t\tvoid previousError;\n\t\tconst retainConnectionMetadata = phase === \"degraded\" || phase === \"draining\";\n\t\tconst state: McpRuntimeStateSnapshot = Object.freeze({\n\t\t\t...(retainConnectionMetadata ? previousWithoutError : {}),\n\t\t\tphase,\n\t\t\tlastTransitionAt,\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t});\n\t\tthis.#set(generationKey, state);\n\t\tthis.#publish(previous, state, timestamp);\n\t\treturn state;\n\t}\n\n\tconnected(\n\t\tgenerationKey: GenerationKey,\n\t\tsnapshot: McpClientConnectionSnapshot,\n\t): McpRuntimeStateSnapshot {\n\t\tconst capabilities = snapshot.serverCapabilities;\n\t\tconst previous = this.#states.get(generationKey);\n\t\tif (previous?.phase === \"quarantined\") return previous;\n\t\tconst timestamp = readTimestamp(this.#now);\n\t\tconst state: McpRuntimeStateSnapshot = Object.freeze({\n\t\t\tphase: \"online\",\n\t\t\tlastTransitionAt:\n\t\t\t\tprevious?.phase === \"online\"\n\t\t\t\t\t? previous.lastTransitionAt\n\t\t\t\t\t: new Date(timestamp).toISOString(),\n\t\t\t...(snapshot.negotiatedProtocolVersion === undefined\n\t\t\t\t? {}\n\t\t\t\t: { protocolVersion: snapshot.negotiatedProtocolVersion }),\n\t\t\t...(snapshot.protocolEra === undefined ? {} : { protocolEra: snapshot.protocolEra }),\n\t\t\t...(snapshot.connectedAt === undefined\n\t\t\t\t? {}\n\t\t\t\t: { connectedAt: new Date(snapshot.connectedAt).toISOString() }),\n\t\t\t...(capabilities === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tcapabilities: Object.freeze({\n\t\t\t\t\t\t\ttools: capabilities.tools !== undefined,\n\t\t\t\t\t\t\tresources: capabilities.resources !== undefined,\n\t\t\t\t\t\t\tprompts: capabilities.prompts !== undefined,\n\t\t\t\t\t\t\tcompletion: capabilities.completions !== undefined,\n\t\t\t\t\t\t\tsubscriptions: capabilities.resources?.subscribe === true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t});\n\t\tthis.#set(generationKey, state);\n\t\tthis.#publish(previous, state, timestamp);\n\t\treturn state;\n\t}\n\n\tforget(generationKey: GenerationKey): void {\n\t\tthis.#states.delete(generationKey);\n\t}\n\n\t#set(generationKey: GenerationKey, state: McpRuntimeStateSnapshot): void {\n\t\tif (this.#states.delete(generationKey)) {\n\t\t\tthis.#states.set(generationKey, state);\n\t\t\treturn;\n\t\t}\n\t\tif (this.#states.size >= this.#maxEntries) {\n\t\t\tfor (const [candidateKey, candidate] of this.#states) {\n\t\t\t\tif (candidate.phase !== \"offline\" && candidate.phase !== \"failed\") continue;\n\t\t\t\tthis.#states.delete(candidateKey);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (this.#states.size >= this.#maxEntries) return;\n\t\t}\n\t\tthis.#states.set(generationKey, state);\n\t}\n\n\tsubscribe(listener: McpRuntimeStateListener): () => void {\n\t\tif (typeof listener !== \"function\") {\n\t\t\tthrow new TypeError(\"MCP runtime state listener must be a function.\");\n\t\t}\n\t\tthis.#listeners.add(listener);\n\t\tlet subscribed = true;\n\t\treturn () => {\n\t\t\tif (!subscribed) return;\n\t\t\tsubscribed = false;\n\t\t\tthis.#listeners.delete(listener);\n\t\t};\n\t}\n\n\t#publish(\n\t\tprevious: McpRuntimeStateSnapshot | undefined,\n\t\tcurrent: McpRuntimeStateSnapshot,\n\t\ttimestamp: number,\n\t): void {\n\t\tif (previous?.phase === current.phase && previous.errorCode === current.errorCode) return;\n\t\tconst event: McpRuntimeStateTransitionEvent = Object.freeze({\n\t\t\ttype: \"runtime.state.changed\",\n\t\t\ttimestamp,\n\t\t\t...(previous === undefined\n\t\t\t\t? { previousPhase: \"offline\" as const }\n\t\t\t\t: { previousPhase: previous.phase }),\n\t\t\tphase: current.phase,\n\t\t\t...(current.errorCode === undefined ? {} : { errorCode: current.errorCode }),\n\t\t\t...(current.protocolEra === undefined ? {} : { protocolEra: current.protocolEra }),\n\t\t\t...(current.capabilities === undefined ? {} : { capabilities: current.capabilities }),\n\t\t});\n\t\tfor (const listener of Array.from(this.#listeners)) {\n\t\t\ttry {\n\t\t\t\tconst result = listener(event);\n\t\t\t\tif (isPromiseLike(result)) {\n\t\t\t\t\tvoid Promise.resolve(result).catch((error: unknown) => {\n\t\t\t\t\t\tthis.#reportListenerError(error, event);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.#reportListenerError(error, event);\n\t\t\t}\n\t\t}\n\t}\n\n\t#reportListenerError(error: unknown, event: McpRuntimeStateTransitionEvent): void {\n\t\tif (this.#onListenerError === undefined) return;\n\t\ttry {\n\t\t\tconst result = this.#onListenerError(error, event);\n\t\t\tif (isPromiseLike(result)) void Promise.resolve(result).catch(() => undefined);\n\t\t} catch {\n\t\t\t// Diagnostics must not replace the runtime lifecycle result.\n\t\t}\n\t}\n}\n\nfunction offlineState(timestamp: number): McpRuntimeStateSnapshot {\n\treturn Object.freeze({\n\t\tphase: \"offline\",\n\t\tlastTransitionAt: new Date(timestamp).toISOString(),\n\t});\n}\n\nfunction readTimestamp(now: () => number): number {\n\ttry {\n\t\tconst timestamp = now();\n\t\tif (Number.isFinite(timestamp)) {\n\t\t\tnew Date(timestamp).toISOString();\n\t\t\treturn timestamp;\n\t\t}\n\t} catch {\n\t\t// The fallback keeps lifecycle state available even when an injected clock fails.\n\t}\n\treturn Date.now();\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"then\" in value &&\n\t\ttypeof value.then === \"function\"\n\t);\n}\n","import {\n\tMCP_RUNTIME_CAPACITY_EXCEEDED,\n\tMCP_RUNTIME_QUEUE_FULL,\n\tMcpRuntimeManagerError,\n\truntimeLeaseModeConflictError,\n\truntimeQuarantinedError,\n} from \"./errors.ts\";\nimport type { McpRuntimeOperationLeaseMode } from \"./types.ts\";\n\ninterface Admission<GenerationKey> {\n\treadonly generationKey: GenerationKey;\n\treadonly key: string | undefined;\n\treadonly mode: McpRuntimeOperationLeaseMode;\n\treadonly limit: number | null;\n}\n\ninterface Waiter<GenerationKey> {\n\treadonly admission: Admission<GenerationKey>;\n\treserve(): boolean;\n\tgrant(): void;\n\treject(error: unknown): void;\n}\n\n/** Atomic process-local admission; transports and their cleanup remain owned by the manager. */\nexport class OperationAdmission<GenerationKey> {\n\treadonly #active = new Set<Admission<GenerationKey>>();\n\treadonly #waiters = new Set<Waiter<GenerationKey>>();\n\treadonly #quarantined = new Set<Admission<GenerationKey>>();\n\treadonly #lastGranted = new Map<string | GenerationKey, number>();\n\t#sequence = 0;\n\t#draining = false;\n\n\tconstructor(\n\t\treadonly maxOperations: number,\n\t\treadonly maxConcurrentOperations: number | null,\n\t) {}\n\n\tget size(): number {\n\t\treturn this.#waiters.size;\n\t}\n\n\thasIsolatedGeneration(generationKey: GenerationKey): boolean {\n\t\treturn [...this.#active].some(\n\t\t\t(active) => active.generationKey === generationKey && active.mode !== \"shared\",\n\t\t);\n\t}\n\n\tasync enter(\n\t\tgenerationKey: GenerationKey,\n\t\tmode: McpRuntimeOperationLeaseMode,\n\t\tkey: string | undefined,\n\t\tqueue: boolean,\n\t\tsignal: AbortSignal,\n\t\tlimit: number | null | undefined,\n\t\treserve: () => boolean,\n\t): Promise<(quarantine: boolean) => void> {\n\t\tconst admission = {\n\t\t\tgenerationKey,\n\t\t\tmode,\n\t\t\tkey,\n\t\t\tlimit: limit === undefined ? this.maxConcurrentOperations : limit,\n\t\t};\n\t\tsignal.throwIfAborted();\n\t\tthis.#assertNotQuarantined(admission);\n\t\tconst conflicts = [...this.#active].filter((active) => this.#related(active, admission));\n\t\t// Retained/shared runtimes never participate in isolated admission waiting.\n\t\tif (conflicts.some((active) => active.mode === \"shared\" && mode !== \"shared\")) {\n\t\t\tthrow runtimeLeaseModeConflictError();\n\t\t}\n\t\tif (queue) this.drain();\n\t\tif (this.#available(admission) && reserve()) {\n\t\t\tthis.#active.add(admission);\n\t\t\tthis.#lastGranted.set(key ?? generationKey, this.#sequence++);\n\t\t} else if (queue) {\n\t\t\tif (this.#waiters.size >= this.maxOperations)\n\t\t\t\tthrow new McpRuntimeManagerError(\n\t\t\t\t\tMCP_RUNTIME_QUEUE_FULL,\n\t\t\t\t\t\"The MCP operation admission queue is full.\",\n\t\t\t\t);\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tconst remove = (): void => {\n\t\t\t\t\tthis.#waiters.delete(waiter);\n\t\t\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t\t\t};\n\t\t\t\tconst waiter: Waiter<GenerationKey> = {\n\t\t\t\t\tadmission,\n\t\t\t\t\treserve,\n\t\t\t\t\tgrant: () => {\n\t\t\t\t\t\tremove();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t\treject: (error) => {\n\t\t\t\t\t\tremove();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst abort = (): void => {\n\t\t\t\t\twaiter.reject(signal.reason);\n\t\t\t\t\tthis.drain();\n\t\t\t\t};\n\t\t\t\tthis.#waiters.add(waiter);\n\t\t\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\t\t\tif (signal.aborted) abort();\n\t\t\t\telse this.drain();\n\t\t\t});\n\t\t} else {\n\t\t\tthrow this.#available(admission) || mode === \"concurrent\"\n\t\t\t\t? this.#capacityError()\n\t\t\t\t: runtimeLeaseModeConflictError();\n\t\t}\n\t\tlet released = false;\n\t\treturn (quarantine) => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (quarantine) this.#quarantined.add(admission);\n\t\t\tthis.#active.delete(admission);\n\t\t\tthis.drain();\n\t\t};\n\t}\n\n\trejectGeneration(generationKey: GenerationKey, reason: unknown): void {\n\t\tfor (const waiter of this.#waiters) {\n\t\t\tif (waiter.admission.generationKey === generationKey) waiter.reject(reason);\n\t\t}\n\t\tthis.drain();\n\t}\n\n\trejectAll(reason: unknown): void {\n\t\tfor (const waiter of this.#waiters) waiter.reject(reason);\n\t}\n\n\t#related(left: Admission<GenerationKey>, right: Admission<GenerationKey>): boolean {\n\t\treturn (\n\t\t\tleft.generationKey === right.generationKey ||\n\t\t\t(left.key !== undefined && left.key === right.key)\n\t\t);\n\t}\n\n\t#available(admission: Admission<GenerationKey>, pending?: Waiter<GenerationKey>): boolean {\n\t\tfor (const waiter of this.#waiters) {\n\t\t\tif (waiter === pending) break;\n\t\t\tif (this.#related(waiter.admission, admission)) return false;\n\t\t}\n\t\tlet count = 0;\n\t\tlet ceiling = admission.limit ?? Number.POSITIVE_INFINITY;\n\t\tfor (const active of this.#active) {\n\t\t\tif (!this.#related(active, admission)) continue;\n\t\t\tif (active.mode === \"shared\" && admission.mode === \"shared\") continue;\n\t\t\tif (\n\t\t\t\tactive.mode !== \"concurrent\" ||\n\t\t\t\tadmission.mode !== \"concurrent\" ||\n\t\t\t\tactive.key !== admission.key\n\t\t\t)\n\t\t\t\treturn false;\n\t\t\tcount += 1;\n\t\t\tceiling = Math.min(ceiling, active.limit ?? Number.POSITIVE_INFINITY);\n\t\t}\n\t\treturn count < ceiling;\n\t}\n\n\t#assertNotQuarantined(admission: Admission<GenerationKey>): void {\n\t\tfor (const failed of this.#quarantined) {\n\t\t\tif (this.#related(failed, admission)) throw runtimeQuarantinedError();\n\t\t}\n\t}\n\n\t/** Woken only when connector admission or the authoritative transport ledger changes. */\n\tdrain(): void {\n\t\tif (this.#draining) return;\n\t\tthis.#draining = true;\n\t\ttry {\n\t\t\twhile (this.#waiters.size > 0) {\n\t\t\t\tconst keys = [\n\t\t\t\t\t...new Set(\n\t\t\t\t\t\t[...this.#waiters].map(({ admission }) => admission.key ?? admission.generationKey),\n\t\t\t\t\t),\n\t\t\t\t];\n\t\t\t\tconst ordered = keys.toSorted(\n\t\t\t\t\t(left, right) =>\n\t\t\t\t\t\t(this.#lastGranted.get(left) ?? -1) - (this.#lastGranted.get(right) ?? -1),\n\t\t\t\t);\n\t\t\t\tlet granted = false;\n\t\t\t\tfor (const key of ordered) {\n\t\t\t\t\tconst waiter = [...this.#waiters].find(\n\t\t\t\t\t\t({ admission }) => (admission.key ?? admission.generationKey) === key,\n\t\t\t\t\t);\n\t\t\t\t\tif (waiter === undefined) continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#assertNotQuarantined(waiter.admission);\n\t\t\t\t\t\tif (!this.#available(waiter.admission, waiter) || !waiter.reserve()) continue;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\twaiter.reject(error);\n\t\t\t\t\t\tgranted = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t// Reservation charges the transport ledger synchronously, before resuming the caller.\n\t\t\t\t\tthis.#active.add(waiter.admission);\n\t\t\t\t\tthis.#lastGranted.set(key, this.#sequence++);\n\t\t\t\t\twaiter.grant();\n\t\t\t\t\tgranted = true;\n\t\t\t\t}\n\t\t\t\tif (!granted) break;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#draining = false;\n\t\t\tconst retained = new Set(\n\t\t\t\t[...this.#active, ...[...this.#waiters].map(({ admission }) => admission)].map(\n\t\t\t\t\t(admission) => admission.key ?? admission.generationKey,\n\t\t\t\t),\n\t\t\t);\n\t\t\tfor (const key of this.#lastGranted.keys())\n\t\t\t\tif (!retained.has(key)) this.#lastGranted.delete(key);\n\t\t}\n\t}\n\n\t#capacityError(): McpRuntimeManagerError {\n\t\treturn new McpRuntimeManagerError(\n\t\t\tMCP_RUNTIME_CAPACITY_EXCEEDED,\n\t\t\t\"The MCP runtime manager has no compatible operation capacity.\",\n\t\t);\n\t}\n}\n","import { AsyncResource } from \"node:async_hooks\";\nimport {\n\tMCP_CLIENT_LEASE_INVALIDATED,\n\tMcpClientLeaseManager,\n\ttype CallToolResult,\n\ttype GetPromptResult,\n\ttype McpClientConnectionSnapshot,\n\ttype McpClientLease,\n\ttype ReadResourceResult,\n} from \"@nest-mcp/client\";\nimport { METHOD_NOT_FOUND, ProtocolError } from \"@modelcontextprotocol/client\";\n\nimport {\n\tMCP_RUNTIME_ADMISSION_TIMEOUT,\n\tMCP_RUNTIME_QUEUE_FULL,\n\tMCP_RUNTIME_CLEANUP_FAILED,\n\tMCP_RUNTIME_CONNECTION_LOST,\n\tMCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED,\n\tMCP_RUNTIME_GENERATION_RETIRED,\n\tMcpRuntimeManagerError,\n\tmapMcpRuntimeManagerError,\n\truntimeLeaseModeConflictError,\n\truntimeManagerClosedError,\n\truntimeManagerErrorCode,\n\truntimeNotReadyError,\n\truntimeQuarantinedError,\n} from \"./errors.ts\";\nimport {\n\tManagedRuntimeFactory,\n\ttype ActiveMcpRuntime,\n\ttype OwnedMcpRuntime,\n} from \"./runtime-factory.ts\";\nimport { RuntimeStateStore } from \"./runtime-state.ts\";\nimport { OperationAdmission } from \"./operation-admission.ts\";\nimport type {\n\tMcpRuntimeAdmissionEvent,\n\tMcpRuntimeCatalogSnapshot,\n\tMcpManagedClientRuntimeOperation,\n\tMcpRuntimeManagerOptions,\n\tMcpRuntimeManagerPort,\n\tMcpRuntimeManagerSnapshot,\n\tMcpRuntimeOperationOptions,\n\tMcpRuntimeProbeSnapshot,\n\tMcpRuntimeStateListener,\n\tMcpRuntimeStateSnapshot,\n\tMcpRuntimeToolCallOptions,\n} from \"./types.ts\";\n\nclass ExclusiveRuntimeLeaseIdentity<GenerationKey> {\n\tconstructor(readonly generationKey: GenerationKey) {}\n}\n\ntype RuntimeLeaseIdentity<GenerationKey> =\n\tGenerationKey | ExclusiveRuntimeLeaseIdentity<GenerationKey>;\n\nexport const MCP_RUNTIME_MANAGER_DEFAULTS = Object.freeze({\n\tmaxConnections: 100,\n\tmaxQueuedOperations: 100,\n\tmaxConcurrentOperationsPerAdmissionKey: 4,\n\tmaxStateEntries: 1_000,\n\trequestTimeoutMs: 10_000,\n\tshutdownTimeoutMs: 30_000,\n\tmaxDiscoveryPages: 16,\n\tmaxDiscoveryItems: 1_000,\n});\n\nexport class McpRuntimeManager<GenerationKey = string>\n\timplements McpRuntimeManagerPort<GenerationKey>, AsyncDisposable\n{\n\treadonly #leases: McpClientLeaseManager<\n\t\tRuntimeLeaseIdentity<GenerationKey>,\n\t\tOwnedMcpRuntime<GenerationKey>\n\t>;\n\treadonly #keepers = new Map<GenerationKey, McpClientLease<OwnedMcpRuntime<GenerationKey>>>();\n\treadonly #exclusiveIdentities = new Map<\n\t\tGenerationKey,\n\t\tSet<ExclusiveRuntimeLeaseIdentity<GenerationKey>>\n\t>();\n\treadonly #admission: OperationAdmission<GenerationKey>;\n\treadonly #onlineTasks = new Map<GenerationKey, Promise<McpRuntimeStateSnapshot>>();\n\treadonly #offlineTasks = new Map<GenerationKey, Promise<McpRuntimeStateSnapshot>>();\n\treadonly #postOfflineOnlineTasks = new Map<GenerationKey, Promise<McpRuntimeStateSnapshot>>();\n\treadonly #states: RuntimeStateStore<GenerationKey>;\n\treadonly #requestTimeoutMs: number;\n\treadonly #maxDiscoveryItems: number;\n\treadonly #now: () => number;\n\t#closed = false;\n\t#closeTask: Promise<void> | undefined;\n\n\tconstructor(options: McpRuntimeManagerOptions<GenerationKey>) {\n\t\tif (\n\t\t\ttypeof options?.generationResolver !== \"object\" ||\n\t\t\toptions.generationResolver === null ||\n\t\t\ttypeof options.generationResolver.resolve !== \"function\"\n\t\t) {\n\t\t\tthrow new TypeError(\"generationResolver.resolve must be a function.\");\n\t\t}\n\t\tconst maxConnections = positiveInteger(\n\t\t\toptions.maxConnections ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxConnections,\n\t\t\t\"maxConnections\",\n\t\t);\n\t\tthis.#admission = new OperationAdmission(\n\t\t\tpositiveInteger(\n\t\t\t\toptions.maxQueuedOperations ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxQueuedOperations,\n\t\t\t\t\"maxQueuedOperations\",\n\t\t\t),\n\t\t\toptions.maxConcurrentOperationsPerAdmissionKey === null\n\t\t\t\t? null\n\t\t\t\t: positiveInteger(\n\t\t\t\t\t\toptions.maxConcurrentOperationsPerAdmissionKey ??\n\t\t\t\t\t\t\tMCP_RUNTIME_MANAGER_DEFAULTS.maxConcurrentOperationsPerAdmissionKey,\n\t\t\t\t\t\t\"maxConcurrentOperationsPerAdmissionKey\",\n\t\t\t\t\t),\n\t\t);\n\t\tconst maxStateEntries = positiveInteger(\n\t\t\toptions.maxStateEntries ??\n\t\t\t\tMath.max(MCP_RUNTIME_MANAGER_DEFAULTS.maxStateEntries, maxConnections),\n\t\t\t\"maxStateEntries\",\n\t\t);\n\t\tif (maxStateEntries < maxConnections) {\n\t\t\tthrow new RangeError(\"maxStateEntries must be greater than or equal to maxConnections.\");\n\t\t}\n\t\tthis.#requestTimeoutMs = positiveFinite(\n\t\t\toptions.requestTimeoutMs ?? MCP_RUNTIME_MANAGER_DEFAULTS.requestTimeoutMs,\n\t\t\t\"requestTimeoutMs\",\n\t\t);\n\t\tconst shutdownTimeoutMs = positiveFinite(\n\t\t\toptions.shutdownTimeoutMs ?? MCP_RUNTIME_MANAGER_DEFAULTS.shutdownTimeoutMs,\n\t\t\t\"shutdownTimeoutMs\",\n\t\t);\n\t\tconst maxDiscoveryPages = positiveInteger(\n\t\t\toptions.maxDiscoveryPages ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxDiscoveryPages,\n\t\t\t\"maxDiscoveryPages\",\n\t\t);\n\t\tthis.#maxDiscoveryItems = positiveInteger(\n\t\t\toptions.maxDiscoveryItems ?? MCP_RUNTIME_MANAGER_DEFAULTS.maxDiscoveryItems,\n\t\t\t\"maxDiscoveryItems\",\n\t\t);\n\t\tif (options.observer !== undefined && typeof options.observer.onEvent !== \"function\") {\n\t\t\tthrow new TypeError(\"observer.onEvent must be a function.\");\n\t\t}\n\t\tthis.#now = safeClock(options.now ?? Date.now);\n\t\tthis.#states = new RuntimeStateStore({\n\t\t\tnow: this.#now,\n\t\t\tmaxEntries: maxStateEntries,\n\t\t\t...(options.onListenerError === undefined\n\t\t\t\t? {}\n\t\t\t\t: { onListenerError: options.onListenerError }),\n\t\t});\n\t\tconst factory = new ManagedRuntimeFactory({\n\t\t\tgenerationResolver: options.generationResolver,\n\t\t\tstates: this.#states,\n\t\t\trequestTimeoutMs: this.#requestTimeoutMs,\n\t\t\tshutdownTimeoutMs,\n\t\t\tmaxDiscoveryPages,\n\t\t\t...(options.clientInfo === undefined ? {} : { clientInfo: options.clientInfo }),\n\t\t\t...(options.observer === undefined ? {} : { observer: options.observer }),\n\t\t\tnow: this.#now,\n\t\t});\n\t\tthis.#leases = new McpClientLeaseManager({\n\t\t\tmaxResources: maxConnections,\n\t\t\tonCapacityAvailable: () => this.#admission.drain(),\n\t\t\tcreate: (identity, context) => factory.create(generationKeyOf(identity), context),\n\t\t\tclose: (owned) => factory.close(owned),\n\t\t});\n\t}\n\n\tasync ensureOnline(\n\t\tgenerationKey: GenerationKey,\n\t\tsignal?: AbortSignal,\n\t): Promise<McpRuntimeStateSnapshot> {\n\t\tthis.#assertOpen();\n\t\tconst offlineTask = this.#offlineTasks.get(generationKey);\n\t\tif (offlineTask !== undefined) {\n\t\t\tlet queued = this.#postOfflineOnlineTasks.get(generationKey);\n\t\t\tif (queued === undefined) {\n\t\t\t\tconst created = this.#reconnectAfterOfflineBarriers(generationKey);\n\t\t\t\tqueued = created;\n\t\t\t\tthis.#postOfflineOnlineTasks.set(generationKey, created);\n\t\t\t\tvoid created.then(\n\t\t\t\t\t() => this.#deletePostOfflineOnlineTask(generationKey, created),\n\t\t\t\t\t() => this.#deletePostOfflineOnlineTask(generationKey, created),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn waitForCaller(queued, signal);\n\t\t}\n\t\tthis.#assertSharedLeaseAvailable(generationKey);\n\t\tthis.#assertNotQuarantined(generationKey);\n\t\treturn waitForCaller(this.#getOrCreateOnlineTask(generationKey), signal);\n\t}\n\n\tasync #reconnectAfterOfflineBarriers(\n\t\tgenerationKey: GenerationKey,\n\t): Promise<McpRuntimeStateSnapshot> {\n\t\tfor (;;) {\n\t\t\tconst barrier = this.#offlineTasks.get(generationKey);\n\t\t\tif (barrier === undefined) break;\n\t\t\tawait barrier;\n\t\t}\n\t\tthis.#assertOpen();\n\t\tthis.#assertSharedLeaseAvailable(generationKey);\n\t\tthis.#assertNotQuarantined(generationKey);\n\t\treturn this.#getOrCreateOnlineTask(generationKey);\n\t}\n\n\t#getOrCreateOnlineTask(generationKey: GenerationKey): Promise<McpRuntimeStateSnapshot> {\n\t\tlet task = this.#onlineTasks.get(generationKey);\n\t\tif (task === undefined) {\n\t\t\ttask = Promise.resolve().then(() => this.#reconcileOnline(generationKey));\n\t\t\tthis.#onlineTasks.set(generationKey, task);\n\t\t\tvoid task.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this.#onlineTasks.get(generationKey) === task) {\n\t\t\t\t\t\tthis.#onlineTasks.delete(generationKey);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this.#onlineTasks.get(generationKey) === task) {\n\t\t\t\t\t\tthis.#onlineTasks.delete(generationKey);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn task;\n\t}\n\n\tsetOffline(generationKey: GenerationKey): Promise<McpRuntimeStateSnapshot> {\n\t\tthis.#assertOpen();\n\t\tthis.#admission.rejectGeneration(\n\t\t\tgenerationKey,\n\t\t\tnew McpRuntimeManagerError(\n\t\t\t\tMCP_RUNTIME_GENERATION_RETIRED,\n\t\t\t\t\"The MCP runtime generation was retired before the operation started.\",\n\t\t\t),\n\t\t);\n\t\tlet task = this.#offlineTasks.get(generationKey);\n\t\tif (task !== undefined) return task;\n\t\ttask = Promise.resolve().then(() => this.#performSetOffline(generationKey));\n\t\tthis.#offlineTasks.set(generationKey, task);\n\t\tvoid task.then(\n\t\t\t() => this.#deleteOfflineTask(generationKey, task),\n\t\t\t() => this.#deleteOfflineTask(generationKey, task),\n\t\t);\n\t\treturn task;\n\t}\n\n\tasync #performSetOffline(generationKey: GenerationKey): Promise<McpRuntimeStateSnapshot> {\n\t\tif (this.#states.read(generationKey).phase === \"quarantined\") {\n\t\t\tthrow runtimeQuarantinedError();\n\t\t}\n\t\tthis.#states.transition(generationKey, \"draining\");\n\t\tconst exclusiveIdentities = [...(this.#exclusiveIdentities.get(generationKey) ?? [])];\n\t\tconst drains = [\n\t\t\tthis.#leases.invalidate(generationKey),\n\t\t\t...exclusiveIdentities.map((identity) => this.#leases.invalidate(identity)),\n\t\t];\n\t\tconst keeper = this.#keepers.get(generationKey);\n\t\tthis.#keepers.delete(generationKey);\n\t\tconst onlineTask = this.#onlineTasks.get(generationKey);\n\t\tconst cleanupTasks = [...drains, ...(keeper === undefined ? [] : [keeper.release()])];\n\t\tconst [cleanupSettled] = await Promise.all([\n\t\t\tPromise.allSettled(cleanupTasks),\n\t\t\tPromise.allSettled(onlineTask === undefined ? [] : [onlineTask]),\n\t\t]);\n\t\tconst cleanupFailed = cleanupSettled.some(\n\t\t\t(result) => result.status === \"rejected\" && !isRetirementError(result.reason),\n\t\t);\n\t\tif (this.#onlineTasks.get(generationKey) === onlineTask) {\n\t\t\tthis.#onlineTasks.delete(generationKey);\n\t\t}\n\t\tif (cleanupFailed) {\n\t\t\treturn this.#states.transition(generationKey, \"quarantined\", MCP_RUNTIME_CLEANUP_FAILED);\n\t\t}\n\t\treturn this.#states.transition(generationKey, \"offline\");\n\t}\n\n\t#deleteOfflineTask(generationKey: GenerationKey, task: Promise<McpRuntimeStateSnapshot>): void {\n\t\tif (this.#offlineTasks.get(generationKey) === task) {\n\t\t\tthis.#offlineTasks.delete(generationKey);\n\t\t}\n\t}\n\n\t#deletePostOfflineOnlineTask(\n\t\tgenerationKey: GenerationKey,\n\t\ttask: Promise<McpRuntimeStateSnapshot>,\n\t): void {\n\t\tif (this.#postOfflineOnlineTasks.get(generationKey) === task) {\n\t\t\tthis.#postOfflineOnlineTasks.delete(generationKey);\n\t\t}\n\t}\n\n\tasync retire(generationKey: GenerationKey): Promise<void> {\n\t\tconst state = await this.setOffline(generationKey);\n\t\tif (state.phase === \"quarantined\") {\n\t\t\tthrow runtimeQuarantinedError();\n\t\t}\n\t\tthis.#states.forget(generationKey);\n\t}\n\n\tasync probe(\n\t\tgenerationKey: GenerationKey,\n\t\toptions?: AbortSignal | McpRuntimeOperationOptions,\n\t): Promise<McpRuntimeProbeSnapshot> {\n\t\tconst controls = normalizeOperationOptions(options, \"probe\");\n\t\tconst observation = await this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\tasync (owned, operationSignal) => {\n\t\t\t\tawait this.#probeProtocolLiveness(owned, operationSignal);\n\t\t\t\tconst { runtime, serverName } = owned;\n\t\t\t\tconst connected = this.#states.connected(generationKey, runtime.snapshot(serverName));\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\treachable: true as const,\n\t\t\t\t\tobservedAt: isoTimestamp(this.#now),\n\t\t\t\t\t...(connected.protocolVersion === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { protocolVersion: connected.protocolVersion }),\n\t\t\t\t\t...(connected.protocolEra === undefined ? {} : { protocolEra: connected.protocolEra }),\n\t\t\t\t\t...(connected.capabilities === undefined ? {} : { capabilities: connected.capabilities }),\n\t\t\t\t});\n\t\t\t},\n\t\t\tcontrols,\n\t\t);\n\t\treturn Object.freeze({\n\t\t\t...observation,\n\t\t\truntime: this.#states.read(generationKey),\n\t\t});\n\t}\n\n\trefreshCatalog(\n\t\tgenerationKey: GenerationKey,\n\t\toptions?: AbortSignal | McpRuntimeOperationOptions,\n\t): Promise<McpRuntimeCatalogSnapshot> {\n\t\tlet controls: McpRuntimeOperationOptions;\n\t\ttry {\n\t\t\tcontrols = normalizeOperationOptions(options, \"refreshCatalog\");\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\tasync (owned, operationSignal) => {\n\t\t\t\tawait this.#probeProtocolLiveness(owned, operationSignal);\n\t\t\t\tconst { runtime, serverName } = owned;\n\t\t\t\tconst capabilities = runtime.snapshot(serverName).serverCapabilities;\n\t\t\t\tconst discoverTools = () =>\n\t\t\t\t\tcapabilities?.tools === undefined\n\t\t\t\t\t\t? Promise.resolve([])\n\t\t\t\t\t\t: runtime\n\t\t\t\t\t\t\t\t.listTools(serverName, undefined, {\n\t\t\t\t\t\t\t\t\tcacheMode: \"refresh\",\n\t\t\t\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.then((result) => result.tools);\n\t\t\t\tconst discoverResources = () =>\n\t\t\t\t\tcapabilities?.resources === undefined\n\t\t\t\t\t\t? Promise.resolve([])\n\t\t\t\t\t\t: runtime\n\t\t\t\t\t\t\t\t.listResources(serverName, undefined, {\n\t\t\t\t\t\t\t\t\tcacheMode: \"refresh\",\n\t\t\t\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.then((result) => result.resources);\n\t\t\t\tconst discoverResourceTemplates = () =>\n\t\t\t\t\tcapabilities?.resources === undefined\n\t\t\t\t\t\t? Promise.resolve([])\n\t\t\t\t\t\t: runtime\n\t\t\t\t\t\t\t\t.listResourceTemplates(serverName, undefined, {\n\t\t\t\t\t\t\t\t\tcacheMode: \"refresh\",\n\t\t\t\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.then((result) => result.resourceTemplates)\n\t\t\t\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\t\t\t\tif (isMethodNotFoundProtocolError(error)) return [];\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t});\n\t\t\t\tconst discoverPrompts = () =>\n\t\t\t\t\tcapabilities?.prompts === undefined\n\t\t\t\t\t\t? Promise.resolve([])\n\t\t\t\t\t\t: runtime\n\t\t\t\t\t\t\t\t.listPrompts(serverName, undefined, {\n\t\t\t\t\t\t\t\t\tcacheMode: \"refresh\",\n\t\t\t\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.then((result) => result.prompts);\n\t\t\t\tconst finalize = (\n\t\t\t\t\ttools: McpRuntimeCatalogSnapshot[\"tools\"],\n\t\t\t\t\tresources: McpRuntimeCatalogSnapshot[\"resources\"],\n\t\t\t\t\tresourceTemplates: McpRuntimeCatalogSnapshot[\"resourceTemplates\"],\n\t\t\t\t\tprompts: McpRuntimeCatalogSnapshot[\"prompts\"],\n\t\t\t\t): McpRuntimeCatalogSnapshot => {\n\t\t\t\t\tconst itemCount =\n\t\t\t\t\t\ttools.length + resources.length + resourceTemplates.length + prompts.length;\n\t\t\t\t\tif (itemCount > this.#maxDiscoveryItems) {\n\t\t\t\t\t\tthrow new McpRuntimeManagerError(\n\t\t\t\t\t\t\tMCP_RUNTIME_DISCOVERY_LIMIT_EXCEEDED,\n\t\t\t\t\t\t\t\"The upstream MCP catalog exceeds the configured discovery limit.\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthis.#states.connected(generationKey, runtime.snapshot(serverName));\n\t\t\t\t\treturn Object.freeze({\n\t\t\t\t\t\tdiscoveredAt: isoTimestamp(this.#now),\n\t\t\t\t\t\ttools: Object.freeze([...tools]),\n\t\t\t\t\t\tresources: Object.freeze([...resources]),\n\t\t\t\t\t\tresourceTemplates: Object.freeze([...resourceTemplates]),\n\t\t\t\t\t\tprompts: Object.freeze([...prompts]),\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (controls.leaseMode === \"exclusive\") {\n\t\t\t\t\tconst tools = await discoverTools();\n\t\t\t\t\tconst resources = await discoverResources();\n\t\t\t\t\tconst resourceTemplates = await discoverResourceTemplates();\n\t\t\t\t\tconst prompts = await discoverPrompts();\n\t\t\t\t\treturn finalize(tools, resources, resourceTemplates, prompts);\n\t\t\t\t}\n\t\t\t\tconst [toolsResult, resourcesResult, resourceTemplatesResult, promptsResult] =\n\t\t\t\t\tawait Promise.allSettled([\n\t\t\t\t\t\tdiscoverTools(),\n\t\t\t\t\t\tdiscoverResources(),\n\t\t\t\t\t\tdiscoverResourceTemplates(),\n\t\t\t\t\t\tdiscoverPrompts(),\n\t\t\t\t\t]);\n\t\t\t\tconst tools = requireDiscoveryResult(toolsResult);\n\t\t\t\tconst resources = requireDiscoveryResult(resourcesResult);\n\t\t\t\tconst resourceTemplates = requireDiscoveryResult(resourceTemplatesResult);\n\t\t\t\tconst prompts = requireDiscoveryResult(promptsResult);\n\t\t\t\treturn finalize(tools, resources, resourceTemplates, prompts);\n\t\t\t},\n\t\t\tcontrols,\n\t\t);\n\t}\n\n\twithClientRuntime<Result>(\n\t\tgenerationKey: GenerationKey,\n\t\toperation: McpManagedClientRuntimeOperation<Result>,\n\t\toptions?: AbortSignal | McpRuntimeOperationOptions,\n\t): Promise<Result> {\n\t\tif (typeof operation !== \"function\") {\n\t\t\treturn Promise.reject(new TypeError(\"operation must be a function.\"));\n\t\t}\n\t\tlet controls: McpRuntimeOperationOptions;\n\t\ttry {\n\t\t\tcontrols = normalizeOperationOptions(options, \"withClientRuntime\");\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\t(owned, operationSignal) =>\n\t\t\t\toperation(\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\truntime: owned.runtime,\n\t\t\t\t\t\tserverName: owned.serverName,\n\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\tcontrols,\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tcallTool(\n\t\tgenerationKey: GenerationKey,\n\t\tname: string,\n\t\targuments_: Readonly<Record<string, unknown>>,\n\t\toptions?: AbortSignal | McpRuntimeToolCallOptions,\n\t): Promise<CallToolResult> {\n\t\tlet controls: McpRuntimeToolCallOptions;\n\t\ttry {\n\t\t\tcontrols = normalizeToolCallOptions(options);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\tconst { toolDefinition } = controls;\n\t\treturn this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\t({ runtime, serverName }, operationSignal) =>\n\t\t\t\truntime.callTool(\n\t\t\t\t\tserverName,\n\t\t\t\t\t{ name, arguments: { ...arguments_ } },\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal: operationSignal,\n\t\t\t\t\t\t...(toolDefinition === undefined ? {} : { toolDefinition }),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\tcontrols,\n\t\t\ttrue,\n\t\t);\n\t}\n\n\treadResource(\n\t\tgenerationKey: GenerationKey,\n\t\turi: string,\n\t\toptions?: AbortSignal | McpRuntimeOperationOptions,\n\t): Promise<ReadResourceResult> {\n\t\tlet controls: McpRuntimeOperationOptions;\n\t\ttry {\n\t\t\tcontrols = normalizeOperationOptions(options, \"readResource\");\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\t({ runtime, serverName }, operationSignal) =>\n\t\t\t\truntime.readResource(serverName, { uri }, { signal: operationSignal }),\n\t\t\tcontrols,\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tgetPrompt(\n\t\tgenerationKey: GenerationKey,\n\t\tname: string,\n\t\targuments_: Readonly<Record<string, string>> | undefined,\n\t\toptions?: AbortSignal | McpRuntimeOperationOptions,\n\t): Promise<GetPromptResult> {\n\t\tlet controls: McpRuntimeOperationOptions;\n\t\ttry {\n\t\t\tcontrols = normalizeOperationOptions(options, \"getPrompt\");\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#withRuntime(\n\t\t\tgenerationKey,\n\t\t\t({ runtime, serverName }, operationSignal) =>\n\t\t\t\truntime.getPrompt(\n\t\t\t\t\tserverName,\n\t\t\t\t\t{\n\t\t\t\t\t\tname,\n\t\t\t\t\t\t...(arguments_ === undefined ? {} : { arguments: { ...arguments_ } }),\n\t\t\t\t\t},\n\t\t\t\t\t{ signal: operationSignal },\n\t\t\t\t),\n\t\t\tcontrols,\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tstate(generationKey: GenerationKey): McpRuntimeStateSnapshot {\n\t\tconst keeper = this.#keepers.get(generationKey);\n\t\tif (keeper === undefined) return this.#states.read(generationKey);\n\t\tconst owned = keeper.resource;\n\t\tif (owned.quarantined) return this.#states.read(generationKey);\n\t\ttry {\n\t\t\tconst snapshot = owned.runtime.snapshot(owned.serverName);\n\t\t\tif (snapshot.state === \"connected\") {\n\t\t\t\treturn this.#states.connected(generationKey, snapshot);\n\t\t\t}\n\t\t} catch {\n\t\t\t// A retained keeper with no readable server snapshot is no longer healthy.\n\t\t}\n\t\tconst current = this.#states.read(generationKey);\n\t\treturn current.phase === \"online\"\n\t\t\t? this.#states.transition(generationKey, \"degraded\", MCP_RUNTIME_CONNECTION_LOST)\n\t\t\t: current;\n\t}\n\n\tsnapshot(): McpRuntimeManagerSnapshot {\n\t\tconst snapshot = this.#leases.snapshot();\n\t\treturn Object.freeze({\n\t\t\tclosed: snapshot.closed,\n\t\t\tmaxConnections: snapshot.maxResources,\n\t\t\tmaxQueuedOperations: this.#admission.maxOperations,\n\t\t\tqueuedOperationCount: this.#admission.size,\n\t\t\tconnectionCount: snapshot.resourceCount,\n\t\t\tpendingConnectionCount: snapshot.pendingResourceCount,\n\t\t\tactiveConnectionCount: snapshot.activeResourceCount,\n\t\t\tclosingConnectionCount: snapshot.closingResourceCount,\n\t\t\tquarantinedConnectionCount: snapshot.failedResourceCount,\n\t\t\toperationReferenceCount: snapshot.referenceCount,\n\t\t\tonlineKeeperCount: this.#keepers.size,\n\t\t});\n\t}\n\n\tsubscribe(listener: McpRuntimeStateListener): () => void {\n\t\treturn this.#states.subscribe(listener);\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#closed = true;\n\t\tthis.#admission.rejectAll(runtimeManagerClosedError());\n\t\tthis.#closeTask = this.#performClose();\n\t\treturn this.#closeTask;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\tasync #performClose(): Promise<void> {\n\t\tconst close = this.#leases.close();\n\t\tconst keepers = [...this.#keepers.values()];\n\t\tthis.#keepers.clear();\n\t\tconst settled = await Promise.allSettled([close, ...keepers.map((keeper) => keeper.release())]);\n\t\tthis.#exclusiveIdentities.clear();\n\t\tconst failures = settled.flatMap((result) =>\n\t\t\tresult.status === \"rejected\" ? [result.reason as unknown] : [],\n\t\t);\n\t\tif (failures.length > 0) {\n\t\t\tthrow new AggregateError(failures, \"The MCP runtime manager failed to close.\");\n\t\t}\n\t}\n\n\tasync #reconcileOnline(generationKey: GenerationKey): Promise<McpRuntimeStateSnapshot> {\n\t\tconst keeper = this.#keepers.get(generationKey);\n\t\tif (keeper === undefined) return this.#bringOnline(generationKey);\n\t\tconst owned = requireActiveRuntime(keeper.resource);\n\t\tlet snapshot: McpClientConnectionSnapshot;\n\t\ttry {\n\t\t\tsnapshot = owned.runtime.snapshot(owned.serverName);\n\t\t} catch (error) {\n\t\t\tconst mapped = mapMcpRuntimeManagerError(error);\n\t\t\tthis.#states.transition(generationKey, \"degraded\", runtimeManagerErrorCode(mapped));\n\t\t\tthrow mapped;\n\t\t}\n\t\tif (snapshot.state === \"connected\") {\n\t\t\treturn this.#states.connected(generationKey, snapshot);\n\t\t}\n\t\tthis.#states.transition(generationKey, \"connecting\");\n\t\ttry {\n\t\t\tawait owned.runtime.connect(owned.serverName, {\n\t\t\t\tsignal: AbortSignal.any([\n\t\t\t\t\towned.generationSignal,\n\t\t\t\t\tAbortSignal.timeout(this.#requestTimeoutMs),\n\t\t\t\t]),\n\t\t\t});\n\t\t\treturn this.#states.connected(generationKey, owned.runtime.snapshot(owned.serverName));\n\t\t} catch (error) {\n\t\t\tconst mapped = mapMcpRuntimeManagerError(error);\n\t\t\tif (this.#states.read(generationKey).phase !== \"quarantined\") {\n\t\t\t\tthis.#states.transition(generationKey, \"degraded\", runtimeManagerErrorCode(mapped));\n\t\t\t}\n\t\t\tthrow mapped;\n\t\t}\n\t}\n\n\tasync #bringOnline(generationKey: GenerationKey): Promise<McpRuntimeStateSnapshot> {\n\t\tthis.#assertNotQuarantined(generationKey);\n\t\tthis.#states.transition(generationKey, \"queued\");\n\t\ttry {\n\t\t\tconst lease = await this.#leases.acquire(generationKey, { releaseMode: \"close\" });\n\t\t\tif (lease.resource.quarantined) {\n\t\t\t\tawait releaseIgnoringFailure(lease);\n\t\t\t\tthrow runtimeQuarantinedError();\n\t\t\t}\n\t\t\tif (this.#closed) {\n\t\t\t\tawait lease.release();\n\t\t\t\tthrow runtimeManagerClosedError();\n\t\t\t}\n\t\t\tthis.#keepers.set(generationKey, lease);\n\t\t\treturn this.#states.read(generationKey);\n\t\t} catch (error) {\n\t\t\tconst mapped = mapMcpRuntimeManagerError(error);\n\t\t\tif (this.#states.read(generationKey).phase !== \"quarantined\") {\n\t\t\t\tthis.#states.transition(generationKey, \"failed\", runtimeManagerErrorCode(mapped));\n\t\t\t}\n\t\t\tthrow mapped;\n\t\t}\n\t}\n\n\tasync #withRuntime<Result>(\n\t\tgenerationKey: GenerationKey,\n\t\toperation: (owned: ActiveMcpRuntime<GenerationKey>, signal: AbortSignal) => Promise<Result>,\n\t\toptions: McpRuntimeOperationOptions,\n\t\trequireOnline = false,\n\t): Promise<Result> {\n\t\tthis.#assertOpen();\n\t\tif (this.#offlineTasks.has(generationKey)) throw runtimeNotReadyError();\n\t\tthis.#assertNotQuarantined(generationKey);\n\t\tconst leaseMode = options.leaseMode ?? \"shared\";\n\t\tif (leaseMode === \"shared\" && requireOnline) this.#assertOnlineKeeper(generationKey);\n\t\tconst callerSignal = options.signal;\n\t\tconst acquisitionSignal = AbortSignal.any([\n\t\t\tAbortSignal.timeout(this.#requestTimeoutMs),\n\t\t\t...(callerSignal === undefined ? [] : [callerSignal]),\n\t\t]);\n\t\tconst identity =\n\t\t\tleaseMode !== \"shared\" ? this.#createExclusiveIdentity(generationKey) : generationKey;\n\t\tlet reserved: Promise<McpClientLease<OwnedMcpRuntime<GenerationKey>>> | undefined;\n\t\tconst startedAt = this.#now();\n\t\tconst observe = (outcome: McpRuntimeAdmissionEvent[\"outcome\"]): void => {\n\t\t\ttry {\n\t\t\t\toptions.onAdmission?.({\n\t\t\t\t\toutcome,\n\t\t\t\t\tdurationMs: Math.max(0, this.#now() - startedAt),\n\t\t\t\t\tqueuedOperationCount: this.#admission.size,\n\t\t\t\t\tactiveConnectionCount: this.#leases.size,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t/* Observers cannot change admission or dispatch. */\n\t\t\t}\n\t\t};\n\t\tlet releaseAdmission: (quarantine: boolean) => void;\n\t\ttry {\n\t\t\tacquisitionSignal.throwIfAborted();\n\t\t\tif (\n\t\t\t\tleaseMode !== \"shared\" &&\n\t\t\t\t(this.#keepers.has(generationKey) || this.#onlineTasks.has(generationKey))\n\t\t\t) {\n\t\t\t\tthrow runtimeLeaseModeConflictError();\n\t\t\t}\n\t\t\treleaseAdmission = await this.#admission.enter(\n\t\t\t\tgenerationKey,\n\t\t\t\tleaseMode,\n\t\t\t\toptions.admissionKey,\n\t\t\t\toptions.exclusiveContention === \"queue\" || options.concurrentContention === \"queue\",\n\t\t\t\tacquisitionSignal,\n\t\t\t\toptions.maxConcurrentOperations,\n\t\t\t\tAsyncResource.bind(() => {\n\t\t\t\t\tacquisitionSignal.throwIfAborted();\n\t\t\t\t\tif (!this.#leases.canAcquire(identity)) return false;\n\t\t\t\t\treserved = this.#leases.acquire(identity, {\n\t\t\t\t\t\treleaseMode: \"close\",\n\t\t\t\t\t\tsignal: acquisitionSignal,\n\t\t\t\t\t\tawaitCleanupOnCancel: leaseMode !== \"shared\",\n\t\t\t\t\t});\n\t\t\t\t\tvoid reserved.catch(() => undefined);\n\t\t\t\t\treturn true;\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.#forgetExclusiveIdentity(identity);\n\t\t\tif (\n\t\t\t\tacquisitionSignal.aborted &&\n\t\t\t\tacquisitionSignal.reason instanceof DOMException &&\n\t\t\t\tacquisitionSignal.reason.name === \"TimeoutError\"\n\t\t\t) {\n\t\t\t\tobserve(\"timeout\");\n\t\t\t\tthrow new McpRuntimeManagerError(\n\t\t\t\t\tMCP_RUNTIME_ADMISSION_TIMEOUT,\n\t\t\t\t\t\"The MCP operation deadline expired while waiting for admission.\",\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\t}\n\t\t\tobserve(\n\t\t\t\tacquisitionSignal.aborted\n\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t: runtimeManagerErrorCode(error) === MCP_RUNTIME_QUEUE_FULL\n\t\t\t\t\t\t? \"queue-full\"\n\t\t\t\t\t\t: \"refused\",\n\t\t\t);\n\t\t\tthrowIfCallerAborted(callerSignal);\n\t\t\tthrow mapMcpRuntimeManagerError(error);\n\t\t}\n\t\tobserve(\"admitted\");\n\t\ttry {\n\t\t\tif (reserved === undefined) throw new Error(\"MCP admission did not reserve a transport.\");\n\t\t\treturn await this.#runOperation(\n\t\t\t\tgenerationKey,\n\t\t\t\toperation,\n\t\t\t\treserved,\n\t\t\t\tacquisitionSignal,\n\t\t\t\tcallerSignal,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.#forgetExclusiveIdentity(identity);\n\t\t\treleaseAdmission(this.#states.read(generationKey).phase === \"quarantined\");\n\t\t}\n\t}\n\n\tasync #runOperation<Result>(\n\t\tgenerationKey: GenerationKey,\n\t\toperation: (owned: ActiveMcpRuntime<GenerationKey>, signal: AbortSignal) => Promise<Result>,\n\t\treservation: Promise<McpClientLease<OwnedMcpRuntime<GenerationKey>>>,\n\t\tacquisitionSignal: AbortSignal,\n\t\tcallerSignal: AbortSignal | undefined,\n\t): Promise<Result> {\n\t\tlet lease: McpClientLease<OwnedMcpRuntime<GenerationKey>>;\n\t\ttry {\n\t\t\tlease = await reservation;\n\t\t} catch (error) {\n\t\t\tthrowIfCallerAborted(callerSignal);\n\t\t\tthrow mapMcpRuntimeManagerError(error);\n\t\t}\n\t\tlet outcome:\n\t\t\t| { readonly success: true; readonly value: Result }\n\t\t\t| { readonly success: false; readonly error: unknown };\n\t\ttry {\n\t\t\t// The lease may have been granted immediately before cancellation or retirement.\n\t\t\tthis.#assertOpen();\n\t\t\tthis.#assertNotQuarantined(generationKey);\n\t\t\tconst owned = requireActiveRuntime(lease.resource);\n\t\t\tconst operationSignal = AbortSignal.any([acquisitionSignal, owned.generationSignal]);\n\t\t\toperationSignal.throwIfAborted();\n\t\t\tif (this.#offlineTasks.has(generationKey))\n\t\t\t\tthrow new McpRuntimeManagerError(\n\t\t\t\t\tMCP_RUNTIME_GENERATION_RETIRED,\n\t\t\t\t\t\"The MCP runtime generation was retired before dispatch.\",\n\t\t\t\t);\n\t\t\toutcome = { success: true, value: await operation(owned, operationSignal) };\n\t\t} catch (error) {\n\t\t\toutcome = { success: false, error };\n\t\t}\n\t\ttry {\n\t\t\tawait lease.release();\n\t\t} catch (error) {\n\t\t\tthis.#states.transition(generationKey, \"quarantined\", MCP_RUNTIME_CLEANUP_FAILED);\n\t\t\tthrow runtimeQuarantinedError(error);\n\t\t}\n\t\tif (!outcome.success) {\n\t\t\tthrowIfCallerAborted(callerSignal);\n\t\t\tthrow mapMcpRuntimeManagerError(outcome.error);\n\t\t}\n\t\treturn outcome.value;\n\t}\n\n\tasync #probeProtocolLiveness(\n\t\towned: ActiveMcpRuntime<GenerationKey>,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\tconst { runtime, serverName } = owned;\n\t\tconst protocolEra = runtime.snapshot(serverName).protocolEra;\n\t\tif (protocolEra === \"legacy\") {\n\t\t\tawait runtime.ping(serverName, { signal });\n\t\t\treturn;\n\t\t}\n\t\tif (protocolEra === \"modern\") {\n\t\t\tawait runtime.discover(serverName, { signal });\n\t\t\treturn;\n\t\t}\n\t\tthrow new McpRuntimeManagerError(\n\t\t\t\"MCP_UPSTREAM_FAILED\",\n\t\t\t\"The connected MCP server did not report a protocol era.\",\n\t\t);\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#closed) throw runtimeManagerClosedError();\n\t}\n\n\t#assertSharedLeaseAvailable(generationKey: GenerationKey): void {\n\t\tif (this.#admission.hasIsolatedGeneration(generationKey)) {\n\t\t\tthrow runtimeLeaseModeConflictError();\n\t\t}\n\t}\n\n\t#createExclusiveIdentity(\n\t\tgenerationKey: GenerationKey,\n\t): ExclusiveRuntimeLeaseIdentity<GenerationKey> {\n\t\tconst identity = new ExclusiveRuntimeLeaseIdentity(generationKey);\n\t\tlet identities = this.#exclusiveIdentities.get(generationKey);\n\t\tif (identities === undefined) {\n\t\t\tidentities = new Set();\n\t\t\tthis.#exclusiveIdentities.set(generationKey, identities);\n\t\t}\n\t\tidentities.add(identity);\n\t\treturn identity;\n\t}\n\n\t#forgetExclusiveIdentity(identity: RuntimeLeaseIdentity<GenerationKey>): void {\n\t\tif (!(identity instanceof ExclusiveRuntimeLeaseIdentity)) return;\n\t\tconst identities = this.#exclusiveIdentities.get(identity.generationKey);\n\t\tif (identities === undefined) return;\n\t\tidentities.delete(identity);\n\t\tif (identities.size === 0) this.#exclusiveIdentities.delete(identity.generationKey);\n\t}\n\n\t#assertNotQuarantined(generationKey: GenerationKey): void {\n\t\tif (this.#states.read(generationKey).phase === \"quarantined\") {\n\t\t\tthrow runtimeQuarantinedError();\n\t\t}\n\t}\n\n\t#assertOnlineKeeper(generationKey: GenerationKey): void {\n\t\tconst keeper = this.#keepers.get(generationKey);\n\t\tif (keeper === undefined) throw runtimeNotReadyError();\n\t\tconst owned = requireActiveRuntime(keeper.resource);\n\t\tconst snapshot = owned.runtime.snapshot(owned.serverName);\n\t\tif (snapshot.state !== \"connected\") {\n\t\t\tthis.#states.transition(generationKey, \"degraded\", MCP_RUNTIME_CONNECTION_LOST);\n\t\t\tthrow runtimeNotReadyError();\n\t\t}\n\t\tthis.#states.connected(generationKey, snapshot);\n\t}\n}\n\nconst EMPTY_OPERATION_OPTIONS: McpRuntimeOperationOptions = Object.freeze({});\nconst EMPTY_TOOL_CALL_OPTIONS: McpRuntimeToolCallOptions = EMPTY_OPERATION_OPTIONS;\n\nfunction normalizeOperationOptions(\n\toptions: AbortSignal | McpRuntimeOperationOptions | undefined,\n\toperationName: string,\n): McpRuntimeOperationOptions {\n\tif (options === undefined) return EMPTY_OPERATION_OPTIONS;\n\tif (typeof options !== \"object\" || options === null) {\n\t\tthrow new TypeError(\n\t\t\t`${operationName} options must be an AbortSignal or an operation options object.`,\n\t\t);\n\t}\n\tif (isAbortSignal(options)) return { signal: options };\n\tlet signal: unknown;\n\tlet leaseMode: unknown;\n\tlet exclusiveContention: unknown;\n\tlet admissionKey: unknown;\n\tlet concurrentContention: unknown;\n\tlet maxConcurrentOperations: unknown;\n\tlet onAdmission: unknown;\n\ttry {\n\t\tsignal = Reflect.get(options, \"signal\");\n\t\tleaseMode = Reflect.get(options, \"leaseMode\");\n\t\texclusiveContention = Reflect.get(options, \"exclusiveContention\");\n\t\tadmissionKey = Reflect.get(options, \"admissionKey\");\n\t\tconcurrentContention = Reflect.get(options, \"concurrentContention\");\n\t\tmaxConcurrentOperations = Reflect.get(options, \"maxConcurrentOperations\");\n\t\tonAdmission = Reflect.get(options, \"onAdmission\");\n\t} catch {\n\t\tthrow new TypeError(`${operationName} options could not be read.`);\n\t}\n\tif (\n\t\tsignal !== undefined &&\n\t\t(typeof signal !== \"object\" || signal === null || !isAbortSignal(signal))\n\t) {\n\t\tthrow new TypeError(`${operationName} options.signal must be an AbortSignal.`);\n\t}\n\tif (\n\t\tleaseMode !== undefined &&\n\t\tleaseMode !== \"shared\" &&\n\t\tleaseMode !== \"exclusive\" &&\n\t\tleaseMode !== \"concurrent\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${operationName} options.leaseMode must be \"shared\", \"exclusive\", or \"concurrent\".`,\n\t\t);\n\t}\n\tif (\n\t\texclusiveContention !== undefined &&\n\t\texclusiveContention !== \"reject\" &&\n\t\texclusiveContention !== \"queue\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${operationName} options.exclusiveContention must be \"reject\" or \"queue\".`,\n\t\t);\n\t}\n\tif (\n\t\tconcurrentContention !== undefined &&\n\t\tconcurrentContention !== \"reject\" &&\n\t\tconcurrentContention !== \"queue\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${operationName} options.concurrentContention must be \"reject\" or \"queue\".`,\n\t\t);\n\t}\n\tif (concurrentContention === \"queue\" && leaseMode !== \"concurrent\") {\n\t\tthrow new TypeError(\n\t\t\t`${operationName} queued concurrent contention requires leaseMode \"concurrent\".`,\n\t\t);\n\t}\n\tif (maxConcurrentOperations !== undefined && maxConcurrentOperations !== null) {\n\t\tif (typeof maxConcurrentOperations !== \"number\")\n\t\t\tthrow new TypeError(\"maxConcurrentOperations must be a positive integer or null.\");\n\t\tpositiveInteger(maxConcurrentOperations, \"maxConcurrentOperations\");\n\t}\n\tif (onAdmission !== undefined && !isAdmissionObserver(onAdmission))\n\t\tthrow new TypeError(\"onAdmission must be a function.\");\n\tif (exclusiveContention === \"queue\" && leaseMode !== \"exclusive\") {\n\t\tthrow new TypeError(`${operationName} queued contention requires leaseMode \"exclusive\".`);\n\t}\n\tif (\n\t\tadmissionKey !== undefined &&\n\t\t(typeof admissionKey !== \"string\" || admissionKey.length === 0 || admissionKey.length > 1024)\n\t) {\n\t\tthrow new TypeError(`${operationName} options.admissionKey must be a nonempty bounded string.`);\n\t}\n\tif (leaseMode === \"concurrent\" && admissionKey === undefined) {\n\t\tthrow new TypeError(`${operationName} concurrent execution requires an admissionKey.`);\n\t}\n\tif (admissionKey !== undefined && leaseMode !== \"concurrent\" && leaseMode !== \"exclusive\") {\n\t\tthrow new TypeError(`${operationName} admissionKey requires an isolated lease mode.`);\n\t}\n\treturn {\n\t\t...(signal === undefined ? {} : { signal }),\n\t\t...(leaseMode === undefined ? {} : { leaseMode }),\n\t\t...(exclusiveContention === undefined ? {} : { exclusiveContention }),\n\t\t...(admissionKey === undefined ? {} : { admissionKey }),\n\t\t...(concurrentContention === undefined ? {} : { concurrentContention }),\n\t\t...(maxConcurrentOperations === undefined ? {} : { maxConcurrentOperations }),\n\t\t...(onAdmission === undefined ? {} : { onAdmission }),\n\t};\n}\n\n/** Accepts the positional cancellation form and the richer per-call options object. */\nfunction normalizeToolCallOptions(\n\toptions: AbortSignal | McpRuntimeToolCallOptions | undefined,\n): McpRuntimeToolCallOptions {\n\tif (options === undefined) return EMPTY_TOOL_CALL_OPTIONS;\n\tif (typeof options !== \"object\" || options === null) {\n\t\tthrow new TypeError(\"callTool options must be an AbortSignal or a tool call options object.\");\n\t}\n\tif (isAbortSignal(options)) return { signal: options };\n\treturn {\n\t\t...normalizeOperationOptions(options, \"callTool\"),\n\t\t...(options.toolDefinition === undefined ? {} : { toolDefinition: options.toolDefinition }),\n\t};\n}\n\nfunction isAdmissionObserver(value: unknown): value is (event: McpRuntimeAdmissionEvent) => void {\n\treturn typeof value === \"function\";\n}\n\nfunction isAbortSignal(value: object): value is AbortSignal {\n\tif (value instanceof AbortSignal) return true;\n\ttry {\n\t\treturn (\n\t\t\ttypeof Reflect.get(value, \"aborted\") === \"boolean\" &&\n\t\t\ttypeof Reflect.get(value, \"addEventListener\") === \"function\"\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isMethodNotFoundProtocolError(error: unknown): error is ProtocolError {\n\treturn ProtocolError.isInstance(error) && error.code === METHOD_NOT_FOUND;\n}\n\nfunction requireDiscoveryResult<Result>(result: PromiseSettledResult<Result>): Result {\n\tif (result.status === \"fulfilled\") return result.value;\n\tthrow result.reason;\n}\n\nfunction generationKeyOf<GenerationKey>(\n\tidentity: RuntimeLeaseIdentity<GenerationKey>,\n): GenerationKey {\n\treturn identity instanceof ExclusiveRuntimeLeaseIdentity ? identity.generationKey : identity;\n}\n\nfunction requireActiveRuntime<GenerationKey>(\n\towned: OwnedMcpRuntime<GenerationKey>,\n): ActiveMcpRuntime<GenerationKey> {\n\tif (owned.quarantined) throw runtimeQuarantinedError();\n\treturn owned;\n}\n\nfunction throwIfCallerAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted === true) throw signal.reason;\n}\n\nfunction isRetirementError(error: unknown): boolean {\n\tif (typeof error !== \"object\" || error === null) return false;\n\ttry {\n\t\tconst code = Reflect.get(error, \"code\");\n\t\treturn code === MCP_CLIENT_LEASE_INVALIDATED || code === MCP_RUNTIME_GENERATION_RETIRED;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function releaseIgnoringFailure<Resource extends object>(\n\tlease: McpClientLease<Resource>,\n): Promise<void> {\n\ttry {\n\t\tawait lease.release();\n\t} catch {\n\t\t// The public disposition remains quarantined; the lease manager retains the failed generation.\n\t}\n}\n\nfunction waitForCaller<Result>(task: Promise<Result>, signal?: AbortSignal): Promise<Result> {\n\tif (signal === undefined) return task;\n\tif (signal.aborted) return Promise.reject(signal.reason);\n\treturn new Promise<Result>((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(signal.reason);\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid task.then(\n\t\t\t(result) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(result);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction positiveInteger(value: number, name: string): number {\n\tif (!Number.isInteger(value) || value <= 0) {\n\t\tthrow new RangeError(`${name} must be a positive integer.`);\n\t}\n\treturn value;\n}\n\nfunction positiveFinite(value: number, name: string): number {\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new RangeError(`${name} must be a positive finite number.`);\n\t}\n\treturn value;\n}\n\nfunction isoTimestamp(now: () => number): string {\n\ttry {\n\t\tconst timestamp = now();\n\t\tif (Number.isFinite(timestamp)) return new Date(timestamp).toISOString();\n\t} catch {\n\t\t// Fall through to the system clock if an injected diagnostics clock fails.\n\t}\n\treturn new Date().toISOString();\n}\n\nfunction safeClock(now: () => number): () => number {\n\treturn () => {\n\t\ttry {\n\t\t\tconst timestamp = now();\n\t\t\tif (Number.isFinite(timestamp)) {\n\t\t\t\tnew Date(timestamp).toISOString();\n\t\t\t\treturn timestamp;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Diagnostics clocks are best-effort; lifecycle ownership must remain available.\n\t\t}\n\t\treturn Date.now();\n\t};\n}\n","import { MCP_RUNTIME_MANAGER_CLOSED } from \"./errors.ts\";\nimport type { McpRuntimeManagerPort } from \"./types.ts\";\n\nexport const MCP_RUNTIME_OWNERSHIP_DEFAULTS = Object.freeze({\n\tmaxOwners: 1_000,\n\tmaxGenerations: 1_000,\n\tmaxReferences: 10_000,\n});\n\nexport const MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS =\n\t\"MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS\" as const;\nexport const MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED =\n\t\"MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED\" as const;\nexport const MCP_RUNTIME_OWNER_RELEASED = \"MCP_RUNTIME_OWNER_RELEASED\" as const;\nexport const MCP_RUNTIME_GENERATION_FENCED = \"MCP_RUNTIME_GENERATION_FENCED\" as const;\nexport const MCP_RUNTIME_RETIREMENT_FAILED = \"MCP_RUNTIME_RETIREMENT_FAILED\" as const;\n\nexport type McpRuntimeOwnershipErrorCode =\n\t| typeof MCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS\n\t| typeof MCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED\n\t| typeof MCP_RUNTIME_OWNER_RELEASED\n\t| typeof MCP_RUNTIME_GENERATION_FENCED\n\t| typeof MCP_RUNTIME_RETIREMENT_FAILED;\n\n/** Stable ownership failure that never retains a generation key or caught manager error. */\nexport class McpRuntimeOwnershipError extends Error {\n\treadonly code: McpRuntimeOwnershipErrorCode;\n\n\tconstructor(code: McpRuntimeOwnershipErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"McpRuntimeOwnershipError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** The only manager operation taken into ownership by this coordinator. */\nexport type McpRuntimeRetirementPort<GenerationKey> = Pick<\n\tMcpRuntimeManagerPort<GenerationKey>,\n\t\"retire\"\n>;\n\nexport interface McpRuntimeOwnershipOptions<GenerationKey> {\n\treadonly manager: McpRuntimeRetirementPort<GenerationKey>;\n\t/** Hard bound over live owner capabilities. */\n\treadonly maxOwners?: number;\n\t/** Hard bound over active generations and retained retirement fences. */\n\treadonly maxGenerations?: number;\n\t/** Hard bound over distinct owner-to-generation references. */\n\treadonly maxReferences?: number;\n}\n\nexport interface McpRuntimeOwner<GenerationKey> extends AsyncDisposable {\n\treadonly released: boolean;\n\t/** Retains after any older retirement barrier settles; concurrent duplicates share one task. */\n\tretain(generationKey: GenerationKey): Promise<void>;\n\t/** Releases every retained generation. Repeated calls share one settlement. */\n\trelease(): Promise<void>;\n}\n\n/** Aggregate diagnostics deliberately omit generation keys and manager failures. */\nexport interface McpRuntimeOwnershipSnapshot {\n\treadonly maxOwners: number;\n\treadonly maxGenerations: number;\n\treadonly maxReferences: number;\n\treadonly ownerCount: number;\n\treadonly generationCount: number;\n\treadonly referenceCount: number;\n\treadonly pendingReferenceCount: number;\n\treadonly retiringGenerationCount: number;\n\treadonly fencedGenerationCount: number;\n}\n\ntype GenerationPhase = \"active\" | \"retiring\" | \"retired\" | \"retirement-failed\";\n\ninterface GenerationEntry<GenerationKey> {\n\treadonly key: GenerationKey;\n\treadonly token: symbol;\n\treadonly owners: Set<ManagedMcpRuntimeOwner<GenerationKey>>;\n\tphase: GenerationPhase;\n\t/** Owners at or below this sequence can never reacquire after a forced retirement. */\n\tforceFenceThrough: number | undefined;\n\tretirementTask: Promise<void> | undefined;\n}\n\n/**\n * Bounded, framework-neutral cooperative ownership for opaque runtime generations.\n *\n * Equal keys use `Map` identity. The final cooperative release retires the manager generation.\n * `forceRetire` immediately revokes every current reference and permanently fences every owner\n * that existed when the force began. No retain can cross an unsettled retirement barrier.\n */\nexport class McpRuntimeOwnership<GenerationKey> {\n\treadonly #retireGeneration: (generationKey: GenerationKey) => Promise<void>;\n\treadonly #maxOwners: number;\n\treadonly #maxGenerations: number;\n\treadonly #maxReferences: number;\n\treadonly #owners = new Set<ManagedMcpRuntimeOwner<GenerationKey>>();\n\treadonly #generations = new Map<GenerationKey, GenerationEntry<GenerationKey>>();\n\t#referenceCount = 0;\n\t#pendingReferenceCount = 0;\n\t#nextOwnerSequence = 0;\n\n\tconstructor(options: McpRuntimeOwnershipOptions<GenerationKey>) {\n\t\tlet manager: McpRuntimeRetirementPort<GenerationKey>;\n\t\tlet retireGeneration: McpRuntimeRetirementPort<GenerationKey>[\"retire\"];\n\t\tlet maxOwners: number;\n\t\tlet maxGenerations: number;\n\t\tlet maxReferences: number;\n\t\ttry {\n\t\t\tmanager = options.manager;\n\t\t\tif ((typeof manager !== \"object\" && typeof manager !== \"function\") || manager === null) {\n\t\t\t\tthrow invalidOptionsError();\n\t\t\t}\n\t\t\tretireGeneration = manager.retire;\n\t\t\tmaxOwners = options.maxOwners ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxOwners;\n\t\t\tmaxGenerations = options.maxGenerations ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxGenerations;\n\t\t\tmaxReferences = options.maxReferences ?? MCP_RUNTIME_OWNERSHIP_DEFAULTS.maxReferences;\n\t\t} catch {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tif (\n\t\t\ttypeof retireGeneration !== \"function\" ||\n\t\t\t!isPositiveSafeInteger(maxOwners) ||\n\t\t\t!isPositiveSafeInteger(maxGenerations) ||\n\t\t\t!isPositiveSafeInteger(maxReferences)\n\t\t) {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tthis.#retireGeneration = (generationKey) => retireGeneration.call(manager, generationKey);\n\t\tthis.#maxOwners = maxOwners;\n\t\tthis.#maxGenerations = maxGenerations;\n\t\tthis.#maxReferences = maxReferences;\n\t}\n\n\tcreateOwner(): McpRuntimeOwner<GenerationKey> {\n\t\tif (\n\t\t\tthis.#owners.size >= this.#maxOwners ||\n\t\t\tthis.#nextOwnerSequence >= Number.MAX_SAFE_INTEGER\n\t\t) {\n\t\t\tthrow capacityExceededError();\n\t\t}\n\t\tthis.#nextOwnerSequence += 1;\n\t\tlet owner: ManagedMcpRuntimeOwner<GenerationKey>;\n\t\towner = new ManagedMcpRuntimeOwner(\n\t\t\tthis.#nextOwnerSequence,\n\t\t\t(generationKey) => this.#retain(owner, generationKey),\n\t\t\t() => this.#release(owner),\n\t\t);\n\t\tthis.#owners.add(owner);\n\t\treturn Object.freeze(owner);\n\t}\n\n\t/**\n\t * Retires a generation regardless of cooperative references.\n\t * Repeated calls against the same generation barrier share one settlement.\n\t */\n\tforceRetire(generationKey: GenerationKey): Promise<void> {\n\t\tlet entry = this.#generations.get(generationKey);\n\t\tif (entry !== undefined && entry.phase !== \"active\") {\n\t\t\t// Every force call is a new linearization point. An owner created after\n\t\t\t// an earlier force but before this call must be fenced by this call even\n\t\t\t// when both callers share the same unsettled retirement barrier.\n\t\t\tentry.forceFenceThrough = Math.max(entry.forceFenceThrough ?? 0, this.#nextOwnerSequence);\n\t\t\treturn requireRetirementTask(entry);\n\t\t}\n\n\t\tif (entry === undefined) {\n\t\t\tthis.#pruneReusableFences();\n\t\t\tif (this.#generations.size >= this.#maxGenerations) {\n\t\t\t\treturn Promise.reject(capacityExceededError());\n\t\t\t}\n\t\t\tentry = this.#createGeneration(generationKey);\n\t\t}\n\n\t\tentry.forceFenceThrough = Math.max(entry.forceFenceThrough ?? 0, this.#nextOwnerSequence);\n\t\tfor (const owner of entry.owners) {\n\t\t\towner.dropRetainedGeneration(generationKey);\n\t\t\tthis.#referenceCount -= 1;\n\t\t}\n\t\tentry.owners.clear();\n\t\treturn this.#startRetirement(entry);\n\t}\n\n\tsnapshot(): McpRuntimeOwnershipSnapshot {\n\t\tlet retiringGenerationCount = 0;\n\t\tlet fencedGenerationCount = 0;\n\t\tfor (const entry of this.#generations.values()) {\n\t\t\tif (entry.phase === \"retiring\") retiringGenerationCount += 1;\n\t\t\tif (entry.phase === \"retirement-failed\" || entry.forceFenceThrough !== undefined) {\n\t\t\t\tfencedGenerationCount += 1;\n\t\t\t}\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tmaxOwners: this.#maxOwners,\n\t\t\tmaxGenerations: this.#maxGenerations,\n\t\t\tmaxReferences: this.#maxReferences,\n\t\t\townerCount: this.#owners.size,\n\t\t\tgenerationCount: this.#generations.size,\n\t\t\treferenceCount: this.#referenceCount,\n\t\t\tpendingReferenceCount: this.#pendingReferenceCount,\n\t\t\tretiringGenerationCount,\n\t\t\tfencedGenerationCount,\n\t\t});\n\t}\n\n\t#retain(\n\t\towner: ManagedMcpRuntimeOwner<GenerationKey>,\n\t\tgenerationKey: GenerationKey,\n\t): Promise<void> {\n\t\tif (owner.released) return Promise.reject(ownerReleasedError());\n\t\tif (owner.hasRetainedGeneration(generationKey)) return Promise.resolve();\n\t\tif (this.#referenceCount + this.#pendingReferenceCount >= this.#maxReferences) {\n\t\t\treturn Promise.reject(capacityExceededError());\n\t\t}\n\n\t\tconst reservation = { pending: true };\n\t\tthis.#pendingReferenceCount += 1;\n\t\treturn this.#performRetain(owner, generationKey, reservation).catch((error: unknown) => {\n\t\t\tif (reservation.pending) {\n\t\t\t\treservation.pending = false;\n\t\t\t\tthis.#pendingReferenceCount -= 1;\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tasync #performRetain(\n\t\towner: ManagedMcpRuntimeOwner<GenerationKey>,\n\t\tgenerationKey: GenerationKey,\n\t\treservation: { pending: boolean },\n\t): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (owner.released) throw ownerReleasedError();\n\t\t\tlet entry = this.#generations.get(generationKey);\n\t\t\tif (entry?.phase === \"retiring\") {\n\t\t\t\tawait waitForRetirementBarrier(requireRetirementTask(entry), owner.releaseSignal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (owner.released) throw ownerReleasedError();\n\n\t\t\tif (entry !== undefined) {\n\t\t\t\tif (entry.phase === \"retirement-failed\") throw generationFencedError();\n\t\t\t\tif (entry.phase === \"retired\") {\n\t\t\t\t\tconst forceFenceThrough = entry.forceFenceThrough;\n\t\t\t\t\tif (forceFenceThrough === undefined || owner.sequence <= forceFenceThrough) {\n\t\t\t\t\t\tthrow generationFencedError();\n\t\t\t\t\t}\n\t\t\t\t\tentry = this.#replaceRetiredGeneration(entry);\n\t\t\t\t} else if (\n\t\t\t\t\tentry.forceFenceThrough !== undefined &&\n\t\t\t\t\towner.sequence <= entry.forceFenceThrough\n\t\t\t\t) {\n\t\t\t\t\tthrow generationFencedError();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.#pruneReusableFences();\n\t\t\t\tif (this.#generations.size >= this.#maxGenerations) throw capacityExceededError();\n\t\t\t\tentry = this.#createGeneration(generationKey);\n\t\t\t}\n\n\t\t\tif (owner.released) throw ownerReleasedError();\n\t\t\tentry.owners.add(owner);\n\t\t\towner.addRetainedGeneration(generationKey);\n\t\t\treservation.pending = false;\n\t\t\tthis.#pendingReferenceCount -= 1;\n\t\t\tthis.#referenceCount += 1;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t#release(owner: ManagedMcpRuntimeOwner<GenerationKey>): Promise<void> {\n\t\tthis.#owners.delete(owner);\n\t\tconst retirementTasks: Promise<void>[] = [];\n\t\tfor (const generationKey of owner.takeRetainedGenerations()) {\n\t\t\tconst entry = this.#generations.get(generationKey);\n\t\t\tif (entry === undefined || !entry.owners.delete(owner)) continue;\n\t\t\tthis.#referenceCount -= 1;\n\t\t\tif (entry.owners.size === 0 && entry.phase === \"active\") {\n\t\t\t\tretirementTasks.push(this.#startRetirement(entry));\n\t\t\t}\n\t\t}\n\t\tthis.#pruneReusableFences();\n\t\treturn settleOwnerRelease(retirementTasks);\n\t}\n\n\t#createGeneration(generationKey: GenerationKey): GenerationEntry<GenerationKey> {\n\t\tconst entry: GenerationEntry<GenerationKey> = {\n\t\t\tkey: generationKey,\n\t\t\ttoken: Symbol(\"mcp-runtime-ownership-generation\"),\n\t\t\towners: new Set(),\n\t\t\tphase: \"active\",\n\t\t\tforceFenceThrough: undefined,\n\t\t\tretirementTask: undefined,\n\t\t};\n\t\tthis.#generations.set(generationKey, entry);\n\t\treturn entry;\n\t}\n\n\t#replaceRetiredGeneration(\n\t\tretired: GenerationEntry<GenerationKey>,\n\t): GenerationEntry<GenerationKey> {\n\t\tconst replacement: GenerationEntry<GenerationKey> = {\n\t\t\tkey: retired.key,\n\t\t\ttoken: Symbol(\"mcp-runtime-ownership-generation\"),\n\t\t\towners: new Set(),\n\t\t\tphase: \"active\",\n\t\t\tforceFenceThrough: retired.forceFenceThrough,\n\t\t\tretirementTask: undefined,\n\t\t};\n\t\tthis.#generations.set(retired.key, replacement);\n\t\treturn replacement;\n\t}\n\n\t#startRetirement(entry: GenerationEntry<GenerationKey>): Promise<void> {\n\t\tif (entry.retirementTask !== undefined) return entry.retirementTask;\n\t\tentry.phase = \"retiring\";\n\t\tconst task = Promise.resolve()\n\t\t\t.then(() => this.#retireGeneration(entry.key))\n\t\t\t.then(\n\t\t\t\t() => this.#settleRetirementSuccess(entry),\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tif (isManagerClosedError(error)) {\n\t\t\t\t\t\tthis.#settleRetirementSuccess(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tentry.phase = \"retirement-failed\";\n\t\t\t\t\tthrow retirementFailedError();\n\t\t\t\t},\n\t\t\t);\n\t\tentry.retirementTask = task;\n\t\treturn task;\n\t}\n\n\t#settleRetirementSuccess(entry: GenerationEntry<GenerationKey>): void {\n\t\tentry.phase = \"retired\";\n\t\tif (this.#generations.get(entry.key)?.token !== entry.token) return;\n\t\tif (entry.forceFenceThrough === undefined || !this.#hasFencedOwner(entry.forceFenceThrough)) {\n\t\t\tthis.#generations.delete(entry.key);\n\t\t}\n\t}\n\n\t#pruneReusableFences(): void {\n\t\tfor (const [generationKey, entry] of this.#generations) {\n\t\t\tif (\n\t\t\t\tentry.phase === \"retired\" &&\n\t\t\t\tentry.forceFenceThrough !== undefined &&\n\t\t\t\t!this.#hasFencedOwner(entry.forceFenceThrough)\n\t\t\t) {\n\t\t\t\tthis.#generations.delete(generationKey);\n\t\t\t}\n\t\t}\n\t}\n\n\t#hasFencedOwner(fenceThrough: number): boolean {\n\t\tfor (const owner of this.#owners) {\n\t\t\tif (owner.sequence <= fenceThrough) return true;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nclass ManagedMcpRuntimeOwner<GenerationKey> implements McpRuntimeOwner<GenerationKey> {\n\treadonly #releaseController = new AbortController();\n\treadonly #retainGeneration: (generationKey: GenerationKey) => Promise<void>;\n\treadonly #releaseOwner: () => Promise<void>;\n\treadonly #retainedGenerations = new Set<GenerationKey>();\n\treadonly #retentionTasks = new Map<GenerationKey, Promise<void>>();\n\treadonly sequence: number;\n\t#releaseStarted = false;\n\t#releaseTask: Promise<void> | undefined;\n\n\tconstructor(\n\t\tsequence: number,\n\t\tretainGeneration: (generationKey: GenerationKey) => Promise<void>,\n\t\treleaseOwner: () => Promise<void>,\n\t) {\n\t\tthis.sequence = sequence;\n\t\tthis.#retainGeneration = retainGeneration;\n\t\tthis.#releaseOwner = releaseOwner;\n\t}\n\n\tget released(): boolean {\n\t\treturn this.#releaseStarted;\n\t}\n\n\tget releaseSignal(): AbortSignal {\n\t\treturn this.#releaseController.signal;\n\t}\n\n\tretain(generationKey: GenerationKey): Promise<void> {\n\t\tif (this.#releaseStarted) return Promise.reject(ownerReleasedError());\n\t\tconst existing = this.#retentionTasks.get(generationKey);\n\t\tif (existing !== undefined) return existing;\n\t\tconst task = this.#retainGeneration(generationKey);\n\t\tthis.#retentionTasks.set(generationKey, task);\n\t\tvoid task.catch(() => {\n\t\t\tif (this.#retentionTasks.get(generationKey) === task) {\n\t\t\t\tthis.#retentionTasks.delete(generationKey);\n\t\t\t}\n\t\t});\n\t\treturn task;\n\t}\n\n\trelease(): Promise<void> {\n\t\tif (this.#releaseTask === undefined) {\n\t\t\tthis.#releaseStarted = true;\n\t\t\tthis.#releaseController.abort();\n\t\t\ttry {\n\t\t\t\tthis.#releaseTask = this.#releaseOwner();\n\t\t\t} catch (error) {\n\t\t\t\tthis.#releaseTask = Promise.reject(error);\n\t\t\t}\n\t\t}\n\t\treturn this.#releaseTask;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.release();\n\t}\n\n\thasRetainedGeneration(generationKey: GenerationKey): boolean {\n\t\treturn this.#retainedGenerations.has(generationKey);\n\t}\n\n\taddRetainedGeneration(generationKey: GenerationKey): void {\n\t\tthis.#retainedGenerations.add(generationKey);\n\t}\n\n\tdropRetainedGeneration(generationKey: GenerationKey): void {\n\t\tthis.#retainedGenerations.delete(generationKey);\n\t\tthis.#retentionTasks.delete(generationKey);\n\t}\n\n\ttakeRetainedGenerations(): readonly GenerationKey[] {\n\t\tconst retained = [...this.#retainedGenerations];\n\t\tthis.#retainedGenerations.clear();\n\t\tfor (const generationKey of retained) this.#retentionTasks.delete(generationKey);\n\t\treturn retained;\n\t}\n}\n\nfunction settleOwnerRelease(tasks: readonly Promise<void>[]): Promise<void> {\n\tif (tasks.length === 0) return Promise.resolve();\n\treturn Promise.allSettled(tasks).then((settled) => {\n\t\tconst failures = settled.flatMap((result) =>\n\t\t\tresult.status === \"rejected\" ? [result.reason as unknown] : [],\n\t\t);\n\t\tif (failures.length > 0) {\n\t\t\tthrow new AggregateError(failures, \"One or more MCP runtime generations failed to retire.\");\n\t\t}\n\t});\n}\n\nfunction requireRetirementTask<GenerationKey>(\n\tentry: GenerationEntry<GenerationKey>,\n): Promise<void> {\n\tif (entry.retirementTask === undefined) {\n\t\tthrow new Error(\"The MCP runtime ownership retirement task is missing.\");\n\t}\n\treturn entry.retirementTask;\n}\n\nfunction waitForRetirementBarrier(task: Promise<void>, releaseSignal: AbortSignal): Promise<void> {\n\tif (releaseSignal.aborted) return Promise.reject(ownerReleasedError());\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (released: boolean): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\treleaseSignal.removeEventListener(\"abort\", onRelease);\n\t\t\tif (released) reject(ownerReleasedError());\n\t\t\telse resolve();\n\t\t};\n\t\tconst onRelease = (): void => finish(true);\n\t\treleaseSignal.addEventListener(\"abort\", onRelease, { once: true });\n\t\tvoid task.then(\n\t\t\t() => finish(false),\n\t\t\t() => finish(false),\n\t\t);\n\t});\n}\n\nfunction isPositiveSafeInteger(value: number): boolean {\n\treturn Number.isSafeInteger(value) && value > 0;\n}\n\nfunction isManagerClosedError(error: unknown): boolean {\n\tif (typeof error !== \"object\" || error === null) return false;\n\ttry {\n\t\treturn Reflect.get(error, \"code\") === MCP_RUNTIME_MANAGER_CLOSED;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction invalidOptionsError(): McpRuntimeOwnershipError {\n\treturn new McpRuntimeOwnershipError(\n\t\tMCP_RUNTIME_OWNERSHIP_INVALID_OPTIONS,\n\t\t\"The MCP runtime ownership options are invalid.\",\n\t);\n}\n\nfunction capacityExceededError(): McpRuntimeOwnershipError {\n\treturn new McpRuntimeOwnershipError(\n\t\tMCP_RUNTIME_OWNERSHIP_CAPACITY_EXCEEDED,\n\t\t\"The MCP runtime ownership coordinator is at its configured capacity.\",\n\t);\n}\n\nfunction ownerReleasedError(): McpRuntimeOwnershipError {\n\treturn new McpRuntimeOwnershipError(\n\t\tMCP_RUNTIME_OWNER_RELEASED,\n\t\t\"The MCP runtime owner has already been released.\",\n\t);\n}\n\nfunction generationFencedError(): McpRuntimeOwnershipError {\n\treturn new McpRuntimeOwnershipError(\n\t\tMCP_RUNTIME_GENERATION_FENCED,\n\t\t\"The MCP runtime generation is fenced from this owner.\",\n\t);\n}\n\nfunction retirementFailedError(): McpRuntimeOwnershipError {\n\treturn new McpRuntimeOwnershipError(\n\t\tMCP_RUNTIME_RETIREMENT_FAILED,\n\t\t\"The MCP runtime generation failed to retire.\",\n\t);\n}\n","import type { StandardSchemaV1, StandardSchemaV1Sync } from \"@modelcontextprotocol/client\";\n\nimport { isRuntimeStateErrorCode, type McpRuntimeStateErrorCode } from \"./errors.ts\";\nimport type {\n\tMcpRuntimeCapabilitiesSnapshot,\n\tMcpRuntimePhase,\n\tMcpRuntimeProbeSnapshot,\n\tMcpRuntimeProtocolEra,\n\tMcpRuntimeStateSnapshot,\n} from \"./types.ts\";\n\n/**\n * Resolves to `Members` only when the tuple lists every member of `Union`.\n *\n * A union member that no entry covers collapses this to `never`, which fails\n * the `satisfies` fence at its declaration. An entry that is not a union member\n * fails the same fence through the `Members` constraint, so a union and its\n * published tuple cannot drift apart without a compile error.\n */\ntype McpExhaustiveMembers<Union extends string, Members extends readonly Union[]> = [\n\tUnion,\n] extends [Members[number]]\n\t? Members\n\t: never;\n\nconst RUNTIME_PHASE_MEMBERS = [\n\t\"offline\",\n\t\"queued\",\n\t\"connecting\",\n\t\"online\",\n\t\"degraded\",\n\t\"draining\",\n\t\"failed\",\n\t\"quarantined\",\n] as const;\n\nconst PROTOCOL_ERA_MEMBERS = [\"legacy\", \"modern\"] as const;\n\nconst CAPABILITY_MEMBERS = [\n\t\"tools\",\n\t\"resources\",\n\t\"prompts\",\n\t\"completion\",\n\t\"subscriptions\",\n] as const;\n\nconst STATE_MEMBERS = [\n\t\"phase\",\n\t\"lastTransitionAt\",\n\t\"protocolVersion\",\n\t\"protocolEra\",\n\t\"connectedAt\",\n\t\"errorCode\",\n\t\"capabilities\",\n] as const;\n\nconst PROBE_MEMBERS = [\n\t\"reachable\",\n\t\"observedAt\",\n\t\"protocolVersion\",\n\t\"protocolEra\",\n\t\"capabilities\",\n\t\"runtime\",\n] as const;\n\n/** Every `McpRuntimePhase`, in lifecycle order, for hosts that persist state projections. */\nexport const MCP_RUNTIME_PHASES = Object.freeze(\n\tRUNTIME_PHASE_MEMBERS satisfies McpExhaustiveMembers<\n\t\tMcpRuntimePhase,\n\t\ttypeof RUNTIME_PHASE_MEMBERS\n\t>,\n);\n\n/** Every `McpRuntimeProtocolEra` a connected managed generation can report. */\nexport const MCP_RUNTIME_PROTOCOL_ERAS = Object.freeze(\n\tPROTOCOL_ERA_MEMBERS satisfies McpExhaustiveMembers<\n\t\tMcpRuntimeProtocolEra,\n\t\ttypeof PROTOCOL_ERA_MEMBERS\n\t>,\n);\n\nconst RUNTIME_PHASES: ReadonlySet<string> = new Set(MCP_RUNTIME_PHASES);\nconst PROTOCOL_ERAS: ReadonlySet<string> = new Set(MCP_RUNTIME_PROTOCOL_ERAS);\n\nconst CAPABILITY_KEYS: ReadonlySet<string> = new Set(\n\tCAPABILITY_MEMBERS satisfies McpExhaustiveMembers<\n\t\tkeyof McpRuntimeCapabilitiesSnapshot,\n\t\ttypeof CAPABILITY_MEMBERS\n\t>,\n);\n\nconst STATE_KEYS: ReadonlySet<string> = new Set(\n\tSTATE_MEMBERS satisfies McpExhaustiveMembers<keyof McpRuntimeStateSnapshot, typeof STATE_MEMBERS>,\n);\n\nconst PROBE_KEYS: ReadonlySet<string> = new Set(\n\tPROBE_MEMBERS satisfies McpExhaustiveMembers<keyof McpRuntimeProbeSnapshot, typeof PROBE_MEMBERS>,\n);\n\nconst ISO_TIMESTAMP_PATTERN =\n\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/u;\n\nconst SNAPSHOT_SCHEMA_VENDOR = \"@nest-mcp/manager\";\n\n/**\n * Standard Schema v1 validator for one snapshot shape produced by the manager.\n *\n * Validation is synchronous and dependency-free. It accepts exactly what the\n * manager itself emits, rejects unknown properties, and returns a frozen\n * normalized snapshot so persisting a validated value round-trips unchanged.\n *\n * @see https://standardschema.dev\n */\nexport type McpRuntimeSnapshotSchema<Snapshot> = StandardSchemaV1Sync<unknown, Snapshot>;\n\ntype McpRuntimeSnapshotParser<Snapshot> = (\n\tvalue: unknown,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n) => Snapshot | undefined;\n\n/** Validates a persisted `McpRuntimeCapabilitiesSnapshot`. */\nexport const mcpRuntimeCapabilitiesSnapshotSchema: McpRuntimeSnapshotSchema<McpRuntimeCapabilitiesSnapshot> =\n\tsnapshotSchema(parseCapabilitiesSnapshot);\n\n/** Validates a persisted `McpRuntimeStateSnapshot`, including an optional capability projection. */\nexport const mcpRuntimeStateSnapshotSchema: McpRuntimeSnapshotSchema<McpRuntimeStateSnapshot> =\n\tsnapshotSchema(parseStateSnapshot);\n\n/** Validates a persisted `McpRuntimeProbeSnapshot`, including its nested state projection. */\nexport const mcpRuntimeProbeSnapshotSchema: McpRuntimeSnapshotSchema<McpRuntimeProbeSnapshot> =\n\tsnapshotSchema(parseProbeSnapshot);\n\nfunction snapshotSchema<Snapshot>(\n\tparse: McpRuntimeSnapshotParser<Snapshot>,\n): McpRuntimeSnapshotSchema<Snapshot> {\n\tconst standard: McpRuntimeSnapshotSchema<Snapshot>[\"~standard\"] = {\n\t\tversion: 1,\n\t\tvendor: SNAPSHOT_SCHEMA_VENDOR,\n\t\tvalidate(value: unknown): StandardSchemaV1.Result<Snapshot> {\n\t\t\tconst issues: StandardSchemaV1.Issue[] = [];\n\t\t\tconst snapshot = parse(value, [], issues);\n\t\t\tif (snapshot === undefined || issues.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tissues: Object.freeze(\n\t\t\t\t\t\tissues.length > 0 ? issues : [issue(\"Expected a valid snapshot.\", [])],\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { value: snapshot };\n\t\t},\n\t};\n\treturn Object.freeze({ \"~standard\": Object.freeze(standard) });\n}\n\nfunction parseCapabilitiesSnapshot(\n\tvalue: unknown,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeCapabilitiesSnapshot | undefined {\n\tconst source = readObject(value, path, issues);\n\tif (source === undefined) return undefined;\n\trejectUnknownKeys(source, CAPABILITY_KEYS, path, issues);\n\tconst issueCount = issues.length;\n\tconst capabilities = Object.freeze({\n\t\ttools: readBoolean(source, \"tools\", path, issues),\n\t\tresources: readBoolean(source, \"resources\", path, issues),\n\t\tprompts: readBoolean(source, \"prompts\", path, issues),\n\t\tcompletion: readBoolean(source, \"completion\", path, issues),\n\t\tsubscriptions: readBoolean(source, \"subscriptions\", path, issues),\n\t});\n\treturn issues.length > issueCount ? undefined : capabilities;\n}\n\nfunction parseStateSnapshot(\n\tvalue: unknown,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeStateSnapshot | undefined {\n\tconst source = readObject(value, path, issues);\n\tif (source === undefined) return undefined;\n\trejectUnknownKeys(source, STATE_KEYS, path, issues);\n\tconst issueCount = issues.length;\n\tconst phase = readPhase(source, path, issues);\n\tconst lastTransitionAt = readRequiredTimestamp(source, \"lastTransitionAt\", path, issues);\n\tconst protocolVersion = readText(source, \"protocolVersion\", path, issues);\n\tconst protocolEra = readProtocolEra(source, path, issues);\n\tconst connectedAt = readOptionalTimestamp(source, \"connectedAt\", path, issues);\n\tconst errorCode = readErrorCode(source, path, issues);\n\tconst capabilities = readCapabilities(source, path, issues);\n\tif (phase === undefined || lastTransitionAt === undefined || issues.length > issueCount) {\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\tphase,\n\t\tlastTransitionAt,\n\t\t...(protocolVersion === undefined ? {} : { protocolVersion }),\n\t\t...(protocolEra === undefined ? {} : { protocolEra }),\n\t\t...(connectedAt === undefined ? {} : { connectedAt }),\n\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t...(capabilities === undefined ? {} : { capabilities }),\n\t});\n}\n\nfunction parseProbeSnapshot(\n\tvalue: unknown,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeProbeSnapshot | undefined {\n\tconst source = readObject(value, path, issues);\n\tif (source === undefined) return undefined;\n\trejectUnknownKeys(source, PROBE_KEYS, path, issues);\n\tconst issueCount = issues.length;\n\tif (Reflect.get(source, \"reachable\") !== true) {\n\t\tissues.push(issue(\"Expected the literal value true.\", [...path, \"reachable\"]));\n\t}\n\tconst observedAt = readRequiredTimestamp(source, \"observedAt\", path, issues);\n\tconst protocolVersion = readText(source, \"protocolVersion\", path, issues);\n\tconst protocolEra = readProtocolEra(source, path, issues);\n\tconst capabilities = readCapabilities(source, path, issues);\n\tconst runtime = readRuntimeState(source, path, issues);\n\tif (observedAt === undefined || runtime === undefined || issues.length > issueCount) {\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\treachable: true as const,\n\t\tobservedAt,\n\t\t...(protocolVersion === undefined ? {} : { protocolVersion }),\n\t\t...(protocolEra === undefined ? {} : { protocolEra }),\n\t\t...(capabilities === undefined ? {} : { capabilities }),\n\t\truntime,\n\t});\n}\n\nfunction readObject(\n\tvalue: unknown,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): object | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tissues.push(issue(\"Expected an object.\", path));\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nfunction rejectUnknownKeys(\n\tsource: object,\n\tknown: ReadonlySet<string>,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): void {\n\tfor (const key of Object.keys(source)) {\n\t\tif (known.has(key)) continue;\n\t\tissues.push(issue(\"Unrecognized property.\", [...path, key]));\n\t}\n}\n\nfunction readBoolean(\n\tsource: object,\n\tkey: string,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): boolean {\n\tconst value: unknown = Reflect.get(source, key);\n\tif (typeof value === \"boolean\") return value;\n\tissues.push(issue(\"Expected a boolean.\", [...path, key]));\n\treturn false;\n}\n\nfunction readPhase(\n\tsource: object,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimePhase | undefined {\n\tconst value: unknown = Reflect.get(source, \"phase\");\n\tif (typeof value === \"string\" && isRuntimePhase(value)) return value;\n\tissues.push(issue(expectedOneOf(MCP_RUNTIME_PHASES), [...path, \"phase\"]));\n\treturn undefined;\n}\n\nfunction readProtocolEra(\n\tsource: object,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeProtocolEra | undefined {\n\tconst value: unknown = Reflect.get(source, \"protocolEra\");\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\" && isProtocolEra(value)) return value;\n\tissues.push(issue(expectedOneOf(MCP_RUNTIME_PROTOCOL_ERAS), [...path, \"protocolEra\"]));\n\treturn undefined;\n}\n\nfunction readErrorCode(\n\tsource: object,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeStateErrorCode | undefined {\n\tconst value: unknown = Reflect.get(source, \"errorCode\");\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\" && isRuntimeStateErrorCode(value)) return value;\n\tissues.push(issue(\"Expected a known MCP runtime state error code.\", [...path, \"errorCode\"]));\n\treturn undefined;\n}\n\nfunction readCapabilities(\n\tsource: object,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeCapabilitiesSnapshot | undefined {\n\tconst value: unknown = Reflect.get(source, \"capabilities\");\n\tif (value === undefined) return undefined;\n\treturn parseCapabilitiesSnapshot(value, [...path, \"capabilities\"], issues);\n}\n\nfunction readRuntimeState(\n\tsource: object,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): McpRuntimeStateSnapshot | undefined {\n\tconst value: unknown = Reflect.get(source, \"runtime\");\n\tconst runtimePath = [...path, \"runtime\"];\n\tif (value === undefined) {\n\t\tissues.push(issue(\"Expected a required value.\", runtimePath));\n\t\treturn undefined;\n\t}\n\treturn parseStateSnapshot(value, runtimePath, issues);\n}\n\nfunction readText(\n\tsource: object,\n\tkey: string,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): string | undefined {\n\tconst value: unknown = Reflect.get(source, key);\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\" && value.length > 0) return value;\n\tissues.push(issue(\"Expected a non-empty string.\", [...path, key]));\n\treturn undefined;\n}\n\nfunction readRequiredTimestamp(\n\tsource: object,\n\tkey: string,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): string | undefined {\n\tif (Reflect.get(source, key) === undefined) {\n\t\tissues.push(issue(\"Expected a required value.\", [...path, key]));\n\t\treturn undefined;\n\t}\n\treturn readOptionalTimestamp(source, key, path, issues);\n}\n\nfunction readOptionalTimestamp(\n\tsource: object,\n\tkey: string,\n\tpath: readonly PropertyKey[],\n\tissues: StandardSchemaV1.Issue[],\n): string | undefined {\n\tconst value: unknown = Reflect.get(source, key);\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\" && ISO_TIMESTAMP_PATTERN.test(value) && isResolvedInstant(value)) {\n\t\treturn value;\n\t}\n\tissues.push(issue(\"Expected an ISO 8601 date-time string.\", [...path, key]));\n\treturn undefined;\n}\n\nfunction issue(message: string, path: readonly PropertyKey[]): StandardSchemaV1.Issue {\n\treturn Object.freeze({ message, path: Object.freeze([...path]) });\n}\n\nfunction expectedOneOf(members: readonly string[]): string {\n\treturn `Expected one of ${members.join(\", \")}.`;\n}\n\nfunction isRuntimePhase(value: string): value is McpRuntimePhase {\n\treturn RUNTIME_PHASES.has(value);\n}\n\nfunction isProtocolEra(value: string): value is McpRuntimeProtocolEra {\n\treturn PROTOCOL_ERAS.has(value);\n}\n\nfunction isResolvedInstant(value: string): boolean {\n\treturn Number.isFinite(Date.parse(value));\n}\n"],"mappings":";;;;;AAMA,MAAa,yBAAyB;AACtC,MAAa,gCAAgC;AAE7C,MAAa,gCAAgC;AAC7C,MAAa,uCAAuC;AACpD,MAAa,iCAAiC;AAC9C,MAAa,kCAAkC;AAC/C,MAAa,wBAAwB;AACrC,MAAa,0BAA0B;AACvC,MAAa,6BAA6B;AAC1C,MAAa,8BAA8B;AAE3C,MAAa,6BAA6B;AAC1C,MAAa,8BAA8B;;AAqB3C,IAAa,yBAAb,cAA4C,MAAM;CACjD;CAEA,YAAY,MAAkC,SAAiB,SAAwB;EACtF,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACb;AACD;AAEA,SAAgB,0BAA0B,OAAyB;CAClE,IAAI,iBAAiB,wBAAwB,OAAO;CACpD,IAAI,iBAAiB,qCAAqC,OAAO,MAAM;CACvE,MAAM,OAAO,cAAc,KAAK;CAChC,IAAI,SAAS,oCACZ,OAAO,IAAI,uBACV,+BACA,0DACA,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0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0-alpha.0",
4
+ "description": "Framework-neutral bounded lifecycle manager for dynamic MCP client runtime generations.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "BSD-3-Clause",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/btwld/nest-mcp.git",
11
+ "directory": "packages/manager"
12
+ },
13
+ "homepage": "https://github.com/btwld/nest-mcp/tree/main/packages/manager#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/btwld/nest-mcp/issues"
16
+ },
17
+ "keywords": [
18
+ "mcp",
19
+ "model-context-protocol",
20
+ "manager",
21
+ "lifecycle",
22
+ "client",
23
+ "runtime",
24
+ "nest-mcp"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22.13.0"
28
+ },
29
+ "types": "./dist/index.d.mts",
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "LICENSE"
35
+ ],
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.mts",
39
+ "import": "./dist/index.mjs",
40
+ "default": "./dist/index.mjs"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "dependencies": {
45
+ "@nest-mcp/client": "^2.0.0-alpha.0",
46
+ "@nest-mcp/core": "^2.0.0-alpha.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@modelcontextprotocol/client": ">=2.0.0 <3.0.0"
50
+ },
51
+ "devDependencies": {
52
+ "@modelcontextprotocol/client": "2.4.0"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "provenance": true
57
+ },
58
+ "scripts": {
59
+ "build": "tsdown",
60
+ "build:watch": "tsdown --watch src",
61
+ "typecheck": "tsc -b",
62
+ "lint": "oxlint --type-aware .",
63
+ "lint:fix": "oxlint --type-aware --fix .",
64
+ "format": "prettier --write . --ignore-unknown",
65
+ "format:check": "prettier --check . --ignore-unknown",
66
+ "test": "vitest run",
67
+ "test:watch": "vitest",
68
+ "test:coverage": "vitest run --coverage",
69
+ "verify:pack": "pnpm run build && publint --strict"
70
+ }
6
71
  }