@nest-mcp/client 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +845 -69
  3. package/dist/ai-sdk/index.d.mts +14 -0
  4. package/dist/ai-sdk/index.d.mts.map +1 -0
  5. package/dist/ai-sdk/index.mjs +27 -0
  6. package/dist/ai-sdk/index.mjs.map +1 -0
  7. package/dist/bootstrap-BIAcDnHp.d.mts +394 -0
  8. package/dist/bootstrap-BIAcDnHp.d.mts.map +1 -0
  9. package/dist/index.d.mts +480 -0
  10. package/dist/index.d.mts.map +1 -0
  11. package/dist/index.mjs +1960 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/oauth/dynamic-registration.d.mts +92 -0
  14. package/dist/oauth/dynamic-registration.d.mts.map +1 -0
  15. package/dist/oauth/dynamic-registration.mjs +392 -0
  16. package/dist/oauth/dynamic-registration.mjs.map +1 -0
  17. package/dist/oauth/index.d.mts +422 -0
  18. package/dist/oauth/index.d.mts.map +1 -0
  19. package/dist/oauth/index.mjs +3349 -0
  20. package/dist/oauth/index.mjs.map +1 -0
  21. package/dist/scope-CxGBCDdr.mjs +22 -0
  22. package/dist/scope-CxGBCDdr.mjs.map +1 -0
  23. package/package.json +76 -50
  24. package/scripts/external-smoke.mjs +693 -0
  25. package/dist/decorators/inject-mcp-client.decorator.d.ts +0 -3
  26. package/dist/decorators/inject-mcp-client.decorator.js +0 -12
  27. package/dist/decorators/on-notification.decorator.d.ts +0 -7
  28. package/dist/decorators/on-notification.decorator.js +0 -13
  29. package/dist/health/mcp-client.health.d.ts +0 -20
  30. package/dist/health/mcp-client.health.js +0 -42
  31. package/dist/index.d.ts +0 -21
  32. package/dist/index.js +0 -64
  33. package/dist/interfaces/client-options.interface.d.ts +0 -139
  34. package/dist/interfaces/client-options.interface.js +0 -3
  35. package/dist/mcp-client.module.d.ts +0 -20
  36. package/dist/mcp-client.module.js +0 -188
  37. package/dist/mcp-client.service.d.ts +0 -558
  38. package/dist/mcp-client.service.js +0 -532
  39. package/dist/mcp-clients.service.d.ts +0 -39
  40. package/dist/mcp-clients.service.js +0 -104
  41. package/dist/testing/mock-client.d.ts +0 -67
  42. package/dist/testing/mock-client.js +0 -154
  43. package/dist/transport/apply-auth-headers.d.ts +0 -3
  44. package/dist/transport/apply-auth-headers.js +0 -13
  45. package/dist/transport/client-transport.factory.d.ts +0 -4
  46. package/dist/transport/client-transport.factory.js +0 -21
  47. package/dist/transport/sse-client.transport.d.ts +0 -4
  48. package/dist/transport/sse-client.transport.js +0 -15
  49. package/dist/transport/stdio-client.transport.d.ts +0 -4
  50. package/dist/transport/stdio-client.transport.js +0 -14
  51. package/dist/transport/streamable-client.transport.d.ts +0 -4
  52. package/dist/transport/streamable-client.transport.js +0 -17
  53. package/dist/utils/format-error-message.d.ts +0 -2
  54. package/dist/utils/format-error-message.js +0 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["exactNext","applyMiddlewares","StreamableHTTPClientTransport","StdioClientTransport","assertNonEmpty","packageMetadata.version","Client","#entries","#clientInfo","#clientFactory","#transportFactory","#middleware","#transforms","#lifecycleMiddleware","#principal","#resolvePrincipal","#attributes","#resolveAttributes","#operationIdFactory","#shutdownTimeoutMs","#now","#closed","#assertOpen","#runOperation","#disconnectEntry","#abortConnectAttempt","#entry","#refreshMetadata","#snapshotEntry","#connectAttempt","#closeTask","#lifecycleEpoch","#delegate","#requestWithInputRequired","#assertOperationCurrent","#manageSubscription","withInputRequired","#assertConnectAttemptCurrent","#connectEntry","#establishConnection","#releaseConnectAttempt","#attachClientLifecycle","#timestamp","#performDisconnect","#releaseDisconnect","#closeConnection","#detachConnection","#assertEntryActive","abortReason","#entries","#generations","#create","#closeResource","#maxResources","#idleTtlMs","#now","#onCapacityAvailable","#closed","#assertOpen","#reserve","#awaitLease","#createEntry","#oldestIdleEntry","#retireEntry","#closeTask","#failCreation","#clearIdle","#cancelReservation","#observeBackground","#dropReference","#releaseReference","#scheduleIdle","#armIdleTimer","#notifyCapacity","#releaseLease","#releaseTask"],"sources":["../src/errors.ts","../src/exact-result-profile.ts","../src/middleware.ts","../src/transport.ts","../package.json","../src/runtime.ts","../src/tool-schema.ts","../src/catalog-inspection.ts","../src/lease-manager.ts"],"sourcesContent":["export const MCP_CLIENT_RUNTIME_CLOSED = \"MCP_CLIENT_RUNTIME_CLOSED\" as const;\nexport const MCP_CLIENT_SERVER_EXISTS = \"MCP_CLIENT_SERVER_EXISTS\" as const;\nexport const MCP_CLIENT_SERVER_NOT_FOUND = \"MCP_CLIENT_SERVER_NOT_FOUND\" as const;\nexport const MCP_CLIENT_NOT_CONNECTED = \"MCP_CLIENT_NOT_CONNECTED\" as const;\nexport const MCP_CLIENT_SHUTDOWN_TIMEOUT = \"MCP_CLIENT_SHUTDOWN_TIMEOUT\" as const;\nexport const MCP_CLIENT_LEASE_MANAGER_CLOSED = \"MCP_CLIENT_LEASE_MANAGER_CLOSED\" as const;\nexport const MCP_CLIENT_LEASE_CAPACITY_EXCEEDED = \"MCP_CLIENT_LEASE_CAPACITY_EXCEEDED\" as const;\nexport const MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT =\n\t\"MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT\" as const;\nexport const MCP_CLIENT_LEASE_INVALIDATED = \"MCP_CLIENT_LEASE_INVALIDATED\" as const;\n\nexport type McpClientRuntimeErrorCode =\n\t| typeof MCP_CLIENT_RUNTIME_CLOSED\n\t| typeof MCP_CLIENT_SERVER_EXISTS\n\t| typeof MCP_CLIENT_SERVER_NOT_FOUND\n\t| typeof MCP_CLIENT_NOT_CONNECTED\n\t| typeof MCP_CLIENT_SHUTDOWN_TIMEOUT;\n\nexport type McpClientLeaseManagerErrorCode =\n\t| typeof MCP_CLIENT_LEASE_MANAGER_CLOSED\n\t| typeof MCP_CLIENT_LEASE_CAPACITY_EXCEEDED\n\t| typeof MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT\n\t| typeof MCP_CLIENT_LEASE_INVALIDATED;\n\n/** Base error for deterministic registry and lifecycle failures. */\nexport class McpClientRuntimeError extends Error {\n\treadonly code: McpClientRuntimeErrorCode;\n\treadonly serverName?: string;\n\n\tconstructor(code: McpClientRuntimeErrorCode, message: string, serverName?: string) {\n\t\tsuper(message);\n\t\tthis.name = \"McpClientRuntimeError\";\n\t\tthis.code = code;\n\t\tif (serverName !== undefined) this.serverName = serverName;\n\t}\n}\n\n/** Key-free error for deterministic lease-manager admission and lifecycle failures. */\nexport class McpClientLeaseManagerError extends Error {\n\treadonly code: McpClientLeaseManagerErrorCode;\n\n\tconstructor(code: McpClientLeaseManagerErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"McpClientLeaseManagerError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport function runtimeClosedError(): McpClientRuntimeError {\n\treturn new McpClientRuntimeError(\n\t\tMCP_CLIENT_RUNTIME_CLOSED,\n\t\t\"The MCP client runtime is closed and cannot accept new work.\",\n\t);\n}\n\nexport function serverExistsError(serverName: string): McpClientRuntimeError {\n\treturn new McpClientRuntimeError(\n\t\tMCP_CLIENT_SERVER_EXISTS,\n\t\t`An MCP server named ${JSON.stringify(serverName)} is already registered.`,\n\t\tserverName,\n\t);\n}\n\nexport function serverNotFoundError(serverName: string): McpClientRuntimeError {\n\treturn new McpClientRuntimeError(\n\t\tMCP_CLIENT_SERVER_NOT_FOUND,\n\t\t`No MCP server named ${JSON.stringify(serverName)} is registered.`,\n\t\tserverName,\n\t);\n}\n\nexport function clientNotConnectedError(serverName: string): McpClientRuntimeError {\n\treturn new McpClientRuntimeError(\n\t\tMCP_CLIENT_NOT_CONNECTED,\n\t\t`The MCP server ${JSON.stringify(serverName)} is not connected.`,\n\t\tserverName,\n\t);\n}\n\nexport function shutdownTimeoutError(serverName: string, timeoutMs: number): McpClientRuntimeError {\n\treturn new McpClientRuntimeError(\n\t\tMCP_CLIENT_SHUTDOWN_TIMEOUT,\n\t\t`The MCP server ${JSON.stringify(serverName)} connection did not stop within ${String(timeoutMs)}ms.`,\n\t\tserverName,\n\t);\n}\n\nexport function leaseManagerClosedError(): McpClientLeaseManagerError {\n\treturn new McpClientLeaseManagerError(\n\t\tMCP_CLIENT_LEASE_MANAGER_CLOSED,\n\t\t\"The MCP client lease manager is closed and cannot accept new work.\",\n\t);\n}\n\nexport function leaseCapacityExceededError(): McpClientLeaseManagerError {\n\treturn new McpClientLeaseManagerError(\n\t\tMCP_CLIENT_LEASE_CAPACITY_EXCEEDED,\n\t\t\"The MCP client lease manager is at capacity.\",\n\t);\n}\n\nexport function leaseReleaseModeConflictError(): McpClientLeaseManagerError {\n\treturn new McpClientLeaseManagerError(\n\t\tMCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT,\n\t\t\"The existing MCP client resource uses a different release mode.\",\n\t);\n}\n\nexport function leaseInvalidatedError(): McpClientLeaseManagerError {\n\treturn new McpClientLeaseManagerError(\n\t\tMCP_CLIENT_LEASE_INVALIDATED,\n\t\t\"The MCP client lease identity was invalidated before acquisition completed.\",\n\t);\n}\n","import type { RequestMethod } from \"@modelcontextprotocol/client\";\n\nimport type { McpClientOperationInput } from \"./types.ts\";\n\n/**\n * Runtime-owned proof that an operation returns the ordinary official result.\n * A method string alone is insufficient because custom-schema, manual-MRTR,\n * and managed-subscription APIs deliberately use different result contracts.\n */\nconst exactResultMethods = new WeakMap<McpClientOperationInput, RequestMethod>();\n\nexport function markExactMcpClientResult(\n\tinput: McpClientOperationInput,\n\tmethod: RequestMethod,\n): void {\n\tif (input.method !== method) {\n\t\tthrow new TypeError(\"The exact client result profile must match the operation method.\");\n\t}\n\texactResultMethods.set(input, method);\n}\n\nexport function hasExactMcpClientResult(\n\tinput: McpClientOperationInput,\n\tmethod: RequestMethod,\n): boolean {\n\treturn exactResultMethods.get(input) === method;\n}\n","import type { RequestMethod } from \"@modelcontextprotocol/client\";\nimport {\n\tcreateMcpPassthroughMiddleware,\n\ttype McpOperation,\n\ttype McpOperationNext,\n} from \"@nest-mcp/core\";\n\nimport { hasExactMcpClientResult } from \"./exact-result-profile.ts\";\nimport type {\n\tMcpClientMiddleware,\n\tMcpClientOperationContext,\n\tMcpClientOperationInput,\n\tMcpClientPassthroughMiddleware,\n\tMcpClientRequestMethod,\n\tMcpClientTransform,\n\tMcpClientTransformInput,\n\tMcpClientTransformResult,\n} from \"./types.ts\";\n\nconst exactClientTransforms = new WeakSet<object>();\n\ntype SingleValueConstraint<Value, Whole = Value> = Value extends unknown\n\t? [Whole] extends [Value]\n\t\t? unknown\n\t\t: never\n\t: never;\n\n/**\n * Defines a transform for one ordinary official request/result pair.\n *\n * Runtime-owned custom-schema, manual-MRTR, input-required, and managed\n * subscription operations are intentionally not dispatched to this helper,\n * even when they share the same protocol method string.\n */\nexport function defineMcpClientTransform<\n\tconst Method extends McpClientRequestMethod,\n\tPrincipal = unknown,\n>(\n\tmethod: Method & SingleValueConstraint<Method>,\n\ttransform: McpClientTransform<Method, Principal>,\n): McpClientMiddleware<Principal> {\n\tassertRequestMethod(method);\n\tif (typeof transform !== \"function\") {\n\t\tthrow new TypeError(\"client transform must be a function.\");\n\t}\n\n\tconst middleware: McpClientMiddleware<Principal> = async (operation, next) => {\n\t\tif (!isExactRequestOperation<Method, Principal>(operation, method)) return next();\n\n\t\toperation.context.signal.throwIfAborted();\n\t\t// This adapter is the sole bridge from the intentionally result-erased\n\t\t// shared chain to the runtime-owned exact-result profile above.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\tconst exactNext = next as McpOperationNext<McpClientTransformResult<Method>>;\n\t\tconst result = await transform(operation, exactNext);\n\t\toperation.context.signal.throwIfAborted();\n\t\treturn result;\n\t};\n\texactClientTransforms.add(middleware);\n\treturn middleware;\n}\n\n/** @internal Runtime partitioning keeps exact continuations downstream of broad middleware. */\nexport function isExactMcpClientTransform<Principal>(\n\tmiddleware: McpClientMiddleware<Principal>,\n): boolean {\n\treturn exactClientTransforms.has(middleware);\n}\n\n/**\n * Binds provider-owned middleware without erasing exact-transform identity.\n *\n * Exact transforms carry runtime-only identity used to keep their typed\n * continuation behind broad middleware. Since `Function.bind()` creates a new\n * function, exact transforms must remain unchanged; their defining adapter\n * already closes over the supplied transform callback.\n */\nexport function bindMcpClientMiddleware<Principal>(\n\tmiddleware: McpClientMiddleware<Principal>,\n\treceiver: object,\n): McpClientMiddleware<Principal> {\n\treturn isExactMcpClientTransform(middleware) ? middleware : middleware.bind(receiver);\n}\n\n/**\n * Creates client middleware that always returns the exact downstream result.\n * The callback can run before and after `next()`, but cannot inspect, replace,\n * or swallow a method-specific result.\n */\nexport function createMcpClientPassthroughMiddleware<Principal = unknown>(\n\tmiddleware: McpClientPassthroughMiddleware<Principal>,\n): McpClientMiddleware<Principal> {\n\treturn createMcpPassthroughMiddleware<\n\t\tMcpClientOperationInput,\n\t\tunknown,\n\t\tMcpClientOperationContext<Principal>\n\t>(middleware);\n}\n\nfunction isExactRequestOperation<Method extends McpClientRequestMethod, Principal>(\n\toperation: McpOperation<McpClientOperationInput, McpClientOperationContext<Principal>>,\n\tmethod: Method,\n): operation is McpOperation<\n\tMcpClientTransformInput<Method>,\n\tMcpClientOperationContext<Principal>\n> {\n\treturn (\n\t\toperation.input.method === method &&\n\t\toperation.context.operation.kind === \"request\" &&\n\t\toperation.context.operation.name === method &&\n\t\thasExactMcpClientResult(operation.input, method)\n\t);\n}\n\nfunction assertRequestMethod(method: RequestMethod): void {\n\tif (typeof method !== \"string\" || method.trim().length === 0) {\n\t\tthrow new TypeError(\"client transform method must be a non-empty string.\");\n\t}\n}\n","import {\n\tStreamableHTTPClientTransport,\n\tapplyMiddlewares,\n\ttype AuthProvider,\n\ttype FetchLike,\n\ttype Middleware,\n\ttype OAuthClientProvider,\n\ttype StreamableHTTPClientTransportOptions,\n\ttype Transport,\n} from \"@modelcontextprotocol/client\";\nimport {\n\tStdioClientTransport,\n\ttype StdioServerParameters,\n} from \"@modelcontextprotocol/client/stdio\";\nimport type { MaybePromise } from \"@nest-mcp/core\";\n\nexport interface McpHttpClientTransportDefinition {\n\treadonly kind: \"http\";\n\treadonly url: string | URL;\n\t/** Passed directly to the official Streamable HTTP transport. */\n\treadonly authProvider?: AuthProvider | OAuthClientProvider;\n\t/** Base fetch implementation wrapped by `middleware`, when supplied. */\n\treadonly fetch?: FetchLike;\n\t/** Official fetch middleware composed with `applyMiddlewares`. */\n\treadonly middleware?: readonly Middleware[];\n\treadonly requestInit?: RequestInit;\n\treadonly options?: Omit<\n\t\tStreamableHTTPClientTransportOptions,\n\t\t\"authProvider\" | \"fetch\" | \"requestInit\"\n\t>;\n}\n\nexport interface McpStdioClientTransportDefinition {\n\treadonly kind: \"stdio\";\n\treadonly command: string;\n\treadonly args?: readonly string[];\n\treadonly env?: Readonly<Record<string, string>>;\n\treadonly stderr?: StdioServerParameters[\"stderr\"];\n\treadonly cwd?: string;\n\treadonly maxBufferSize?: number;\n}\n\nexport type McpClientTransportDefinition =\n\tMcpHttpClientTransportDefinition | McpStdioClientTransportDefinition;\n\nexport interface McpClientTransportFactoryContext {\n\treadonly serverName: string;\n\treadonly signal: AbortSignal;\n}\n\n/** Injectable seam for custom, in-memory, and test transports. */\nexport interface McpClientTransportFactory {\n\tcreateTransport(\n\t\tdefinition: McpClientTransportDefinition,\n\t\tcontext: McpClientTransportFactoryContext,\n\t): MaybePromise<Transport>;\n}\n\n/** Applies the official SDK's fetch-middleware composition semantics. */\nexport function composeMcpFetchMiddleware(\n\tmiddleware: readonly Middleware[],\n\tbaseFetch: FetchLike = defaultFetch,\n): FetchLike {\n\treturn applyMiddlewares(...middleware)(baseFetch);\n}\n\n/** Creates the official MCP v2 Streamable HTTP client transport. */\nexport function createMcpHttpClientTransport(\n\tdefinition: McpHttpClientTransportDefinition,\n): StreamableHTTPClientTransport {\n\tconst url = normalizeHttpUrl(definition.url);\n\tconst middleware = definition.middleware ?? [];\n\tvalidateMiddleware(middleware);\n\n\tconst wrappedFetch =\n\t\tmiddleware.length === 0\n\t\t\t? definition.fetch\n\t\t\t: composeMcpFetchMiddleware(middleware, definition.fetch ?? defaultFetch);\n\tconst options: StreamableHTTPClientTransportOptions = {\n\t\t...definition.options,\n\t\t...(definition.authProvider === undefined ? {} : { authProvider: definition.authProvider }),\n\t\t...(wrappedFetch === undefined ? {} : { fetch: wrappedFetch }),\n\t\t...(definition.requestInit === undefined ? {} : { requestInit: definition.requestInit }),\n\t};\n\n\treturn new StreamableHTTPClientTransport(url, options);\n}\n\n/** Creates the official Node.js stdio transport. */\nexport function createMcpStdioClientTransport(\n\tdefinition: McpStdioClientTransportDefinition,\n): StdioClientTransport {\n\tassertNonEmpty(definition.command, \"stdio command\");\n\tconst parameters: StdioServerParameters = {\n\t\tcommand: definition.command,\n\t\t...(definition.args === undefined ? {} : { args: [...definition.args] }),\n\t\t...(definition.env === undefined ? {} : { env: { ...definition.env } }),\n\t\t...(definition.stderr === undefined ? {} : { stderr: definition.stderr }),\n\t\t...(definition.cwd === undefined ? {} : { cwd: definition.cwd }),\n\t\t...(definition.maxBufferSize === undefined ? {} : { maxBufferSize: definition.maxBufferSize }),\n\t};\n\treturn new StdioClientTransport(parameters);\n}\n\n/** Creates one of the official transports from a discriminated definition. */\nexport function createMcpClientTransport(\n\tdefinition: McpClientTransportDefinition,\n): StreamableHTTPClientTransport | StdioClientTransport {\n\tswitch (definition.kind) {\n\t\tcase \"http\":\n\t\t\treturn createMcpHttpClientTransport(definition);\n\t\tcase \"stdio\":\n\t\t\treturn createMcpStdioClientTransport(definition);\n\t\tdefault:\n\t\t\tthrow new TypeError(\"MCP client transport kind must be http or stdio.\");\n\t}\n}\n\n/** Stateless transport factory used by runtimes that do not inject a custom factory. */\nexport const defaultMcpClientTransportFactory: McpClientTransportFactory = Object.freeze({\n\tcreateTransport(definition: McpClientTransportDefinition): Transport {\n\t\treturn createMcpClientTransport(definition);\n\t},\n});\n\nconst defaultFetch: FetchLike = (url, init) => globalThis.fetch(url, init);\n\nfunction normalizeHttpUrl(value: string | URL): URL {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n\t\tthrow new TypeError(\"MCP Streamable HTTP URLs must use http: or https:.\");\n\t}\n\treturn url;\n}\n\nfunction validateMiddleware(middleware: readonly Middleware[]): void {\n\tfor (const [index, entry] of middleware.entries()) {\n\t\tif (typeof entry !== \"function\") {\n\t\t\tthrow new TypeError(`HTTP middleware[${String(index)}] must be a function.`);\n\t\t}\n\t}\n}\n\nfunction assertNonEmpty(value: string, field: string): void {\n\tif (value.trim().length === 0) throw new TypeError(`${field} must be a non-empty string.`);\n}\n","","import { randomUUID } from \"node:crypto\";\n\nimport {\n\tClient,\n\ttype CacheableRequestOptions,\n\ttype CallToolRequest,\n\ttype CallToolRequestOptions,\n\ttype CallToolResult,\n\ttype ClientOptions,\n\ttype CompleteRequest,\n\ttype CompleteResult,\n\ttype ConnectOptions,\n\ttype DiscoverResult,\n\ttype EmptyResult,\n\ttype GetPromptRequest,\n\ttype GetPromptResult,\n\ttype Implementation,\n\ttype InputRequiredResult,\n\ttype InputResponses,\n\ttype ListPromptsRequest,\n\ttype ListPromptsResult,\n\ttype ListResourcesRequest,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesRequest,\n\ttype ListResourceTemplatesResult,\n\ttype ListToolsRequest,\n\ttype ListToolsResult,\n\ttype LoggingLevel,\n\ttype McpSubscription,\n\ttype Notification,\n\ttype NotificationOptions,\n\ttype PriorDiscovery,\n\ttype ReadResourceRequest,\n\ttype ReadResourceResult,\n\ttype Request,\n\ttype RequestMethod,\n\ttype RequestOptions,\n\ttype ResultTypeMap,\n\ttype StandardSchemaV1,\n\ttype SubscribeRequest,\n\ttype SubscriptionFilter,\n\ttype Transport,\n\ttype UnsubscribeRequest,\n\twithInputRequired,\n} from \"@modelcontextprotocol/client\";\nimport {\n\tcomposeMcpMiddleware,\n\tcreateMcpLifecycleMiddleware,\n\tcreateMcpOperation,\n\tcreateMcpOperationContext,\n\ttoMcpErrorDetails,\n\ttype McpAttributes,\n} from \"@nest-mcp/core\";\n\nimport {\n\tclientNotConnectedError,\n\truntimeClosedError,\n\tserverExistsError,\n\tserverNotFoundError,\n\tshutdownTimeoutError,\n} from \"./errors.ts\";\nimport { markExactMcpClientResult } from \"./exact-result-profile.ts\";\nimport { isExactMcpClientTransform } from \"./middleware.ts\";\nimport { defaultMcpClientTransportFactory } from \"./transport.ts\";\nimport type {\n\tMcpClientConnectionSnapshot,\n\tMcpClientConnectionState,\n\tMcpClientMiddleware,\n\tMcpClientMrtrMethod,\n\tMcpClientMrtrRequest,\n\tMcpClientMrtrRequestOptions,\n\tMcpClientMrtrResult,\n\tMcpClientOperationContext,\n\tMcpClientOperationInput,\n\tMcpClientProtocolRequest,\n\tMcpClientRuntimeOptions,\n\tMcpClientServerDefinition,\n\tMcpClientSubscription,\n\tMcpSdkClientFactory,\n} from \"./types.ts\";\nimport packageMetadata from \"../package.json\" with { type: \"json\" };\n\nconst DEFAULT_CLIENT_INFO = Object.freeze({\n\tname: \"@nest-mcp/client\",\n\tversion: packageMetadata.version,\n}) satisfies Implementation;\n\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\nconst MRTR_CAPABILITY = Object.freeze({\n\t\"prompts/get\": \"prompts\",\n\t\"resources/read\": \"resources\",\n\t\"tools/call\": \"tools\",\n}) satisfies Readonly<Record<McpClientMrtrMethod, string>>;\n\ninterface ConnectionMetadata {\n\tsessionId: string | undefined;\n\tnegotiatedProtocolVersion: string | undefined;\n\tprotocolEra: McpClientConnectionSnapshot[\"protocolEra\"] | undefined;\n\tserverInfo: McpClientConnectionSnapshot[\"serverInfo\"] | undefined;\n\tserverCapabilities: McpClientConnectionSnapshot[\"serverCapabilities\"] | undefined;\n\tinstructions: string | undefined;\n\tdiscoverResult: DiscoverResult | undefined;\n}\n\ninterface RegistryEntry {\n\treadonly definition: McpClientServerDefinition;\n\tstate: McpClientConnectionState;\n\tprior: PriorDiscovery | undefined;\n\tclient: Client | undefined;\n\ttransport: Transport | undefined;\n\tconnectTask: Promise<EstablishedConnection> | undefined;\n\tconnectAbortController: AbortController | undefined;\n\tconnectAttemptToken: symbol | undefined;\n\tconnectDetachment: ConnectAttemptDetachment | undefined;\n\tconnectUnlinkCallerSignal: (() => void) | undefined;\n\tdisconnectTask: Promise<void> | undefined;\n\tdisconnectToken: symbol | undefined;\n\tconnectedAt: number | undefined;\n\tdisconnectedAt: number | undefined;\n\tlastError: ReturnType<typeof toMcpErrorDetails> | undefined;\n\treadonly metadata: ConnectionMetadata;\n\treadonly subscriptions: Set<ManagedSubscription>;\n\tautoOpenedSubscription: McpClientSubscription | undefined;\n\tconnectionGeneration: number;\n\tconnectionToken: symbol | undefined;\n\tretired: boolean;\n}\n\ninterface ConnectAttemptDetachment {\n\treadonly promise: Promise<never>;\n\tdetach(error: unknown): void;\n}\n\ninterface EstablishedConnection {\n\treadonly client: Client;\n\treadonly generation: number;\n\treadonly connectionToken: symbol;\n}\n\ninterface ConnectAttemptResult {\n\treadonly client: Client;\n\treadonly generation: number;\n\t/** Present only when this caller atomically created the shared connection task. */\n\treadonly ownedConnectionToken?: symbol;\n}\n\ninterface OperationDescriptor {\n\treadonly method: string;\n\t/** Runtime-owned proof that the ordinary ResultTypeMap entry is returned. */\n\treadonly exactResultMethod?: RequestMethod;\n\treadonly kind?: \"request\" | \"notification\";\n\treadonly capability?: string;\n\treadonly params?: unknown;\n\treadonly options?: unknown;\n\treadonly signal?: AbortSignal | undefined;\n}\n\ninterface ManagedSubscription {\n\treadonly sdk: McpSubscription;\n\treadonly handle: McpClientSubscription;\n}\n\nconst defaultSdkClientFactory = Object.freeze({\n\tcreateClient(clientInfo: Implementation, options: ClientOptions): Client {\n\t\treturn new Client(clientInfo, options);\n\t},\n}) satisfies McpSdkClientFactory;\n\n/**\n * Owns a registry of named MCP servers and their independent official Client\n * instances. One runtime may safely connect, disconnect, and inspect many\n * upstreams while applying a shared middleware and lifecycle policy.\n */\nexport class McpClientRuntime<Principal = unknown> implements AsyncDisposable {\n\treadonly #entries = new Map<string, RegistryEntry>();\n\treadonly #clientInfo: Implementation;\n\treadonly #clientFactory: McpSdkClientFactory;\n\treadonly #transportFactory: NonNullable<McpClientRuntimeOptions[\"transportFactory\"]>;\n\treadonly #middleware: readonly McpClientMiddleware<Principal>[];\n\treadonly #transforms: readonly McpClientMiddleware<Principal>[];\n\treadonly #lifecycleMiddleware: McpClientMiddleware<Principal> | undefined;\n\treadonly #principal: Principal | undefined;\n\treadonly #resolvePrincipal: McpClientRuntimeOptions<Principal>[\"resolvePrincipal\"];\n\treadonly #attributes: McpAttributes;\n\treadonly #resolveAttributes: McpClientRuntimeOptions<Principal>[\"resolveAttributes\"];\n\treadonly #operationIdFactory: () => string;\n\treadonly #shutdownTimeoutMs: number;\n\treadonly #now: () => number;\n\t#closed = false;\n\t#lifecycleEpoch = 0;\n\t#closeTask: Promise<void> | undefined;\n\n\tconstructor(options: McpClientRuntimeOptions<Principal> = {}) {\n\t\tassertPositiveFinite(\n\t\t\toptions.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS,\n\t\t\t\"shutdownTimeoutMs\",\n\t\t);\n\t\tthis.#clientInfo = Object.freeze({ ...(options.clientInfo ?? DEFAULT_CLIENT_INFO) });\n\t\tthis.#clientFactory = options.clientFactory ?? defaultSdkClientFactory;\n\t\tthis.#transportFactory = options.transportFactory ?? defaultMcpClientTransportFactory;\n\t\tthis.#principal = options.principal;\n\t\tthis.#resolvePrincipal = options.resolvePrincipal;\n\t\tthis.#attributes = Object.freeze({ ...options.attributes });\n\t\tthis.#resolveAttributes = options.resolveAttributes;\n\t\tthis.#operationIdFactory = options.operationIdFactory ?? randomUUID;\n\t\tthis.#shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\t\tthis.#now = options.now ?? Date.now;\n\n\t\tconst middleware = [...(options.middleware ?? [])];\n\t\tthis.#middleware = Object.freeze(\n\t\t\tmiddleware.filter((entry) => !isExactMcpClientTransform(entry)),\n\t\t);\n\t\tthis.#transforms = Object.freeze(\n\t\t\tmiddleware.filter((entry) => isExactMcpClientTransform(entry)),\n\t\t);\n\t\tthis.#lifecycleMiddleware =\n\t\t\toptions.observer === undefined\n\t\t\t\t? undefined\n\t\t\t\t: createMcpLifecycleMiddleware<\n\t\t\t\t\t\tMcpClientOperationInput,\n\t\t\t\t\t\tunknown,\n\t\t\t\t\t\tMcpClientOperationContext<Principal>\n\t\t\t\t\t>(options.observer, options.lifecycle);\n\n\t\tfor (const definition of options.servers ?? []) this.register(definition);\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed;\n\t}\n\n\tget size(): number {\n\t\treturn this.names().length;\n\t}\n\n\tregister(definition: McpClientServerDefinition): this {\n\t\tthis.#assertOpen();\n\t\tconst normalized = normalizeServerDefinition(definition);\n\t\tif (this.#entries.has(normalized.name)) throw serverExistsError(normalized.name);\n\t\tthis.#entries.set(normalized.name, createRegistryEntry(normalized));\n\t\treturn this;\n\t}\n\n\tasync unregister(serverName: string): Promise<boolean> {\n\t\tthis.#assertOpen();\n\t\tconst entry = this.#entries.get(serverName);\n\t\tif (entry === undefined || entry.retired) return false;\n\t\tentry.retired = true;\n\t\ttry {\n\t\t\tconst operation = this.#runOperation(\n\t\t\t\tentry,\n\t\t\t\t{ method: \"runtime/disconnect\" },\n\t\t\t\t() => this.#disconnectEntry(entry),\n\t\t\t\ttrue,\n\t\t\t);\n\t\t\tthis.#abortConnectAttempt(entry, serverNotFoundError(serverName));\n\t\t\tawait operation;\n\t\t} finally {\n\t\t\t// Identity-aware removal never deletes a replacement entry, should a\n\t\t\t// future registry operation allow one before old cleanup settles.\n\t\t\tif (this.#entries.get(serverName) === entry) this.#entries.delete(serverName);\n\t\t}\n\t\treturn true;\n\t}\n\n\thas(serverName: string): boolean {\n\t\treturn this.#entries.get(serverName)?.retired === false;\n\t}\n\n\tnames(): readonly string[] {\n\t\treturn Object.freeze(\n\t\t\t[...this.#entries].filter(([, entry]) => !entry.retired).map(([serverName]) => serverName),\n\t\t);\n\t}\n\n\tgetDefinition(serverName: string): McpClientServerDefinition {\n\t\treturn this.#entry(serverName).definition;\n\t}\n\n\tsetPriorDiscovery(serverName: string, prior: PriorDiscovery | undefined): this {\n\t\tthis.#entry(serverName).prior = prior;\n\t\treturn this;\n\t}\n\n\t/** Returns a persistable current verdict without automatically reusing it. */\n\tgetPriorDiscovery(serverName: string): PriorDiscovery | undefined {\n\t\tconst entry = this.#entry(serverName);\n\t\tthis.#refreshMetadata(entry);\n\t\tif (entry.metadata.discoverResult !== undefined) {\n\t\t\treturn Object.freeze({ kind: \"modern\", discover: entry.metadata.discoverResult });\n\t\t}\n\t\tif (entry.metadata.protocolEra === \"legacy\") return Object.freeze({ kind: \"legacy\" });\n\t\treturn entry.prior;\n\t}\n\n\tgetClient(serverName: string): Client | undefined {\n\t\tconst entry = this.#entries.get(serverName);\n\t\treturn entry?.retired === false && entry.state === \"connected\" ? entry.client : undefined;\n\t}\n\n\trequireClient(serverName: string): Client {\n\t\tconst client = this.getClient(serverName);\n\t\tif (client === undefined) throw clientNotConnectedError(serverName);\n\t\treturn client;\n\t}\n\n\tsnapshot(): readonly McpClientConnectionSnapshot[];\n\tsnapshot(serverName: string): McpClientConnectionSnapshot;\n\tsnapshot(\n\t\tserverName?: string,\n\t): McpClientConnectionSnapshot | readonly McpClientConnectionSnapshot[] {\n\t\tif (serverName !== undefined) return this.#snapshotEntry(this.#entry(serverName));\n\t\treturn Object.freeze(\n\t\t\t[...this.#entries.values()]\n\t\t\t\t.filter((entry) => !entry.retired)\n\t\t\t\t.map((entry) => this.#snapshotEntry(entry)),\n\t\t);\n\t}\n\n\tasync connect(serverName: string, options?: ConnectOptions): Promise<Client> {\n\t\treturn (await this.#connectAttempt(serverName, options)).client;\n\t}\n\n\tasync connectAll(\n\t\toptions: Readonly<Record<string, ConnectOptions | undefined>> = {},\n\t): Promise<ReadonlyMap<string, Client>> {\n\t\tthis.#assertOpen();\n\t\tconst attempts = this.names().map((name) => {\n\t\t\tconst entry = this.#entry(name);\n\t\t\treturn { name, entry, promise: this.#connectAttempt(name, options[name]) };\n\t\t});\n\t\tconst settled = await Promise.allSettled(attempts.map((attempt) => attempt.promise));\n\t\tconst connectFailures = settled\n\t\t\t.filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n\t\t\t.map((result) => result.reason as unknown);\n\n\t\tif (connectFailures.length > 0) {\n\t\t\tconst rollback = attempts.flatMap((attempt, index) => {\n\t\t\t\tconst result = settled[index];\n\t\t\t\tif (\n\t\t\t\t\tresult?.status !== \"fulfilled\" ||\n\t\t\t\t\tresult.value.ownedConnectionToken === undefined ||\n\t\t\t\t\tattempt.entry.state !== \"connected\" ||\n\t\t\t\t\tattempt.entry.client !== result.value.client ||\n\t\t\t\t\tattempt.entry.connectionGeneration !== result.value.generation ||\n\t\t\t\t\tattempt.entry.connectionToken !== result.value.ownedConnectionToken\n\t\t\t\t) {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn [\n\t\t\t\t\tthis.#runOperation(\n\t\t\t\t\t\tattempt.entry,\n\t\t\t\t\t\t{ method: \"runtime/disconnect\" },\n\t\t\t\t\t\t() => this.#disconnectEntry(attempt.entry),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t),\n\t\t\t\t];\n\t\t\t});\n\t\t\tconst rollbackSettled = await Promise.allSettled(rollback);\n\t\t\tconst rollbackFailures = rollbackSettled\n\t\t\t\t.filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n\t\t\t\t.map((result) => result.reason as unknown);\n\t\t\tthrowFailures(\n\t\t\t\t[...connectFailures, ...rollbackFailures],\n\t\t\t\t\"One or more MCP clients failed to connect, and rollback may also have failed.\",\n\t\t\t);\n\t\t}\n\n\t\tconst connected = new Map<string, Client>();\n\t\tfor (const [index, attempt] of attempts.entries()) {\n\t\t\tconst result = settled[index];\n\t\t\tif (result?.status === \"fulfilled\") connected.set(attempt.name, result.value.client);\n\t\t}\n\t\treturn connected;\n\t}\n\n\tasync disconnect(serverName: string): Promise<void> {\n\t\tconst entry = this.#entry(serverName, true);\n\t\tconst operation = this.#runOperation(\n\t\t\tentry,\n\t\t\t{ method: \"runtime/disconnect\" },\n\t\t\t() => this.#disconnectEntry(entry),\n\t\t\ttrue,\n\t\t);\n\t\tthis.#abortConnectAttempt(entry, connectionAbortedError(serverName));\n\t\tawait operation;\n\t}\n\n\tasync disconnectAll(): Promise<void> {\n\t\tconst settled = await Promise.allSettled(\n\t\t\t[...this.#entries.keys()].map((name) => this.disconnect(name)),\n\t\t);\n\t\tthrowSettledFailures(settled, \"One or more MCP clients failed to disconnect.\");\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#closed = true;\n\t\tthis.#lifecycleEpoch += 1;\n\t\t// Assign the shared promise before executing cleanup. A resolver,\n\t\t// observer, or middleware invoked by disconnectAll may re-enter close().\n\t\tthis.#closeTask = Promise.resolve().then(() => this.disconnectAll());\n\t\tfor (const entry of this.#entries.values()) {\n\t\t\tthis.#abortConnectAttempt(entry, runtimeClosedError());\n\t\t}\n\t\treturn this.#closeTask;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\tasync discover(serverName: string, options?: RequestOptions): Promise<DiscoverResult> {\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\tconst result = await this.#delegate<DiscoverResult>(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"server/discover\",\n\t\t\t\texactResultMethod: \"server/discover\",\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.discover(stableOptions),\n\t\t);\n\t\tthis.#refreshMetadata(this.#entry(serverName));\n\t\treturn result;\n\t}\n\n\t/** Checks that a connected server is responsive. */\n\tping(serverName: string, options?: RequestOptions): Promise<EmptyResult> {\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"ping\",\n\t\t\t\texactResultMethod: \"ping\",\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.ping(stableOptions),\n\t\t);\n\t}\n\n\t/** Sends any official method-keyed request through runtime policy and lifecycle hooks. */\n\trequest<const RequestValue extends McpClientProtocolRequest>(\n\t\tserverName: string,\n\t\trequest: RequestValue,\n\t\toptions: RequestOptions & { readonly allowInputRequired: true },\n\t): Promise<\n\t\tResultTypeMap[RequestValue[\"method\"]] | InputRequiredResultForMethod<RequestValue[\"method\"]>\n\t>;\n\trequest<const RequestValue extends McpClientProtocolRequest>(\n\t\tserverName: string,\n\t\trequest: RequestValue,\n\t\toptions?: RequestOptions & { readonly allowInputRequired?: false | undefined },\n\t): Promise<ResultTypeMap[RequestValue[\"method\"]]>;\n\trequest<const RequestValue extends McpClientProtocolRequest>(\n\t\tserverName: string,\n\t\trequest: RequestValue,\n\t\toptions?: RequestOptions,\n\t): Promise<\n\t\tResultTypeMap[RequestValue[\"method\"]] | InputRequiredResultForMethod<RequestValue[\"method\"]>\n\t>;\n\trequest<const RequestValue extends McpClientProtocolRequest>(\n\t\tserverName: string,\n\t\trequest: RequestValue,\n\t\toptions?: RequestOptions,\n\t): Promise<ResultTypeMap[RequestValue[\"method\"]] | InputRequiredResult> {\n\t\tconst stableRequest = snapshotProtocolValue(request, \"MCP client request\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: stableRequest.method,\n\t\t\t\texactResultMethod: stableRequest.method,\n\t\t\t\tparams: stableRequest.params,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.request(toOfficialProtocolRequest(stableRequest), stableOptions),\n\t\t);\n\t}\n\n\t/** Sends a custom extension request and validates its result with a Standard Schema. */\n\trequestWithSchema<Schema extends StandardSchemaV1>(\n\t\tserverName: string,\n\t\trequest: Request,\n\t\tresultSchema: Schema,\n\t\toptions?: RequestOptions,\n\t): Promise<StandardSchemaV1.InferOutput<Schema>> {\n\t\tconst stableRequest = snapshotProtocolValue(request, \"MCP client extension request\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: stableRequest.method,\n\t\t\t\tparams: stableRequest.params,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.request(stableRequest, resultSchema, stableOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Sends a modern multi-round-trip request in manual mode.\n\t *\n\t * A complete response is validated by `resultSchema`; an `input_required`\n\t * response is returned as the official typed continuation payload.\n\t */\n\trequestWithInputRequired<Method extends McpClientMrtrMethod, Schema extends StandardSchemaV1>(\n\t\tserverName: string,\n\t\trequest: McpClientMrtrRequest<Method>,\n\t\tresultSchema: Schema,\n\t\toptions?: McpClientMrtrRequestOptions,\n\t): Promise<McpClientMrtrResult<Schema>> {\n\t\treturn this.#requestWithInputRequired(serverName, request, resultSchema, options);\n\t}\n\n\t/**\n\t * Resumes one manual modern multi-round-trip round through a fresh official\n\t * request. The server-owned `requestState` is echoed without interpretation.\n\t * Only this round's `inputResponses` are included.\n\t */\n\tresumeInputRequired<Method extends McpClientMrtrMethod, Schema extends StandardSchemaV1>(\n\t\tserverName: string,\n\t\toriginalRequest: McpClientMrtrRequest<Method>,\n\t\tinputRequired: InputRequiredResult,\n\t\tinputResponses: InputResponses,\n\t\tresultSchema: Schema,\n\t\toptions?: McpClientMrtrRequestOptions,\n\t): Promise<McpClientMrtrResult<Schema>> {\n\t\tconst stableOriginalRequest = snapshotProtocolValue(\n\t\t\toriginalRequest,\n\t\t\t\"MCP input-required original request\",\n\t\t);\n\t\tconst stableInputResponses = snapshotProtocolValue(\n\t\t\tinputResponses,\n\t\t\t\"MCP input-required responses\",\n\t\t);\n\t\tconst params: Record<string, unknown> = { ...stableOriginalRequest.params };\n\t\t// A caller may retain the immutable original across rounds. Never carry\n\t\t// continuation material from an earlier round into the next one.\n\t\tReflect.deleteProperty(params, \"inputResponses\");\n\t\tReflect.deleteProperty(params, \"requestState\");\n\t\tif (Object.keys(stableInputResponses).length > 0) {\n\t\t\tparams.inputResponses = stableInputResponses;\n\t\t}\n\t\tif (inputRequired.requestState !== undefined) {\n\t\t\tparams.requestState = inputRequired.requestState;\n\t\t}\n\t\treturn this.#requestWithInputRequired(\n\t\t\tserverName,\n\t\t\t{ method: stableOriginalRequest.method, params },\n\t\t\tresultSchema,\n\t\t\toptions,\n\t\t);\n\t}\n\n\t/** Sends an official notification through runtime policy and lifecycle hooks. */\n\tnotification(\n\t\tserverName: string,\n\t\tnotification: Notification,\n\t\toptions?: NotificationOptions,\n\t): Promise<void> {\n\t\tconst stableNotification = snapshotProtocolValue(notification, \"MCP client notification\");\n\t\tconst stableOptions = snapshotProtocolValue(options, \"MCP notification options\");\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: stableNotification.method,\n\t\t\t\tkind: \"notification\",\n\t\t\t\tparams: stableNotification.params,\n\t\t\t\toptions: stableOptions,\n\t\t\t},\n\t\t\t(client) => client.notification(stableNotification, stableOptions),\n\t\t);\n\t}\n\n\t/** Requests argument suggestions for a prompt or resource template. */\n\tcomplete(\n\t\tserverName: string,\n\t\tparams: CompleteRequest[\"params\"],\n\t\toptions?: RequestOptions,\n\t): Promise<CompleteResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP completion parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"completion/complete\",\n\t\t\t\texactResultMethod: \"completion/complete\",\n\t\t\t\tcapability: \"completions\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.complete(stableParams, stableOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Sets the minimum server log level on protocol eras that support it.\n\t *\n\t * @deprecated Deprecated by MCP 2026-07-28. Prefer stderr or OpenTelemetry.\n\t */\n\tsetLoggingLevel(\n\t\tserverName: string,\n\t\tlevel: LoggingLevel,\n\t\toptions?: RequestOptions,\n\t): Promise<EmptyResult> {\n\t\tconst stableParams = snapshotProtocolValue({ level }, \"MCP logging/setLevel parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"logging/setLevel\",\n\t\t\t\texactResultMethod: \"logging/setLevel\",\n\t\t\t\tcapability: \"logging\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.setLoggingLevel(stableParams.level, stableOptions),\n\t\t);\n\t}\n\n\tlistTools(\n\t\tserverName: string,\n\t\tparams?: ListToolsRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions,\n\t): Promise<ListToolsResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP tools/list parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"tools/list\",\n\t\t\t\texactResultMethod: \"tools/list\",\n\t\t\t\tcapability: \"tools\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.listTools(stableParams, stableOptions),\n\t\t);\n\t}\n\n\tcallTool(\n\t\tserverName: string,\n\t\tparams: CallToolRequest[\"params\"],\n\t\toptions: CallToolRequestOptions & { readonly allowInputRequired: true },\n\t): Promise<CallToolResult | InputRequiredResult>;\n\tcallTool(\n\t\tserverName: string,\n\t\tparams: CallToolRequest[\"params\"],\n\t\toptions?: CallToolRequestOptions & {\n\t\t\treadonly allowInputRequired?: false | undefined;\n\t\t},\n\t): Promise<CallToolResult>;\n\tcallTool(\n\t\tserverName: string,\n\t\tparams: CallToolRequest[\"params\"],\n\t\toptions: CallToolRequestOptions,\n\t): Promise<CallToolResult | InputRequiredResult>;\n\tcallTool(\n\t\tserverName: string,\n\t\tparams: CallToolRequest[\"params\"],\n\t\toptions?: CallToolRequestOptions,\n\t): Promise<CallToolResult | InputRequiredResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP tools/call parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\texactResultMethod: \"tools/call\",\n\t\t\t\tcapability: \"tools\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.callTool(stableParams, stableOptions),\n\t\t);\n\t}\n\n\tlistResources(\n\t\tserverName: string,\n\t\tparams?: ListResourcesRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions,\n\t): Promise<ListResourcesResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP resources/list parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"resources/list\",\n\t\t\t\texactResultMethod: \"resources/list\",\n\t\t\t\tcapability: \"resources\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.listResources(stableParams, stableOptions),\n\t\t);\n\t}\n\n\tlistResourceTemplates(\n\t\tserverName: string,\n\t\tparams?: ListResourceTemplatesRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions,\n\t): Promise<ListResourceTemplatesResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP resources/templates/list parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"resources/templates/list\",\n\t\t\t\texactResultMethod: \"resources/templates/list\",\n\t\t\t\tcapability: \"resources\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.listResourceTemplates(stableParams, stableOptions),\n\t\t);\n\t}\n\n\treadResource(\n\t\tserverName: string,\n\t\tparams: ReadResourceRequest[\"params\"],\n\t\toptions: CacheableRequestOptions & { readonly allowInputRequired: true },\n\t): Promise<ReadResourceResult | InputRequiredResult>;\n\treadResource(\n\t\tserverName: string,\n\t\tparams: ReadResourceRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions & {\n\t\t\treadonly allowInputRequired?: false | undefined;\n\t\t},\n\t): Promise<ReadResourceResult>;\n\treadResource(\n\t\tserverName: string,\n\t\tparams: ReadResourceRequest[\"params\"],\n\t\toptions: CacheableRequestOptions,\n\t): Promise<ReadResourceResult | InputRequiredResult>;\n\treadResource(\n\t\tserverName: string,\n\t\tparams: ReadResourceRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions,\n\t): Promise<ReadResourceResult | InputRequiredResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP resources/read parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"resources/read\",\n\t\t\t\texactResultMethod: \"resources/read\",\n\t\t\t\tcapability: \"resources\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.readResource(stableParams, stableOptions),\n\t\t);\n\t}\n\n\t/** Uses the legacy-era per-resource subscription request. */\n\tsubscribeResource(\n\t\tserverName: string,\n\t\tparams: SubscribeRequest[\"params\"],\n\t\toptions?: RequestOptions,\n\t): Promise<EmptyResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP resources/subscribe parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"resources/subscribe\",\n\t\t\t\texactResultMethod: \"resources/subscribe\",\n\t\t\t\tcapability: \"resources\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.subscribeResource(stableParams, stableOptions),\n\t\t);\n\t}\n\n\t/** Uses the legacy-era per-resource unsubscribe request. */\n\tunsubscribeResource(\n\t\tserverName: string,\n\t\tparams: UnsubscribeRequest[\"params\"],\n\t\toptions?: RequestOptions,\n\t): Promise<EmptyResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP resources/unsubscribe parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"resources/unsubscribe\",\n\t\t\t\texactResultMethod: \"resources/unsubscribe\",\n\t\t\t\tcapability: \"resources\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.unsubscribeResource(stableParams, stableOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Opens a modern change-notification stream and binds it to this runtime's\n\t * connection lifecycle. Register notification handlers in `configureClient`\n\t * before connecting.\n\t */\n\tasync listen(\n\t\tserverName: string,\n\t\tfilter: SubscriptionFilter,\n\t\toptions?: RequestOptions,\n\t): Promise<McpClientSubscription> {\n\t\tconst stableFilter = snapshotProtocolValue(filter, \"MCP subscription filter\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\tconst lifecycleEpoch = this.#lifecycleEpoch;\n\t\tconst entry = this.#entry(serverName);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"subscriptions/listen\",\n\t\t\t\tcapability: \"subscriptions\",\n\t\t\t\tparams: stableFilter,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\tasync (client) => {\n\t\t\t\tconst subscription = await client.listen(stableFilter, stableOptions);\n\t\t\t\ttry {\n\t\t\t\t\tthis.#assertOperationCurrent(entry, lifecycleEpoch);\n\t\t\t\t} catch (entryError) {\n\t\t\t\t\treturn closeUnmanagedSubscription(subscription, entryError);\n\t\t\t\t}\n\t\t\t\treturn this.#manageSubscription(entry, subscription);\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Returns runtime-opened subscription streams for one logical server. */\n\tactiveSubscriptions(serverName: string): readonly McpClientSubscription[] {\n\t\treturn Object.freeze(\n\t\t\t[...this.#entry(serverName).subscriptions].map((subscription) => subscription.handle),\n\t\t);\n\t}\n\n\t/** Returns the runtime-owned stream opened by `ClientOptions.listChanged`, when present. */\n\tgetAutoOpenedSubscription(serverName: string): McpClientSubscription | undefined {\n\t\treturn this.#entry(serverName).autoOpenedSubscription;\n\t}\n\n\tlistPrompts(\n\t\tserverName: string,\n\t\tparams?: ListPromptsRequest[\"params\"],\n\t\toptions?: CacheableRequestOptions,\n\t): Promise<ListPromptsResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP prompts/list parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"prompts/list\",\n\t\t\t\texactResultMethod: \"prompts/list\",\n\t\t\t\tcapability: \"prompts\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.listPrompts(stableParams, stableOptions),\n\t\t);\n\t}\n\n\tgetPrompt(\n\t\tserverName: string,\n\t\tparams: GetPromptRequest[\"params\"],\n\t\toptions: RequestOptions & { readonly allowInputRequired: true },\n\t): Promise<GetPromptResult | InputRequiredResult>;\n\tgetPrompt(\n\t\tserverName: string,\n\t\tparams: GetPromptRequest[\"params\"],\n\t\toptions?: RequestOptions & {\n\t\t\treadonly allowInputRequired?: false | undefined;\n\t\t},\n\t): Promise<GetPromptResult>;\n\tgetPrompt(\n\t\tserverName: string,\n\t\tparams: GetPromptRequest[\"params\"],\n\t\toptions: RequestOptions,\n\t): Promise<GetPromptResult | InputRequiredResult>;\n\tgetPrompt(\n\t\tserverName: string,\n\t\tparams: GetPromptRequest[\"params\"],\n\t\toptions?: RequestOptions,\n\t): Promise<GetPromptResult | InputRequiredResult> {\n\t\tconst stableParams = snapshotProtocolValue(params, \"MCP prompts/get parameters\");\n\t\tconst stableOptions = snapshotRequestOptions(options);\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"prompts/get\",\n\t\t\t\texactResultMethod: \"prompts/get\",\n\t\t\t\tcapability: \"prompts\",\n\t\t\t\tparams: stableParams,\n\t\t\t\toptions: stableOptions,\n\t\t\t\tsignal: stableOptions?.signal,\n\t\t\t},\n\t\t\t(client) => client.getPrompt(stableParams, stableOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Notifies a legacy-era server that the client's roots changed.\n\t *\n\t * @deprecated Deprecated by MCP 2026-07-28. Pass paths through tool inputs,\n\t * resource URIs, or configuration instead.\n\t */\n\tsendRootsListChanged(serverName: string): Promise<void> {\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: \"notifications/roots/list_changed\",\n\t\t\t\tkind: \"notification\",\n\t\t\t\tcapability: \"roots\",\n\t\t\t},\n\t\t\t(client) => client.sendRootsListChanged(),\n\t\t);\n\t}\n\n\t#manageSubscription(\n\t\tentry: RegistryEntry,\n\t\tsdkSubscription: McpSubscription,\n\t): McpClientSubscription {\n\t\tlet closeTask: Promise<void> | undefined;\n\t\tlet settled = false;\n\t\tlet managed: ManagedSubscription;\n\n\t\tconst handle: McpClientSubscription = Object.freeze({\n\t\t\tserverName: entry.definition.name,\n\t\t\thonoredFilter: sdkSubscription.honoredFilter,\n\t\t\tclosed: sdkSubscription.closed,\n\t\t\tclose: () => {\n\t\t\t\tif (settled) return Promise.resolve();\n\t\t\t\tif (closeTask !== undefined) return closeTask;\n\t\t\t\tconst task = this.#runOperation(\n\t\t\t\t\tentry,\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: \"notifications/cancelled\",\n\t\t\t\t\t\tkind: \"notification\",\n\t\t\t\t\t\tcapability: \"subscriptions\",\n\t\t\t\t\t},\n\t\t\t\t\t() => sdkSubscription.close(),\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t\tcloseTask = task;\n\t\t\t\tvoid task.catch(() => {\n\t\t\t\t\tif (closeTask === task) closeTask = undefined;\n\t\t\t\t});\n\t\t\t\treturn task;\n\t\t\t},\n\t\t});\n\t\tmanaged = Object.freeze({ sdk: sdkSubscription, handle });\n\t\tentry.subscriptions.add(managed);\n\t\tvoid sdkSubscription.closed.then(() => {\n\t\t\tsettled = true;\n\t\t\tentry.subscriptions.delete(managed);\n\t\t\tif (entry.autoOpenedSubscription === handle) entry.autoOpenedSubscription = undefined;\n\t\t});\n\t\treturn handle;\n\t}\n\n\t#requestWithInputRequired<Schema extends StandardSchemaV1>(\n\t\tserverName: string,\n\t\trequest: Request & { readonly method: McpClientMrtrMethod },\n\t\tresultSchema: Schema,\n\t\toptions?: McpClientMrtrRequestOptions,\n\t): Promise<McpClientMrtrResult<Schema>> {\n\t\tconst stableRequest = snapshotProtocolValue(request, \"MCP input-required request\");\n\t\tconst requestOptions = snapshotRequestOptions({ ...options, allowInputRequired: true });\n\t\treturn this.#delegate(\n\t\t\tserverName,\n\t\t\t{\n\t\t\t\tmethod: stableRequest.method,\n\t\t\t\tcapability: MRTR_CAPABILITY[stableRequest.method],\n\t\t\t\tparams: stableRequest.params,\n\t\t\t\toptions: requestOptions,\n\t\t\t\tsignal: requestOptions.signal,\n\t\t\t},\n\t\t\t(client) => client.request(stableRequest, withInputRequired(resultSchema), requestOptions),\n\t\t);\n\t}\n\n\t#connectAttempt(\n\t\tserverName: string,\n\t\toptions: ConnectOptions | undefined,\n\t): Promise<ConnectAttemptResult> {\n\t\tthis.#assertOpen();\n\t\tconst lifecycleEpoch = this.#lifecycleEpoch;\n\t\tconst entry = this.#entry(serverName);\n\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch);\n\t\tconst connectOptions = mergeConnectOptions(entry, options);\n\t\tconst operation = this.#runOperation(\n\t\t\tentry,\n\t\t\t{\n\t\t\t\tmethod: \"runtime/connect\",\n\t\t\t\tparams: connectOptions.prior === undefined ? undefined : { prior: connectOptions.prior },\n\t\t\t\toptions: connectOptions,\n\t\t\t\tsignal: connectOptions.signal,\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch);\n\t\t\t\treturn this.#connectEntry(entry, connectOptions, lifecycleEpoch);\n\t\t\t},\n\t\t);\n\t\tconst attempt = operation.then((result) => {\n\t\t\t// A middleware may hold the pipeline open after `next()` while close()\n\t\t\t// disconnects the connection established by the terminal.\n\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch);\n\t\t\treturn result;\n\t\t});\n\t\treturn attempt;\n\t}\n\n\tasync #delegate<Output>(\n\t\tserverName: string,\n\t\tdescriptor: OperationDescriptor,\n\t\tterminal: (client: Client) => Promise<Output>,\n\t): Promise<Output> {\n\t\tthis.#assertOpen();\n\t\tconst lifecycleEpoch = this.#lifecycleEpoch;\n\t\tconst entry = this.#entry(serverName);\n\t\tthis.#assertOperationCurrent(entry, lifecycleEpoch);\n\t\tconst result = await this.#runOperation(entry, descriptor, () => {\n\t\t\tthis.#assertOperationCurrent(entry, lifecycleEpoch);\n\t\t\tconst client =\n\t\t\t\tentry.state === \"connected\" && entry.client !== undefined ? entry.client : undefined;\n\t\t\tif (client === undefined) throw clientNotConnectedError(serverName);\n\t\t\treturn terminal(client);\n\t\t});\n\t\t// Do not let a middleware-held operation from a retired entry appear to\n\t\t// succeed after that logical server has been unregistered.\n\t\tthis.#assertOperationCurrent(entry, lifecycleEpoch);\n\t\treturn result;\n\t}\n\n\tasync #runOperation<Output>(\n\t\tentry: RegistryEntry,\n\t\tdescriptor: OperationDescriptor,\n\t\tterminal: () => Promise<Output>,\n\t\trequireTerminal = false,\n\t): Promise<Output> {\n\t\tlet terminalTask: Promise<Output> | undefined;\n\t\tconst invokeTerminal = (): Promise<Output> => {\n\t\t\tterminalTask ??= Promise.resolve().then(terminal);\n\t\t\treturn terminalTask;\n\t\t};\n\n\t\ttry {\n\t\t\tconst operationInput = freezeOperationInput(entry.definition.name, descriptor);\n\t\t\tif (\n\t\t\t\tdescriptor.exactResultMethod !== undefined &&\n\t\t\t\t!canReturnInputRequired(descriptor.exactResultMethod, descriptor.options)\n\t\t\t) {\n\t\t\t\tmarkExactMcpClientResult(operationInput, descriptor.exactResultMethod);\n\t\t\t}\n\t\t\tconst resolvedPrincipal =\n\t\t\t\tthis.#resolvePrincipal === undefined\n\t\t\t\t\t? this.#principal\n\t\t\t\t\t: await this.#resolvePrincipal(operationInput);\n\t\t\tconst resolvedAttributes =\n\t\t\t\tthis.#resolveAttributes === undefined ? {} : await this.#resolveAttributes(operationInput);\n\t\t\tconst context = createMcpOperationContext<Principal>({\n\t\t\t\toperationId: this.#operationIdFactory(),\n\t\t\t\trole: \"client\",\n\t\t\t\toperation: {\n\t\t\t\t\tname: descriptor.method,\n\t\t\t\t\tkind: descriptor.kind ?? \"request\",\n\t\t\t\t\t...(descriptor.capability === undefined ? {} : { capability: descriptor.capability }),\n\t\t\t\t\ttarget: entry.definition.name,\n\t\t\t\t\tattributes: { transportKind: entry.definition.transport.kind },\n\t\t\t\t},\n\t\t\t\t...(descriptor.signal === undefined ? {} : { signal: descriptor.signal }),\n\t\t\t\t...(entry.transport?.sessionId === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { sessionId: entry.transport.sessionId }),\n\t\t\t\t...(resolvedPrincipal === undefined ? {} : { principal: resolvedPrincipal }),\n\t\t\t\tattributes: {\n\t\t\t\t\t...this.#attributes,\n\t\t\t\t\t...entry.definition.attributes,\n\t\t\t\t\t...resolvedAttributes,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst operation = createMcpOperation(operationInput, context);\n\t\t\tconst middleware: McpClientMiddleware<Principal>[] =\n\t\t\t\tthis.#lifecycleMiddleware === undefined ? [] : [this.#lifecycleMiddleware];\n\t\t\tif (requireTerminal) {\n\t\t\t\tmiddleware.push(async (_operation, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait next();\n\t\t\t\t\t} catch (middlewareError) {\n\t\t\t\t\t\treturn invokeRequiredTerminal(invokeTerminal, middlewareError);\n\t\t\t\t\t}\n\t\t\t\t\treturn invokeTerminal();\n\t\t\t\t});\n\t\t\t}\n\t\t\tmiddleware.push(...this.#middleware, ...this.#transforms);\n\t\t\tconst pipeline = composeMcpMiddleware<\n\t\t\t\tMcpClientOperationInput,\n\t\t\t\tunknown,\n\t\t\t\tMcpClientOperationContext<Principal>\n\t\t\t>(middleware, requireTerminal ? invokeTerminal : terminal);\n\t\t\t// The shared chain deliberately erases per-method output shapes; the terminal preserves Output.\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\t\treturn (await pipeline(operation)) as Output;\n\t\t} catch (operationError) {\n\t\t\tif (!requireTerminal || terminalTask !== undefined) throw operationError;\n\t\t\treturn invokeRequiredTerminal(invokeTerminal, operationError);\n\t\t}\n\t}\n\n\tasync #connectEntry(\n\t\tentry: RegistryEntry,\n\t\toptions: ConnectOptions,\n\t\tlifecycleEpoch: number,\n\t): Promise<ConnectAttemptResult> {\n\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch);\n\t\toptions.signal?.throwIfAborted();\n\t\tif (entry.state === \"connected\" && entry.client !== undefined) {\n\t\t\treturn { client: entry.client, generation: entry.connectionGeneration };\n\t\t}\n\t\tif (entry.connectTask !== undefined) {\n\t\t\tconst { client, generation } = await observeConnectAttempt(\n\t\t\t\tentry.connectTask,\n\t\t\t\tentry.connectDetachment?.promise,\n\t\t\t\toptions.signal,\n\t\t\t);\n\t\t\treturn { client, generation };\n\t\t}\n\t\tif (entry.disconnectTask !== undefined) {\n\t\t\tawait entry.disconnectTask;\n\t\t\t// Another caller may have won the connection transition while this\n\t\t\t// caller was waiting for teardown. Re-enter the atomic checks.\n\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch);\n\t\t\treturn this.#connectEntry(entry, options, lifecycleEpoch);\n\t\t}\n\n\t\tentry.state = \"connecting\";\n\t\tentry.connectedAt = undefined;\n\t\tentry.disconnectedAt = undefined;\n\t\tentry.lastError = undefined;\n\n\t\tconst connectionToken = Symbol(entry.definition.name);\n\t\tconst connectAttemptToken = Symbol(`${entry.definition.name}:connect-attempt`);\n\t\tconst connectAbortController = new AbortController();\n\t\tconst connectDetachment = createConnectAttemptDetachment();\n\t\tconst unlinkCallerSignal = linkAbortSignal(options.signal, connectAbortController);\n\t\tconst connectOptions: ConnectOptions & { readonly signal: AbortSignal } = {\n\t\t\t...options,\n\t\t\tsignal: connectAbortController.signal,\n\t\t};\n\t\tentry.connectAttemptToken = connectAttemptToken;\n\t\tentry.connectAbortController = connectAbortController;\n\t\tentry.connectDetachment = connectDetachment;\n\t\tentry.connectUnlinkCallerSignal = unlinkCallerSignal;\n\t\tconst task = this.#establishConnection(\n\t\t\tentry,\n\t\t\tconnectOptions,\n\t\t\tconnectionToken,\n\t\t\tconnectAttemptToken,\n\t\t\tlifecycleEpoch,\n\t\t);\n\t\tentry.connectTask = task;\n\t\tvoid task.then(\n\t\t\t() => {\n\t\t\t\tthis.#releaseConnectAttempt(entry, task, connectAttemptToken);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.#releaseConnectAttempt(entry, task, connectAttemptToken);\n\t\t\t},\n\t\t);\n\t\tconst established = await observeConnectAttempt(\n\t\t\ttask,\n\t\t\tconnectDetachment.promise,\n\t\t\toptions.signal,\n\t\t);\n\t\treturn {\n\t\t\tclient: established.client,\n\t\t\tgeneration: established.generation,\n\t\t\townedConnectionToken: established.connectionToken,\n\t\t};\n\t}\n\n\tasync #establishConnection(\n\t\tentry: RegistryEntry,\n\t\toptions: ConnectOptions & { readonly signal: AbortSignal },\n\t\tconnectionToken: symbol,\n\t\tconnectAttemptToken: symbol,\n\t\tlifecycleEpoch: number,\n\t): Promise<EstablishedConnection> {\n\t\tconst definition = entry.definition;\n\t\tconst clientOptions = resolveClientOptions(definition.clientOptions);\n\t\tconst client = this.#clientFactory.createClient(\n\t\t\tdefinition.clientInfo ?? this.#clientInfo,\n\t\t\tclientOptions,\n\t\t\t{ serverName: definition.name, definition },\n\t\t);\n\t\tentry.client = client;\n\t\tlet unownedTransport: Transport | undefined;\n\n\t\ttry {\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tawait definition.configureClient?.(client, {\n\t\t\t\tserverName: definition.name,\n\t\t\t\tdefinition,\n\t\t\t});\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);\n\t\t\tthis.#attachClientLifecycle(entry, client);\n\t\t\tconst transportFactory = definition.transportFactory ?? this.#transportFactory;\n\t\t\tunownedTransport = await transportFactory.createTransport(definition.transport, {\n\t\t\t\tserverName: definition.name,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);\n\t\t\tconst transport = unownedTransport;\n\t\t\tentry.transport = transport;\n\t\t\t// Client.connect synchronously takes ownership before its first await.\n\t\t\tunownedTransport = undefined;\n\t\t\tawait client.connect(transport, options);\n\t\t\toptions.signal.throwIfAborted();\n\t\t\tthis.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);\n\t\t\tif (client.autoOpenedSubscription !== undefined) {\n\t\t\t\tentry.autoOpenedSubscription = this.#manageSubscription(\n\t\t\t\t\tentry,\n\t\t\t\t\tclient.autoOpenedSubscription,\n\t\t\t\t);\n\t\t\t}\n\t\t\tentry.connectionGeneration += 1;\n\t\t\tentry.connectionToken = connectionToken;\n\t\t\tentry.state = \"connected\";\n\t\t\tentry.connectedAt = this.#timestamp();\n\t\t\tentry.lastError = undefined;\n\t\t\tthis.#refreshMetadata(entry);\n\t\t\treturn { client, generation: entry.connectionGeneration, connectionToken };\n\t\t} catch (error) {\n\t\t\tconst failure = await closeAfterFailedConnect(client, error, unownedTransport);\n\t\t\tif (entry.connectAttemptToken === connectAttemptToken) {\n\t\t\t\tentry.state = \"failed\";\n\t\t\t\tentry.lastError = toMcpErrorDetails(failure);\n\t\t\t\tif (entry.client === client) {\n\t\t\t\t\tentry.client = undefined;\n\t\t\t\t\tentry.transport = undefined;\n\t\t\t\t\tentry.connectionToken = undefined;\n\t\t\t\t\tentry.subscriptions.clear();\n\t\t\t\t\tentry.autoOpenedSubscription = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\t#attachClientLifecycle(entry: RegistryEntry, client: Client): void {\n\t\tconst configuredOnClose = client.onclose;\n\t\t// The official SDK exposes callback slots rather than EventTarget listeners.\n\t\t// oxlint-disable-next-line unicorn/prefer-add-event-listener\n\t\tclient.onclose = () => {\n\t\t\tif (entry.client === client && entry.state === \"connected\") {\n\t\t\t\tthis.#refreshMetadata(entry);\n\t\t\t\tentry.state = \"disconnected\";\n\t\t\t\tentry.disconnectedAt = this.#timestamp();\n\t\t\t\tentry.client = undefined;\n\t\t\t\tentry.transport = undefined;\n\t\t\t\tentry.connectionToken = undefined;\n\t\t\t\tentry.subscriptions.clear();\n\t\t\t\tentry.autoOpenedSubscription = undefined;\n\t\t\t}\n\t\t\tconfiguredOnClose?.();\n\t\t};\n\n\t\tconst configuredOnError = client.onerror;\n\t\t// The official SDK exposes callback slots rather than EventTarget listeners.\n\t\t// oxlint-disable-next-line unicorn/prefer-add-event-listener\n\t\tclient.onerror = (error) => {\n\t\t\tentry.lastError = toMcpErrorDetails(error);\n\t\t\tconfiguredOnError?.(error);\n\t\t};\n\t}\n\n\t#disconnectEntry(entry: RegistryEntry): Promise<void> {\n\t\tif (entry.disconnectTask !== undefined) return entry.disconnectTask;\n\t\tconst disconnectToken = Symbol(`${entry.definition.name}:disconnect`);\n\t\tentry.disconnectToken = disconnectToken;\n\t\tconst task = this.#performDisconnect(entry, disconnectToken);\n\t\tentry.disconnectTask = task;\n\t\tvoid task.then(\n\t\t\t() => {\n\t\t\t\tthis.#releaseDisconnect(entry, task, disconnectToken);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.#releaseDisconnect(entry, task, disconnectToken);\n\t\t\t},\n\t\t);\n\t\treturn task;\n\t}\n\n\tasync #performDisconnect(entry: RegistryEntry, disconnectToken: symbol): Promise<void> {\n\t\tconst failures: unknown[] = [];\n\t\tconst deadline = performance.now() + this.#shutdownTimeoutMs;\n\t\tlet timedOut = false;\n\t\tconst connectTask = entry.connectTask;\n\t\tconst connectAttemptToken = entry.connectAttemptToken;\n\t\tif (connectTask !== undefined) {\n\t\t\tconst outcome = await settleTaskWithin(connectTask, remainingTime(deadline));\n\t\t\tif (outcome.status === \"timeout\") {\n\t\t\t\ttimedOut = true;\n\t\t\t\tconst timeoutError = shutdownTimeoutError(entry.definition.name, this.#shutdownTimeoutMs);\n\t\t\t\tfailures.push(timeoutError);\n\t\t\t\tentry.connectDetachment?.detach(timeoutError);\n\t\t\t\tthis.#releaseConnectAttempt(entry, connectTask, connectAttemptToken);\n\t\t\t}\n\t\t}\n\n\t\tconst client = entry.client;\n\t\tif (client === undefined) {\n\t\t\tentry.state = \"disconnected\";\n\t\t\tentry.disconnectedAt = this.#timestamp();\n\t\t\tentry.transport = undefined;\n\t\t\tentry.connectionToken = undefined;\n\t\t\tentry.subscriptions.clear();\n\t\t\tentry.autoOpenedSubscription = undefined;\n\t\t} else {\n\t\t\tentry.state = \"disconnecting\";\n\t\t\tthis.#refreshMetadata(entry);\n\t\t\tconst cleanupFailures: unknown[] = [];\n\t\t\tconst cleanupTimedOut = await this.#closeConnection(\n\t\t\t\tentry,\n\t\t\t\tclient,\n\t\t\t\tdisconnectToken,\n\t\t\t\tcleanupFailures,\n\t\t\t\tdeadline,\n\t\t\t);\n\t\t\tfailures.push(...cleanupFailures);\n\t\t\tif (cleanupTimedOut && !timedOut) {\n\t\t\t\ttimedOut = true;\n\t\t\t\tfailures.push(shutdownTimeoutError(entry.definition.name, this.#shutdownTimeoutMs));\n\t\t\t}\n\t\t}\n\n\t\tif (failures.length === 0) return;\n\t\tconst failure =\n\t\t\tfailures.length === 1\n\t\t\t\t? failures[0]\n\t\t\t\t: new AggregateError(\n\t\t\t\t\t\tfailures,\n\t\t\t\t\t\t`The MCP server ${JSON.stringify(entry.definition.name)} did not shut down cleanly.`,\n\t\t\t\t\t);\n\t\tentry.state = \"failed\";\n\t\tentry.lastError = toMcpErrorDetails(failure);\n\t\tthrow failure;\n\t}\n\n\tasync #closeConnection(\n\t\tentry: RegistryEntry,\n\t\tclient: Client,\n\t\tdisconnectToken: symbol,\n\t\tfailures: unknown[],\n\t\tdeadline: number,\n\t): Promise<boolean> {\n\t\tlet timedOut = false;\n\t\tconst subscriptionTask = Promise.all(\n\t\t\t[...entry.subscriptions].map(async (subscription) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait subscription.handle.close();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailures.push(error);\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\tconst subscriptionOutcome = await settleTaskWithin(subscriptionTask, remainingTime(deadline));\n\t\tswitch (subscriptionOutcome.status) {\n\t\t\tcase \"fulfilled\":\n\t\t\t\tbreak;\n\t\t\tcase \"rejected\":\n\t\t\t\tfailures.push(subscriptionOutcome.reason);\n\t\t\t\tbreak;\n\t\t\tcase \"timeout\":\n\t\t\t\ttimedOut = true;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst clientCloseTask = Promise.resolve().then(() => client.close());\n\t\tconst clientCloseOutcome = await settleTaskWithin(clientCloseTask, remainingTime(deadline));\n\t\tswitch (clientCloseOutcome.status) {\n\t\t\tcase \"fulfilled\":\n\t\t\t\tbreak;\n\t\t\tcase \"rejected\":\n\t\t\t\tfailures.push(clientCloseOutcome.reason);\n\t\t\t\tbreak;\n\t\t\tcase \"timeout\":\n\t\t\t\ttimedOut = true;\n\t\t\t\tbreak;\n\t\t}\n\t\tif (entry.disconnectToken === disconnectToken) this.#detachConnection(entry, client);\n\n\t\tif (entry.disconnectToken !== disconnectToken) return timedOut;\n\t\tentry.disconnectedAt = this.#timestamp();\n\t\tif (failures.length === 0) entry.state = \"disconnected\";\n\t\treturn timedOut;\n\t}\n\n\t#detachConnection(entry: RegistryEntry, client: Client): void {\n\t\tentry.subscriptions.clear();\n\t\tentry.autoOpenedSubscription = undefined;\n\t\tif (entry.client === client) {\n\t\t\tentry.client = undefined;\n\t\t\tentry.transport = undefined;\n\t\t\tentry.connectionToken = undefined;\n\t\t}\n\t}\n\n\t#releaseDisconnect(entry: RegistryEntry, task: Promise<void>, disconnectToken: symbol): void {\n\t\tif (entry.disconnectTask === task) entry.disconnectTask = undefined;\n\t\tif (entry.disconnectToken === disconnectToken) entry.disconnectToken = undefined;\n\t}\n\n\t#snapshotEntry(entry: RegistryEntry): McpClientConnectionSnapshot {\n\t\tthis.#refreshMetadata(entry);\n\t\treturn Object.freeze({\n\t\t\tname: entry.definition.name,\n\t\t\tstate: entry.state,\n\t\t\ttransportKind: entry.definition.transport.kind,\n\t\t\t...(entry.metadata.sessionId === undefined ? {} : { sessionId: entry.metadata.sessionId }),\n\t\t\t...(entry.connectedAt === undefined ? {} : { connectedAt: entry.connectedAt }),\n\t\t\t...(entry.disconnectedAt === undefined ? {} : { disconnectedAt: entry.disconnectedAt }),\n\t\t\t...(entry.metadata.negotiatedProtocolVersion === undefined\n\t\t\t\t? {}\n\t\t\t\t: { negotiatedProtocolVersion: entry.metadata.negotiatedProtocolVersion }),\n\t\t\t...(entry.metadata.protocolEra === undefined\n\t\t\t\t? {}\n\t\t\t\t: { protocolEra: entry.metadata.protocolEra }),\n\t\t\t...(entry.metadata.serverInfo === undefined ? {} : { serverInfo: entry.metadata.serverInfo }),\n\t\t\t...(entry.metadata.serverCapabilities === undefined\n\t\t\t\t? {}\n\t\t\t\t: { serverCapabilities: entry.metadata.serverCapabilities }),\n\t\t\t...(entry.metadata.instructions === undefined\n\t\t\t\t? {}\n\t\t\t\t: { instructions: entry.metadata.instructions }),\n\t\t\t...(entry.metadata.discoverResult === undefined\n\t\t\t\t? {}\n\t\t\t\t: { discoverResult: entry.metadata.discoverResult }),\n\t\t\t...(entry.lastError === undefined ? {} : { lastError: entry.lastError }),\n\t\t});\n\t}\n\n\t#refreshMetadata(entry: RegistryEntry): void {\n\t\tconst client = entry.client;\n\t\tif (client === undefined) return;\n\t\tentry.metadata.sessionId = entry.transport?.sessionId;\n\t\tentry.metadata.negotiatedProtocolVersion = client.getNegotiatedProtocolVersion();\n\t\tentry.metadata.protocolEra = client.getProtocolEra();\n\t\tentry.metadata.serverInfo = client.getServerVersion();\n\t\tentry.metadata.serverCapabilities = client.getServerCapabilities();\n\t\tentry.metadata.instructions = client.getInstructions();\n\t\tentry.metadata.discoverResult = client.getDiscoverResult();\n\t}\n\n\t#entry(serverName: string, allowRetired = false): RegistryEntry {\n\t\tconst entry = this.#entries.get(serverName);\n\t\tif (entry === undefined || (!allowRetired && entry.retired)) {\n\t\t\tthrow serverNotFoundError(serverName);\n\t\t}\n\t\treturn entry;\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#closed) throw runtimeClosedError();\n\t}\n\n\t#abortConnectAttempt(entry: RegistryEntry, reason: unknown): void {\n\t\tentry.connectAbortController?.abort(reason);\n\t}\n\n\t#releaseConnectAttempt(\n\t\tentry: RegistryEntry,\n\t\ttask: Promise<EstablishedConnection>,\n\t\tconnectAttemptToken: symbol | undefined,\n\t): void {\n\t\tif (entry.connectTask === task) entry.connectTask = undefined;\n\t\tif (connectAttemptToken !== undefined && entry.connectAttemptToken === connectAttemptToken) {\n\t\t\tentry.connectUnlinkCallerSignal?.();\n\t\t\tentry.connectAttemptToken = undefined;\n\t\t\tentry.connectAbortController = undefined;\n\t\t\tentry.connectDetachment = undefined;\n\t\t\tentry.connectUnlinkCallerSignal = undefined;\n\t\t}\n\t}\n\n\t#assertConnectAttemptCurrent(\n\t\tentry: RegistryEntry,\n\t\tlifecycleEpoch: number,\n\t\tconnectAttemptToken?: symbol,\n\t): void {\n\t\tif (connectAttemptToken !== undefined && entry.connectAttemptToken !== connectAttemptToken) {\n\t\t\tthrow staleConnectAttemptError(entry, this.#closed);\n\t\t}\n\t\tthis.#assertOperationCurrent(entry, lifecycleEpoch);\n\t}\n\n\t#assertOperationCurrent(entry: RegistryEntry, lifecycleEpoch: number): void {\n\t\tif (this.#closed || lifecycleEpoch !== this.#lifecycleEpoch) throw runtimeClosedError();\n\t\tthis.#assertEntryActive(entry);\n\t}\n\n\t#assertEntryActive(entry: RegistryEntry): void {\n\t\tif (entry.retired || this.#entries.get(entry.definition.name) !== entry) {\n\t\t\tthrow serverNotFoundError(entry.definition.name);\n\t\t}\n\t}\n\n\t#timestamp(): number {\n\t\tconst timestamp = this.#now();\n\t\tif (!Number.isFinite(timestamp))\n\t\t\tthrow new TypeError(\"Runtime clock must return a finite timestamp.\");\n\t\treturn timestamp;\n\t}\n}\n\nfunction createRegistryEntry(definition: McpClientServerDefinition): RegistryEntry {\n\treturn {\n\t\tdefinition,\n\t\tstate: \"disconnected\",\n\t\tprior: definition.prior ?? definition.connectOptions?.prior,\n\t\tclient: undefined,\n\t\ttransport: undefined,\n\t\tconnectTask: undefined,\n\t\tconnectAbortController: undefined,\n\t\tconnectAttemptToken: undefined,\n\t\tconnectDetachment: undefined,\n\t\tconnectUnlinkCallerSignal: undefined,\n\t\tdisconnectTask: undefined,\n\t\tdisconnectToken: undefined,\n\t\tconnectedAt: undefined,\n\t\tdisconnectedAt: undefined,\n\t\tlastError: undefined,\n\t\tsubscriptions: new Set(),\n\t\tautoOpenedSubscription: undefined,\n\t\tconnectionGeneration: 0,\n\t\tconnectionToken: undefined,\n\t\tretired: false,\n\t\tmetadata: {\n\t\t\tsessionId: undefined,\n\t\t\tnegotiatedProtocolVersion: undefined,\n\t\t\tprotocolEra: undefined,\n\t\t\tserverInfo: undefined,\n\t\t\tserverCapabilities: undefined,\n\t\t\tinstructions: undefined,\n\t\t\tdiscoverResult: undefined,\n\t\t},\n\t};\n}\n\nasync function invokeRequiredTerminal<Output>(\n\tterminal: () => Promise<Output>,\n\tprimaryError: unknown,\n): Promise<never> {\n\ttry {\n\t\tawait terminal();\n\t} catch (cleanupError) {\n\t\tif (cleanupError !== primaryError) {\n\t\t\t// Both caught failures are retained explicitly in AggregateError.errors.\n\t\t\t// oxlint-disable-next-line eslint/preserve-caught-error\n\t\t\tthrow new AggregateError(\n\t\t\t\t[primaryError, cleanupError],\n\t\t\t\t\"MCP cleanup middleware and its required terminal both failed.\",\n\t\t\t\t{ cause: cleanupError },\n\t\t\t);\n\t\t}\n\t}\n\tthrow primaryError;\n}\n\nasync function closeUnmanagedSubscription(\n\tsubscription: McpSubscription,\n\tprimaryError: unknown,\n): Promise<never> {\n\ttry {\n\t\tawait subscription.close();\n\t} catch (cleanupError) {\n\t\t// oxlint-disable-next-line eslint/preserve-caught-error\n\t\tthrow new AggregateError(\n\t\t\t[primaryError, cleanupError],\n\t\t\t\"The MCP subscription opened for a retired client failed to close.\",\n\t\t\t{ cause: cleanupError },\n\t\t);\n\t}\n\tthrow primaryError;\n}\n\nfunction toOfficialProtocolRequest<const RequestValue extends McpClientProtocolRequest>(\n\trequest: RequestValue,\n): {\n\treadonly method: RequestValue[\"method\"];\n\treadonly params?: Record<string, unknown>;\n} {\n\treturn {\n\t\tmethod: request.method,\n\t\t...(!(\"params\" in request) || request.params === undefined ? {} : { params: request.params }),\n\t};\n}\n\nfunction normalizeServerDefinition(\n\tdefinition: McpClientServerDefinition,\n): McpClientServerDefinition {\n\tif (typeof definition !== \"object\" || definition === null) {\n\t\tthrow new TypeError(\"MCP server definition must be an object.\");\n\t}\n\tassertNonEmpty(definition.name, \"server name\");\n\tif (typeof definition.transport !== \"object\" || definition.transport === null) {\n\t\tthrow new TypeError(\"MCP server transport definition must be an object.\");\n\t}\n\n\tlet transport: McpClientServerDefinition[\"transport\"];\n\tswitch (definition.transport.kind) {\n\t\tcase \"http\":\n\t\t\ttransport = Object.freeze({\n\t\t\t\t...definition.transport,\n\t\t\t\t...(definition.transport.middleware === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { middleware: Object.freeze([...definition.transport.middleware]) }),\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"stdio\":\n\t\t\ttransport = Object.freeze({\n\t\t\t\t...definition.transport,\n\t\t\t\t...(definition.transport.args === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { args: Object.freeze([...definition.transport.args]) }),\n\t\t\t\t...(definition.transport.env === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { env: Object.freeze({ ...definition.transport.env }) }),\n\t\t\t});\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(\"MCP server transport kind must be http or stdio.\");\n\t}\n\n\treturn Object.freeze({\n\t\t...definition,\n\t\ttransport,\n\t\t...(definition.clientInfo === undefined\n\t\t\t? {}\n\t\t\t: { clientInfo: Object.freeze({ ...definition.clientInfo }) }),\n\t\t...(definition.clientOptions === undefined\n\t\t\t? {}\n\t\t\t: { clientOptions: { ...definition.clientOptions } }),\n\t\t...(definition.connectOptions === undefined\n\t\t\t? {}\n\t\t\t: { connectOptions: { ...definition.connectOptions } }),\n\t\t...(definition.attributes === undefined\n\t\t\t? {}\n\t\t\t: { attributes: Object.freeze({ ...definition.attributes }) }),\n\t});\n}\n\nfunction resolveClientOptions(options: ClientOptions | undefined): ClientOptions {\n\treturn {\n\t\t...options,\n\t\tversionNegotiation: {\n\t\t\t...options?.versionNegotiation,\n\t\t\tmode: options?.versionNegotiation?.mode ?? \"auto\",\n\t\t},\n\t};\n}\n\nfunction mergeConnectOptions(\n\tentry: RegistryEntry,\n\toverride: ConnectOptions | undefined,\n): ConnectOptions {\n\tconst configured = entry.definition.connectOptions;\n\tconst prior = override?.prior ?? entry.prior ?? configured?.prior;\n\treturn {\n\t\t...configured,\n\t\t...override,\n\t\t...(prior === undefined ? {} : { prior }),\n\t};\n}\n\nfunction linkAbortSignal(source: AbortSignal | undefined, target: AbortController): () => void {\n\tif (source === undefined) return () => undefined;\n\tconst abort = (): void => target.abort(source.reason);\n\tif (source.aborted) {\n\t\tabort();\n\t\treturn () => undefined;\n\t}\n\tsource.addEventListener(\"abort\", abort, { once: true });\n\treturn () => source.removeEventListener(\"abort\", abort);\n}\n\nfunction observeConnectAttempt<Value>(\n\ttask: Promise<Value>,\n\tdetachment: Promise<never> | undefined,\n\tcallerSignal: AbortSignal | undefined,\n): Promise<Value> {\n\tconst alternatives: Array<Promise<Value>> = [task];\n\tif (detachment !== undefined) alternatives.push(detachment);\n\tif (callerSignal === undefined) {\n\t\treturn alternatives.length === 1 ? task : Promise.race(alternatives);\n\t}\n\tif (callerSignal.aborted) return Promise.reject(abortReason(callerSignal));\n\treturn new Promise<Value>((resolve, reject) => {\n\t\tconst aborted = (): void => reject(abortReason(callerSignal));\n\t\tcallerSignal.addEventListener(\"abort\", aborted, { once: true });\n\t\tvoid Promise.race(alternatives).then(\n\t\t\t(value) => {\n\t\t\t\tcallerSignal.removeEventListener(\"abort\", aborted);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tcallerSignal.removeEventListener(\"abort\", aborted);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction staleConnectAttemptError(entry: RegistryEntry, runtimeClosed: boolean): Error {\n\tif (runtimeClosed) return runtimeClosedError();\n\treturn entry.retired\n\t\t? serverNotFoundError(entry.definition.name)\n\t\t: connectionAbortedError(entry.definition.name);\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n\treturn signal.reason ?? new DOMException(\"The MCP connection was aborted.\", \"AbortError\");\n}\n\nfunction createConnectAttemptDetachment(): ConnectAttemptDetachment {\n\tlet detach: ((error: unknown) => void) | undefined;\n\tlet detached = false;\n\tconst promise = new Promise<never>((_resolve, reject) => {\n\t\tdetach = reject;\n\t});\n\treturn {\n\t\tpromise,\n\t\tdetach(error: unknown): void {\n\t\t\tif (detached) return;\n\t\t\tdetached = true;\n\t\t\tdetach?.(error);\n\t\t},\n\t};\n}\n\ntype TaskOutcome<Value> =\n\t| { readonly status: \"fulfilled\"; readonly value: Value }\n\t| { readonly status: \"rejected\"; readonly reason: unknown }\n\t| { readonly status: \"timeout\" };\n\nasync function settleTaskWithin<Value>(\n\ttask: Promise<Value>,\n\ttimeoutMs: number,\n): Promise<TaskOutcome<Value>> {\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tconst expired = new Promise<TaskOutcome<Value>>((resolve) => {\n\t\ttimeout = setTimeout(resolve, timeoutMs, { status: \"timeout\" });\n\t});\n\ttry {\n\t\treturn await Promise.race([\n\t\t\ttask.then(\n\t\t\t\t(value): TaskOutcome<Value> => ({ status: \"fulfilled\", value }),\n\t\t\t\t(reason: unknown): TaskOutcome<Value> => ({ status: \"rejected\", reason }),\n\t\t\t),\n\t\t\texpired,\n\t\t]);\n\t} finally {\n\t\tif (timeout !== undefined) clearTimeout(timeout);\n\t}\n}\n\nfunction remainingTime(deadline: number): number {\n\treturn Math.max(0, deadline - performance.now());\n}\n\nfunction connectionAbortedError(serverName: string): DOMException {\n\treturn new DOMException(\n\t\t`The MCP server ${JSON.stringify(serverName)} connection was disconnected.`,\n\t\t\"AbortError\",\n\t);\n}\n\nfunction freezeOperationInput(\n\tserverName: string,\n\tdescriptor: OperationDescriptor,\n): McpClientOperationInput {\n\treturn Object.freeze({\n\t\tserverName,\n\t\tmethod: descriptor.method,\n\t\t...(descriptor.params === undefined ? {} : { params: descriptor.params }),\n\t\t...(descriptor.options === undefined ? {} : { options: descriptor.options }),\n\t});\n}\n\nfunction snapshotRequestOptions<Options extends RequestOptions | undefined>(\n\toptions: Options,\n): Options {\n\tif (options === undefined) return options;\n\tconst toolDefinition =\n\t\t\"toolDefinition\" in options ? Reflect.get(options, \"toolDefinition\") : undefined;\n\tconst snapshot = Object.freeze({\n\t\t...options,\n\t\t...(options.headers === undefined ? {} : { headers: Object.freeze({ ...options.headers }) }),\n\t\t...(toolDefinition === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\ttoolDefinition: snapshotProtocolValue(toolDefinition, \"MCP call tool definition\"),\n\t\t\t\t}),\n\t});\n\t// A shallow option snapshot preserves callback/signal identities and every\n\t// subtype field while making result-affecting flags immutable for this call.\n\treturn snapshot;\n}\n\nfunction snapshotProtocolValue<Value>(value: Value, label: string): Value {\n\tlet snapshot: Value;\n\ttry {\n\t\tsnapshot = structuredClone(value);\n\t} catch (cause) {\n\t\tthrow new TypeError(`${label} must be structured-cloneable JSON.`, { cause });\n\t}\n\tfreezeProtocolValue(snapshot, label, new Set(), new Set());\n\treturn snapshot;\n}\n\nfunction freezeProtocolValue(\n\tvalue: unknown,\n\tlabel: string,\n\tancestors: Set<object>,\n\tvisited: Set<object>,\n): void {\n\tif (\n\t\tvalue === undefined ||\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\"\n\t) {\n\t\treturn;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow new TypeError(`${label} must not contain non-finite numbers.`);\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`${label} must contain only JSON-compatible values.`);\n\t}\n\tif (visited.has(value)) return;\n\tif (ancestors.has(value)) throw new TypeError(`${label} must not contain cycles.`);\n\tif (!Array.isArray(value)) {\n\t\tconst prototype = Object.getPrototypeOf(value) as unknown;\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new TypeError(`${label} must contain only JSON arrays and objects.`);\n\t\t}\n\t}\n\tancestors.add(value);\n\tfor (const entry of Array.isArray(value) ? value : Object.values(value)) {\n\t\tfreezeProtocolValue(entry, label, ancestors, visited);\n\t}\n\tancestors.delete(value);\n\tvisited.add(value);\n\tObject.freeze(value);\n}\n\nfunction canReturnInputRequired(method: RequestMethod, options: unknown): boolean {\n\treturn (\n\t\t(method === \"tools/call\" || method === \"prompts/get\" || method === \"resources/read\") &&\n\t\ttypeof options === \"object\" &&\n\t\toptions !== null &&\n\t\t\"allowInputRequired\" in options &&\n\t\toptions.allowInputRequired === true\n\t);\n}\n\ntype InputRequiredResultForMethod<Method extends RequestMethod> = Method extends McpClientMrtrMethod\n\t? InputRequiredResult\n\t: never;\n\nasync function closeAfterFailedConnect(\n\tclient: Client,\n\tprimary: unknown,\n\tunownedTransport?: Transport,\n): Promise<unknown> {\n\tconst failures: unknown[] = [primary];\n\tif (unownedTransport !== undefined) {\n\t\ttry {\n\t\t\tawait unownedTransport.close();\n\t\t} catch (cleanupError) {\n\t\t\tfailures.push(cleanupError);\n\t\t}\n\t}\n\ttry {\n\t\tawait client.close();\n\t} catch (cleanupError) {\n\t\tfailures.push(cleanupError);\n\t}\n\treturn failures.length === 1\n\t\t? primary\n\t\t: new AggregateError(\n\t\t\t\tfailures,\n\t\t\t\t\"The MCP connection failed and one or more owned resources failed to close.\",\n\t\t\t);\n}\n\nfunction throwSettledFailures(\n\tsettled: readonly PromiseSettledResult<unknown>[],\n\tmessage: string,\n): void {\n\tconst failures = settled\n\t\t.filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n\t\t.map((result) => result.reason as unknown);\n\tthrowFailures(failures, message);\n}\n\nfunction throwFailures(failures: readonly unknown[], message: string): void {\n\tif (failures.length === 1) throw failures[0];\n\tif (failures.length > 1) throw new AggregateError(failures, message);\n}\n\nfunction assertNonEmpty(value: string, field: string): void {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new TypeError(`${field} must be a non-empty string.`);\n\t}\n}\n\nfunction assertPositiveFinite(value: number, field: string): void {\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new TypeError(`MCP client ${field} must be a positive finite number.`);\n\t}\n}\n","import type { JsonSchemaType } from \"@modelcontextprotocol/client\";\nimport { AjvJsonSchemaValidator } from \"@modelcontextprotocol/client/validators/ajv\";\nimport { z } from \"zod/v4\";\n\nimport type { McpClientToolInputSchema, McpClientToolOutputSchema } from \"./types.ts\";\n\nconst JSON_SCHEMA_2020_12 = \"https://json-schema.org/draft/2020-12/schema\";\nconst JSON_SCHEMA_2020_12_URIS = new Set([\n\tJSON_SCHEMA_2020_12,\n\t\"http://json-schema.org/draft/2020-12/schema\",\n]);\n\nexport interface McpClientToolSchemaIssue {\n\treadonly message: string;\n}\n\nexport type McpClientToolSchemaResult =\n\t{ readonly value: unknown } | { readonly issues: readonly McpClientToolSchemaIssue[] };\n\n/** Standard Schema compatibility retained by the Zod tool schema. */\nexport interface McpClientToolStandardSchema {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => Promise<McpClientToolSchemaResult>;\n\t\treadonly jsonSchema: {\n\t\t\treadonly input: (options: unknown) => Record<string, unknown>;\n\t\t\treadonly output: (options: unknown) => Record<string, unknown>;\n\t\t};\n\t};\n}\n\n/** Runtime Zod view of a dynamically discovered MCP tool JSON Schema. */\nexport type McpClientToolSchema = McpClientToolStandardSchema & z.ZodType;\n\n/**\n * Converts a discovered MCP tool JSON Schema into a Zod v4 schema.\n *\n * Zod v4 schemas also implement Standard Schema and Standard JSON Schema, so\n * the returned schema can be passed directly to either kind of consumer. The\n * official MCP validator remains the exact predicate because a discovered\n * Draft 2020-12 schema can contain constraints that Zod cannot reconstruct.\n * Invalid or unsupported schemas fail synchronously during construction.\n */\nexport function createMcpClientToolSchema(\n\tschema: McpClientToolInputSchema | McpClientToolOutputSchema,\n): McpClientToolSchema {\n\tconst jsonSchema = Object.fromEntries(Object.entries(structuredClone(schema)));\n\tassertDraft202012(jsonSchema);\n\tdeepFreezeJson(jsonSchema);\n\n\tconst validatorSchema: JsonSchemaType = structuredClone(jsonSchema);\n\tconst validate = new AjvJsonSchemaValidator().getValidator<unknown>(validatorSchema);\n\tconst zodMetadata = structuredClone(jsonSchema);\n\tzodMetadata.$schema = JSON_SCHEMA_2020_12;\n\tdeepFreezeJson(zodMetadata);\n\tconst zodSchema = z\n\t\t.unknown()\n\t\t.superRefine((value, context) => {\n\t\t\tconst result = validate(value);\n\t\t\tif (!result.valid) {\n\t\t\t\tcontext.addIssue({ code: \"custom\", message: result.errorMessage });\n\t\t\t}\n\t\t})\n\t\t.meta(zodMetadata);\n\tconst validateWithZod = zodSchema[\"~standard\"].validate;\n\tconst toJsonSchemaWithZod = zodSchema.toJSONSchema.bind(zodSchema);\n\tconst projectJsonSchema = (options: unknown): Record<string, unknown> => {\n\t\tassertDraft202012Target(readTarget(options));\n\n\t\treturn structuredClone(jsonSchema);\n\t};\n\n\t// Preserve the detached remote definition for Standard JSON Schema consumers.\n\t// Zod metadata keeps native projections on the same immutable 2020-12 dialect.\n\tObject.defineProperties(zodSchema[\"~standard\"], {\n\t\tvalidate: {\n\t\t\tconfigurable: false,\n\t\t\tenumerable: true,\n\t\t\twritable: false,\n\t\t\tasync value(value: unknown): Promise<McpClientToolSchemaResult> {\n\t\t\t\treturn await validateWithZod(value);\n\t\t\t},\n\t\t},\n\t\tjsonSchema: {\n\t\t\tconfigurable: false,\n\t\t\tenumerable: true,\n\t\t\twritable: false,\n\t\t\tvalue: Object.freeze({\n\t\t\t\tinput: projectJsonSchema,\n\t\t\t\toutput: projectJsonSchema,\n\t\t\t}),\n\t\t},\n\t});\n\tObject.defineProperty(zodSchema, \"toJSONSchema\", {\n\t\tconfigurable: false,\n\t\tenumerable: true,\n\t\twritable: false,\n\t\tvalue(parameters?: Parameters<z.ZodType[\"toJSONSchema\"]>[0]) {\n\t\t\tassertDraft202012Target(parameters?.target);\n\t\t\treturn toJsonSchemaWithZod({ ...parameters, target: \"draft-2020-12\" });\n\t\t},\n\t});\n\n\t// The runtime overrides above retain the legacy Promise-only Standard\n\t// validation surface in addition to the concrete Zod API.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\treturn zodSchema as McpClientToolSchema;\n}\n\nfunction assertDraft202012(schema: Readonly<Record<string, unknown>>): void {\n\tif (!(\"$schema\" in schema)) {\n\t\treturn;\n\t}\n\n\tconst dialect = schema.$schema;\n\tif (typeof dialect === \"string\" && JSON_SCHEMA_2020_12_URIS.has(dialect.replace(/#$/u, \"\"))) {\n\t\treturn;\n\t}\n\n\tthrow new TypeError(\n\t\t\"createMcpClientToolSchema supports JSON Schema Draft 2020-12 declarations only.\",\n\t);\n}\n\nfunction assertDraft202012Target(target: unknown): void {\n\tif (target === undefined || target === \"draft-2020-12\") {\n\t\treturn;\n\t}\n\n\tthrow new TypeError(\n\t\t\"MCP tool schemas use JSON Schema Draft 2020-12 and cannot be projected to another target.\",\n\t);\n}\n\nfunction readTarget(options: unknown): unknown {\n\treturn isJsonObject(options) ? options.target : undefined;\n}\n\nfunction deepFreezeJson(value: unknown, seen = new WeakSet<object>()): void {\n\tif (Array.isArray(value)) {\n\t\tif (seen.has(value)) {\n\t\t\treturn;\n\t\t}\n\n\t\tseen.add(value);\n\t\tconst items: readonly unknown[] = value;\n\t\tfor (const item of items) {\n\t\t\tdeepFreezeJson(item, seen);\n\t\t}\n\t\tObject.freeze(value);\n\t\treturn;\n\t}\n\n\tif (!isJsonObject(value) || seen.has(value)) {\n\t\treturn;\n\t}\n\n\tseen.add(value);\n\tfor (const nested of Object.values(value)) {\n\t\tdeepFreezeJson(nested, seen);\n\t}\n\tObject.freeze(value);\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n","import {\n\tMETHOD_NOT_FOUND,\n\tProtocolError,\n\ttype Tool,\n\ttype Resource,\n\ttype ResourceTemplateType,\n\ttype Prompt,\n} from \"@modelcontextprotocol/client\";\nimport {\n\tcaptureMcpConformanceValue,\n\tcaptureMcpToolArguments,\n\ttype McpPassiveDiscoveryTarget,\n} from \"@nest-mcp/conformance\";\nimport type { McpClientRuntime } from \"./runtime.ts\";\nimport { createMcpClientToolSchema } from \"./tool-schema.ts\";\n\nexport interface McpClientCatalogSnapshot {\n\treadonly tools: readonly Tool[];\n\treadonly resources: readonly Resource[];\n\treadonly resourceTemplates: readonly ResourceTemplateType[];\n\treadonly prompts: readonly Prompt[];\n}\n\nexport interface McpClientCatalogInspectionOptions {\n\treadonly runtime: Pick<McpClientRuntime, \"request\" | \"snapshot\">;\n\treadonly serverName: string;\n\treadonly signal: AbortSignal;\n\treadonly maxPages: number;\n\treadonly maxItems: number;\n\t/** Parallel waves settle every request before returning. Credential-bound callers use sequential. */\n\treadonly mode?: \"sequential\" | \"parallel\";\n}\n\nexport class McpClientCatalogLimitError extends Error {\n\treadonly code = \"MCP_CLIENT_CATALOG_LIMIT_EXCEEDED\" as const;\n\tconstructor() {\n\t\tsuper(\"The MCP catalog exceeds its configured page or item limit.\");\n\t\tthis.name = \"McpClientCatalogLimitError\";\n\t}\n}\n\nconst ITEM_LIMITS = Object.freeze({\n\tmaxBytes: 2 * 1_024 * 1_024,\n\tmaxDepth: 64,\n\tmaxItems: 8_192,\n\tmaxProperties: 20_000,\n\tmaxStringBytes: 1_024 * 1_024,\n});\n\n/** Fresh bounded protocol traversal on an already acquired runtime; owns no lease or cache. */\nexport async function discoverMcpClientCatalog(\n\tinput: McpClientCatalogInspectionOptions,\n): Promise<McpClientCatalogSnapshot> {\n\tif (\n\t\t![input.maxPages, input.maxItems].every((n) => Number.isSafeInteger(n) && n > 0) ||\n\t\t(input.mode !== undefined && input.mode !== \"sequential\" && input.mode !== \"parallel\")\n\t) {\n\t\tthrow new TypeError(\"MCP catalog inspection requires positive bounds and a supported mode.\");\n\t}\n\tconst { runtime, serverName, signal } = input;\n\tsignal.throwIfAborted();\n\tconst capabilities = runtime.snapshot(serverName).serverCapabilities;\n\tlet totalItems = 0;\n\tconst account = <Value>(items: readonly Value[]): readonly Value[] => {\n\t\ttotalItems += items.length;\n\t\tif (totalItems > input.maxItems) throw new McpClientCatalogLimitError();\n\t\treturn items.map((item) => captureMcpConformanceValue(item, ITEM_LIMITS) as Value);\n\t};\n\tconst tools = () =>\n\t\tcapabilities?.tools === undefined\n\t\t\t? Promise.resolve([])\n\t\t\t: aggregatePages<Tool>(\n\t\t\t\t\tasync (cursor) => {\n\t\t\t\t\t\tconst page = await runtime.request(\n\t\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\t{ method: \"tools/list\", params: cursor === undefined ? {} : { cursor } },\n\t\t\t\t\t\t\t{ signal },\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\titems: account(page.tools),\n\t\t\t\t\t\t\t...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tinput.maxPages,\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\tconst resources = () =>\n\t\tcapabilities?.resources === undefined\n\t\t\t? Promise.resolve([])\n\t\t\t: aggregatePages<Resource>(\n\t\t\t\t\tasync (cursor) => {\n\t\t\t\t\t\tconst page = await runtime.request(\n\t\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\t{ method: \"resources/list\", params: cursor === undefined ? {} : { cursor } },\n\t\t\t\t\t\t\t{ signal },\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\titems: account(page.resources),\n\t\t\t\t\t\t\t...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tinput.maxPages,\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\tconst resourceTemplates = async (): Promise<readonly ResourceTemplateType[]> => {\n\t\tif (capabilities?.resources === undefined) return [];\n\t\ttry {\n\t\t\treturn await aggregatePages<ResourceTemplateType>(\n\t\t\t\tasync (cursor) => {\n\t\t\t\t\tconst page = await runtime.request(\n\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t{ method: \"resources/templates/list\", params: cursor === undefined ? {} : { cursor } },\n\t\t\t\t\t\t{ signal },\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\titems: account(page.resourceTemplates),\n\t\t\t\t\t\t...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tinput.maxPages,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (ProtocolError.isInstance(error) && error.code === METHOD_NOT_FOUND) return [];\n\t\t\tthrow error;\n\t\t}\n\t};\n\tconst prompts = () =>\n\t\tcapabilities?.prompts === undefined\n\t\t\t? Promise.resolve([])\n\t\t\t: aggregatePages<Prompt>(\n\t\t\t\t\tasync (cursor) => {\n\t\t\t\t\t\tconst page = await runtime.request(\n\t\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\t{ method: \"prompts/list\", params: cursor === undefined ? {} : { cursor } },\n\t\t\t\t\t\t\t{ signal },\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\titems: account(page.prompts),\n\t\t\t\t\t\t\t...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tinput.maxPages,\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\tlet catalog: McpClientCatalogSnapshot;\n\tif (input.mode === \"parallel\") {\n\t\tconst [t, r, rt, p] = await Promise.allSettled([\n\t\t\ttools(),\n\t\t\tresources(),\n\t\t\tresourceTemplates(),\n\t\t\tprompts(),\n\t\t]);\n\t\tcatalog = {\n\t\t\ttools: settledValue(t),\n\t\t\tresources: settledValue(r),\n\t\t\tresourceTemplates: settledValue(rt),\n\t\t\tprompts: settledValue(p),\n\t\t};\n\t} else {\n\t\tcatalog = {\n\t\t\ttools: await tools(),\n\t\t\tresources: await resources(),\n\t\t\tresourceTemplates: await resourceTemplates(),\n\t\t\tprompts: await prompts(),\n\t\t};\n\t}\n\tsignal.throwIfAborted();\n\treturn Object.freeze({\n\t\ttools: Object.freeze(catalog.tools),\n\t\tresources: Object.freeze(catalog.resources),\n\t\tresourceTemplates: Object.freeze(catalog.resourceTemplates),\n\t\tprompts: Object.freeze(catalog.prompts),\n\t});\n}\n\n/** Per-run diagnostic target. It shares discovery across checks and never opens a nested lease. */\nexport function createMcpClientInspectionTarget(\n\tinput: Omit<McpClientCatalogInspectionOptions, \"signal\" | \"mode\"> & {\n\t\treadonly leaseSignal: AbortSignal;\n\t},\n): McpPassiveDiscoveryTarget {\n\tlet catalogTask: Promise<McpClientCatalogSnapshot> | undefined;\n\treturn Object.freeze({\n\t\tsnapshot: () => input.runtime.snapshot(input.serverName),\n\t\tasync ping(signal: AbortSignal): Promise<void> {\n\t\t\tawait input.runtime.request(\n\t\t\t\tinput.serverName,\n\t\t\t\t{ method: \"ping\" },\n\t\t\t\t{ signal: AbortSignal.any([input.leaseSignal, signal]) },\n\t\t\t);\n\t\t},\n\t\tcatalog(signal: AbortSignal): Promise<McpClientCatalogSnapshot> {\n\t\t\tinput.leaseSignal.throwIfAborted();\n\t\t\tsignal.throwIfAborted();\n\t\t\tcatalogTask ??= discoverMcpClientCatalog({\n\t\t\t\t...input,\n\t\t\t\tsignal: AbortSignal.any([input.leaseSignal, signal]),\n\t\t\t\tmode: \"sequential\",\n\t\t\t});\n\t\t\treturn catalogTask;\n\t\t},\n\t\tschemaCompiles(schema: unknown): boolean {\n\t\t\ttry {\n\t\t\t\tconst captured = captureMcpToolArguments(schema, ITEM_LIMITS);\n\t\t\t\tif (captured.type !== \"object\") return false;\n\t\t\t\tcreateMcpClientToolSchema({ ...captured, type: \"object\" });\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t});\n}\n\nasync function aggregatePages<Value>(\n\tload: (\n\t\tcursor: string | undefined,\n\t) => Promise<{ readonly items: readonly Value[]; readonly nextCursor?: string }>,\n\tmaxPages: number,\n\tsignal: AbortSignal,\n): Promise<Value[]> {\n\tconst result: Value[] = [];\n\tconst cursors = new Set<string>();\n\tlet cursor: string | undefined;\n\tfor (let index = 0; index < maxPages; index += 1) {\n\t\tsignal.throwIfAborted();\n\t\tconst page = await load(cursor);\n\t\tsignal.throwIfAborted();\n\t\tresult.push(...page.items);\n\t\tif (page.nextCursor === undefined || page.nextCursor.length === 0) return result;\n\t\tif (cursors.has(page.nextCursor)) throw new TypeError(\"The MCP catalog cursor repeated.\");\n\t\tcursors.add(page.nextCursor);\n\t\tcursor = page.nextCursor;\n\t}\n\tthrow new McpClientCatalogLimitError();\n}\n\nfunction settledValue<Value>(result: PromiseSettledResult<Value>): Value {\n\tif (result.status === \"rejected\") throw result.reason;\n\treturn result.value;\n}\n","import {\n\tleaseCapacityExceededError,\n\tleaseInvalidatedError,\n\tleaseManagerClosedError,\n\tleaseReleaseModeConflictError,\n} from \"./errors.ts\";\n\nconst DEFAULT_MAX_RESOURCES = 100;\nconst DEFAULT_IDLE_TTL_MS = 60_000;\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\nconst CREATION_SETTLED = Symbol(\"creation-settled\");\nconst ENTRY_RETIRED = Symbol(\"entry-retired\");\nconst CALLER_ABORTED = Symbol(\"caller-aborted\");\n\n/** Determines what happens when the final reference to one resource is released. */\nexport type McpClientLeaseReleaseMode = \"close\" | \"idle\";\n\nexport interface McpClientLeaseFactoryContext {\n\t/** Aborted when this identity generation is invalidated, abandoned, or shut down. */\n\treadonly signal: AbortSignal;\n}\n\nexport interface McpClientLeaseManagerOptions<Identity, Resource extends object> {\n\t/** A stable, non-secret identity is passed only to this caller-owned factory. */\n\treadonly create: (identity: Identity, context: McpClientLeaseFactoryContext) => Promise<Resource>;\n\t/** Closes a resource exactly once after its identity generation is retired. */\n\treadonly close: (resource: Resource) => Promise<void> | void;\n\t/** Hard bound across pending, ready, and retiring resource generations. */\n\treadonly maxResources?: number;\n\t/** Retention window for resources explicitly acquired in `idle` mode. */\n\treadonly idleTtlMs?: number;\n\t/** Injectable monotonic-enough wall clock for deterministic expiry tests. */\n\treadonly now?: () => number;\n\t/** Called after capacity is released; observer failures cannot affect cleanup. */\n\treadonly onCapacityAvailable?: () => void;\n}\n\nexport interface McpClientLeaseAcquireOptions {\n\t/** Defaults to `close`; use `idle` only for resources safe to reuse. */\n\treadonly releaseMode?: McpClientLeaseReleaseMode;\n\t/** Cancels only this acquisition, never another caller sharing the same creation. */\n\treadonly signal?: AbortSignal;\n\t/** Wait for this reservation's required cleanup on cancellation; defaults to false. */\n\treadonly awaitCleanupOnCancel?: boolean;\n}\n\nexport interface McpClientLease<Resource extends object> extends AsyncDisposable {\n\treadonly resource: Resource;\n\treadonly released: boolean;\n\t/** Releases this reference. Repeated calls return the same settlement. */\n\trelease(): Promise<void>;\n}\n\n/** Aggregate diagnostics deliberately omit opaque identity keys and resources. */\nexport interface McpClientLeaseManagerSnapshot {\n\treadonly closed: boolean;\n\treadonly maxResources: number;\n\treadonly resourceCount: number;\n\treadonly pendingResourceCount: number;\n\treadonly activeResourceCount: number;\n\treadonly idleResourceCount: number;\n\treadonly closingResourceCount: number;\n\treadonly failedResourceCount: number;\n\treadonly referenceCount: number;\n}\n\ntype LeaseEntryState = \"pending\" | \"ready\" | \"closing\" | \"close-failed\";\n\ninterface LeaseEntry<Identity, Resource extends object> {\n\treadonly identity: Identity;\n\treadonly token: symbol;\n\treadonly releaseMode: McpClientLeaseReleaseMode;\n\treadonly controller: AbortController;\n\tstate: LeaseEntryState;\n\trefCount: number;\n\tresource: Resource | undefined;\n\tcreationFailed: boolean;\n\tcreationFailure: unknown;\n\tcreateTask: Promise<void> | undefined;\n\tretired: boolean;\n\tretirementReason: unknown;\n\tdrainTask: Promise<void> | undefined;\n\tresolveDrain: (() => void) | undefined;\n\tcloseTask: Promise<void> | undefined;\n\tidleSince: number | undefined;\n\tidleTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\ninterface AbortWait<Result extends symbol> {\n\treadonly promise: Promise<Result>;\n\tdetach(): void;\n}\n\n/**\n * Bounded, framework-neutral ownership for identity-isolated MCP client resources.\n * Identity keys are compared opaquely with `Map` semantics and are never emitted.\n */\nexport class McpClientLeaseManager<Identity, Resource extends object> implements AsyncDisposable {\n\treadonly #entries = new Map<Identity, LeaseEntry<Identity, Resource>>();\n\treadonly #generations = new Set<LeaseEntry<Identity, Resource>>();\n\treadonly #create: McpClientLeaseManagerOptions<Identity, Resource>[\"create\"];\n\treadonly #closeResource: McpClientLeaseManagerOptions<Identity, Resource>[\"close\"];\n\treadonly #maxResources: number;\n\treadonly #idleTtlMs: number;\n\treadonly #now: () => number;\n\treadonly #onCapacityAvailable: (() => void) | undefined;\n\t#closed = false;\n\t#closeTask: Promise<void> | undefined;\n\n\tconstructor(options: McpClientLeaseManagerOptions<Identity, Resource>) {\n\t\tconst maxResources = options.maxResources ?? DEFAULT_MAX_RESOURCES;\n\t\tconst idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;\n\t\tif (!Number.isInteger(maxResources) || maxResources <= 0) {\n\t\t\tthrow new RangeError(\"McpClientLeaseManager maxResources must be a positive integer.\");\n\t\t}\n\t\tif (!Number.isFinite(idleTtlMs) || idleTtlMs < 0) {\n\t\t\tthrow new RangeError(\"McpClientLeaseManager idleTtlMs must be a non-negative number.\");\n\t\t}\n\t\tthis.#create = options.create;\n\t\tthis.#closeResource = options.close;\n\t\tthis.#maxResources = maxResources;\n\t\tthis.#idleTtlMs = idleTtlMs;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#onCapacityAvailable = options.onCapacityAvailable;\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed;\n\t}\n\n\tget size(): number {\n\t\treturn this.#generations.size;\n\t}\n\n\tsnapshot(): McpClientLeaseManagerSnapshot {\n\t\tlet pendingResourceCount = 0;\n\t\tlet activeResourceCount = 0;\n\t\tlet idleResourceCount = 0;\n\t\tlet closingResourceCount = 0;\n\t\tlet failedResourceCount = 0;\n\t\tlet referenceCount = 0;\n\n\t\tfor (const entry of this.#generations) {\n\t\t\treferenceCount += entry.refCount;\n\t\t\tswitch (entry.state) {\n\t\t\t\tcase \"pending\": {\n\t\t\t\t\tpendingResourceCount += 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"ready\": {\n\t\t\t\t\tif (entry.refCount === 0) idleResourceCount += 1;\n\t\t\t\t\telse activeResourceCount += 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"closing\": {\n\t\t\t\t\tclosingResourceCount += 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"close-failed\": {\n\t\t\t\t\tfailedResourceCount += 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn Object.freeze({\n\t\t\tclosed: this.#closed,\n\t\t\tmaxResources: this.#maxResources,\n\t\t\tresourceCount: this.#generations.size,\n\t\t\tpendingResourceCount,\n\t\t\tactiveResourceCount,\n\t\t\tidleResourceCount,\n\t\t\tclosingResourceCount,\n\t\t\tfailedResourceCount,\n\t\t\treferenceCount,\n\t\t});\n\t}\n\n\t/** Read-only availability for a synchronous acquire reservation. Includes all cleanup. */\n\tcanAcquire(identity: Identity): boolean {\n\t\tif (this.#closed) return false;\n\t\tconst entry = this.#entries.get(identity);\n\t\treturn (entry !== undefined && !entry.retired) || this.#generations.size < this.#maxResources;\n\t}\n\n\tasync acquire(\n\t\tidentity: Identity,\n\t\toptions: McpClientLeaseAcquireOptions = {},\n\t): Promise<McpClientLease<Resource>> {\n\t\tconst releaseMode = options.releaseMode ?? \"close\";\n\t\tassertReleaseMode(releaseMode);\n\t\tif (\n\t\t\toptions.awaitCleanupOnCancel !== undefined &&\n\t\t\ttypeof options.awaitCleanupOnCancel !== \"boolean\"\n\t\t) {\n\t\t\tthrow new TypeError(\"McpClientLeaseManager awaitCleanupOnCancel must be a boolean.\");\n\t\t}\n\t\tthrowIfAborted(options.signal);\n\n\t\tfor (;;) {\n\t\t\tthis.#assertOpen();\n\t\t\tthrowIfAborted(options.signal);\n\n\t\t\tconst existing = this.#entries.get(identity);\n\t\t\tif (existing !== undefined && !existing.retired) {\n\t\t\t\tif (existing.releaseMode !== releaseMode) throw leaseReleaseModeConflictError();\n\t\t\t\tthis.#reserve(existing);\n\t\t\t\treturn this.#awaitLease(existing, options.signal, options.awaitCleanupOnCancel ?? false);\n\t\t\t}\n\n\t\t\tif (this.#generations.size < this.#maxResources) {\n\t\t\t\tconst entry = this.#createEntry(identity, releaseMode);\n\t\t\t\tthis.#reserve(entry);\n\t\t\t\treturn this.#awaitLease(entry, options.signal, options.awaitCleanupOnCancel ?? false);\n\t\t\t}\n\n\t\t\tconst idle = this.#oldestIdleEntry();\n\t\t\tif (idle === undefined) throw leaseCapacityExceededError();\n\t\t\tconst eviction = this.#retireEntry(idle, resourceEvictedReason());\n\t\t\tawait waitForTask(eviction, options.signal);\n\t\t}\n\t}\n\n\t/** Retires the current identity generation before waiting for its close. */\n\tasync invalidate(identity: Identity): Promise<boolean> {\n\t\tthis.#assertOpen();\n\t\tconst entry = this.#entries.get(identity);\n\t\tif (entry === undefined || entry.retired) return false;\n\t\tawait this.#retireEntry(entry, leaseInvalidatedError());\n\t\treturn true;\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#closed = true;\n\n\t\tlet resolveClose: (() => void) | undefined;\n\t\tlet rejectClose: ((error: unknown) => void) | undefined;\n\t\tthis.#closeTask = new Promise<void>((resolve, reject) => {\n\t\t\tresolveClose = resolve;\n\t\t\trejectClose = reject;\n\t\t});\n\n\t\tconst reason = leaseManagerClosedError();\n\t\tconst closeTasks = [...this.#generations].map((entry) => this.#retireEntry(entry, reason));\n\t\tvoid Promise.allSettled(closeTasks).then((settled) => {\n\t\t\tconst failures = settled.flatMap((result) =>\n\t\t\t\tresult.status === \"rejected\" ? [result.reason as unknown] : [],\n\t\t\t);\n\t\t\tif (failures.length === 0) resolveClose?.();\n\t\t\telse {\n\t\t\t\trejectClose?.(\n\t\t\t\t\tnew AggregateError(failures, \"One or more MCP client lease resources failed to close.\"),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\treturn this.#closeTask;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\t#createEntry(\n\t\tidentity: Identity,\n\t\treleaseMode: McpClientLeaseReleaseMode,\n\t): LeaseEntry<Identity, Resource> {\n\t\tconst entry: LeaseEntry<Identity, Resource> = {\n\t\t\tidentity,\n\t\t\ttoken: Symbol(\"mcp-client-lease-generation\"),\n\t\t\treleaseMode,\n\t\t\tcontroller: new AbortController(),\n\t\t\tstate: \"pending\",\n\t\t\trefCount: 0,\n\t\t\tresource: undefined,\n\t\t\tcreationFailed: false,\n\t\t\tcreationFailure: undefined,\n\t\t\tcreateTask: undefined,\n\t\t\tretired: false,\n\t\t\tretirementReason: undefined,\n\t\t\tdrainTask: undefined,\n\t\t\tresolveDrain: undefined,\n\t\t\tcloseTask: undefined,\n\t\t\tidleSince: undefined,\n\t\t\tidleTimer: undefined,\n\t\t};\n\t\tthis.#entries.set(identity, entry);\n\t\tthis.#generations.add(entry);\n\n\t\tconst context = Object.freeze({ signal: entry.controller.signal });\n\t\tentry.createTask = Promise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tconst resource = await this.#create(identity, context);\n\t\t\t\tassertResource(resource);\n\t\t\t\tentry.resource = resource;\n\t\t\t\tif (!entry.retired) entry.state = \"ready\";\n\t\t\t} catch (error) {\n\t\t\t\tentry.creationFailed = true;\n\t\t\t\tentry.creationFailure = error;\n\t\t\t\tif (!entry.retired) this.#failCreation(entry, error);\n\t\t\t}\n\t\t});\n\n\t\treturn entry;\n\t}\n\n\t#reserve(entry: LeaseEntry<Identity, Resource>): void {\n\t\tthis.#clearIdle(entry);\n\t\tentry.refCount += 1;\n\t}\n\n\tasync #awaitLease(\n\t\tentry: LeaseEntry<Identity, Resource>,\n\t\tcallerSignal: AbortSignal | undefined,\n\t\tawaitCleanupOnCancel: boolean,\n\t): Promise<McpClientLease<Resource>> {\n\t\tconst createTask = requireCreateTask(entry);\n\t\tconst retired = waitForAbort(entry.controller.signal, ENTRY_RETIRED);\n\t\tconst caller =\n\t\t\tcallerSignal === undefined ? undefined : waitForAbort(callerSignal, CALLER_ABORTED);\n\n\t\ttry {\n\t\t\tconst outcome = await Promise.race([\n\t\t\t\tcreateTask.then(() => CREATION_SETTLED),\n\t\t\t\tretired.promise,\n\t\t\t\t...(caller === undefined ? [] : [caller.promise]),\n\t\t\t]);\n\n\t\t\tif (outcome === CALLER_ABORTED) {\n\t\t\t\tconst cleanup = this.#cancelReservation(entry);\n\t\t\t\tif (awaitCleanupOnCancel) await cleanup;\n\t\t\t\telse this.#observeBackground(cleanup);\n\t\t\t\tthrow abortReason(callerSignal);\n\t\t\t}\n\t\t\tif (entry.retired || outcome === ENTRY_RETIRED) {\n\t\t\t\tthis.#dropReference(entry);\n\t\t\t\tif (awaitCleanupOnCancel) await entry.closeTask;\n\t\t\t\tthrow entry.retirementReason;\n\t\t\t}\n\t\t\tif (entry.creationFailed) {\n\t\t\t\tthis.#dropReference(entry);\n\t\t\t\tthrow entry.creationFailure;\n\t\t\t}\n\t\t\tif (entry.state !== \"ready\" || entry.resource === undefined) {\n\t\t\t\tconst cleanup = this.#cancelReservation(entry);\n\t\t\t\tif (awaitCleanupOnCancel) await cleanup;\n\t\t\t\telse this.#observeBackground(cleanup);\n\t\t\t\tthrow new Error(\"The MCP client lease resource did not become ready.\");\n\t\t\t}\n\n\t\t\treturn new ManagedMcpClientLease(entry.resource, () => this.#releaseReference(entry));\n\t\t} finally {\n\t\t\tretired.detach();\n\t\t\tcaller?.detach();\n\t\t}\n\t}\n\n\t#releaseReference(entry: LeaseEntry<Identity, Resource>): Promise<void> {\n\t\tthis.#dropReference(entry);\n\t\tif (entry.refCount !== 0) return Promise.resolve();\n\t\tif (entry.retired) return entry.closeTask ?? Promise.resolve();\n\n\t\tif (entry.state === \"pending\") {\n\t\t\treturn this.#retireEntry(entry, acquisitionAbandonedReason());\n\t\t}\n\t\tif (entry.state !== \"ready\") return Promise.resolve();\n\t\tif (entry.releaseMode === \"close\") {\n\t\t\treturn this.#retireEntry(entry, finalReleaseReason());\n\t\t}\n\t\treturn this.#scheduleIdle(entry);\n\t}\n\n\t#cancelReservation(entry: LeaseEntry<Identity, Resource>): Promise<void> {\n\t\tthis.#dropReference(entry);\n\t\tif (entry.refCount !== 0) return Promise.resolve();\n\t\tif (entry.retired) return entry.closeTask ?? Promise.resolve();\n\t\treturn this.#retireEntry(entry, acquisitionAbandonedReason());\n\t}\n\n\t#dropReference(entry: LeaseEntry<Identity, Resource>): void {\n\t\tif (entry.refCount === 0) return;\n\t\tentry.refCount -= 1;\n\t\tif (entry.refCount === 0) {\n\t\t\tentry.resolveDrain?.();\n\t\t\tentry.resolveDrain = undefined;\n\t\t}\n\t}\n\n\t#scheduleIdle(entry: LeaseEntry<Identity, Resource>): Promise<void> {\n\t\tentry.idleSince = this.#now();\n\t\tif (this.#idleTtlMs === 0) {\n\t\t\treturn this.#retireEntry(entry, idleExpiredReason());\n\t\t}\n\t\tthis.#armIdleTimer(entry, entry.idleSince);\n\t\treturn Promise.resolve();\n\t}\n\n\t#armIdleTimer(entry: LeaseEntry<Identity, Resource>, idleSince: number): void {\n\t\tconst remaining = Math.max(0, idleSince + this.#idleTtlMs - this.#now());\n\t\tconst timer = setTimeout(\n\t\t\t() => {\n\t\t\t\tif (entry.idleTimer !== timer) return;\n\t\t\t\tentry.idleTimer = undefined;\n\t\t\t\tif (\n\t\t\t\t\tentry.retired ||\n\t\t\t\t\tentry.state !== \"ready\" ||\n\t\t\t\t\tentry.refCount !== 0 ||\n\t\t\t\t\tentry.idleSince !== idleSince\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.#now() < idleSince + this.#idleTtlMs) {\n\t\t\t\t\tthis.#armIdleTimer(entry, idleSince);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.#observeBackground(this.#retireEntry(entry, idleExpiredReason()));\n\t\t\t},\n\t\t\tMath.min(remaining, MAX_TIMER_DELAY_MS),\n\t\t);\n\t\ttimer.unref?.();\n\t\tentry.idleTimer = timer;\n\t}\n\n\t#clearIdle(entry: LeaseEntry<Identity, Resource>): void {\n\t\tif (entry.idleTimer !== undefined) clearTimeout(entry.idleTimer);\n\t\tentry.idleTimer = undefined;\n\t\tentry.idleSince = undefined;\n\t}\n\n\t#oldestIdleEntry(): LeaseEntry<Identity, Resource> | undefined {\n\t\tlet oldest: LeaseEntry<Identity, Resource> | undefined;\n\t\tfor (const entry of this.#entries.values()) {\n\t\t\tif (\n\t\t\t\tentry.retired ||\n\t\t\t\tentry.state !== \"ready\" ||\n\t\t\t\tentry.refCount !== 0 ||\n\t\t\t\tentry.releaseMode !== \"idle\" ||\n\t\t\t\tentry.idleSince === undefined\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (oldest === undefined || entry.idleSince < (oldest.idleSince ?? Infinity)) {\n\t\t\t\toldest = entry;\n\t\t\t}\n\t\t}\n\t\treturn oldest;\n\t}\n\n\t#retireEntry(entry: LeaseEntry<Identity, Resource>, reason: unknown): Promise<void> {\n\t\tif (entry.closeTask !== undefined) return entry.closeTask;\n\t\tentry.retired = true;\n\t\tentry.retirementReason = reason;\n\t\tentry.state = \"closing\";\n\t\tthis.#clearIdle(entry);\n\t\tif (this.#entries.get(entry.identity)?.token === entry.token) {\n\t\t\tthis.#entries.delete(entry.identity);\n\t\t}\n\t\tif (entry.refCount === 0) {\n\t\t\tentry.drainTask = Promise.resolve();\n\t\t} else {\n\t\t\tentry.drainTask = new Promise<void>((resolve) => {\n\t\t\t\tentry.resolveDrain = resolve;\n\t\t\t});\n\t\t}\n\n\t\tentry.closeTask = Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tawait Promise.all([requireCreateTask(entry), requireDrainTask(entry)]);\n\t\t\t\tif (entry.resource !== undefined) {\n\t\t\t\t\tawait this.#closeResource(entry.resource);\n\t\t\t\t\tentry.resource = undefined;\n\t\t\t\t}\n\t\t\t\tthis.#generations.delete(entry);\n\t\t\t\tthis.#notifyCapacity();\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tentry.state = \"close-failed\";\n\t\t\t\tthrow error;\n\t\t\t});\n\t\tentry.controller.abort(reason);\n\t\treturn entry.closeTask;\n\t}\n\n\t#failCreation(entry: LeaseEntry<Identity, Resource>, error: unknown): void {\n\t\tentry.retired = true;\n\t\tentry.retirementReason = error;\n\t\tif (this.#entries.get(entry.identity)?.token === entry.token) {\n\t\t\tthis.#entries.delete(entry.identity);\n\t\t}\n\t\tthis.#generations.delete(entry);\n\t\tentry.controller.abort(error);\n\t\tthis.#notifyCapacity();\n\t}\n\n\t#notifyCapacity(): void {\n\t\ttry {\n\t\t\tthis.#onCapacityAvailable?.();\n\t\t} catch {\n\t\t\t/* Observers cannot fail resource cleanup. */\n\t\t}\n\t}\n\n\t#observeBackground(task: Promise<void>): void {\n\t\tvoid task.catch(() => undefined);\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#closed) throw leaseManagerClosedError();\n\t}\n}\n\nclass ManagedMcpClientLease<Resource extends object> implements McpClientLease<Resource> {\n\treadonly resource: Resource;\n\treadonly #releaseLease: () => Promise<void>;\n\t#releaseTask: Promise<void> | undefined;\n\n\tconstructor(resource: Resource, releaseLease: () => Promise<void>) {\n\t\tthis.resource = resource;\n\t\tthis.#releaseLease = releaseLease;\n\t}\n\n\tget released(): boolean {\n\t\treturn this.#releaseTask !== undefined;\n\t}\n\n\trelease(): Promise<void> {\n\t\tif (this.#releaseTask === undefined) {\n\t\t\ttry {\n\t\t\t\tthis.#releaseTask = this.#releaseLease();\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\nfunction requireCreateTask<Identity, Resource extends object>(\n\tentry: LeaseEntry<Identity, Resource>,\n): Promise<void> {\n\tif (entry.createTask === undefined) {\n\t\tthrow new Error(\"The MCP client lease resource factory did not start.\");\n\t}\n\treturn entry.createTask;\n}\n\nfunction requireDrainTask<Identity, Resource extends object>(\n\tentry: LeaseEntry<Identity, Resource>,\n): Promise<void> {\n\tif (entry.drainTask === undefined) {\n\t\tthrow new Error(\"The MCP client lease resource retirement did not start.\");\n\t}\n\treturn entry.drainTask;\n}\n\nfunction waitForAbort<Result extends symbol>(\n\tsignal: AbortSignal,\n\tresult: Result,\n): AbortWait<Result> {\n\tif (signal.aborted) {\n\t\treturn { promise: Promise.resolve(result), detach: noop };\n\t}\n\tlet resolveAbort: ((value: Result) => void) | undefined;\n\tconst promise = new Promise<Result>((resolve) => {\n\t\tresolveAbort = resolve;\n\t});\n\tconst onAbort = (): void => resolveAbort?.(result);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\treturn {\n\t\tpromise,\n\t\tdetach(): void {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t},\n\t};\n}\n\nasync function waitForTask(task: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (signal === undefined) {\n\t\tawait task;\n\t\treturn;\n\t}\n\tthrowIfAborted(signal);\n\tconst aborted = waitForAbort(signal, CALLER_ABORTED);\n\ttry {\n\t\tconst result = await Promise.race([task.then(() => CREATION_SETTLED), aborted.promise]);\n\t\tif (result === CALLER_ABORTED) throw abortReason(signal);\n\t} finally {\n\t\taborted.detach();\n\t}\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted === true) throw abortReason(signal);\n}\n\nfunction abortReason(signal: AbortSignal | undefined): unknown {\n\treturn signal?.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\nfunction assertReleaseMode(mode: string): asserts mode is McpClientLeaseReleaseMode {\n\tif (mode !== \"close\" && mode !== \"idle\") {\n\t\tthrow new TypeError('McpClientLeaseManager releaseMode must be \"close\" or \"idle\".');\n\t}\n}\n\nfunction assertResource(resource: object): void {\n\tif (resource === null || (typeof resource !== \"object\" && typeof resource !== \"function\")) {\n\t\tthrow new TypeError(\"McpClientLeaseManager create must resolve to a resource object.\");\n\t}\n}\n\nfunction acquisitionAbandonedReason(): DOMException {\n\treturn new DOMException(\"The MCP client resource creation was abandoned.\", \"AbortError\");\n}\n\nfunction resourceEvictedReason(): DOMException {\n\treturn new DOMException(\"The idle MCP client resource was evicted.\", \"AbortError\");\n}\n\nfunction idleExpiredReason(): DOMException {\n\treturn new DOMException(\"The idle MCP client resource expired.\", \"AbortError\");\n}\n\nfunction finalReleaseReason(): DOMException {\n\treturn new DOMException(\"The MCP client resource's final lease was released.\", \"AbortError\");\n}\n\nfunction noop(): void {}\n"],"mappings":";;;;;;;;AAAA,MAAa,4BAA4B;AACzC,MAAa,2BAA2B;AACxC,MAAa,8BAA8B;AAC3C,MAAa,2BAA2B;AACxC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;AAC/C,MAAa,qCAAqC;AAClD,MAAa,yCACZ;AACD,MAAa,+BAA+B;;AAgB5C,IAAa,wBA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,MAAM,YAAY,MAAM;CACxD,UAAU;EACT,QAAQ,OAAO;CAChB;AACD;AAEA,SAAS,eAAe,QAAuC;CAC9D,IAAI,QAAQ,YAAY,MAAM,MAAM,YAAY,MAAM;AACvD;AAEA,SAAS,YAAY,QAA0C;CAC9D,OAAO,QAAQ,UAAU,IAAI,aAAa,8BAA8B,YAAY;AACrF;AAEA,SAAS,kBAAkB,MAAyD;CACnF,IAAI,SAAS,WAAW,SAAS,QAChC,MAAM,IAAI,UAAU,kEAA8D;AAEpF;AAEA,SAAS,eAAe,UAAwB;CAC/C,IAAI,aAAa,QAAS,OAAO,aAAa,YAAY,OAAO,aAAa,YAC7E,MAAM,IAAI,UAAU,iEAAiE;AAEvF;AAEA,SAAS,6BAA2C;CACnD,OAAO,IAAI,aAAa,mDAAmD,YAAY;AACxF;AAEA,SAAS,wBAAsC;CAC9C,OAAO,IAAI,aAAa,6CAA6C,YAAY;AAClF;AAEA,SAAS,oBAAkC;CAC1C,OAAO,IAAI,aAAa,yCAAyC,YAAY;AAC9E;AAEA,SAAS,qBAAmC;CAC3C,OAAO,IAAI,aAAa,uDAAuD,YAAY;AAC5F;AAEA,SAAS,OAAa,CAAC"}
@@ -0,0 +1,92 @@
1
+ import { S as McpClientOAuthClient, n as McpClientOAuthBootstrapCandidate } from "../bootstrap-BIAcDnHp.mjs";
2
+ import { FetchLike } from "@modelcontextprotocol/client";
3
+ //#region src/oauth/dynamic-registration.d.ts
4
+ /** Stable, secret-free failure categories for explicitly enabled legacy DCR. */
5
+ declare const McpClientOAuthDynamicRegistrationErrorCode: {
6
+ readonly InvalidOptions: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_INVALID_OPTIONS";
7
+ readonly Unsupported: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_UNSUPPORTED";
8
+ readonly EndpointRejected: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_ENDPOINT_REJECTED";
9
+ readonly RegistrationRejected: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_REJECTED";
10
+ readonly ResponseInvalid: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_RESPONSE_INVALID";
11
+ readonly OutcomeUnknown: "MCP_CLIENT_OAUTH_DYNAMIC_REGISTRATION_OUTCOME_UNKNOWN";
12
+ };
13
+ type McpClientOAuthDynamicRegistrationErrorCode = (typeof McpClientOAuthDynamicRegistrationErrorCode)[keyof typeof McpClientOAuthDynamicRegistrationErrorCode];
14
+ /** Public errors contain no remote body, URL, client identifier, or host exception text. */
15
+ declare class McpClientOAuthDynamicRegistrationError extends Error {
16
+ readonly code: McpClientOAuthDynamicRegistrationErrorCode;
17
+ /** Whether the registration POST was handed to the host fetch. */
18
+ readonly requestDispatched: boolean;
19
+ /** False after dispatch: retrying could create a second client registration. */
20
+ readonly retrySafe: boolean;
21
+ constructor(code: McpClientOAuthDynamicRegistrationErrorCode, requestDispatched?: boolean);
22
+ }
23
+ interface McpClientOAuthDynamicRegistrationEndpointPolicyInput {
24
+ /** A disposable copy; mutation cannot change the request destination. */
25
+ readonly endpoint: URL;
26
+ readonly exactRegistrationEndpoint: string;
27
+ readonly issuer: URL;
28
+ /** Preserved exactly for issuer binding and RFC 9207 comparisons. */
29
+ readonly exactIssuer: string;
30
+ readonly serverUrl: URL;
31
+ readonly resource: URL;
32
+ readonly method: "POST";
33
+ readonly credentialed: false;
34
+ readonly signal?: AbortSignal;
35
+ }
36
+ /** Only literal `true` admits the single registration POST. */
37
+ type McpClientOAuthDynamicRegistrationEndpointPolicy = (input: McpClientOAuthDynamicRegistrationEndpointPolicyInput) => boolean | PromiseLike<boolean>;
38
+ interface McpClientOAuthDynamicRegistrationOptions {
39
+ /**
40
+ * A host-owned SSRF-hardened fetch with DNS pinning, response byte/time limits, and no retries.
41
+ * This primitive additionally forces `redirect: "error"` and invokes it exactly once.
42
+ */
43
+ readonly fetch: FetchLike;
44
+ readonly endpointPolicy: McpClientOAuthDynamicRegistrationEndpointPolicy;
45
+ }
46
+ /** Narrow allowlist for a public authorization-code client's RFC 7591 request metadata. */
47
+ interface McpClientOAuthDynamicRegistrationClientMetadata {
48
+ readonly clientName: string;
49
+ /** Explicit RFC 7591 application classification; never inferred from redirect URI shape. */
50
+ readonly applicationType: "native" | "web";
51
+ readonly redirectUris: readonly string[];
52
+ readonly clientUri?: string;
53
+ readonly contacts?: readonly string[];
54
+ readonly softwareId?: string;
55
+ readonly softwareVersion?: string;
56
+ }
57
+ interface McpClientOAuthDynamicRegistrationInput {
58
+ /** Must be the selected `ready.candidate` returned by `McpClientOAuthBootstrap`. */
59
+ readonly candidate: McpClientOAuthBootstrapCandidate;
60
+ readonly clientMetadata: McpClientOAuthDynamicRegistrationClientMetadata;
61
+ readonly scopes?: readonly string[];
62
+ readonly signal?: AbortSignal;
63
+ }
64
+ interface McpClientOAuthDynamicRegistrationResult {
65
+ readonly issuer: string;
66
+ /** Directly consumable by `McpClientOAuthProtocol.startAuthorization`. */
67
+ readonly client: McpClientOAuthClient;
68
+ /** Some legacy servers issue a non-confidential secret even to public clients. */
69
+ readonly clientSecret?: string;
70
+ readonly clientIdIssuedAt?: number;
71
+ readonly clientSecretExpiresAt?: number;
72
+ readonly registeredScopes?: readonly string[];
73
+ }
74
+ /**
75
+ * Explicit compatibility primitive for deprecated Dynamic Client Registration.
76
+ *
77
+ * It is intentionally exported only from `@nest-mcp/client/oauth/dynamic-registration`; normal
78
+ * strict OAuth imports cannot invoke it. The host owns persistence, encryption, tenant policy,
79
+ * browser state, and the decision to opt into this legacy operation.
80
+ */
81
+ declare class McpClientOAuthDynamicRegistration {
82
+ #private;
83
+ constructor(options: McpClientOAuthDynamicRegistrationOptions);
84
+ /**
85
+ * Performs one registration attempt. When a rejected error has `retrySafe === false`, the POST
86
+ * was already dispatched and the same logical registration must never be retried.
87
+ */
88
+ register(input: McpClientOAuthDynamicRegistrationInput): Promise<McpClientOAuthDynamicRegistrationResult>;
89
+ }
90
+ //#endregion
91
+ export { McpClientOAuthDynamicRegistration, McpClientOAuthDynamicRegistrationClientMetadata, McpClientOAuthDynamicRegistrationEndpointPolicy, McpClientOAuthDynamicRegistrationEndpointPolicyInput, McpClientOAuthDynamicRegistrationError, McpClientOAuthDynamicRegistrationErrorCode, McpClientOAuthDynamicRegistrationInput, McpClientOAuthDynamicRegistrationOptions, McpClientOAuthDynamicRegistrationResult };
92
+ //# sourceMappingURL=dynamic-registration.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dynamic-registration.d.mts","names":[],"sources":["../../src/oauth/dynamic-registration.ts"],"mappings":";;;;cAkBa;WACZ;WACA;WACA;WACA;WACA;WACA;;KAGW,qDACH,yDAAyD;;cAGrD,+CAA+C;WAClD,MAAM;;WAEN;;WAEA;EAET,YAAY,MAAM,4CAA4C;;UAS9C;;WAEP,UAAU;WACV;WACA,QAAQ;;WAER;WACA,WAAW;WACX,UAAU;WACV;WACA;WACA,SAAS;;;KAIP,mDACX,OAAO,mEACO;UAEE;;;;;WAKP,OAAO;WACP,gBAAgB;;;UAIT;WACP;;WAEA;WACA;WACA;WACA;WACA;WACA;;UAGO;;WAEP,WAAW;WACX,gBAAgB;WAChB;WACA,SAAS;;UAGF;WACP;;WAEA,QAAQ;;WAER;WACA;WACA;WACA;;;;;;;;;cAUG;;EAIZ,YAAY,SAAS;;;;;EAiBf,SACL,OAAO,yCACL,QAAQ"}