@nest-mcp/client 1.0.2 → 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":["#identity","#expectedCredentialRevision","#store","#refreshCoordinator","#selectBearerToken","#lifecycleController","#inFlight","#closed","#start","#loadCurrent","#readBearerToken","#assertActive","#loadOptional","refreshFailedError","invalidStoreResultError","#closeTask","credentialMissingError","storeFailedError","isObjectLike","invalidOptionsError","invalidOptionsError","containsControlCharacter","MAX_URL_LENGTH","MAX_SCOPE_COUNT","MAX_SCOPE_STRING_LENGTH","MAX_METADATA_LIST_LENGTH","MAX_METADATA_VALUE_LENGTH","#fetch","#endpointPolicy","#authorizationTransactionTtlMs","#now","invalidOptionsError","normalizeDiscoveryInput","#createFetch","#authorizeEndpoint","copyAuthority","requireSecureUrl","combineAbortSignals","isExactResponseUrl","awaitWithSignal","normalizeMetadataList","containsControlCharacter","throwIfAborted","#fetch","#endpointPolicy","#protocolVersion","#createFetch","#authorizeEndpoint","#store","#refreshCredential","#classifyRefreshFailure","#onInvalidated","#maxInFlightKeys","#refreshes","#invalidations","#retiredRevisions","#closed","#inFlightKeyCount","#assertOpen","#assertGenerationUsable","#waitForRefresh","#assertCapacity","#createRefreshEntry","#waitForInvalidation","#waitForSettlingInvalidation","#createInvalidationEntry","#retireRefresh","#closeTask","#executeRefresh","#executeInvalidation","#claimRefresh","#settleClaimUncertainty","#settleUnclaimed","#clearRetiredRevision","#handleRefreshFailure","#retireGeneration","#commitRefresh","#settleCommitUncertainty","#releaseRetrySafeClaim","#releaseRefreshClaim","#load","#notifyInvalidated","#invalidateStored","#failClosedGeneration","#reloadAfterInvalidationConflict","#retireRevision","invalidOptions","#controller","#cancellations","#readers","#fetch","#requests","#cancelBody","#bounded","#bytes"],"sources":["../../src/oauth/credential-store.ts","../../src/oauth/auth-provider.ts","../../src/oauth/state.ts","../../src/oauth/protocol-error-brand.ts","../../src/oauth/snapshot-data.ts","../../src/oauth/protocol.ts","../../src/oauth/bootstrap.ts","../../src/oauth/refresh-coordinator.ts","../../src/oauth/provisioning.ts","../../src/oauth/challenge-probe.ts","../../src/oauth/authentication-detection.ts"],"sourcesContent":["declare const MCP_CLIENT_OAUTH_CREDENTIAL_REVISION: unique symbol;\n\n/** A database-safe, positive revision used for exact credential-generation CAS. */\nexport type McpClientOAuthCredentialRevision = number & {\n\treadonly [MCP_CLIENT_OAUTH_CREDENTIAL_REVISION]: \"McpClientOAuthCredentialRevision\";\n};\n\n/** Fresh, opaque ownership proof for one durable pre-dispatch refresh claim. */\nexport interface McpClientOAuthRefreshClaimId {\n\treadonly value: string;\n}\n\n/** Stable reasons used for exact-generation invalidation or disappearance notification. */\nexport const McpClientOAuthCredentialInvalidationReason = {\n\tExplicit: \"explicit\",\n\tInvalidGrant: \"invalid-grant\",\n\t/** The exact generation was absent when observed, without a local invalidation mutation. */\n\tObservedExternal: \"observed-external\",\n\tTerminalRefreshFailure: \"terminal-refresh-failure\",\n} as const;\n\nexport type McpClientOAuthCredentialInvalidationReason =\n\t(typeof McpClientOAuthCredentialInvalidationReason)[keyof typeof McpClientOAuthCredentialInvalidationReason];\n\n/** Terminal refresh reasons accepted from a refresh-failure classifier. */\nexport type McpClientOAuthTerminalRefreshReason =\n\t| typeof McpClientOAuthCredentialInvalidationReason.InvalidGrant\n\t| typeof McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure;\n\n/**\n * One authoritative credential generation.\n *\n * `credential` is the complete replacement set, including a rotated refresh token when one was\n * returned. The wrapper is immutable; credential implementations must likewise treat their value\n * as immutable and replace it atomically instead of editing it in place.\n */\nexport interface McpClientOAuthCredentialSnapshot<Credential extends object> {\n\treadonly revision: McpClientOAuthCredentialRevision;\n\treadonly credential: Readonly<Credential>;\n}\n\n/** Cancellation owned by the coordinator lifecycle, never by one caller waiting on shared work. */\nexport interface McpClientOAuthCredentialStoreContext {\n\treadonly signal: AbortSignal;\n}\n\nexport interface McpClientOAuthRefreshClaimed<Credential extends object> {\n\treadonly status: \"claimed\";\n\t/** The exact generation durably fenced for this claim before any refresh request is sent. */\n\treadonly snapshot: McpClientOAuthCredentialSnapshot<Credential>;\n}\n\nexport interface McpClientOAuthRefreshClaimBusy {\n\treadonly status: \"busy\";\n}\n\nexport interface McpClientOAuthRefreshClaimConflict {\n\treadonly status: \"conflict\";\n}\n\nexport type McpClientOAuthRefreshClaimResult<Credential extends object> =\n\t| McpClientOAuthRefreshClaimed<Credential>\n\t| McpClientOAuthRefreshClaimBusy\n\t| McpClientOAuthRefreshClaimConflict;\n\nexport interface McpClientOAuthRefreshCommitApplied<Credential extends object> {\n\treadonly status: \"applied\";\n\t/** The authoritative, complete replacement persisted at exactly the next revision. */\n\treadonly snapshot: McpClientOAuthCredentialSnapshot<Credential>;\n}\n\nexport interface McpClientOAuthRefreshCommitConflict {\n\treadonly status: \"conflict\";\n}\n\nexport type McpClientOAuthRefreshCommitResult<Credential extends object> =\n\tMcpClientOAuthRefreshCommitApplied<Credential> | McpClientOAuthRefreshCommitConflict;\n\nexport interface McpClientOAuthRefreshClaimReleased {\n\treadonly status: \"released\";\n}\n\nexport interface McpClientOAuthRefreshClaimReleaseConflict {\n\treadonly status: \"conflict\";\n}\n\nexport type McpClientOAuthRefreshClaimReleaseResult =\n\tMcpClientOAuthRefreshClaimReleased | McpClientOAuthRefreshClaimReleaseConflict;\n\n/** Exact CAS for non-refresh credential writers such as an authorization callback. */\nexport interface McpClientOAuthCredentialCompareAndSwapApplied<Credential extends object> {\n\treadonly status: \"applied\";\n\treadonly snapshot: McpClientOAuthCredentialSnapshot<Credential>;\n}\n\nexport interface McpClientOAuthCredentialCompareAndSwapConflict {\n\treadonly status: \"conflict\";\n}\n\nexport type McpClientOAuthCredentialCompareAndSwapResult<Credential extends object> =\n\t| McpClientOAuthCredentialCompareAndSwapApplied<Credential>\n\t| McpClientOAuthCredentialCompareAndSwapConflict;\n\nexport interface McpClientOAuthCredentialInvalidationApplied {\n\treadonly status: \"applied\";\n}\n\nexport interface McpClientOAuthCredentialInvalidationConflict {\n\treadonly status: \"conflict\";\n}\n\nexport type McpClientOAuthCredentialInvalidationResult =\n\tMcpClientOAuthCredentialInvalidationApplied | McpClientOAuthCredentialInvalidationConflict;\n\n/**\n * Persistence port for one opaque, non-secret OAuth credential identity.\n *\n * `claimRefresh` must atomically and durably transition the exact active generation to claimed\n * before returning it. Only its fresh `claimId` may commit or explicitly release that claim. A\n * claimed generation must never become active automatically: stale or abandoned claims are\n * terminal and must be invalidated by store policy. Ambiguous claim/commit failures must leave the\n * exact generation claimed or terminal, never active. A successful commit atomically stores the\n * complete credential set at `expectedRevision + 1`. `invalidate` must invalidate the exact\n * revision even while claimed. Conflict results must not mutate a newer generation.\n */\nexport interface McpClientOAuthCredentialStore<Identity, Credential extends object> {\n\t/** Returns the authoritative snapshot for active or durably claimed state; absent is terminal. */\n\tload(\n\t\tidentity: Identity,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthCredentialSnapshot<Credential> | undefined>;\n\n\tclaimRefresh(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\tclaimId: McpClientOAuthRefreshClaimId,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthRefreshClaimResult<Credential>>;\n\n\tcommitRefresh(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\tclaimId: McpClientOAuthRefreshClaimId,\n\t\tcredential: Readonly<Credential>,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthRefreshCommitResult<Credential>>;\n\n\treleaseRefreshClaim(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\tclaimId: McpClientOAuthRefreshClaimId,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthRefreshClaimReleaseResult>;\n\n\t/** Non-refresh exact writer. It must never reactivate or overwrite a claimed generation. */\n\tcompareAndSwap(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\tcredential: Readonly<Credential>,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthCredentialCompareAndSwapResult<Credential>>;\n\n\tinvalidate(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\treason: McpClientOAuthCredentialInvalidationReason,\n\t\tcontext: McpClientOAuthCredentialStoreContext,\n\t): Promise<McpClientOAuthCredentialInvalidationResult>;\n}\n\n/** Validates and brands an exact positive credential revision. */\nexport function createMcpClientOAuthCredentialRevision(\n\tvalue: number,\n): McpClientOAuthCredentialRevision {\n\tif (!isMcpClientOAuthCredentialRevision(value)) {\n\t\tthrow new RangeError(\"An OAuth credential revision must be a positive safe integer.\");\n\t}\n\treturn value;\n}\n\n/** Runtime predicate for values crossing persistence or serialization boundaries. */\nexport function isMcpClientOAuthCredentialRevision(\n\tvalue: unknown,\n): value is McpClientOAuthCredentialRevision {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n}\n\n/** Returns the only revision valid for a successful exact compare-and-swap. */\nexport function nextMcpClientOAuthCredentialRevision(\n\trevision: McpClientOAuthCredentialRevision,\n): McpClientOAuthCredentialRevision {\n\treturn createMcpClientOAuthCredentialRevision(revision + 1);\n}\n\n/** Creates the frozen wrapper shared by stores and refresh callers. */\nexport function createMcpClientOAuthCredentialSnapshot<Credential extends object>(\n\trevision: number,\n\tcredential: Readonly<Credential>,\n): McpClientOAuthCredentialSnapshot<Credential> {\n\tassertCredentialObject(credential);\n\treturn Object.freeze({\n\t\trevision: createMcpClientOAuthCredentialRevision(revision),\n\t\tcredential,\n\t});\n}\n\nfunction assertCredentialObject(credential: object): void {\n\tif (credential === null || (typeof credential !== \"object\" && typeof credential !== \"function\")) {\n\t\tthrow new TypeError(\"An OAuth credential snapshot must contain a credential object.\");\n\t}\n}\n","import type { AuthProvider } from \"@modelcontextprotocol/client\";\n\nimport {\n\tcreateMcpClientOAuthCredentialSnapshot,\n\tisMcpClientOAuthCredentialRevision,\n\ttype McpClientOAuthCredentialSnapshot,\n\ttype McpClientOAuthCredentialRevision,\n\ttype McpClientOAuthCredentialStore,\n} from \"./credential-store.ts\";\nimport type { McpClientOAuthRefreshCoordinator } from \"./refresh-coordinator.ts\";\n\nconst MAX_BEARER_TOKEN_LENGTH = 65_536;\nconst BEARER_TOKEN_PATTERN = /^[-A-Za-z0-9._~+/]+=*$/u;\n\ntype UnauthorizedContext = Parameters<NonNullable<AuthProvider[\"onUnauthorized\"]>>[0];\n\n/** Stable, identity- and secret-free transport-bridge failures. */\nexport const McpClientOAuthAuthProviderErrorCode = {\n\tInvalidOptions: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_INVALID_OPTIONS\",\n\tClosed: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_CLOSED\",\n\tCredentialMissing: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_CREDENTIAL_MISSING\",\n\tCredentialRevisionChanged: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_CREDENTIAL_REVISION_CHANGED\",\n\tStoreFailed: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_STORE_FAILED\",\n\tInvalidStoreResult: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_STORE_RESULT_INVALID\",\n\tTokenMissing: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_MISSING\",\n\tTokenInvalid: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_INVALID\",\n\tTokenAccessorFailed: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_ACCESSOR_FAILED\",\n\tRefreshFailed: \"MCP_CLIENT_OAUTH_AUTH_PROVIDER_REFRESH_FAILED\",\n} as const;\n\nexport type McpClientOAuthAuthProviderErrorCode =\n\t(typeof McpClientOAuthAuthProviderErrorCode)[keyof typeof McpClientOAuthAuthProviderErrorCode];\n\n/** Error whose public fields and message never contain an identity, token, or upstream response. */\nexport class McpClientOAuthAuthProviderError extends Error {\n\treadonly code: McpClientOAuthAuthProviderErrorCode;\n\n\tconstructor(code: McpClientOAuthAuthProviderErrorCode) {\n\t\tsuper(authProviderErrorMessage(code));\n\t\tthis.name = \"McpClientOAuthAuthProviderError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface McpClientOAuthBearerTokenAccessorContext {\n\t/** Provider-lifecycle cancellation. Accessors must stop promptly when it aborts. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Selects the bearer token from one complete, immutable credential generation.\n * Returning `undefined` is a deterministic missing-token failure.\n */\nexport type McpClientOAuthBearerTokenAccessor<Credential extends object> = (\n\tsnapshot: McpClientOAuthCredentialSnapshot<Credential>,\n\tcontext: McpClientOAuthBearerTokenAccessorContext,\n) => string | undefined | PromiseLike<string | undefined>;\n\nexport interface McpClientOAuthAuthProviderOptions<Identity, Credential extends object> {\n\t/** One opaque, stable, non-secret credential binding. It is never exposed by the provider. */\n\treadonly identity: Identity;\n\t/** Pin one operation to an exact revision. Rotation requires a new provider; delayed 401s cannot refresh its replacement. */\n\treadonly expectedCredentialRevision?: McpClientOAuthCredentialRevision;\n\treadonly store: McpClientOAuthCredentialStore<Identity, Credential>;\n\treadonly refreshCoordinator: McpClientOAuthRefreshCoordinator<Identity, Credential>;\n\treadonly selectBearerToken: McpClientOAuthBearerTokenAccessor<Credential>;\n}\n\n/**\n * Per-binding bridge from revisioned OAuth credentials to the SDK's minimal `AuthProvider`.\n *\n * It intentionally has no `tokens()` or `clientInformation()` members, so the official\n * transport cannot classify it as an `OAuthClientProvider` and cannot start interactive or\n * Dynamic Client Registration flows. The store and coordinator are borrowed; closing this\n * bridge never closes either dependency. It follows successful credential revisions within one\n * stable binding by default. Set expectedCredentialRevision for an operation that must close\n * and be reacquired after rotation; its token and refresh paths both enforce the exact revision.\n */\nexport class McpClientOAuthAuthProvider<Identity, Credential extends object>\n\timplements AuthProvider, AsyncDisposable\n{\n\treadonly #identity: Identity;\n\treadonly #expectedCredentialRevision: McpClientOAuthCredentialRevision | undefined;\n\treadonly #store: McpClientOAuthCredentialStore<Identity, Credential>;\n\treadonly #refreshCoordinator: McpClientOAuthRefreshCoordinator<Identity, Credential>;\n\treadonly #selectBearerToken: McpClientOAuthBearerTokenAccessor<Credential>;\n\treadonly #lifecycleController = new AbortController();\n\treadonly #inFlight = new Set<Promise<unknown>>();\n\t#closed = false;\n\t#closeTask: Promise<void> | undefined;\n\n\tconstructor(options: McpClientOAuthAuthProviderOptions<Identity, Credential>) {\n\t\tconst normalized = normalizeOptions(options);\n\t\tthis.#identity = normalized.identity;\n\t\tthis.#expectedCredentialRevision = normalized.expectedCredentialRevision;\n\t\tthis.#store = normalized.store;\n\t\tthis.#refreshCoordinator = normalized.refreshCoordinator;\n\t\tthis.#selectBearerToken = normalized.selectBearerToken;\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed;\n\t}\n\n\t/** Loads the authoritative generation on every request; no token is cached in the bridge. */\n\ttoken(): Promise<string | undefined> {\n\t\treturn this.#start(async () => {\n\t\t\tconst snapshot = await this.#loadCurrent();\n\t\t\treturn this.#readBearerToken(snapshot);\n\t\t});\n\t}\n\n\t/**\n\t * Refreshes exactly the authoritative revision loaded for this binding. Concurrent 401s join\n\t * in the coordinator. A process-external claim or winner is accepted only after an authoritative\n\t * reload; only a strictly newer revision completes this call, and this bridge never retries the\n\t * stale refresh token. The\n\t * SDK does not identify the failed request's credential revision in this callback. A delayed 401\n\t * can therefore arrive after another request published a newer generation and refresh that newer\n\t * generation. An expectedCredentialRevision fences this reload before refresh: a pinned provider\n\t * never refreshes or adopts a replacement. Its successful refresh still publishes for a fresh\n\t * acquisition, while the old operation fails closed. Unpinned hosts need request correlation\n\t * or conservative close/reacquire; the transport bounds each wire request to one retry.\n\t */\n\tonUnauthorized(_context: UnauthorizedContext): Promise<void> {\n\t\treturn this.#start(async () => {\n\t\t\tconst current = await this.#loadCurrent();\n\t\t\tlet refreshed: McpClientOAuthCredentialSnapshot<Credential>;\n\t\t\ttry {\n\t\t\t\trefreshed = await this.#refreshCoordinator.refresh(this.#identity, current.revision, {\n\t\t\t\t\tsignal: this.#lifecycleController.signal,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tthis.#assertActive();\n\t\t\t\tconst winner = await this.#loadOptional();\n\t\t\t\tif (winner !== undefined && winner.revision > current.revision) {\n\t\t\t\t\tawait this.#readBearerToken(winner);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthrow refreshFailedError();\n\t\t\t}\n\n\t\t\tthis.#assertActive();\n\t\t\tconst published = await this.#loadCurrent();\n\t\t\tif (published.revision < refreshed.revision) throw invalidStoreResultError();\n\t\t\tawait this.#readBearerToken(published);\n\t\t});\n\t}\n\n\t/** Fences new work, cancels this provider's waits, and drains all accepted bridge calls. */\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#closed = true;\n\t\tthis.#lifecycleController.abort(providerClosedAbortReason());\n\t\tconst accepted = [...this.#inFlight];\n\t\tthis.#closeTask = Promise.allSettled(accepted).then(() => undefined);\n\t\treturn this.#closeTask;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\t#start<Result>(operation: () => Promise<Result>): Promise<Result> {\n\t\tif (this.#closed) return Promise.reject(providerClosedError());\n\t\tconst task = Promise.resolve().then(operation);\n\t\tthis.#inFlight.add(task);\n\t\tconst remove = (): void => {\n\t\t\tthis.#inFlight.delete(task);\n\t\t};\n\t\tvoid task.then(remove, remove);\n\t\treturn task;\n\t}\n\n\tasync #loadCurrent(): Promise<McpClientOAuthCredentialSnapshot<Credential>> {\n\t\tconst snapshot = await this.#loadOptional();\n\t\tif (snapshot === undefined) throw credentialMissingError();\n\t\treturn snapshot;\n\t}\n\n\tasync #loadOptional(): Promise<McpClientOAuthCredentialSnapshot<Credential> | undefined> {\n\t\tthis.#assertActive();\n\t\tlet snapshot: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\tsnapshot = await this.#store.load(\n\t\t\t\tthis.#identity,\n\t\t\t\tObject.freeze({ signal: this.#lifecycleController.signal }),\n\t\t\t);\n\t\t} catch {\n\t\t\tthis.#assertActive();\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\tthis.#assertActive();\n\t\tif (snapshot === undefined) return undefined;\n\n\t\tlet captured: McpClientOAuthCredentialSnapshot<Credential>;\n\t\ttry {\n\t\t\tif (\n\t\t\t\t!isMcpClientOAuthCredentialRevision(snapshot.revision) ||\n\t\t\t\t!isObjectLike(snapshot.credential)\n\t\t\t) {\n\t\t\t\tthrow invalidStoreResultError();\n\t\t\t}\n\t\t\tcaptured = createMcpClientOAuthCredentialSnapshot<Credential>(\n\t\t\t\tsnapshot.revision,\n\t\t\t\tsnapshot.credential,\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow invalidStoreResultError();\n\t\t}\n\t\tif (\n\t\t\tthis.#expectedCredentialRevision !== undefined &&\n\t\t\tcaptured.revision !== this.#expectedCredentialRevision\n\t\t) {\n\t\t\tthrow new McpClientOAuthAuthProviderError(\n\t\t\t\tMcpClientOAuthAuthProviderErrorCode.CredentialRevisionChanged,\n\t\t\t);\n\t\t}\n\t\treturn captured;\n\t}\n\n\tasync #readBearerToken(snapshot: McpClientOAuthCredentialSnapshot<Credential>): Promise<string> {\n\t\tthis.#assertActive();\n\t\tlet token: string | undefined;\n\t\ttry {\n\t\t\ttoken = await this.#selectBearerToken(\n\t\t\t\tsnapshot,\n\t\t\t\tObject.freeze({ signal: this.#lifecycleController.signal }),\n\t\t\t);\n\t\t} catch {\n\t\t\tthis.#assertActive();\n\t\t\tthrow tokenAccessorFailedError();\n\t\t}\n\t\tthis.#assertActive();\n\t\tif (token === undefined) throw tokenMissingError();\n\t\tif (!isValidBearerToken(token)) throw tokenInvalidError();\n\t\treturn token;\n\t}\n\n\t#assertActive(): void {\n\t\tif (this.#closed || this.#lifecycleController.signal.aborted) {\n\t\t\tthrow providerClosedError();\n\t\t}\n\t}\n}\n\nfunction normalizeOptions<Identity, Credential extends object>(\n\toptions: McpClientOAuthAuthProviderOptions<Identity, Credential>,\n): McpClientOAuthAuthProviderOptions<Identity, Credential> {\n\tif (!isObjectLike(options)) throw invalidOptionsError();\n\tlet identity: Identity;\n\tlet expectedCredentialRevision: McpClientOAuthCredentialRevision | undefined;\n\tlet store: McpClientOAuthCredentialStore<Identity, Credential>;\n\tlet refreshCoordinator: McpClientOAuthRefreshCoordinator<Identity, Credential>;\n\tlet selectBearerToken: McpClientOAuthBearerTokenAccessor<Credential>;\n\ttry {\n\t\tidentity = options.identity;\n\t\texpectedCredentialRevision = options.expectedCredentialRevision;\n\t\tstore = options.store;\n\t\trefreshCoordinator = options.refreshCoordinator;\n\t\tselectBearerToken = options.selectBearerToken;\n\t} catch {\n\t\tthrow invalidOptionsError();\n\t}\n\tlet valid = false;\n\ttry {\n\t\tvalid =\n\t\t\t(expectedCredentialRevision === undefined ||\n\t\t\t\tisMcpClientOAuthCredentialRevision(expectedCredentialRevision)) &&\n\t\t\tisObjectLike(store) &&\n\t\t\ttypeof store.load === \"function\" &&\n\t\t\ttypeof store.claimRefresh === \"function\" &&\n\t\t\ttypeof store.commitRefresh === \"function\" &&\n\t\t\ttypeof store.releaseRefreshClaim === \"function\" &&\n\t\t\ttypeof store.compareAndSwap === \"function\" &&\n\t\t\ttypeof store.invalidate === \"function\" &&\n\t\t\tisObjectLike(refreshCoordinator) &&\n\t\t\ttypeof refreshCoordinator.refresh === \"function\" &&\n\t\t\ttypeof selectBearerToken === \"function\";\n\t} catch {\n\t\tvalid = false;\n\t}\n\tif (!valid) {\n\t\tthrow invalidOptionsError();\n\t}\n\treturn Object.freeze({\n\t\tidentity,\n\t\tstore,\n\t\trefreshCoordinator,\n\t\tselectBearerToken,\n\t\t...(expectedCredentialRevision === undefined ? {} : { expectedCredentialRevision }),\n\t});\n}\n\nfunction isObjectLike(value: unknown): value is object {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\");\n}\n\nfunction isValidBearerToken(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= MAX_BEARER_TOKEN_LENGTH &&\n\t\tBEARER_TOKEN_PATTERN.test(value)\n\t);\n}\n\nfunction invalidOptionsError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.InvalidOptions);\n}\n\nfunction providerClosedError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.Closed);\n}\n\nfunction credentialMissingError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.CredentialMissing);\n}\n\nfunction storeFailedError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.StoreFailed);\n}\n\nfunction invalidStoreResultError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(\n\t\tMcpClientOAuthAuthProviderErrorCode.InvalidStoreResult,\n\t);\n}\n\nfunction tokenMissingError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.TokenMissing);\n}\n\nfunction tokenInvalidError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.TokenInvalid);\n}\n\nfunction tokenAccessorFailedError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(\n\t\tMcpClientOAuthAuthProviderErrorCode.TokenAccessorFailed,\n\t);\n}\n\nfunction refreshFailedError(): McpClientOAuthAuthProviderError {\n\treturn new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.RefreshFailed);\n}\n\nfunction authProviderErrorMessage(code: McpClientOAuthAuthProviderErrorCode): string {\n\tswitch (code) {\n\t\tcase McpClientOAuthAuthProviderErrorCode.InvalidOptions:\n\t\t\treturn \"The OAuth auth-provider options are invalid.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.Closed:\n\t\t\treturn \"The OAuth auth provider is closed and cannot accept new work.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.CredentialMissing:\n\t\t\treturn \"The OAuth credential generation is unavailable.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.CredentialRevisionChanged:\n\t\t\treturn \"The OAuth credential revision changed; acquire a new operation.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.StoreFailed:\n\t\t\treturn \"The OAuth credential store operation failed.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.InvalidStoreResult:\n\t\t\treturn \"The OAuth credential store returned an invalid result.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.TokenMissing:\n\t\t\treturn \"The OAuth credential has no bearer token.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.TokenInvalid:\n\t\t\treturn \"The OAuth bearer token is invalid.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.TokenAccessorFailed:\n\t\t\treturn \"The OAuth bearer-token accessor failed.\";\n\t\tcase McpClientOAuthAuthProviderErrorCode.RefreshFailed:\n\t\t\treturn \"The OAuth credential could not be refreshed.\";\n\t\tdefault:\n\t\t\treturn \"The OAuth auth provider failed.\";\n\t}\n}\n\nfunction providerClosedAbortReason(): DOMException {\n\treturn new DOMException(\"The OAuth auth provider was closed.\", \"AbortError\");\n}\n","import { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nconst OAUTH_STATE_DIGEST_DOMAIN = \"nest-mcp.client.oauth-state.v1\\u0000\";\nconst SHA_256_BYTES = 32;\nconst SHA_256_BASE64URL_LENGTH = 43;\nconst DEFAULT_STATE_ENTROPY_BYTES = 32;\nconst MIN_STATE_ENTROPY_BYTES = 16;\nconst MAX_STATE_ENTROPY_BYTES = 64;\nconst DEFAULT_PKCE_ENTROPY_BYTES = 32;\nconst MIN_PKCE_ENTROPY_BYTES = 32;\nconst MAX_PKCE_ENTROPY_BYTES = 96;\nconst MIN_PKCE_VERIFIER_LENGTH = 43;\nconst MAX_PKCE_VERIFIER_LENGTH = 128;\n\nconst CALLBACK_PARAMETER_LIMITS = {\n\tcode: 4_096,\n\tstate: 512,\n\tiss: 2_048,\n\terror: 256,\n\terror_description: 1_024,\n\terror_uri: 2_048,\n} as const;\n\nconst RESERVED_CALLBACK_PARAMETERS = [\n\t\"code\",\n\t\"state\",\n\t\"iss\",\n\t\"error\",\n\t\"error_description\",\n\t\"error_uri\",\n] as const satisfies readonly (keyof typeof CALLBACK_PARAMETER_LIMITS)[];\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;\nconst PKCE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]+$/u;\n\n/** Stable, secret-free failure categories for OAuth state and callback handling. */\nexport const McpOAuthStateErrorCode = {\n\tInvalidOptions: \"MCP_OAUTH_STATE_INVALID_OPTIONS\",\n\tInvalidCallback: \"MCP_OAUTH_CALLBACK_INVALID\",\n\tInvalidDigest: \"MCP_OAUTH_STATE_DIGEST_INVALID\",\n\tStateMismatch: \"MCP_OAUTH_STATE_MISMATCH\",\n\tStateExpired: \"MCP_OAUTH_STATE_EXPIRED\",\n\tStateNotYetValid: \"MCP_OAUTH_STATE_NOT_YET_VALID\",\n\tInvalidPkceVerifier: \"MCP_OAUTH_PKCE_VERIFIER_INVALID\",\n} as const;\n\nexport type McpOAuthStateErrorCode =\n\t(typeof McpOAuthStateErrorCode)[keyof typeof McpOAuthStateErrorCode];\n\n/** An OAuth state/protocol error whose message never includes callback or secret material. */\nexport class McpOAuthStateError extends Error {\n\treadonly code: McpOAuthStateErrorCode;\n\n\tconstructor(code: McpOAuthStateErrorCode) {\n\t\tsuper(stateErrorMessage(code));\n\t\tthis.name = \"McpOAuthStateError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface McpOAuthStateGenerationOptions {\n\t/** CSPRNG bytes. The resulting base64url state is always between 22 and 86 characters. */\n\treadonly entropyBytes?: number;\n}\n\nexport interface McpOAuthPkceGenerationOptions {\n\t/** CSPRNG bytes. The resulting verifier is always within RFC 7636's 43-128 character bound. */\n\treadonly entropyBytes?: number;\n}\n\nexport interface McpOAuthStateValidationInput {\n\t/** State received from the authorization callback. */\n\treadonly actualState: string;\n\t/** Domain-separated SHA-256 digest retained with the transaction; never the plaintext state. */\n\treadonly expectedDigest: string;\n\t/** Transaction creation time as Unix epoch milliseconds. */\n\treadonly createdAtMs: number;\n\t/** Positive transaction lifetime in milliseconds. */\n\treadonly ttlMs: number;\n\t/** Injectable clock for deterministic validation. Defaults to `Date.now()`. */\n\treadonly nowMs?: number;\n}\n\nexport interface McpOAuthCallbackSuccess {\n\treadonly kind: \"success\";\n\treadonly code: string;\n\treadonly state: string;\n\treadonly issuer?: string;\n}\n\nexport interface McpOAuthCallbackError {\n\treadonly kind: \"error\";\n\treadonly error: string;\n\treadonly state: string;\n\treadonly issuer?: string;\n}\n\nexport type McpOAuthCallbackParameters = McpOAuthCallbackSuccess | McpOAuthCallbackError;\n\nexport type McpOAuthCallbackParameterInput = URL | URLSearchParams;\n\n/** Generates an unpredictable OAuth state value using Node's CSPRNG. */\nexport function createOAuthState(options: McpOAuthStateGenerationOptions = {}): string {\n\tconst entropyBytes = options.entropyBytes ?? DEFAULT_STATE_ENTROPY_BYTES;\n\tassertEntropyBytes(entropyBytes, MIN_STATE_ENTROPY_BYTES, MAX_STATE_ENTROPY_BYTES);\n\treturn randomBytes(entropyBytes).toString(\"base64url\");\n}\n\n/**\n * Derives the opaque key used to look up an authorization transaction.\n * The domain prefix prevents the digest from being reused as an unscoped SHA-256 identifier.\n */\nexport function createOAuthStateLookupDigest(state: string): string {\n\tassertStateValue(state);\n\treturn createHash(\"sha256\")\n\t\t.update(OAUTH_STATE_DIGEST_DOMAIN, \"utf8\")\n\t\t.update(state, \"utf8\")\n\t\t.digest(\"base64url\");\n}\n\n/**\n * Validates a callback state against a digest-only transaction record and its lifetime.\n * Both valid digests are decoded to fixed-size byte arrays before constant-time comparison.\n */\nexport function validateOAuthState(input: McpOAuthStateValidationInput): void {\n\tassertStateValue(input.actualState);\n\tconst expectedDigest = decodeStateDigest(input.expectedDigest);\n\tconst actualDigest = Buffer.from(createOAuthStateLookupDigest(input.actualState), \"base64url\");\n\tconst matches = timingSafeEqual(actualDigest, expectedDigest);\n\n\tif (!matches) {\n\t\tthrow new McpOAuthStateError(McpOAuthStateErrorCode.StateMismatch);\n\t}\n\n\tconst nowMs = input.nowMs ?? Date.now();\n\tassertEpochMilliseconds(input.createdAtMs);\n\tassertEpochMilliseconds(nowMs);\n\tif (!Number.isSafeInteger(input.ttlMs) || input.ttlMs <= 0) {\n\t\tthrow invalidOptionsError();\n\t}\n\tif (nowMs < input.createdAtMs) {\n\t\tthrow new McpOAuthStateError(McpOAuthStateErrorCode.StateNotYetValid);\n\t}\n\tif (nowMs - input.createdAtMs >= input.ttlMs) {\n\t\tthrow new McpOAuthStateError(McpOAuthStateErrorCode.StateExpired);\n\t}\n}\n\n/**\n * Parses an authorization callback query without normalizing opaque values.\n * Unknown extension parameters are ignored as required by OAuth; reserved parameters are strict.\n */\nexport function parseOAuthCallbackParameters(\n\tinput: McpOAuthCallbackParameterInput,\n): McpOAuthCallbackParameters {\n\tif (input instanceof URL && input.hash.length > 0) throw invalidCallbackError();\n\tconst parameters = input instanceof URL ? input.searchParams : input;\n\tif (!(parameters instanceof URLSearchParams)) throw invalidCallbackError();\n\n\tfor (const name of RESERVED_CALLBACK_PARAMETERS) {\n\t\tconst values = parameters.getAll(name);\n\t\tif (values.length > 1) throw invalidCallbackError();\n\t\tif (values.length === 1) assertCallbackValue(values[0], CALLBACK_PARAMETER_LIMITS[name]);\n\t}\n\n\tconst code = parameters.get(\"code\");\n\tconst state = parameters.get(\"state\");\n\tconst issuer = optionalCallbackValue(parameters, \"iss\");\n\tconst error = parameters.get(\"error\");\n\n\tif (state === null) throw invalidCallbackError();\n\tif ((code === null) === (error === null)) throw invalidCallbackError();\n\n\tif (code !== null) {\n\t\tif (parameters.has(\"error_description\") || parameters.has(\"error_uri\")) {\n\t\t\tthrow invalidCallbackError();\n\t\t}\n\t\treturn {\n\t\t\tkind: \"success\",\n\t\t\tcode,\n\t\t\tstate,\n\t\t\t...(issuer === undefined ? {} : { issuer }),\n\t\t};\n\t}\n\n\tif (error === null) throw invalidCallbackError();\n\treturn {\n\t\tkind: \"error\",\n\t\terror,\n\t\tstate,\n\t\t...(issuer === undefined ? {} : { issuer }),\n\t};\n}\n\n/** Generates an RFC 7636 code verifier using Node's CSPRNG. */\nexport function createPkceVerifier(options: McpOAuthPkceGenerationOptions = {}): string {\n\tconst entropyBytes = options.entropyBytes ?? DEFAULT_PKCE_ENTROPY_BYTES;\n\tassertEntropyBytes(entropyBytes, MIN_PKCE_ENTROPY_BYTES, MAX_PKCE_ENTROPY_BYTES);\n\treturn randomBytes(entropyBytes).toString(\"base64url\");\n}\n\n/** Derives the RFC 7636 `S256` code challenge for a validated verifier. */\nexport function createPkceS256Challenge(verifier: string): string {\n\tif (\n\t\ttypeof verifier !== \"string\" ||\n\t\tverifier.length < MIN_PKCE_VERIFIER_LENGTH ||\n\t\tverifier.length > MAX_PKCE_VERIFIER_LENGTH ||\n\t\t!PKCE_VERIFIER_PATTERN.test(verifier)\n\t) {\n\t\tthrow new McpOAuthStateError(McpOAuthStateErrorCode.InvalidPkceVerifier);\n\t}\n\treturn createHash(\"sha256\").update(verifier, \"ascii\").digest(\"base64url\");\n}\n\nfunction assertEntropyBytes(value: number, minimum: number, maximum: number): void {\n\tif (!Number.isSafeInteger(value) || value < minimum || value > maximum) {\n\t\tthrow invalidOptionsError();\n\t}\n}\n\nfunction assertEpochMilliseconds(value: number): void {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow invalidOptionsError();\n\t}\n}\n\nfunction assertStateValue(state: string): void {\n\tif (\n\t\ttypeof state !== \"string\" ||\n\t\tstate.length < base64urlLength(MIN_STATE_ENTROPY_BYTES) ||\n\t\tstate.length > base64urlLength(MAX_STATE_ENTROPY_BYTES) ||\n\t\t!BASE64URL_PATTERN.test(state)\n\t) {\n\t\tthrow new McpOAuthStateError(McpOAuthStateErrorCode.InvalidCallback);\n\t}\n}\n\nfunction decodeStateDigest(value: string): Buffer {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length !== SHA_256_BASE64URL_LENGTH ||\n\t\t!BASE64URL_PATTERN.test(value)\n\t) {\n\t\tthrow invalidDigestError();\n\t}\n\tconst decoded = Buffer.from(value, \"base64url\");\n\tif (decoded.length !== SHA_256_BYTES || decoded.toString(\"base64url\") !== value) {\n\t\tthrow invalidDigestError();\n\t}\n\treturn decoded;\n}\n\nfunction assertCallbackValue(\n\tvalue: string | undefined,\n\tmaximumLength: number,\n): asserts value is string {\n\tif (\n\t\tvalue === undefined ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maximumLength ||\n\t\tcontainsControlCharacter(value)\n\t) {\n\t\tthrow invalidCallbackError();\n\t}\n}\n\nfunction containsControlCharacter(value: string): boolean {\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0);\n\t\tif (\n\t\t\tcodePoint !== undefined &&\n\t\t\t(codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction optionalCallbackValue(parameters: URLSearchParams, name: \"iss\"): string | undefined {\n\tconst value = parameters.get(name);\n\treturn value === null ? undefined : value;\n}\n\nfunction base64urlLength(bytes: number): number {\n\treturn Math.ceil((bytes * 8) / 6);\n}\n\nfunction invalidOptionsError(): McpOAuthStateError {\n\treturn new McpOAuthStateError(McpOAuthStateErrorCode.InvalidOptions);\n}\n\nfunction invalidCallbackError(): McpOAuthStateError {\n\treturn new McpOAuthStateError(McpOAuthStateErrorCode.InvalidCallback);\n}\n\nfunction invalidDigestError(): McpOAuthStateError {\n\treturn new McpOAuthStateError(McpOAuthStateErrorCode.InvalidDigest);\n}\n\nfunction stateErrorMessage(code: McpOAuthStateErrorCode): string {\n\tswitch (code) {\n\t\tcase McpOAuthStateErrorCode.InvalidOptions:\n\t\t\treturn \"The OAuth state operation options are invalid.\";\n\t\tcase McpOAuthStateErrorCode.InvalidCallback:\n\t\t\treturn \"The OAuth callback parameters are invalid.\";\n\t\tcase McpOAuthStateErrorCode.InvalidDigest:\n\t\t\treturn \"The stored OAuth state digest is invalid.\";\n\t\tcase McpOAuthStateErrorCode.StateMismatch:\n\t\t\treturn \"The OAuth callback state does not match the authorization transaction.\";\n\t\tcase McpOAuthStateErrorCode.StateExpired:\n\t\t\treturn \"The OAuth authorization transaction has expired.\";\n\t\tcase McpOAuthStateErrorCode.StateNotYetValid:\n\t\t\treturn \"The OAuth authorization transaction is not yet valid.\";\n\t\tcase McpOAuthStateErrorCode.InvalidPkceVerifier:\n\t\t\treturn \"The PKCE verifier is invalid.\";\n\t\tdefault:\n\t\t\treturn \"The OAuth state operation failed.\";\n\t}\n}\n","import type { McpClientOAuthProtocolError } from \"./protocol.ts\";\n\nconst internalProtocolErrors = new WeakSet<object>();\n\n/** Package-internal authenticity marker; intentionally not exported from the OAuth entry point. */\nexport function markInternalMcpClientOAuthProtocolError<\n\tProtocolError extends McpClientOAuthProtocolError,\n>(error: ProtocolError): ProtocolError {\n\tinternalProtocolErrors.add(error);\n\treturn error;\n}\n\n/** Distinguishes fixed, library-origin failures from public-constructor lookalikes. */\nexport function isInternalMcpClientOAuthProtocolError(\n\terror: unknown,\n): error is McpClientOAuthProtocolError {\n\treturn (\n\t\terror !== null &&\n\t\t(typeof error === \"object\" || typeof error === \"function\") &&\n\t\tinternalProtocolErrors.has(error)\n\t);\n}\n","import { captureMcpConformanceValue } from \"@nest-mcp/conformance\";\n\n/** Optional stricter storage bounds; they cannot widen the protocol's fixed ceilings. */\nexport interface McpClientOAuthSnapshotOptions {\n\treadonly maxBytes?: number;\n\treadonly maxUrlLength?: number;\n}\n\n/** Never retains the decoded value, a validation cause, URLs, or secret material. */\nexport class McpClientOAuthSnapshotError extends Error {\n\treadonly code = \"MCP_CLIENT_OAUTH_SNAPSHOT_INVALID\" as const;\n\tconstructor() {\n\t\tsuper(\"The MCP OAuth snapshot is invalid or exceeds its bounds.\");\n\t\tthis.name = \"McpClientOAuthSnapshotError\";\n\t}\n}\n\nexport function parseOAuthSnapshot<Value>(\n\tvalue: unknown,\n\toptions: McpClientOAuthSnapshotOptions,\n\tparse: (record: Readonly<Record<string, unknown>>, maxUrlLength: number) => Value,\n): Value {\n\ttry {\n\t\tconst maxBytes = bound(options.maxBytes, 2 * 1_024 * 1_024);\n\t\tconst maxUrlLength = bound(options.maxUrlLength, 4_096);\n\t\tconst captured = captureMcpConformanceValue(\n\t\t\tvalue,\n\t\t\t{\n\t\t\t\tmaxBytes,\n\t\t\t\tmaxDepth: 8,\n\t\t\t\tmaxItems: 8_192,\n\t\t\t\tmaxProperties: 4_096,\n\t\t\t\tmaxStringBytes: 65_536,\n\t\t\t},\n\t\t\t{ undefinedPolicy: \"reject\" },\n\t\t);\n\t\treturn parse(oauthSnapshotRecord(captured), maxUrlLength);\n\t} catch {\n\t\tthrow new McpClientOAuthSnapshotError();\n\t}\n}\n\nexport function oauthSnapshotRecord(value: unknown): Readonly<Record<string, unknown>> {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new McpClientOAuthSnapshotError();\n\t}\n\treturn value as Readonly<Record<string, unknown>>;\n}\n\nexport function assertOAuthSnapshotKeys(\n\tvalue: Readonly<Record<string, unknown>>,\n\tkeys: readonly string[],\n): void {\n\tconst allowed = new Set(keys);\n\tif (Object.keys(value).some((key) => !allowed.has(key))) throw new McpClientOAuthSnapshotError();\n}\n\nexport function oauthSnapshotString(value: unknown, maximum: number): string {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > maximum) {\n\t\tthrow new McpClientOAuthSnapshotError();\n\t}\n\treturn value;\n}\n\nexport function oauthSnapshotStrings(value: unknown, maximum: number): readonly string[] {\n\tif (!Array.isArray(value) || value.length > maximum) throw new McpClientOAuthSnapshotError();\n\tconst entries: readonly unknown[] = value;\n\tif (!entries.every((entry): entry is string => typeof entry === \"string\")) {\n\t\tthrow new McpClientOAuthSnapshotError();\n\t}\n\treturn entries;\n}\n\nexport function oauthSnapshotBoolean(value: unknown): boolean {\n\tif (typeof value !== \"boolean\") throw new McpClientOAuthSnapshotError();\n\treturn value;\n}\n\nfunction bound(value: number | undefined, maximum: number): number {\n\tconst result = value ?? maximum;\n\tif (!Number.isSafeInteger(result) || result < 1 || result > maximum) {\n\t\tthrow new McpClientOAuthSnapshotError();\n\t}\n\treturn result;\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n\tOAuthError,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthProtectedResourceMetadata,\n\texchangeAuthorization,\n\trefreshAuthorization,\n\tstartAuthorization,\n} from \"@modelcontextprotocol/client\";\nimport type {\n\tAddClientAuthentication,\n\tAuthorizationServerMetadata,\n\tFetchLike,\n\tOAuthClientInformationMixed,\n\tOAuthTokens,\n} from \"@modelcontextprotocol/client\";\n\nimport {\n\tcreateOAuthState,\n\tcreateOAuthStateLookupDigest,\n\tcreatePkceS256Challenge,\n\tparseOAuthCallbackParameters,\n\tvalidateOAuthState,\n} from \"./state.ts\";\nimport type { McpOAuthCallbackParameterInput } from \"./state.ts\";\nimport {\n\tisInternalMcpClientOAuthProtocolError,\n\tmarkInternalMcpClientOAuthProtocolError,\n} from \"./protocol-error-brand.ts\";\nimport { isMcpClientOAuthScopeToken } from \"./scope.ts\";\nimport {\n\tassertOAuthSnapshotKeys,\n\toauthSnapshotBoolean,\n\toauthSnapshotString,\n\toauthSnapshotStrings,\n\tparseOAuthSnapshot,\n\ttype McpClientOAuthSnapshotOptions,\n} from \"./snapshot-data.ts\";\n\nconst DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS = 10 * 60 * 1_000;\nconst MAX_AUTHORIZATION_TRANSACTION_TTL_MS = 60 * 60 * 1_000;\nconst MAX_URL_LENGTH = 4_096;\nconst MAX_CLIENT_ID_LENGTH = 2_048;\nconst MAX_CLIENT_SECRET_LENGTH = 8_192;\nconst MAX_TOKEN_LENGTH = 65_536;\nconst MAX_SCOPE_COUNT = 128;\nconst MAX_SCOPE_STRING_LENGTH = 4_096;\nconst MAX_METADATA_LIST_LENGTH = 256;\nconst MAX_METADATA_VALUE_LENGTH = 2_048;\nconst AUTHORITY_DIGEST_DOMAIN = \"nest-mcp.client.oauth-authority.v1\\u0000\";\nconst PRIVATE_KEY_JWT_ASSERTION_TYPE = \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\";\nconst PRIVATE_KEY_JWT_PARAMETER_NAMES = Object.freeze([\n\t\"client_id\",\n\t\"client_assertion_type\",\n\t\"client_assertion\",\n]);\n\n/** Stable, secret-free failure categories for the strict outbound OAuth facade. */\nexport const McpClientOAuthProtocolErrorCode = {\n\tInvalidOptions: \"MCP_CLIENT_OAUTH_INVALID_OPTIONS\",\n\tEndpointRejected: \"MCP_CLIENT_OAUTH_ENDPOINT_REJECTED\",\n\tDiscoveryFailed: \"MCP_CLIENT_OAUTH_DISCOVERY_FAILED\",\n\tAuthorityInvalid: \"MCP_CLIENT_OAUTH_AUTHORITY_INVALID\",\n\tClientUnsupported: \"MCP_CLIENT_OAUTH_CLIENT_UNSUPPORTED\",\n\tTransactionInvalid: \"MCP_CLIENT_OAUTH_TRANSACTION_INVALID\",\n\tAuthorizationDenied: \"MCP_CLIENT_OAUTH_AUTHORIZATION_DENIED\",\n\tAuthorizationFailed: \"MCP_CLIENT_OAUTH_AUTHORIZATION_FAILED\",\n\tInvalidGrant: \"MCP_CLIENT_OAUTH_INVALID_GRANT\",\n\tInvalidClient: \"MCP_CLIENT_OAUTH_INVALID_CLIENT\",\n\tTokenExchangeFailed: \"MCP_CLIENT_OAUTH_TOKEN_EXCHANGE_FAILED\",\n\tTokenRefreshFailed: \"MCP_CLIENT_OAUTH_TOKEN_REFRESH_FAILED\",\n\tRefreshOutcomeUnknown: \"MCP_CLIENT_OAUTH_REFRESH_OUTCOME_UNKNOWN\",\n} as const;\n\nexport type McpClientOAuthProtocolErrorCode =\n\t(typeof McpClientOAuthProtocolErrorCode)[keyof typeof McpClientOAuthProtocolErrorCode];\n\n/**\n * Public protocol-error shape. Library-emitted instances use fixed, secret-free messages; callers\n * constructing this class directly remain responsible for their message and receive no internal\n * authenticity brand.\n */\nexport class McpClientOAuthProtocolError extends Error {\n\treadonly code: McpClientOAuthProtocolErrorCode;\n\n\tconstructor(code: McpClientOAuthProtocolErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"McpClientOAuthProtocolError\";\n\t\tthis.code = code;\n\t}\n}\n\nfunction createInternalProtocolError(\n\tcode: McpClientOAuthProtocolErrorCode,\n\tmessage: string,\n): McpClientOAuthProtocolError {\n\treturn markInternalMcpClientOAuthProtocolError(new McpClientOAuthProtocolError(code, message));\n}\n\nexport type McpClientOAuthEndpointKind =\n\t\"resource-metadata\" | \"authorization-server-metadata\" | \"authorization\" | \"token\";\n\nexport interface McpClientOAuthEndpointPolicyInput {\n\t/** A disposable URL copy. Mutating it never changes the destination used by the facade. */\n\treadonly endpoint: URL;\n\treadonly kind: McpClientOAuthEndpointKind;\n\treadonly credentialed: boolean;\n\treadonly exactResource: string;\n\treadonly exactIssuer: string;\n\treadonly resource: URL;\n\treadonly issuer: URL;\n\treadonly signal?: AbortSignal;\n}\n\n/** Only literal `true` admits an endpoint; false, undefined, or an exception fails closed. */\nexport type McpClientOAuthEndpointPolicy = (\n\tinput: McpClientOAuthEndpointPolicyInput,\n) => boolean | PromiseLike<boolean>;\n\nexport interface McpClientOAuthProtocolOptions {\n\t/**\n\t * A host-owned SSRF-hardened fetch. It must pin DNS, reject redirects, and bound bodies/time.\n\t * It must never automatically retry credentialed token POSTs: the facade invokes the host fetch\n\t * once and must receive ambiguous failures unchanged. The facade also forces `redirect: \"error\"`\n\t * and applies `endpointPolicy` before each call.\n\t */\n\treadonly fetch: FetchLike;\n\treadonly endpointPolicy: McpClientOAuthEndpointPolicy;\n\treadonly authorizationTransactionTtlMs?: number;\n\treadonly now?: () => number;\n}\n\nexport interface McpClientOAuthDiscoveryInput {\n\t/** MCP HTTP endpoint used to derive RFC 9728 discovery locations. */\n\treadonly serverUrl: string;\n\t/** Exact RFC 8707 resource indicator expected in RFC 9728 metadata. */\n\treadonly resource: string;\n\t/** Exact authorization-server issuer selected by application policy. */\n\treadonly issuer: string;\n\treadonly resourceMetadataUrl?: string;\n\treadonly signal?: AbortSignal;\n}\n\n/**\n * A bounded, serializable authority snapshot. It intentionally excludes registration endpoints\n * and unknown metadata so it cannot enable Dynamic Client Registration.\n */\nexport interface McpClientOAuthAuthority {\n\treadonly serverUrl: string;\n\treadonly resource: string;\n\treadonly issuer: string;\n\treadonly authorizationEndpoint: string;\n\treadonly tokenEndpoint: string;\n\treadonly responseTypesSupported: readonly string[];\n\treadonly codeChallengeMethodsSupported: readonly string[];\n\treadonly tokenEndpointAuthMethodsSupported: readonly string[];\n\treadonly grantTypesSupported?: readonly string[];\n\treadonly resourceScopesSupported?: readonly string[];\n\treadonly authorizationScopesSupported?: readonly string[];\n\t/** Whether RFC 9207 requires an `iss` parameter in the authorization response. */\n\treadonly authorizationResponseIssuerParameterSupported: boolean;\n}\n\nexport type McpClientOAuthClientAuthentication =\n\t| { readonly method: \"none\" }\n\t| { readonly method: \"client_secret_basic\"; readonly clientSecret: string }\n\t| { readonly method: \"client_secret_post\"; readonly clientSecret: string }\n\t| {\n\t\t\treadonly method: \"private_key_jwt\";\n\t\t\treadonly addClientAuthentication: AddClientAuthentication;\n\t };\n\n/** Client information must be provisioned out of band; this API has no registration operation. */\nexport interface McpClientOAuthClient {\n\treadonly clientId: string;\n\treadonly authentication: McpClientOAuthClientAuthentication;\n}\n\nexport interface McpClientOAuthStartAuthorizationInput {\n\treadonly authority: McpClientOAuthAuthority;\n\treadonly client: McpClientOAuthClient;\n\treadonly redirectUri: string;\n\treadonly scopes?: readonly string[];\n\treadonly signal?: AbortSignal;\n}\n\n/**\n * Secret-bearing redirect transaction. Persist it encrypted and bind it to the browser session.\n * `stateDigest` is suitable for lookup; plaintext state is intentionally not retained here.\n */\nexport interface McpClientOAuthAuthorizationTransaction {\n\treadonly authority: McpClientOAuthAuthority;\n\t/** Non-secret corruption/swap coordinate; authenticated host storage remains mandatory. */\n\treadonly authorityDigest: string;\n\treadonly stateDigest: string;\n\treadonly codeVerifier: string;\n\treadonly redirectUri: string;\n\treadonly clientId: string;\n\treadonly clientAuthenticationMethod: McpClientOAuthClientAuthentication[\"method\"];\n\treadonly scope?: string;\n\treadonly createdAtMs: number;\n}\n\nexport interface McpClientOAuthStartAuthorizationResult {\n\treadonly authorizationUrl: string;\n\treadonly transaction: McpClientOAuthAuthorizationTransaction;\n}\n\nexport interface McpClientOAuthExchangeAuthorizationInput {\n\t/**\n\t * The host must first parse state, atomically take the transaction by its digest, and then call\n\t * this method exactly once. A network-ambiguous exchange must never make the code replayable.\n\t */\n\treadonly transaction: McpClientOAuthAuthorizationTransaction;\n\treadonly client: McpClientOAuthClient;\n\treadonly callback: McpOAuthCallbackParameterInput;\n\treadonly signal?: AbortSignal;\n}\n\nexport interface McpClientOAuthRefreshInput {\n\treadonly authority: McpClientOAuthAuthority;\n\treadonly client: McpClientOAuthClient;\n\t/** Current effective grant, retained when a conforming refresh response omits `scope`. */\n\treadonly currentScope?: string;\n\treadonly refreshToken: string;\n\treadonly signal?: AbortSignal;\n}\n\ninterface McpClientOAuthHostFetchAttempt {\n\tinvoked: boolean;\n\tresponseReturned: boolean;\n}\n\n/**\n * Strict, framework-neutral OAuth protocol facade for outbound MCP clients.\n *\n * It deliberately exposes no dynamic registration and never constructs an OAuthClientProvider,\n * preventing the MCP transport from launching interactive or DCR flows implicitly.\n */\nexport class McpClientOAuthProtocol {\n\treadonly #fetch: FetchLike;\n\treadonly #endpointPolicy: McpClientOAuthEndpointPolicy;\n\treadonly #authorizationTransactionTtlMs: number;\n\treadonly #now: () => number;\n\n\tconstructor(options: McpClientOAuthProtocolOptions) {\n\t\tif (\n\t\t\ttypeof options !== \"object\" ||\n\t\t\toptions === null ||\n\t\t\ttypeof options.fetch !== \"function\" ||\n\t\t\ttypeof options.endpointPolicy !== \"function\" ||\n\t\t\t(options.now !== undefined && typeof options.now !== \"function\")\n\t\t) {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tconst ttlMs = options.authorizationTransactionTtlMs ?? DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS;\n\t\tif (\n\t\t\t!Number.isSafeInteger(ttlMs) ||\n\t\t\tttlMs <= 0 ||\n\t\t\tttlMs > MAX_AUTHORIZATION_TRANSACTION_TTL_MS\n\t\t) {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tthis.#fetch = options.fetch;\n\t\tthis.#endpointPolicy = options.endpointPolicy;\n\t\tthis.#authorizationTransactionTtlMs = ttlMs;\n\t\tthis.#now = options.now ?? Date.now;\n\t}\n\n\t/** Resolves and freezes exact RFC 9728/RFC 8414 authority without following DCR. */\n\tasync discover(input: McpClientOAuthDiscoveryInput): Promise<McpClientOAuthAuthority> {\n\t\tconst operation = normalizeDiscoveryInput(input);\n\t\tthrowIfAborted(operation.signal);\n\n\t\tlet resourceMetadata;\n\t\ttry {\n\t\t\tresourceMetadata = await discoverOAuthProtectedResourceMetadata(\n\t\t\t\toperation.serverUrl,\n\t\t\t\toperation.resourceMetadataUrl === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: { resourceMetadataUrl: operation.resourceMetadataUrl },\n\t\t\t\tthis.#createFetch({\n\t\t\t\t\tkind: \"resource-metadata\",\n\t\t\t\t\tcredentialed: false,\n\t\t\t\t\tresource: operation.resource,\n\t\t\t\t\tissuer: operation.issuer,\n\t\t\t\t\tsignal: operation.signal,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrowIfAborted(operation.signal);\n\t\t\tif (error instanceof McpClientOAuthProtocolError) {\n\t\t\t\tthrow canonicalizeProtocolError(error, discoveryFailedError);\n\t\t\t}\n\t\t\tthrow discoveryFailedError();\n\t\t}\n\n\t\tif (\n\t\t\tresourceMetadata.resource !== operation.resource ||\n\t\t\tresourceMetadata.authorization_servers === undefined ||\n\t\t\t!resourceMetadata.authorization_servers.includes(operation.issuer)\n\t\t) {\n\t\t\tthrow authorityInvalidError();\n\t\t}\n\t\tif (\n\t\t\t(resourceMetadata.bearer_methods_supported !== undefined &&\n\t\t\t\t!resourceMetadata.bearer_methods_supported.includes(\"header\")) ||\n\t\t\tresourceMetadata.tls_client_certificate_bound_access_tokens === true ||\n\t\t\tresourceMetadata.dpop_bound_access_tokens_required === true\n\t\t) {\n\t\t\tthrow authorityInvalidError();\n\t\t}\n\n\t\tlet metadata: AuthorizationServerMetadata | undefined;\n\t\ttry {\n\t\t\tmetadata = await discoverAuthorizationServerMetadata(operation.issuer, {\n\t\t\t\tfetchFn: this.#createFetch({\n\t\t\t\t\tkind: \"authorization-server-metadata\",\n\t\t\t\t\tcredentialed: false,\n\t\t\t\t\tresource: operation.resource,\n\t\t\t\t\tissuer: operation.issuer,\n\t\t\t\t\tsignal: operation.signal,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrowIfAborted(operation.signal);\n\t\t\tif (error instanceof McpClientOAuthProtocolError) {\n\t\t\t\tthrow canonicalizeProtocolError(error, discoveryFailedError);\n\t\t\t}\n\t\t\tthrow discoveryFailedError();\n\t\t}\n\n\t\tthrowIfAborted(operation.signal);\n\t\tif (metadata === undefined || metadata.issuer !== operation.issuer) {\n\t\t\tthrow authorityInvalidError();\n\t\t}\n\n\t\tconst authority = createAuthority({\n\t\t\tserverUrl: operation.serverUrl,\n\t\t\tresource: operation.resource,\n\t\t\tissuer: operation.issuer,\n\t\t\tmetadata,\n\t\t\t...(resourceMetadata.scopes_supported === undefined\n\t\t\t\t? {}\n\t\t\t\t: { resourceScopesSupported: resourceMetadata.scopes_supported }),\n\t\t});\n\t\tawait this.#authorizeEndpoint(authority.authorizationEndpoint, {\n\t\t\tkind: \"authorization\",\n\t\t\tcredentialed: false,\n\t\t\tresource: authority.resource,\n\t\t\tissuer: authority.issuer,\n\t\t\tsignal: operation.signal,\n\t\t});\n\t\tawait this.#authorizeEndpoint(authority.tokenEndpoint, {\n\t\t\tkind: \"token\",\n\t\t\tcredentialed: true,\n\t\t\tresource: authority.resource,\n\t\t\tissuer: authority.issuer,\n\t\t\tsignal: operation.signal,\n\t\t});\n\t\treturn authority;\n\t}\n\n\t/** Starts a PKCE S256 authorization request and returns an endpoint-pinned transaction. */\n\tasync startAuthorization(\n\t\tinput: McpClientOAuthStartAuthorizationInput,\n\t): Promise<McpClientOAuthStartAuthorizationResult> {\n\t\tif (typeof input !== \"object\" || input === null) throw invalidOptionsError();\n\t\tconst authority = normalizeAuthority(input.authority);\n\t\tconst client = normalizeClient(input.client, authority);\n\t\tconst redirectUri = requireRedirectUri(input.redirectUri).href;\n\t\tconst scope = normalizeScopes(input.scopes, authority);\n\t\tthrowIfAborted(input.signal);\n\t\tawait this.#authorizeEndpoint(authority.authorizationEndpoint, {\n\t\t\tkind: \"authorization\",\n\t\t\tcredentialed: false,\n\t\t\tresource: authority.resource,\n\t\t\tissuer: authority.issuer,\n\t\t\tsignal: input.signal,\n\t\t});\n\n\t\tconst state = createOAuthState();\n\t\tlet started;\n\t\ttry {\n\t\t\tstarted = await startAuthorization(authority.issuer, {\n\t\t\t\tmetadata: toSdkMetadata(authority),\n\t\t\t\tclientInformation: toSdkClientInformation(client),\n\t\t\t\tredirectUrl: redirectUri,\n\t\t\t\tstate,\n\t\t\t\tresource: new URL(authority.resource),\n\t\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\t});\n\t\t} catch {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tthrow authorizationFailedError();\n\t\t}\n\t\tthrowIfAborted(input.signal);\n\t\tconst codeChallenge = createPkceS256Challenge(started.codeVerifier);\n\t\tassertAuthorizationUrl(started.authorizationUrl, {\n\t\t\texactEndpoint: authority.authorizationEndpoint,\n\t\t\tclientId: client.clientId,\n\t\t\tredirectUri,\n\t\t\tresource: authority.resource,\n\t\t\tstate,\n\t\t\tcodeChallenge,\n\t\t\tscope,\n\t\t});\n\n\t\tconst createdAtMs = this.#now();\n\t\tif (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw invalidOptionsError();\n\t\tconst transaction = Object.freeze({\n\t\t\tauthority: copyAuthority(authority),\n\t\t\tauthorityDigest: createAuthorityDigest(authority),\n\t\t\tstateDigest: createOAuthStateLookupDigest(state),\n\t\t\tcodeVerifier: started.codeVerifier,\n\t\t\tredirectUri,\n\t\t\tclientId: client.clientId,\n\t\t\tclientAuthenticationMethod: client.authentication.method,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tcreatedAtMs,\n\t\t});\n\t\treturn Object.freeze({ authorizationUrl: started.authorizationUrl.href, transaction });\n\t}\n\n\t/** Redeems a callback against the originally pinned authority exactly once. */\n\tasync exchangeAuthorization(\n\t\tinput: McpClientOAuthExchangeAuthorizationInput,\n\t): Promise<OAuthTokens> {\n\t\tif (typeof input !== \"object\" || input === null) throw invalidOptionsError();\n\t\tconst transaction = normalizeTransaction(input.transaction);\n\t\tconst authority = transaction.authority;\n\t\tconst client = normalizeClient(input.client, authority);\n\t\tassertTransactionClient(transaction, client);\n\t\tconst callback = parseOAuthCallbackParameters(input.callback);\n\t\tvalidateOAuthState({\n\t\t\tactualState: callback.state,\n\t\t\texpectedDigest: transaction.stateDigest,\n\t\t\tcreatedAtMs: transaction.createdAtMs,\n\t\t\tttlMs: this.#authorizationTransactionTtlMs,\n\t\t\tnowMs: this.#now(),\n\t\t});\n\t\tassertCallbackIssuer(callback.issuer, authority);\n\t\tif (callback.kind === \"error\") throw authorizationDeniedError();\n\t\tthrowIfAborted(input.signal);\n\t\tawait this.#authorizeEndpoint(authority.tokenEndpoint, {\n\t\t\tkind: \"token\",\n\t\t\tcredentialed: true,\n\t\t\tresource: authority.resource,\n\t\t\tissuer: authority.issuer,\n\t\t\tsignal: input.signal,\n\t\t});\n\n\t\ttry {\n\t\t\tconst tokens = await exchangeAuthorization(authority.issuer, {\n\t\t\t\tmetadata: toSdkMetadata(authority),\n\t\t\t\tclientInformation: toSdkClientInformation(client),\n\t\t\t\tauthorizationCode: callback.code,\n\t\t\t\tcodeVerifier: transaction.codeVerifier,\n\t\t\t\tredirectUri: transaction.redirectUri,\n\t\t\t\tresource: new URL(authority.resource),\n\t\t\t\taddClientAuthentication: createClientAuthentication(client, authority),\n\t\t\t\tfetchFn: this.#createFetch({\n\t\t\t\t\tkind: \"token\",\n\t\t\t\t\tcredentialed: true,\n\t\t\t\t\tresource: authority.resource,\n\t\t\t\t\tissuer: authority.issuer,\n\t\t\t\t\tsignal: input.signal,\n\t\t\t\t\texactEndpoint: authority.tokenEndpoint,\n\t\t\t\t}),\n\t\t\t\t...(callback.issuer === undefined ? {} : { iss: callback.issuer }),\n\t\t\t});\n\t\t\tthrowIfAborted(input.signal);\n\t\t\treturn validateTokens(tokens, \"exchange\", transaction.scope);\n\t\t} catch (error) {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tthrow translateTokenError(error, \"exchange\");\n\t\t}\n\t}\n\n\t/** Refreshes with the same exact authority and configured authentication method. */\n\tasync refreshAuthorization(input: McpClientOAuthRefreshInput): Promise<OAuthTokens> {\n\t\tif (typeof input !== \"object\" || input === null) throw invalidOptionsError();\n\t\tconst authority = normalizeAuthority(input.authority);\n\t\tconst client = normalizeClient(input.client, authority);\n\t\tconst currentScope = input.currentScope;\n\t\tif (currentScope !== undefined) assertScopeString(currentScope);\n\t\tassertSecretValue(input.refreshToken, MAX_TOKEN_LENGTH);\n\t\tif (\n\t\t\tauthority.grantTypesSupported === undefined ||\n\t\t\t!authority.grantTypesSupported.includes(\"refresh_token\")\n\t\t) {\n\t\t\tthrow clientUnsupportedError();\n\t\t}\n\t\tthrowIfAborted(input.signal);\n\t\tawait this.#authorizeEndpoint(authority.tokenEndpoint, {\n\t\t\tkind: \"token\",\n\t\t\tcredentialed: true,\n\t\t\tresource: authority.resource,\n\t\t\tissuer: authority.issuer,\n\t\t\tsignal: input.signal,\n\t\t});\n\t\tconst fetchAttempt: McpClientOAuthHostFetchAttempt = {\n\t\t\tinvoked: false,\n\t\t\tresponseReturned: false,\n\t\t};\n\n\t\ttry {\n\t\t\tconst tokens = await refreshAuthorization(authority.issuer, {\n\t\t\t\tmetadata: toSdkMetadata(authority),\n\t\t\t\tclientInformation: toSdkClientInformation(client),\n\t\t\t\trefreshToken: input.refreshToken,\n\t\t\t\tresource: new URL(authority.resource),\n\t\t\t\taddClientAuthentication: createClientAuthentication(client, authority),\n\t\t\t\tfetchFn: this.#createFetch({\n\t\t\t\t\tkind: \"token\",\n\t\t\t\t\tcredentialed: true,\n\t\t\t\t\tresource: authority.resource,\n\t\t\t\t\tissuer: authority.issuer,\n\t\t\t\t\tsignal: input.signal,\n\t\t\t\t\texactEndpoint: authority.tokenEndpoint,\n\t\t\t\t\thostFetchAttempt: fetchAttempt,\n\t\t\t\t}),\n\t\t\t});\n\t\t\tthrowIfAborted(input.signal);\n\t\t\treturn validateTokens(tokens, \"refresh\", currentScope);\n\t\t} catch (error) {\n\t\t\tif (!fetchAttempt.invoked) throwIfAborted(input.signal);\n\t\t\tthrow translateTokenError(error, \"refresh\", fetchAttempt);\n\t\t}\n\t}\n\n\t#createFetch(input: {\n\t\treadonly kind: McpClientOAuthEndpointKind;\n\t\treadonly credentialed: boolean;\n\t\treadonly resource: string;\n\t\treadonly issuer: string;\n\t\treadonly signal: AbortSignal | undefined;\n\t\treadonly exactEndpoint?: string;\n\t\treadonly hostFetchAttempt?: McpClientOAuthHostFetchAttempt;\n\t}): FetchLike {\n\t\treturn async (url, init) => {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tconst endpoint = requireSecureUrl(String(url), { query: true });\n\t\t\tif (input.exactEndpoint !== undefined && endpoint.href !== input.exactEndpoint) {\n\t\t\t\tthrow endpointRejectedError();\n\t\t\t}\n\t\t\tawait this.#authorizeEndpoint(endpoint.href, input);\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tconst signal = combineAbortSignals(input.signal, init?.signal);\n\t\t\tconst requestInit: RequestInit = { ...init, redirect: \"error\" };\n\t\t\tif (signal !== undefined) requestInit.signal = signal;\n\t\t\tif (input.hostFetchAttempt !== undefined) input.hostFetchAttempt.invoked = true;\n\t\t\tconst response = await this.#fetch(new URL(endpoint.href), requestInit);\n\t\t\tif (input.hostFetchAttempt !== undefined) input.hostFetchAttempt.responseReturned = true;\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tif (\n\t\t\t\tresponse.redirected ||\n\t\t\t\t(input.exactEndpoint !== undefined &&\n\t\t\t\t\tresponse.url.length > 0 &&\n\t\t\t\t\t!isExactResponseUrl(response.url, input.exactEndpoint))\n\t\t\t) {\n\t\t\t\tthrow endpointRejectedError();\n\t\t\t}\n\t\t\treturn response;\n\t\t};\n\t}\n\n\tasync #authorizeEndpoint(\n\t\tendpointValue: string,\n\t\tinput: {\n\t\t\treadonly kind: McpClientOAuthEndpointKind;\n\t\t\treadonly credentialed: boolean;\n\t\t\treadonly resource: string;\n\t\t\treadonly issuer: string;\n\t\t\treadonly signal: AbortSignal | undefined;\n\t\t},\n\t): Promise<void> {\n\t\tthrowIfAborted(input.signal);\n\t\tconst endpoint = requireSecureUrl(endpointValue, { query: true });\n\t\tlet admitted: unknown;\n\t\ttry {\n\t\t\tadmitted = await awaitWithSignal(\n\t\t\t\tPromise.resolve().then(() =>\n\t\t\t\t\tthis.#endpointPolicy(\n\t\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t\tendpoint: new URL(endpoint.href),\n\t\t\t\t\t\t\tkind: input.kind,\n\t\t\t\t\t\t\tcredentialed: input.credentialed,\n\t\t\t\t\t\t\texactResource: input.resource,\n\t\t\t\t\t\t\texactIssuer: input.issuer,\n\t\t\t\t\t\t\tresource: new URL(input.resource),\n\t\t\t\t\t\t\tissuer: new URL(input.issuer),\n\t\t\t\t\t\t\t...(input.signal === undefined ? {} : { signal: input.signal }),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tinput.signal,\n\t\t\t);\n\t\t} catch {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tthrow endpointRejectedError();\n\t\t}\n\t\tthrowIfAborted(input.signal);\n\t\tif (admitted !== true) throw endpointRejectedError();\n\t}\n}\n\nfunction normalizeDiscoveryInput(input: McpClientOAuthDiscoveryInput): {\n\treadonly serverUrl: string;\n\treadonly resource: string;\n\treadonly issuer: string;\n\treadonly resourceMetadataUrl?: string;\n\treadonly signal: AbortSignal | undefined;\n} {\n\tif (typeof input !== \"object\" || input === null) throw invalidOptionsError();\n\tconst serverUrl = requireSecureUrl(input.serverUrl, { query: true }).href;\n\tconst resource = requireCanonicalResource(input.resource);\n\trequireSecureUrl(input.issuer, { query: false });\n\tconst issuer = input.issuer;\n\tconst resourceMetadataUrl =\n\t\tinput.resourceMetadataUrl === undefined\n\t\t\t? undefined\n\t\t\t: requireSecureUrl(input.resourceMetadataUrl, { query: true }).href;\n\treturn Object.freeze({\n\t\tserverUrl,\n\t\tresource,\n\t\tissuer,\n\t\t...(resourceMetadataUrl === undefined ? {} : { resourceMetadataUrl }),\n\t\tsignal: input.signal,\n\t});\n}\n\nfunction createAuthority(input: {\n\treadonly serverUrl: string;\n\treadonly resource: string;\n\treadonly issuer: string;\n\treadonly metadata: AuthorizationServerMetadata;\n\treadonly resourceScopesSupported?: readonly string[];\n}): McpClientOAuthAuthority {\n\tconst responseTypesSupported = normalizeMetadataList(input.metadata.response_types_supported);\n\tconst codeChallengeMethodsSupported = normalizeMetadataList(\n\t\tinput.metadata.code_challenge_methods_supported,\n\t);\n\tconst tokenEndpointAuthMethodsSupported = normalizeMetadataList(\n\t\tinput.metadata.token_endpoint_auth_methods_supported,\n\t);\n\tif (\n\t\t!responseTypesSupported.includes(\"code\") ||\n\t\t!codeChallengeMethodsSupported.includes(\"S256\") ||\n\t\ttokenEndpointAuthMethodsSupported.length === 0 ||\n\t\t(input.metadata.grant_types_supported !== undefined &&\n\t\t\t!input.metadata.grant_types_supported.includes(\"authorization_code\")) ||\n\t\t(input.metadata.response_modes_supported !== undefined &&\n\t\t\t!input.metadata.response_modes_supported.includes(\"query\"))\n\t) {\n\t\tthrow authorityInvalidError();\n\t}\n\treturn copyAuthority({\n\t\tserverUrl: input.serverUrl,\n\t\tresource: input.resource,\n\t\tissuer: input.issuer,\n\t\tauthorizationEndpoint: requireSecureUrl(input.metadata.authorization_endpoint, {\n\t\t\tquery: true,\n\t\t}).href,\n\t\ttokenEndpoint: requireSecureUrl(input.metadata.token_endpoint, { query: true }).href,\n\t\tresponseTypesSupported,\n\t\tcodeChallengeMethodsSupported,\n\t\ttokenEndpointAuthMethodsSupported,\n\t\t...(input.metadata.grant_types_supported === undefined\n\t\t\t? {}\n\t\t\t: { grantTypesSupported: normalizeMetadataList(input.metadata.grant_types_supported) }),\n\t\t...(input.resourceScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { resourceScopesSupported: normalizeScopeMetadataList(input.resourceScopesSupported) }),\n\t\t...(input.metadata.scopes_supported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tauthorizationScopesSupported: normalizeScopeMetadataList(input.metadata.scopes_supported),\n\t\t\t\t}),\n\t\tauthorizationResponseIssuerParameterSupported:\n\t\t\tinput.metadata.authorization_response_iss_parameter_supported === true,\n\t});\n}\n\n/** Decode authenticated host storage; this does not admit endpoints or authorize execution. */\nexport function parseMcpClientOAuthAuthority(\n\tvalue: unknown,\n\toptions: McpClientOAuthSnapshotOptions = {},\n): McpClientOAuthAuthority {\n\treturn parseOAuthSnapshot(value, options, (record, maximum) => {\n\t\tassertOAuthSnapshotKeys(record, [\n\t\t\t\"serverUrl\",\n\t\t\t\"resource\",\n\t\t\t\"issuer\",\n\t\t\t\"authorizationEndpoint\",\n\t\t\t\"tokenEndpoint\",\n\t\t\t\"responseTypesSupported\",\n\t\t\t\"codeChallengeMethodsSupported\",\n\t\t\t\"tokenEndpointAuthMethodsSupported\",\n\t\t\t\"grantTypesSupported\",\n\t\t\t\"resourceScopesSupported\",\n\t\t\t\"authorizationScopesSupported\",\n\t\t\t\"authorizationResponseIssuerParameterSupported\",\n\t\t]);\n\t\treturn normalizeAuthority({\n\t\t\tserverUrl: oauthSnapshotString(record.serverUrl, maximum),\n\t\t\tresource: oauthSnapshotString(record.resource, maximum),\n\t\t\tissuer: oauthSnapshotString(record.issuer, maximum),\n\t\t\tauthorizationEndpoint: oauthSnapshotString(record.authorizationEndpoint, maximum),\n\t\t\ttokenEndpoint: oauthSnapshotString(record.tokenEndpoint, maximum),\n\t\t\tresponseTypesSupported: oauthSnapshotStrings(\n\t\t\t\trecord.responseTypesSupported,\n\t\t\t\tMAX_METADATA_LIST_LENGTH,\n\t\t\t),\n\t\t\tcodeChallengeMethodsSupported: oauthSnapshotStrings(\n\t\t\t\trecord.codeChallengeMethodsSupported,\n\t\t\t\tMAX_METADATA_LIST_LENGTH,\n\t\t\t),\n\t\t\ttokenEndpointAuthMethodsSupported: oauthSnapshotStrings(\n\t\t\t\trecord.tokenEndpointAuthMethodsSupported,\n\t\t\t\tMAX_METADATA_LIST_LENGTH,\n\t\t\t),\n\t\t\t...(record.grantTypesSupported === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tgrantTypesSupported: oauthSnapshotStrings(\n\t\t\t\t\t\t\trecord.grantTypesSupported,\n\t\t\t\t\t\t\tMAX_METADATA_LIST_LENGTH,\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t...(record.resourceScopesSupported === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tresourceScopesSupported: oauthSnapshotStrings(\n\t\t\t\t\t\t\trecord.resourceScopesSupported,\n\t\t\t\t\t\t\tMAX_SCOPE_COUNT,\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t...(record.authorizationScopesSupported === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tauthorizationScopesSupported: oauthSnapshotStrings(\n\t\t\t\t\t\t\trecord.authorizationScopesSupported,\n\t\t\t\t\t\t\tMAX_SCOPE_COUNT,\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\tauthorizationResponseIssuerParameterSupported: oauthSnapshotBoolean(\n\t\t\t\trecord.authorizationResponseIssuerParameterSupported,\n\t\t\t),\n\t\t});\n\t});\n}\n\n/** Pure decoding and authority-digest verification; host session binding and atomic take remain required. */\nexport function parseMcpClientOAuthAuthorizationTransaction(\n\tvalue: unknown,\n\toptions: McpClientOAuthSnapshotOptions = {},\n): McpClientOAuthAuthorizationTransaction {\n\treturn parseOAuthSnapshot(value, options, (record, maximum) => {\n\t\tassertOAuthSnapshotKeys(record, [\n\t\t\t\"authority\",\n\t\t\t\"authorityDigest\",\n\t\t\t\"stateDigest\",\n\t\t\t\"codeVerifier\",\n\t\t\t\"redirectUri\",\n\t\t\t\"clientId\",\n\t\t\t\"clientAuthenticationMethod\",\n\t\t\t\"scope\",\n\t\t\t\"createdAtMs\",\n\t\t]);\n\t\tconst method = record.clientAuthenticationMethod;\n\t\tconst stateDigest = oauthSnapshotString(record.stateDigest, 43);\n\t\tif (\n\t\t\t!isClientAuthenticationMethod(method) ||\n\t\t\t!/^[A-Za-z0-9_-]{43}$/u.test(stateDigest) ||\n\t\t\ttypeof record.createdAtMs !== \"number\"\n\t\t)\n\t\t\tthrow transactionInvalidError();\n\t\treturn normalizeTransaction({\n\t\t\tauthority: parseMcpClientOAuthAuthority(record.authority, options),\n\t\t\tauthorityDigest: oauthSnapshotString(record.authorityDigest, 43),\n\t\t\tstateDigest,\n\t\t\tcodeVerifier: oauthSnapshotString(record.codeVerifier, 128),\n\t\t\tredirectUri: oauthSnapshotString(record.redirectUri, maximum),\n\t\t\tclientId: oauthSnapshotString(record.clientId, MAX_CLIENT_ID_LENGTH),\n\t\t\tclientAuthenticationMethod: method,\n\t\t\t...(record.scope === undefined\n\t\t\t\t? {}\n\t\t\t\t: { scope: oauthSnapshotString(record.scope, MAX_SCOPE_STRING_LENGTH) }),\n\t\t\tcreatedAtMs: record.createdAtMs,\n\t\t});\n\t});\n}\n\nfunction normalizeAuthority(authority: McpClientOAuthAuthority): McpClientOAuthAuthority {\n\tif (typeof authority !== \"object\" || authority === null) throw authorityInvalidError();\n\tconst normalized = copyAuthority({\n\t\tserverUrl: requireSecureUrl(authority.serverUrl, { query: true }).href,\n\t\tresource: requireCanonicalResource(authority.resource),\n\t\tissuer: requireExactIssuer(authority.issuer),\n\t\tauthorizationEndpoint: requireSecureUrl(authority.authorizationEndpoint, {\n\t\t\tquery: true,\n\t\t}).href,\n\t\ttokenEndpoint: requireSecureUrl(authority.tokenEndpoint, { query: true }).href,\n\t\tresponseTypesSupported: normalizeMetadataList(authority.responseTypesSupported),\n\t\tcodeChallengeMethodsSupported: normalizeMetadataList(authority.codeChallengeMethodsSupported),\n\t\ttokenEndpointAuthMethodsSupported: normalizeMetadataList(\n\t\t\tauthority.tokenEndpointAuthMethodsSupported,\n\t\t),\n\t\t...(authority.grantTypesSupported === undefined\n\t\t\t? {}\n\t\t\t: { grantTypesSupported: normalizeMetadataList(authority.grantTypesSupported) }),\n\t\t...(authority.resourceScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tresourceScopesSupported: normalizeScopeMetadataList(authority.resourceScopesSupported),\n\t\t\t\t}),\n\t\t...(authority.authorizationScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tauthorizationScopesSupported: normalizeScopeMetadataList(\n\t\t\t\t\t\tauthority.authorizationScopesSupported,\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\tauthorizationResponseIssuerParameterSupported:\n\t\t\tauthority.authorizationResponseIssuerParameterSupported,\n\t});\n\tif (\n\t\ttypeof normalized.authorizationResponseIssuerParameterSupported !== \"boolean\" ||\n\t\t!normalized.responseTypesSupported.includes(\"code\") ||\n\t\t!normalized.codeChallengeMethodsSupported.includes(\"S256\") ||\n\t\tnormalized.tokenEndpointAuthMethodsSupported.length === 0 ||\n\t\t(normalized.grantTypesSupported !== undefined &&\n\t\t\t!normalized.grantTypesSupported.includes(\"authorization_code\"))\n\t) {\n\t\tthrow authorityInvalidError();\n\t}\n\treturn normalized;\n}\n\nfunction copyAuthority(authority: McpClientOAuthAuthority): McpClientOAuthAuthority {\n\treturn Object.freeze({\n\t\tserverUrl: authority.serverUrl,\n\t\tresource: authority.resource,\n\t\tissuer: authority.issuer,\n\t\tauthorizationEndpoint: authority.authorizationEndpoint,\n\t\ttokenEndpoint: authority.tokenEndpoint,\n\t\tresponseTypesSupported: Object.freeze([...authority.responseTypesSupported]),\n\t\tcodeChallengeMethodsSupported: Object.freeze([...authority.codeChallengeMethodsSupported]),\n\t\ttokenEndpointAuthMethodsSupported: Object.freeze([\n\t\t\t...authority.tokenEndpointAuthMethodsSupported,\n\t\t]),\n\t\t...(authority.grantTypesSupported === undefined\n\t\t\t? {}\n\t\t\t: { grantTypesSupported: Object.freeze([...authority.grantTypesSupported]) }),\n\t\t...(authority.resourceScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { resourceScopesSupported: Object.freeze([...authority.resourceScopesSupported]) }),\n\t\t...(authority.authorizationScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tauthorizationScopesSupported: Object.freeze([...authority.authorizationScopesSupported]),\n\t\t\t\t}),\n\t\tauthorizationResponseIssuerParameterSupported:\n\t\t\tauthority.authorizationResponseIssuerParameterSupported,\n\t});\n}\n\nfunction createAuthorityDigest(authority: McpClientOAuthAuthority): string {\n\tconst canonical = JSON.stringify([\n\t\tauthority.serverUrl,\n\t\tauthority.resource,\n\t\tauthority.issuer,\n\t\tauthority.authorizationEndpoint,\n\t\tauthority.tokenEndpoint,\n\t\tauthority.responseTypesSupported,\n\t\tauthority.codeChallengeMethodsSupported,\n\t\tauthority.tokenEndpointAuthMethodsSupported,\n\t\tauthority.grantTypesSupported ?? null,\n\t\tauthority.resourceScopesSupported ?? null,\n\t\tauthority.authorizationScopesSupported ?? null,\n\t\tauthority.authorizationResponseIssuerParameterSupported,\n\t]);\n\treturn createHash(\"sha256\")\n\t\t.update(AUTHORITY_DIGEST_DOMAIN, \"utf8\")\n\t\t.update(canonical, \"utf8\")\n\t\t.digest(\"base64url\");\n}\n\nfunction normalizeTransaction(\n\ttransaction: McpClientOAuthAuthorizationTransaction,\n): McpClientOAuthAuthorizationTransaction {\n\tif (typeof transaction !== \"object\" || transaction === null) throw transactionInvalidError();\n\tconst authority = normalizeAuthority(transaction.authority);\n\tif (transaction.authorityDigest !== createAuthorityDigest(authority)) {\n\t\tthrow transactionInvalidError();\n\t}\n\tconst redirectUri = requireRedirectUri(transaction.redirectUri).href;\n\tassertBoundedOpaqueValue(transaction.clientId, MAX_CLIENT_ID_LENGTH);\n\tif (!isClientAuthenticationMethod(transaction.clientAuthenticationMethod)) {\n\t\tthrow transactionInvalidError();\n\t}\n\tcreatePkceS256Challenge(transaction.codeVerifier);\n\tif (!Number.isSafeInteger(transaction.createdAtMs) || transaction.createdAtMs < 0) {\n\t\tthrow transactionInvalidError();\n\t}\n\tif (transaction.scope !== undefined) assertScopeString(transaction.scope);\n\treturn Object.freeze({\n\t\tauthority,\n\t\tauthorityDigest: transaction.authorityDigest,\n\t\tstateDigest: transaction.stateDigest,\n\t\tcodeVerifier: transaction.codeVerifier,\n\t\tredirectUri,\n\t\tclientId: transaction.clientId,\n\t\tclientAuthenticationMethod: transaction.clientAuthenticationMethod,\n\t\t...(transaction.scope === undefined ? {} : { scope: transaction.scope }),\n\t\tcreatedAtMs: transaction.createdAtMs,\n\t});\n}\n\nfunction normalizeClient(\n\tclient: McpClientOAuthClient,\n\tauthority: McpClientOAuthAuthority,\n): McpClientOAuthClient {\n\tif (typeof client !== \"object\" || client === null) throw clientUnsupportedError();\n\tassertBoundedOpaqueValue(client.clientId, MAX_CLIENT_ID_LENGTH);\n\tconst authentication = client.authentication;\n\tif (typeof authentication !== \"object\" || authentication === null) {\n\t\tthrow clientUnsupportedError();\n\t}\n\tswitch (authentication.method) {\n\t\tcase \"none\":\n\t\t\tbreak;\n\t\tcase \"client_secret_basic\":\n\t\tcase \"client_secret_post\":\n\t\t\tassertSecretValue(authentication.clientSecret, MAX_CLIENT_SECRET_LENGTH);\n\t\t\tbreak;\n\t\tcase \"private_key_jwt\":\n\t\t\tif (typeof authentication.addClientAuthentication !== \"function\") {\n\t\t\t\tthrow clientUnsupportedError();\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow clientUnsupportedError();\n\t}\n\tif (!authority.tokenEndpointAuthMethodsSupported.includes(authentication.method)) {\n\t\tthrow clientUnsupportedError();\n\t}\n\tconst copiedAuthentication: McpClientOAuthClientAuthentication =\n\t\tauthentication.method === \"none\"\n\t\t\t? Object.freeze({ method: \"none\" })\n\t\t\t: authentication.method === \"private_key_jwt\"\n\t\t\t\t? Object.freeze({\n\t\t\t\t\t\tmethod: \"private_key_jwt\",\n\t\t\t\t\t\taddClientAuthentication: authentication.addClientAuthentication,\n\t\t\t\t\t})\n\t\t\t\t: Object.freeze({\n\t\t\t\t\t\tmethod: authentication.method,\n\t\t\t\t\t\tclientSecret: authentication.clientSecret,\n\t\t\t\t\t});\n\treturn Object.freeze({ clientId: client.clientId, authentication: copiedAuthentication });\n}\n\nfunction toSdkClientInformation(client: McpClientOAuthClient): OAuthClientInformationMixed {\n\treturn {\n\t\tclient_id: client.clientId,\n\t\ttoken_endpoint_auth_method: client.authentication.method,\n\t};\n}\n\nfunction createClientAuthentication(\n\tclient: McpClientOAuthClient,\n\tauthority: McpClientOAuthAuthority,\n): AddClientAuthentication {\n\tconst exactTokenEndpoint = authority.tokenEndpoint;\n\treturn async (headers, parameters, url, metadata) => {\n\t\tif (\n\t\t\trequireSecureUrl(String(url), { query: true }).href !== exactTokenEndpoint ||\n\t\t\tmetadata?.token_endpoint !== exactTokenEndpoint\n\t\t) {\n\t\t\tthrow endpointRejectedError();\n\t\t}\n\t\theaders.delete(\"Authorization\");\n\t\tparameters.delete(\"client_id\");\n\t\tparameters.delete(\"client_secret\");\n\t\tparameters.delete(\"client_assertion_type\");\n\t\tparameters.delete(\"client_assertion\");\n\t\tswitch (client.authentication.method) {\n\t\t\tcase \"none\":\n\t\t\t\tparameters.set(\"client_id\", client.clientId);\n\t\t\t\treturn;\n\t\t\tcase \"client_secret_basic\": {\n\t\t\t\tconst username = encodeFormComponent(client.clientId);\n\t\t\t\tconst password = encodeFormComponent(client.authentication.clientSecret);\n\t\t\t\theaders.set(\n\t\t\t\t\t\"Authorization\",\n\t\t\t\t\t`Basic ${Buffer.from(`${username}:${password}`, \"utf8\").toString(\"base64\")}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"client_secret_post\":\n\t\t\t\tparameters.set(\"client_id\", client.clientId);\n\t\t\t\tparameters.set(\"client_secret\", client.authentication.clientSecret);\n\t\t\t\treturn;\n\t\t\tcase \"private_key_jwt\": {\n\t\t\t\tconst signerHeaders = new Headers();\n\t\t\t\tconst signerParameters = new URLSearchParams({ client_id: client.clientId });\n\t\t\t\ttry {\n\t\t\t\t\tawait client.authentication.addClientAuthentication(\n\t\t\t\t\t\tsignerHeaders,\n\t\t\t\t\t\tsignerParameters,\n\t\t\t\t\t\tnew URL(exactTokenEndpoint),\n\t\t\t\t\t\ttoSdkMetadata(authority),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof McpClientOAuthProtocolError) {\n\t\t\t\t\t\tthrow canonicalizeProtocolError(error, clientUnsupportedError);\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tconst assertion = requirePrivateKeyJwtSignerOutput(\n\t\t\t\t\tsignerHeaders,\n\t\t\t\t\tsignerParameters,\n\t\t\t\t\tclient.clientId,\n\t\t\t\t);\n\t\t\t\tparameters.set(\"client_id\", client.clientId);\n\t\t\t\tparameters.set(\"client_assertion_type\", PRIVATE_KEY_JWT_ASSERTION_TYPE);\n\t\t\t\tparameters.set(\"client_assertion\", assertion);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction requirePrivateKeyJwtSignerOutput(\n\theaders: Headers,\n\tparameters: URLSearchParams,\n\texactClientId: string,\n): string {\n\tif ([...headers].length !== 0) throw clientUnsupportedError();\n\tconst entries = [...parameters];\n\tif (\n\t\tentries.length !== PRIVATE_KEY_JWT_PARAMETER_NAMES.length ||\n\t\tentries.some(([name]) => !PRIVATE_KEY_JWT_PARAMETER_NAMES.includes(name)) ||\n\t\tparameters.getAll(\"client_id\").length !== 1 ||\n\t\tparameters.get(\"client_id\") !== exactClientId ||\n\t\tparameters.getAll(\"client_assertion_type\").length !== 1 ||\n\t\tparameters.get(\"client_assertion_type\") !== PRIVATE_KEY_JWT_ASSERTION_TYPE ||\n\t\tparameters.getAll(\"client_assertion\").length !== 1\n\t) {\n\t\tthrow clientUnsupportedError();\n\t}\n\tconst assertion = parameters.get(\"client_assertion\");\n\tassertSecretValue(assertion, MAX_TOKEN_LENGTH);\n\treturn assertion;\n}\n\nfunction toSdkMetadata(authority: McpClientOAuthAuthority): AuthorizationServerMetadata {\n\treturn {\n\t\tissuer: authority.issuer,\n\t\tauthorization_endpoint: authority.authorizationEndpoint,\n\t\ttoken_endpoint: authority.tokenEndpoint,\n\t\tresponse_types_supported: [...authority.responseTypesSupported],\n\t\tcode_challenge_methods_supported: [...authority.codeChallengeMethodsSupported],\n\t\ttoken_endpoint_auth_methods_supported: [...authority.tokenEndpointAuthMethodsSupported],\n\t\t...(authority.grantTypesSupported === undefined\n\t\t\t? {}\n\t\t\t: { grant_types_supported: [...authority.grantTypesSupported] }),\n\t\t...(authority.authorizationScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { scopes_supported: [...authority.authorizationScopesSupported] }),\n\t\tauthorization_response_iss_parameter_supported:\n\t\t\tauthority.authorizationResponseIssuerParameterSupported,\n\t};\n}\n\nfunction normalizeScopes(\n\tscopes: readonly string[] | undefined,\n\tauthority: McpClientOAuthAuthority,\n): string | undefined {\n\tif (scopes === undefined) return undefined;\n\tif (!Array.isArray(scopes)) throw invalidOptionsError();\n\tif (scopes.length === 0) return undefined;\n\tif (scopes.length > MAX_SCOPE_COUNT) throw invalidOptionsError();\n\tconst normalized = [...new Set(scopes)];\n\tfor (const scope of normalized) {\n\t\tassertScopeToken(scope);\n\t\tif (\n\t\t\tauthority.authorizationScopesSupported !== undefined &&\n\t\t\t!authority.authorizationScopesSupported.includes(scope)\n\t\t) {\n\t\t\tthrow clientUnsupportedError();\n\t\t}\n\t\tif (\n\t\t\tscope !== \"offline_access\" &&\n\t\t\tauthority.resourceScopesSupported !== undefined &&\n\t\t\t!authority.resourceScopesSupported.includes(scope)\n\t\t) {\n\t\t\tthrow clientUnsupportedError();\n\t\t}\n\t}\n\tconst value = normalized.join(\" \");\n\tassertScopeString(value);\n\treturn value;\n}\n\nfunction normalizeMetadataList(values: readonly string[] | undefined): readonly string[] {\n\tif (values === undefined) return Object.freeze([]);\n\tif (!Array.isArray(values) || values.length > MAX_METADATA_LIST_LENGTH) {\n\t\tthrow authorityInvalidError();\n\t}\n\tconst normalized = [...new Set(values)];\n\tfor (const value of normalized) {\n\t\tif (\n\t\t\ttypeof value !== \"string\" ||\n\t\t\tvalue.length === 0 ||\n\t\t\tvalue.length > MAX_METADATA_VALUE_LENGTH ||\n\t\t\tcontainsControlCharacter(value)\n\t\t) {\n\t\t\tthrow authorityInvalidError();\n\t\t}\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction assertScopeToken(value: string): void {\n\tif (!isMcpClientOAuthScopeToken(value)) throw invalidOptionsError();\n}\n\nfunction assertScopeString(value: unknown): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_SCOPE_STRING_LENGTH) {\n\t\tthrow invalidOptionsError();\n\t}\n\tfor (const scope of value.split(\" \")) assertScopeToken(scope);\n}\n\nfunction normalizeScopeMetadataList(values: readonly string[]): readonly string[] {\n\tif (!Array.isArray(values) || values.length > MAX_SCOPE_COUNT) throw authorityInvalidError();\n\tconst normalized = [...new Set(values)];\n\tif (\n\t\t!normalized.every(isMcpClientOAuthScopeToken) ||\n\t\tnormalized.join(\" \").length > MAX_SCOPE_STRING_LENGTH\n\t) {\n\t\tthrow authorityInvalidError();\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction assertTransactionClient(\n\ttransaction: McpClientOAuthAuthorizationTransaction,\n\tclient: McpClientOAuthClient,\n): void {\n\tif (\n\t\ttransaction.clientId !== client.clientId ||\n\t\ttransaction.clientAuthenticationMethod !== client.authentication.method\n\t) {\n\t\tthrow transactionInvalidError();\n\t}\n}\n\nfunction assertCallbackIssuer(\n\tcallbackIssuer: string | undefined,\n\tauthority: McpClientOAuthAuthority,\n): void {\n\tif (callbackIssuer === undefined) {\n\t\tif (authority.authorizationResponseIssuerParameterSupported) {\n\t\t\tthrow transactionInvalidError();\n\t\t}\n\t\treturn;\n\t}\n\tif (callbackIssuer !== authority.issuer) {\n\t\tthrow transactionInvalidError();\n\t}\n}\n\nfunction assertAuthorizationUrl(\n\tvalue: URL,\n\tinput: {\n\t\treadonly exactEndpoint: string;\n\t\treadonly clientId: string;\n\t\treadonly redirectUri: string;\n\t\treadonly resource: string;\n\t\treadonly state: string;\n\t\treadonly codeChallenge: string;\n\t\treadonly scope: string | undefined;\n\t},\n): void {\n\tconst endpoint = requireSecureUrl(input.exactEndpoint, { query: true });\n\tconst actual = requireSecureUrl(value.href, { query: true });\n\tif (\n\t\tactual.origin !== endpoint.origin ||\n\t\tactual.pathname !== endpoint.pathname ||\n\t\tactual.searchParams.get(\"response_type\") !== \"code\" ||\n\t\tactual.searchParams.get(\"client_id\") !== input.clientId ||\n\t\tactual.searchParams.get(\"redirect_uri\") !== input.redirectUri ||\n\t\tactual.searchParams.get(\"resource\") !== new URL(input.resource).href ||\n\t\tactual.searchParams.get(\"state\") !== input.state ||\n\t\tactual.searchParams.get(\"code_challenge_method\") !== \"S256\" ||\n\t\tactual.searchParams.get(\"code_challenge\") !== input.codeChallenge ||\n\t\tactual.searchParams.get(\"scope\") !== (input.scope ?? null)\n\t) {\n\t\tthrow authorizationFailedError();\n\t}\n}\n\nfunction validateTokens(\n\ttokens: OAuthTokens,\n\toperation: \"exchange\" | \"refresh\",\n\tfallbackScope?: string,\n): OAuthTokens {\n\tassertTokenValue(tokens.access_token, operation);\n\tif (\n\t\ttokens.token_type.length === 0 ||\n\t\ttokens.token_type.length > 64 ||\n\t\tcontainsControlCharacter(tokens.token_type) ||\n\t\ttokens.token_type.toLowerCase() !== \"bearer\"\n\t) {\n\t\tthrow tokenResponseInvalidError(operation);\n\t}\n\tif (tokens.refresh_token !== undefined) assertTokenValue(tokens.refresh_token, operation);\n\tif (tokens.id_token !== undefined) assertTokenValue(tokens.id_token, operation);\n\tif (\n\t\ttokens.expires_in !== undefined &&\n\t\t(!Number.isFinite(tokens.expires_in) || tokens.expires_in <= 0)\n\t) {\n\t\tthrow tokenResponseInvalidError(operation);\n\t}\n\tif (\n\t\ttokens.scope !== undefined &&\n\t\t(tokens.scope.length === 0 ||\n\t\t\ttokens.scope.length > MAX_SCOPE_STRING_LENGTH ||\n\t\t\ttokens.scope.split(\" \").length > MAX_SCOPE_COUNT ||\n\t\t\t!tokens.scope.split(\" \").every(isMcpClientOAuthScopeToken))\n\t) {\n\t\tthrow tokenResponseInvalidError(operation);\n\t}\n\tif (\n\t\ttokens.scope !== undefined &&\n\t\tfallbackScope !== undefined &&\n\t\t!isScopeSubset(tokens.scope, fallbackScope)\n\t) {\n\t\tthrow tokenResponseInvalidError(operation);\n\t}\n\treturn tokens.scope === undefined && fallbackScope !== undefined\n\t\t? { ...tokens, scope: fallbackScope }\n\t\t: tokens;\n}\n\nfunction isScopeSubset(candidate: string, available: string): boolean {\n\tconst availableTokens = new Set(available.split(\" \"));\n\treturn candidate.split(\" \").every((scope) => availableTokens.has(scope));\n}\n\nfunction assertTokenValue(value: string, operation: \"exchange\" | \"refresh\"): void {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_TOKEN_LENGTH ||\n\t\tcontainsControlCharacter(value)\n\t) {\n\t\tthrow tokenResponseInvalidError(operation);\n\t}\n}\n\nfunction assertBoundedOpaqueValue(value: string, maximumLength: number): void {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maximumLength ||\n\t\tcontainsControlCharacter(value)\n\t) {\n\t\tthrow clientUnsupportedError();\n\t}\n}\n\nfunction assertSecretValue(value: string | null, maximumLength: number): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > maximumLength) {\n\t\tthrow clientUnsupportedError();\n\t}\n}\n\nfunction requireSecureUrl(value: string, options: { readonly query: boolean }): URL {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_URL_LENGTH) {\n\t\tthrow authorityInvalidError();\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow authorityInvalidError();\n\t}\n\tif (\n\t\turl.protocol !== \"https:\" ||\n\t\turl.username.length > 0 ||\n\t\turl.password.length > 0 ||\n\t\turl.hash.length > 0 ||\n\t\t(!options.query && url.search.length > 0)\n\t) {\n\t\tthrow authorityInvalidError();\n\t}\n\treturn url;\n}\n\nfunction requireRedirectUri(value: string): URL {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_URL_LENGTH) {\n\t\tthrow authorityInvalidError();\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow authorityInvalidError();\n\t}\n\tif (\n\t\turl.username.length > 0 ||\n\t\turl.password.length > 0 ||\n\t\turl.hash.length > 0 ||\n\t\t(url.protocol !== \"https:\" && !isLoopbackHttpRedirect(url))\n\t) {\n\t\tthrow authorityInvalidError();\n\t}\n\treturn url;\n}\n\nfunction isLoopbackHttpRedirect(url: URL): boolean {\n\tif (url.protocol !== \"http:\") return false;\n\tconst host = url.hostname.toLowerCase();\n\tif (host === \"localhost\" || host === \"[::1]\") return true;\n\tconst octets = host.split(\".\");\n\treturn octets.length === 4 && octets[0] === \"127\" && octets.every(isDecimalOctet);\n}\n\nfunction isDecimalOctet(value: string): boolean {\n\tif (!/^\\d{1,3}$/u.test(value)) return false;\n\tconst parsed = Number(value);\n\treturn parsed >= 0 && parsed <= 255 && String(parsed) === value;\n}\n\nfunction requireCanonicalResource(value: string): string {\n\tconst resource = requireSecureUrl(value, { query: true });\n\tif (resource.href !== value) throw authorityInvalidError();\n\treturn value;\n}\n\nfunction requireExactIssuer(value: string): string {\n\trequireSecureUrl(value, { query: false });\n\treturn value;\n}\n\nfunction combineAbortSignals(\n\toperationSignal: AbortSignal | undefined,\n\trequestSignal: AbortSignal | null | undefined,\n): AbortSignal | undefined {\n\tif (operationSignal === undefined) return requestSignal ?? undefined;\n\tif (requestSignal === undefined || requestSignal === null || requestSignal === operationSignal) {\n\t\treturn operationSignal;\n\t}\n\treturn AbortSignal.any([operationSignal, requestSignal]);\n}\n\nfunction awaitWithSignal<Value>(\n\tpromise: PromiseLike<Value>,\n\tsignal: AbortSignal | undefined,\n): Promise<Value> {\n\tif (signal === undefined) return Promise.resolve(promise);\n\tsignal.throwIfAborted();\n\treturn new Promise<Value>((resolve, reject) => {\n\t\tconst onAbort = (): void => reject(signal.reason);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tPromise.resolve(promise).then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isExactResponseUrl(actual: string, expected: string): boolean {\n\ttry {\n\t\treturn requireSecureUrl(actual, { query: true }).href === expected;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tsignal?.throwIfAborted();\n}\n\nfunction encodeFormComponent(value: string): string {\n\tconst encoded = new URLSearchParams({ value }).toString();\n\treturn encoded.slice(\"value=\".length);\n}\n\nfunction containsControlCharacter(value: string): boolean {\n\tfor (const character of value) {\n\t\tconst point = character.codePointAt(0);\n\t\tif (point !== undefined && (point <= 0x1f || (point >= 0x7f && point <= 0x9f))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction isClientAuthenticationMethod(\n\tvalue: unknown,\n): value is McpClientOAuthClientAuthentication[\"method\"] {\n\treturn (\n\t\tvalue === \"none\" ||\n\t\tvalue === \"client_secret_basic\" ||\n\t\tvalue === \"client_secret_post\" ||\n\t\tvalue === \"private_key_jwt\"\n\t);\n}\n\nfunction translateTokenError(\n\terror: unknown,\n\toperation: \"exchange\" | \"refresh\",\n\thostFetchAttempt?: McpClientOAuthHostFetchAttempt,\n): McpClientOAuthProtocolError {\n\tif (operation === \"refresh\" && hostFetchAttempt?.invoked === true) {\n\t\tif (hostFetchAttempt.responseReturned && OAuthError.isInstance(error)) {\n\t\t\tif (error.code === \"invalid_grant\") return invalidGrantError();\n\t\t\tif (error.code === \"invalid_client\") return invalidClientError();\n\t\t}\n\t\treturn refreshOutcomeUnknownError();\n\t}\n\tif (error instanceof McpClientOAuthProtocolError) {\n\t\treturn canonicalizeProtocolError(\n\t\t\terror,\n\t\t\toperation === \"exchange\" ? tokenExchangeFailedError : tokenRefreshFailedError,\n\t\t);\n\t}\n\tif (OAuthError.isInstance(error)) {\n\t\tif (error.code === \"invalid_grant\") return invalidGrantError();\n\t\tif (error.code === \"invalid_client\") return invalidClientError();\n\t}\n\treturn operation === \"exchange\" ? tokenExchangeFailedError() : tokenRefreshFailedError();\n}\n\nfunction canonicalizeProtocolError(\n\terror: McpClientOAuthProtocolError,\n\tfallback: () => McpClientOAuthProtocolError,\n): McpClientOAuthProtocolError {\n\tif (!isInternalMcpClientOAuthProtocolError(error)) return fallback();\n\ttry {\n\t\tswitch (error.code) {\n\t\t\tcase McpClientOAuthProtocolErrorCode.InvalidOptions:\n\t\t\t\treturn invalidOptionsError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.EndpointRejected:\n\t\t\t\treturn endpointRejectedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.DiscoveryFailed:\n\t\t\t\treturn discoveryFailedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.AuthorityInvalid:\n\t\t\t\treturn authorityInvalidError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.ClientUnsupported:\n\t\t\t\treturn clientUnsupportedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.TransactionInvalid:\n\t\t\t\treturn transactionInvalidError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.AuthorizationDenied:\n\t\t\t\treturn authorizationDeniedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.AuthorizationFailed:\n\t\t\t\treturn authorizationFailedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.InvalidGrant:\n\t\t\t\treturn invalidGrantError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.InvalidClient:\n\t\t\t\treturn invalidClientError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.TokenExchangeFailed:\n\t\t\t\treturn tokenExchangeFailedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.TokenRefreshFailed:\n\t\t\t\treturn tokenRefreshFailedError();\n\t\t\tcase McpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown:\n\t\t\t\treturn refreshOutcomeUnknownError();\n\t\t}\n\t} catch {\n\t\treturn fallback();\n\t}\n\treturn fallback();\n}\n\nfunction invalidOptionsError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.InvalidOptions,\n\t\t\"The MCP OAuth client options are invalid.\",\n\t);\n}\n\nfunction endpointRejectedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.EndpointRejected,\n\t\t\"The MCP OAuth endpoint policy rejected the operation.\",\n\t);\n}\n\nfunction discoveryFailedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.DiscoveryFailed,\n\t\t\"MCP OAuth authority discovery failed.\",\n\t);\n}\n\nfunction authorityInvalidError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.AuthorityInvalid,\n\t\t\"The MCP OAuth authority is invalid or does not match the configured identity.\",\n\t);\n}\n\nfunction clientUnsupportedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.ClientUnsupported,\n\t\t\"The provisioned MCP OAuth client is invalid or unsupported by this authority.\",\n\t);\n}\n\nfunction transactionInvalidError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.TransactionInvalid,\n\t\t\"The MCP OAuth authorization transaction is invalid.\",\n\t);\n}\n\nfunction authorizationDeniedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.AuthorizationDenied,\n\t\t\"The MCP OAuth authorization request was not approved.\",\n\t);\n}\n\nfunction authorizationFailedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.AuthorizationFailed,\n\t\t\"The MCP OAuth authorization request could not be created.\",\n\t);\n}\n\nfunction invalidGrantError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.InvalidGrant,\n\t\t\"The MCP OAuth authorization grant is no longer valid.\",\n\t);\n}\n\nfunction invalidClientError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.InvalidClient,\n\t\t\"The provisioned MCP OAuth client was rejected.\",\n\t);\n}\n\nfunction tokenExchangeFailedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.TokenExchangeFailed,\n\t\t\"The MCP OAuth authorization code exchange failed.\",\n\t);\n}\n\nfunction tokenRefreshFailedError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.TokenRefreshFailed,\n\t\t\"The MCP OAuth token refresh failed.\",\n\t);\n}\n\nfunction refreshOutcomeUnknownError(): McpClientOAuthProtocolError {\n\treturn createInternalProtocolError(\n\t\tMcpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown,\n\t\t\"The MCP OAuth token refresh outcome is unknown and must not be retried automatically.\",\n\t);\n}\n\nfunction tokenResponseInvalidError(operation: \"exchange\" | \"refresh\"): McpClientOAuthProtocolError {\n\treturn operation === \"exchange\" ? tokenExchangeFailedError() : tokenRefreshFailedError();\n}\n","import {\n\tLATEST_PROTOCOL_VERSION,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthProtectedResourceMetadata,\n\tresourceUrlFromServerUrl,\n} from \"@modelcontextprotocol/client\";\nimport type {\n\tAuthorizationServerMetadata,\n\tFetchLike,\n\tOAuthProtectedResourceMetadata,\n} from \"@modelcontextprotocol/client\";\n\nimport { parseMcpClientOAuthAuthority, type McpClientOAuthAuthority } from \"./protocol.ts\";\nimport { isMcpClientOAuthScopeToken } from \"./scope.ts\";\nimport {\n\tassertOAuthSnapshotKeys,\n\toauthSnapshotBoolean,\n\toauthSnapshotRecord,\n\toauthSnapshotString,\n\toauthSnapshotStrings,\n\tparseOAuthSnapshot,\n\ttype McpClientOAuthSnapshotOptions,\n} from \"./snapshot-data.ts\";\n\nconst MAX_URL_LENGTH = 4_096;\nconst MAX_PROTOCOL_VERSION_LENGTH = 64;\nconst MAX_AUTHORIZATION_SERVER_COUNT = 16;\nconst MAX_METADATA_LIST_LENGTH = 256;\nconst MAX_METADATA_VALUE_LENGTH = 2_048;\nconst MAX_SCOPE_COUNT = 128;\nconst MAX_SCOPE_STRING_LENGTH = 4_096;\nconst MAX_WWW_AUTHENTICATE_LENGTH = 8_192;\nconst STRICT_TOKEN_ENDPOINT_AUTHENTICATION_METHODS: ReadonlySet<string> = new Set([\n\t\"none\",\n\t\"client_secret_basic\",\n\t\"client_secret_post\",\n\t\"private_key_jwt\",\n]);\n\n/** Stable, secret-free failure categories for OAuth bootstrap discovery. */\nexport const McpClientOAuthBootstrapErrorCode = {\n\tInvalidOptions: \"MCP_CLIENT_OAUTH_BOOTSTRAP_INVALID_OPTIONS\",\n\tEndpointRejected: \"MCP_CLIENT_OAUTH_BOOTSTRAP_ENDPOINT_REJECTED\",\n\tDiscoveryFailed: \"MCP_CLIENT_OAUTH_BOOTSTRAP_DISCOVERY_FAILED\",\n\tProtectedResourceInvalid: \"MCP_CLIENT_OAUTH_BOOTSTRAP_PROTECTED_RESOURCE_INVALID\",\n\tAuthorityInvalid: \"MCP_CLIENT_OAUTH_BOOTSTRAP_AUTHORITY_INVALID\",\n} as const;\n\nexport type McpClientOAuthBootstrapErrorCode =\n\t(typeof McpClientOAuthBootstrapErrorCode)[keyof typeof McpClientOAuthBootstrapErrorCode];\n\n/** A bounded public error. Its message never contains remote response data or URLs. */\nexport class McpClientOAuthBootstrapError extends Error {\n\treadonly code: McpClientOAuthBootstrapErrorCode;\n\n\tconstructor(code: McpClientOAuthBootstrapErrorCode) {\n\t\tsuper(bootstrapErrorMessage(code));\n\t\tthis.name = \"McpClientOAuthBootstrapError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport type McpClientOAuthBootstrapEndpointKind =\n\t\"resource-metadata\" | \"authorization-server-metadata\" | \"authorization\" | \"token\";\n\nexport interface McpClientOAuthBootstrapEndpointPolicyInput {\n\t/** A disposable copy. Mutating it never changes the endpoint used by the bootstrap. */\n\treadonly endpoint: URL;\n\treadonly kind: McpClientOAuthBootstrapEndpointKind;\n\treadonly credentialed: boolean;\n\treadonly serverUrl: URL;\n\t/** Present only after protected-resource metadata has been validated. */\n\treadonly resource?: URL;\n\t/** Exact, non-normalized RFC 8707 resource string corresponding to `resource`. */\n\treadonly exactResource?: string;\n\t/** Present only after an advertised authorization server has been selected. */\n\treadonly issuer?: URL;\n\t/** Exact, non-normalized issuer identifier corresponding to `issuer`. */\n\treadonly exactIssuer?: string;\n\treadonly signal?: AbortSignal;\n}\n\n/** Only literal `true` admits an endpoint; every other result fails closed. */\nexport type McpClientOAuthBootstrapEndpointPolicy = (\n\tinput: McpClientOAuthBootstrapEndpointPolicyInput,\n) => boolean | PromiseLike<boolean>;\n\nexport interface McpClientOAuthBootstrapOptions {\n\t/**\n\t * A host-owned SSRF-hardened fetch. It must pin DNS, reject redirects, and bound response\n\t * bodies and time. The bootstrap additionally forces `redirect: \"error\"` and calls the\n\t * endpoint policy before every generated discovery request.\n\t */\n\treadonly fetch: FetchLike;\n\treadonly endpointPolicy: McpClientOAuthBootstrapEndpointPolicy;\n\treadonly protocolVersion?: string;\n}\n\n/** Values extracted by the host from the MCP server's `WWW-Authenticate: Bearer` challenge. */\nexport interface McpClientOAuthBootstrapChallenge {\n\treadonly resourceMetadataUrl?: string;\n\treadonly scope?: string;\n}\n\nexport interface McpClientOAuthBootstrapDiscoveryInput {\n\treadonly serverUrl: string;\n\t/**\n\t * Challenge values take priority over constructed well-known locations and resource metadata\n\t * scopes, as required by the MCP authorization specification.\n\t */\n\treadonly challenge?: McpClientOAuthBootstrapChallenge;\n\t/**\n\t * Raw response header from the initial `401`. The bootstrap extracts a bounded Bearer\n\t * `resource_metadata` and `scope`; it is mutually exclusive with `challenge`.\n\t */\n\treadonly wwwAuthenticate?: string;\n\t/** Exact issuer previously selected by host policy from a selection-required result. */\n\treadonly issuer?: string;\n\treadonly signal?: AbortSignal;\n}\n\n/** Bounded protected-resource discovery material that a host may persist. */\nexport interface McpClientOAuthBootstrapResource {\n\treadonly serverUrl: string;\n\treadonly resource: string;\n\treadonly resourceMetadataUrl: string;\n\treadonly scopesSupported?: readonly string[];\n}\n\nexport interface McpClientOAuthBootstrapIssuerCandidate {\n\treadonly issuer: string;\n}\n\n/**\n * Reasons a current-spec authority cannot be handed to the intentionally stricter runtime\n * protocol. These are compatibility facts, not a reason to trust or expose its endpoints.\n */\nexport const McpClientOAuthStrictCompatibilityIssue = {\n\tAuthorizationCodeResponseUnsupported: \"authorization_code_response_unsupported\",\n\tPkceS256Unsupported: \"pkce_s256_unsupported\",\n\tTokenEndpointAuthenticationUnsupported: \"token_endpoint_authentication_unsupported\",\n\tAuthorizationCodeGrantUnsupported: \"authorization_code_grant_unsupported\",\n\tQueryResponseModeUnsupported: \"query_response_mode_unsupported\",\n\t/** @deprecated RFC 9207 support is optional and this issue is no longer emitted. */\n\tAuthorizationResponseIssuerUnsupported: \"authorization_response_issuer_unsupported\",\n} as const;\n\nexport type McpClientOAuthStrictCompatibilityIssue =\n\t(typeof McpClientOAuthStrictCompatibilityIssue)[keyof typeof McpClientOAuthStrictCompatibilityIssue];\n\n/** A selected authority that composes directly with `McpClientOAuthProtocol.startAuthorization`. */\nexport interface McpClientOAuthBootstrapCandidate {\n\treadonly authority: McpClientOAuthAuthority;\n\treadonly clientIdMetadataDocumentSupported: boolean;\n\t/**\n\t * A validated, bounded legacy capability only. Discovery never invokes Dynamic Client\n\t * Registration; a host must opt into any future registration operation separately.\n\t */\n\treadonly legacyDynamicRegistrationEndpoint?: string;\n}\n\nexport interface McpClientOAuthBootstrapSelectionRequired {\n\treadonly kind: \"authorization-server-selection-required\";\n\treadonly resource: McpClientOAuthBootstrapResource;\n\treadonly scopes?: readonly string[];\n\treadonly candidates: readonly McpClientOAuthBootstrapIssuerCandidate[];\n}\n\nexport interface McpClientOAuthBootstrapReady {\n\treadonly kind: \"ready\";\n\treadonly resource: McpClientOAuthBootstrapResource;\n\treadonly scopes?: readonly string[];\n\treadonly candidate: McpClientOAuthBootstrapCandidate;\n}\n\nexport interface McpClientOAuthBootstrapStrictProtocolUnsupported {\n\treadonly kind: \"strict-protocol-unsupported\";\n\treadonly resource: McpClientOAuthBootstrapResource;\n\treadonly scopes?: readonly string[];\n\t/** Validated RFC 8414/OIDC issuer; no unadmitted endpoint metadata is exposed. */\n\treadonly issuer: string;\n\treadonly issues: readonly McpClientOAuthStrictCompatibilityIssue[];\n}\n\nexport type McpClientOAuthBootstrapDiscoveryResult =\n\t| McpClientOAuthBootstrapSelectionRequired\n\t| McpClientOAuthBootstrapReady\n\t| McpClientOAuthBootstrapStrictProtocolUnsupported;\n\n/** Decode bounded host-persisted discovery without fetching, admitting endpoints, or registering clients. */\nexport function parseMcpClientOAuthBootstrapDiscoveryResult(\n\tvalue: unknown,\n\toptions: McpClientOAuthSnapshotOptions = {},\n): McpClientOAuthBootstrapDiscoveryResult {\n\treturn parseOAuthSnapshot(value, options, (record, maximum) => {\n\t\tconst resourceValue = oauthSnapshotRecord(record.resource);\n\t\tassertOAuthSnapshotKeys(resourceValue, [\n\t\t\t\"serverUrl\",\n\t\t\t\"resource\",\n\t\t\t\"resourceMetadataUrl\",\n\t\t\t\"scopesSupported\",\n\t\t]);\n\t\tconst url = (input: unknown, query = true): string => {\n\t\t\tconst text = oauthSnapshotString(input, maximum);\n\t\t\trequireSecureUrl(text, query);\n\t\t\treturn text;\n\t\t};\n\t\tconst scopes = (input: unknown) =>\n\t\t\tnormalizeScopeList(\n\t\t\t\toauthSnapshotStrings(input, MAX_SCOPE_COUNT),\n\t\t\t\tMcpClientOAuthBootstrapErrorCode.InvalidOptions,\n\t\t\t);\n\t\tconst resource: McpClientOAuthBootstrapResource = Object.freeze({\n\t\t\tserverUrl: url(resourceValue.serverUrl),\n\t\t\tresource: url(resourceValue.resource),\n\t\t\tresourceMetadataUrl: url(resourceValue.resourceMetadataUrl),\n\t\t\t...(resourceValue.scopesSupported === undefined\n\t\t\t\t? {}\n\t\t\t\t: { scopesSupported: scopes(resourceValue.scopesSupported) }),\n\t\t});\n\t\tconst selectedScopes = record.scopes === undefined ? undefined : scopes(record.scopes);\n\t\tif (record.kind === \"authorization-server-selection-required\") {\n\t\t\tassertOAuthSnapshotKeys(record, [\"kind\", \"resource\", \"scopes\", \"candidates\"]);\n\t\t\tif (\n\t\t\t\t!Array.isArray(record.candidates) ||\n\t\t\t\trecord.candidates.length < 2 ||\n\t\t\t\trecord.candidates.length > MAX_AUTHORIZATION_SERVER_COUNT\n\t\t\t) {\n\t\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t\t\t}\n\t\t\tconst candidates: readonly unknown[] = record.candidates;\n\t\t\tconst issuers = candidates.map((item) => {\n\t\t\t\tconst candidate = oauthSnapshotRecord(item);\n\t\t\t\tassertOAuthSnapshotKeys(candidate, [\"issuer\"]);\n\t\t\t\treturn url(candidate.issuer, false);\n\t\t\t});\n\t\t\tif (new Set(issuers).size !== issuers.length)\n\t\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t\t\treturn freezeSelectionRequired(resource, selectedScopes, issuers);\n\t\t}\n\t\tif (record.kind === \"ready\") {\n\t\t\tassertOAuthSnapshotKeys(record, [\"kind\", \"resource\", \"scopes\", \"candidate\"]);\n\t\t\tconst candidate = oauthSnapshotRecord(record.candidate);\n\t\t\tassertOAuthSnapshotKeys(candidate, [\n\t\t\t\t\"authority\",\n\t\t\t\t\"clientIdMetadataDocumentSupported\",\n\t\t\t\t\"legacyDynamicRegistrationEndpoint\",\n\t\t\t]);\n\t\t\tconst authority = parseMcpClientOAuthAuthority(candidate.authority, options);\n\t\t\tif (authority.serverUrl !== resource.serverUrl || authority.resource !== resource.resource) {\n\t\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t\t\t}\n\t\t\treturn freezeReady(resource, selectedScopes, {\n\t\t\t\tauthority,\n\t\t\t\tclientIdMetadataDocumentSupported: oauthSnapshotBoolean(\n\t\t\t\t\tcandidate.clientIdMetadataDocumentSupported,\n\t\t\t\t),\n\t\t\t\t...(candidate.legacyDynamicRegistrationEndpoint === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tlegacyDynamicRegistrationEndpoint: url(candidate.legacyDynamicRegistrationEndpoint),\n\t\t\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t\tif (record.kind === \"strict-protocol-unsupported\") {\n\t\t\tassertOAuthSnapshotKeys(record, [\"kind\", \"resource\", \"scopes\", \"issuer\", \"issues\"]);\n\t\t\tconst issues = oauthSnapshotStrings(record.issues, 6);\n\t\t\tif (\n\t\t\t\tissues.length === 0 ||\n\t\t\t\t!issues.every(isCompatibilityIssue) ||\n\t\t\t\tnew Set(issues).size !== issues.length\n\t\t\t) {\n\t\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t\t\t}\n\t\t\treturn freezeStrictUnsupported(resource, selectedScopes, url(record.issuer, false), issues);\n\t\t}\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t});\n}\n\nfunction isCompatibilityIssue(value: string): value is McpClientOAuthStrictCompatibilityIssue {\n\treturn Object.values(McpClientOAuthStrictCompatibilityIssue).some((issue) => issue === value);\n}\n\n/**\n * Parses the bounded fields needed from a raw `WWW-Authenticate` header. It deliberately drops\n * attacker-controlled OAuth error text and returns `undefined` when no Bearer challenge exists.\n */\nexport function parseMcpClientOAuthBootstrapChallenge(\n\twwwAuthenticate: string,\n): McpClientOAuthBootstrapChallenge | undefined {\n\tif (\n\t\ttypeof wwwAuthenticate !== \"string\" ||\n\t\twwwAuthenticate.length === 0 ||\n\t\twwwAuthenticate.length > MAX_WWW_AUTHENTICATE_LENGTH ||\n\t\tcontainsForbiddenHeaderCharacter(wwwAuthenticate)\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\tconst bearer = findBearerChallenge(wwwAuthenticate);\n\tif (bearer === undefined) return undefined;\n\tconst parameters = parseBearerParameters(bearer);\n\tif (parameters === null) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\treturn Object.freeze({\n\t\t...(parameters.resourceMetadataUrl === undefined\n\t\t\t? {}\n\t\t\t: { resourceMetadataUrl: requireSecureUrl(parameters.resourceMetadataUrl, true).href }),\n\t\t...(parameters.scope === undefined\n\t\t\t? {}\n\t\t\t: { scope: normalizeScopeString(parameters.scope).join(\" \") }),\n\t});\n}\n\n/**\n * Framework-neutral discovery bootstrap for an application-owned interactive OAuth flow.\n *\n * It owns no persistence, tenant policy, browser redirect, client registration, or token state.\n * Hosts retain those responsibilities and pass a ready authority to `McpClientOAuthProtocol`.\n */\nexport class McpClientOAuthBootstrap {\n\treadonly #fetch: FetchLike;\n\treadonly #endpointPolicy: McpClientOAuthBootstrapEndpointPolicy;\n\treadonly #protocolVersion: string;\n\n\tconstructor(options: McpClientOAuthBootstrapOptions) {\n\t\tif (\n\t\t\ttypeof options !== \"object\" ||\n\t\t\toptions === null ||\n\t\t\ttypeof options.fetch !== \"function\" ||\n\t\t\ttypeof options.endpointPolicy !== \"function\"\n\t\t) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t\t}\n\t\tthis.#fetch = options.fetch;\n\t\tthis.#endpointPolicy = options.endpointPolicy;\n\t\tthis.#protocolVersion = normalizeProtocolVersion(\n\t\t\toptions.protocolVersion ?? LATEST_PROTOCOL_VERSION,\n\t\t);\n\t}\n\n\tasync discover(\n\t\tinput: McpClientOAuthBootstrapDiscoveryInput,\n\t): Promise<McpClientOAuthBootstrapDiscoveryResult> {\n\t\tconst operation = normalizeDiscoveryInput(input);\n\t\tthrowIfAborted(operation.signal);\n\n\t\tlet discoveredResourceMetadataUrl: string | undefined;\n\t\tlet metadata: OAuthProtectedResourceMetadata;\n\t\ttry {\n\t\t\tmetadata = await discoverOAuthProtectedResourceMetadata(\n\t\t\t\toperation.serverUrl,\n\t\t\t\t{\n\t\t\t\t\tprotocolVersion: this.#protocolVersion,\n\t\t\t\t\t...(operation.challenge?.resourceMetadataUrl === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { resourceMetadataUrl: operation.challenge.resourceMetadataUrl }),\n\t\t\t\t},\n\t\t\t\tthis.#createFetch({\n\t\t\t\t\tkind: \"resource-metadata\",\n\t\t\t\t\tcredentialed: false,\n\t\t\t\t\tserverUrl: operation.serverUrl,\n\t\t\t\t\tsignal: operation.signal,\n\t\t\t\t\tonAcceptedResponse(endpoint, response) {\n\t\t\t\t\t\tif (response.ok) discoveredResourceMetadataUrl = endpoint;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrowIfAborted(operation.signal);\n\t\t\tif (error instanceof McpClientOAuthBootstrapError) throw error;\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);\n\t\t}\n\n\t\tthrowIfAborted(operation.signal);\n\t\tconst resource = normalizeProtectedResource({\n\t\t\tserverUrl: operation.serverUrl,\n\t\t\tresourceMetadataUrl:\n\t\t\t\tdiscoveredResourceMetadataUrl ?? operation.challenge?.resourceMetadataUrl,\n\t\t\tchallengeResourceMetadataUrl: operation.challenge?.resourceMetadataUrl,\n\t\t\tmetadata,\n\t\t});\n\t\tconst scopes = selectScopes(operation.challenge?.scope, resource.scopesSupported);\n\t\tconst issuers = normalizeAuthorizationServers(metadata.authorization_servers);\n\t\tif (operation.issuer === undefined && issuers.length > 1) {\n\t\t\treturn freezeSelectionRequired(resource, scopes, issuers);\n\t\t}\n\n\t\tconst issuer = operation.issuer ?? issuers[0];\n\t\tif (issuer === undefined || !issuers.includes(issuer)) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t\t}\n\n\t\tlet authorizationMetadata: AuthorizationServerMetadata | undefined;\n\t\ttry {\n\t\t\tauthorizationMetadata = await discoverAuthorizationServerMetadata(issuer, {\n\t\t\t\tfetchFn: this.#createFetch({\n\t\t\t\t\tkind: \"authorization-server-metadata\",\n\t\t\t\t\tcredentialed: false,\n\t\t\t\t\tserverUrl: operation.serverUrl,\n\t\t\t\t\tresource: resource.resource,\n\t\t\t\t\tissuer,\n\t\t\t\t\tsignal: operation.signal,\n\t\t\t\t}),\n\t\t\t\tprotocolVersion: this.#protocolVersion,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrowIfAborted(operation.signal);\n\t\t\tif (error instanceof McpClientOAuthBootstrapError) throw error;\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);\n\t\t}\n\t\tthrowIfAborted(operation.signal);\n\t\tif (authorizationMetadata === undefined || authorizationMetadata.issuer !== issuer) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t\t}\n\n\t\tconst compatibilityIssues = strictCompatibilityIssues(authorizationMetadata);\n\t\tif (compatibilityIssues.length > 0) {\n\t\t\treturn freezeStrictUnsupported(resource, scopes, issuer, compatibilityIssues);\n\t\t}\n\n\t\tconst authority = createStrictAuthority({\n\t\t\tserverUrl: operation.serverUrl,\n\t\t\tresource,\n\t\t\tissuer,\n\t\t\tmetadata: authorizationMetadata,\n\t\t\t...(operation.challenge?.scope === undefined\n\t\t\t\t? {}\n\t\t\t\t: { challengedScope: operation.challenge.scope }),\n\t\t});\n\t\tawait this.#authorizeEndpoint(authority.authorizationEndpoint, {\n\t\t\tkind: \"authorization\",\n\t\t\tcredentialed: false,\n\t\t\tserverUrl: operation.serverUrl,\n\t\t\tresource: authority.resource,\n\t\t\tissuer,\n\t\t\tsignal: operation.signal,\n\t\t});\n\t\tawait this.#authorizeEndpoint(authority.tokenEndpoint, {\n\t\t\tkind: \"token\",\n\t\t\tcredentialed: true,\n\t\t\tserverUrl: operation.serverUrl,\n\t\t\tresource: authority.resource,\n\t\t\tissuer,\n\t\t\tsignal: operation.signal,\n\t\t});\n\n\t\tconst legacyDynamicRegistrationEndpoint = normalizeOptionalLegacyRegistrationEndpoint(\n\t\t\tauthorizationMetadata.registration_endpoint,\n\t\t);\n\t\treturn freezeReady(resource, scopes, {\n\t\t\tauthority,\n\t\t\tclientIdMetadataDocumentSupported:\n\t\t\t\tauthorizationMetadata.client_id_metadata_document_supported === true,\n\t\t\t...(legacyDynamicRegistrationEndpoint === undefined\n\t\t\t\t? {}\n\t\t\t\t: { legacyDynamicRegistrationEndpoint }),\n\t\t});\n\t}\n\n\t#createFetch(input: {\n\t\treadonly kind: \"resource-metadata\" | \"authorization-server-metadata\";\n\t\treadonly credentialed: false;\n\t\treadonly serverUrl: string;\n\t\treadonly resource?: string;\n\t\treadonly issuer?: string;\n\t\treadonly signal: AbortSignal | undefined;\n\t\treadonly onAcceptedResponse?: (endpoint: string, response: Response) => void;\n\t}): FetchLike {\n\t\treturn async (url, init) => {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tconst endpoint = requireSecureUrl(String(url), true);\n\t\t\tawait this.#authorizeEndpoint(endpoint.href, input);\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tconst signal = combineAbortSignals(input.signal, init?.signal);\n\t\t\tconst requestInit: RequestInit = { ...init, redirect: \"error\" };\n\t\t\tif (signal !== undefined) requestInit.signal = signal;\n\t\t\tconst response = await this.#fetch(new URL(endpoint.href), requestInit);\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tif (\n\t\t\t\tresponse.redirected ||\n\t\t\t\t(response.url.length > 0 && !isExactResponseUrl(response.url, endpoint.href))\n\t\t\t) {\n\t\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);\n\t\t\t}\n\t\t\tinput.onAcceptedResponse?.(endpoint.href, response);\n\t\t\treturn response;\n\t\t};\n\t}\n\n\tasync #authorizeEndpoint(\n\t\tendpointValue: string,\n\t\tinput: {\n\t\t\treadonly kind: McpClientOAuthBootstrapEndpointKind;\n\t\t\treadonly credentialed: boolean;\n\t\t\treadonly serverUrl: string;\n\t\t\treadonly resource?: string;\n\t\t\treadonly issuer?: string;\n\t\t\treadonly signal: AbortSignal | undefined;\n\t\t},\n\t): Promise<void> {\n\t\tthrowIfAborted(input.signal);\n\t\tconst endpoint = requireSecureUrl(endpointValue, true);\n\t\tlet admitted: unknown;\n\t\ttry {\n\t\t\tadmitted = await awaitWithSignal(\n\t\t\t\tPromise.resolve().then(() =>\n\t\t\t\t\tthis.#endpointPolicy(\n\t\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t\tendpoint: new URL(endpoint.href),\n\t\t\t\t\t\t\tkind: input.kind,\n\t\t\t\t\t\t\tcredentialed: input.credentialed,\n\t\t\t\t\t\t\tserverUrl: new URL(input.serverUrl),\n\t\t\t\t\t\t\t...(input.resource === undefined ? {} : { resource: new URL(input.resource) }),\n\t\t\t\t\t\t\t...(input.resource === undefined ? {} : { exactResource: input.resource }),\n\t\t\t\t\t\t\t...(input.issuer === undefined\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: { issuer: new URL(input.issuer), exactIssuer: input.issuer }),\n\t\t\t\t\t\t\t...(input.signal === undefined ? {} : { signal: input.signal }),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tinput.signal,\n\t\t\t);\n\t\t} catch {\n\t\t\tthrowIfAborted(input.signal);\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);\n\t\t}\n\t\tthrowIfAborted(input.signal);\n\t\tif (admitted !== true) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);\n\t\t}\n\t}\n}\n\nfunction normalizeDiscoveryInput(input: McpClientOAuthBootstrapDiscoveryInput): {\n\treadonly serverUrl: string;\n\treadonly challenge?: Readonly<McpClientOAuthBootstrapChallenge>;\n\treadonly issuer?: string;\n\treadonly signal: AbortSignal | undefined;\n} {\n\tif (typeof input !== \"object\" || input === null) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\tif (input.challenge !== undefined && input.wwwAuthenticate !== undefined) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\tconst serverUrl = requireSecureUrl(input.serverUrl, true).href;\n\tlet challenge =\n\t\tinput.wwwAuthenticate === undefined\n\t\t\t? undefined\n\t\t\t: parseMcpClientOAuthBootstrapChallenge(input.wwwAuthenticate);\n\tif (input.challenge !== undefined) {\n\t\tif (typeof input.challenge !== \"object\" || input.challenge === null) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t\t}\n\t\tchallenge = Object.freeze({\n\t\t\t...(input.challenge.resourceMetadataUrl === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tresourceMetadataUrl: requireSecureUrl(input.challenge.resourceMetadataUrl, true).href,\n\t\t\t\t\t}),\n\t\t\t...(input.challenge.scope === undefined\n\t\t\t\t? {}\n\t\t\t\t: { scope: normalizeScopeString(input.challenge.scope).join(\" \") }),\n\t\t});\n\t}\n\tif (input.issuer !== undefined) requireSecureUrl(input.issuer, false);\n\tconst issuer = input.issuer;\n\treturn Object.freeze({\n\t\tserverUrl,\n\t\t...(challenge === undefined ? {} : { challenge }),\n\t\t...(issuer === undefined ? {} : { issuer }),\n\t\tsignal: input.signal,\n\t});\n}\n\nfunction normalizeProtectedResource(input: {\n\treadonly serverUrl: string;\n\treadonly resourceMetadataUrl: string | undefined;\n\treadonly challengeResourceMetadataUrl: string | undefined;\n\treadonly metadata: OAuthProtectedResourceMetadata;\n}): McpClientOAuthBootstrapResource {\n\tif (input.resourceMetadataUrl === undefined) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);\n\t}\n\tconst resource = requireSecureUrl(input.metadata.resource, true);\n\tif (input.metadata.resource !== resource.href) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);\n\t}\n\tconst metadataEndpoint = requireSecureUrl(input.resourceMetadataUrl, true);\n\tconst sourceBound =\n\t\tinput.challengeResourceMetadataUrl === undefined\n\t\t\t? protectedResourceWellKnownUrl(resource).href === metadataEndpoint.href\n\t\t\t: resourceUrlFromServerUrl(input.serverUrl).href === resource.href;\n\tif (!sourceBound) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);\n\t}\n\tif (\n\t\t(input.metadata.bearer_methods_supported !== undefined &&\n\t\t\t!input.metadata.bearer_methods_supported.includes(\"header\")) ||\n\t\tinput.metadata.tls_client_certificate_bound_access_tokens === true ||\n\t\tinput.metadata.dpop_bound_access_tokens_required === true\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);\n\t}\n\tconst scopesSupported =\n\t\tinput.metadata.scopes_supported === undefined\n\t\t\t? undefined\n\t\t\t: normalizeScopeList(\n\t\t\t\t\tinput.metadata.scopes_supported,\n\t\t\t\t\tMcpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid,\n\t\t\t\t);\n\treturn Object.freeze({\n\t\tserverUrl: input.serverUrl,\n\t\tresource: resource.href,\n\t\tresourceMetadataUrl: metadataEndpoint.href,\n\t\t...(scopesSupported === undefined ? {} : { scopesSupported }),\n\t});\n}\n\nfunction protectedResourceWellKnownUrl(resource: URL): URL {\n\tlet pathname = resource.pathname;\n\tif (pathname.endsWith(\"/\")) pathname = pathname.slice(0, -1);\n\tconst metadataUrl = new URL(`/.well-known/oauth-protected-resource${pathname}`, resource.origin);\n\tmetadataUrl.search = resource.search;\n\treturn metadataUrl;\n}\n\nfunction normalizeAuthorizationServers(values: readonly string[] | undefined): readonly string[] {\n\tif (\n\t\t!Array.isArray(values) ||\n\t\tvalues.length === 0 ||\n\t\tvalues.length > MAX_AUTHORIZATION_SERVER_COUNT\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);\n\t}\n\tconst normalized = [...new Set(values)];\n\tfor (const value of normalized) requireSecureUrl(value, false);\n\tif (normalized.length === 0) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction strictCompatibilityIssues(\n\tmetadata: AuthorizationServerMetadata,\n): readonly McpClientOAuthStrictCompatibilityIssue[] {\n\tconst issues: McpClientOAuthStrictCompatibilityIssue[] = [];\n\tconst responseTypes = normalizeMetadataList(metadata.response_types_supported);\n\tconst codeChallengeMethods = normalizeMetadataList(metadata.code_challenge_methods_supported);\n\tconst tokenAuthenticationMethods = normalizeMetadataList(\n\t\tmetadata.token_endpoint_auth_methods_supported,\n\t);\n\tif (!responseTypes.includes(\"code\")) {\n\t\tissues.push(McpClientOAuthStrictCompatibilityIssue.AuthorizationCodeResponseUnsupported);\n\t}\n\tif (!codeChallengeMethods.includes(\"S256\")) {\n\t\tissues.push(McpClientOAuthStrictCompatibilityIssue.PkceS256Unsupported);\n\t}\n\tif (\n\t\t!tokenAuthenticationMethods.some((method) =>\n\t\t\tSTRICT_TOKEN_ENDPOINT_AUTHENTICATION_METHODS.has(method),\n\t\t)\n\t) {\n\t\tissues.push(McpClientOAuthStrictCompatibilityIssue.TokenEndpointAuthenticationUnsupported);\n\t}\n\tif (\n\t\tmetadata.grant_types_supported !== undefined &&\n\t\t!normalizeMetadataList(metadata.grant_types_supported).includes(\"authorization_code\")\n\t) {\n\t\tissues.push(McpClientOAuthStrictCompatibilityIssue.AuthorizationCodeGrantUnsupported);\n\t}\n\tif (\n\t\tmetadata.response_modes_supported !== undefined &&\n\t\t!normalizeMetadataList(metadata.response_modes_supported).includes(\"query\")\n\t) {\n\t\tissues.push(McpClientOAuthStrictCompatibilityIssue.QueryResponseModeUnsupported);\n\t}\n\treturn Object.freeze(issues);\n}\n\nfunction createStrictAuthority(input: {\n\treadonly serverUrl: string;\n\treadonly resource: McpClientOAuthBootstrapResource;\n\treadonly issuer: string;\n\treadonly metadata: AuthorizationServerMetadata;\n\treadonly challengedScope?: string;\n}): McpClientOAuthAuthority {\n\treturn Object.freeze({\n\t\tserverUrl: input.serverUrl,\n\t\tresource: input.resource.resource,\n\t\tissuer: input.issuer,\n\t\tauthorizationEndpoint: requireSecureUrl(input.metadata.authorization_endpoint, true).href,\n\t\ttokenEndpoint: requireSecureUrl(input.metadata.token_endpoint, true).href,\n\t\tresponseTypesSupported: normalizeMetadataList(input.metadata.response_types_supported),\n\t\tcodeChallengeMethodsSupported: normalizeMetadataList(\n\t\t\tinput.metadata.code_challenge_methods_supported,\n\t\t),\n\t\ttokenEndpointAuthMethodsSupported: normalizeMetadataList(\n\t\t\tinput.metadata.token_endpoint_auth_methods_supported,\n\t\t),\n\t\t...(input.metadata.grant_types_supported === undefined\n\t\t\t? {}\n\t\t\t: { grantTypesSupported: normalizeMetadataList(input.metadata.grant_types_supported) }),\n\t\t// A challenge scope is authoritative and need not be a subset of either advertised list.\n\t\t// Keep the raw PRM list in `resource`, but omit these strict validation hints for this flow.\n\t\t...(input.challengedScope !== undefined || input.resource.scopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { resourceScopesSupported: input.resource.scopesSupported }),\n\t\t...(input.challengedScope !== undefined || input.metadata.scopes_supported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tauthorizationScopesSupported: normalizeScopeList(\n\t\t\t\t\t\tinput.metadata.scopes_supported,\n\t\t\t\t\t\tMcpClientOAuthBootstrapErrorCode.AuthorityInvalid,\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\tauthorizationResponseIssuerParameterSupported:\n\t\t\tinput.metadata.authorization_response_iss_parameter_supported === true,\n\t});\n}\n\nfunction selectScopes(\n\tchallengeScope: string | undefined,\n\tresourceScopes: readonly string[] | undefined,\n): readonly string[] | undefined {\n\tif (challengeScope !== undefined) return normalizeScopeString(challengeScope);\n\treturn resourceScopes;\n}\n\nfunction normalizeScopeString(value: string): readonly string[] {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_SCOPE_STRING_LENGTH ||\n\t\tcontainsControlCharacter(value)\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\treturn normalizeScopeList(value.split(\" \"), McpClientOAuthBootstrapErrorCode.InvalidOptions);\n}\n\nfunction normalizeScopeList(\n\tvalues: readonly string[],\n\terrorCode: McpClientOAuthBootstrapErrorCode,\n): readonly string[] {\n\tif (!Array.isArray(values) || values.length > MAX_SCOPE_COUNT) {\n\t\tthrow bootstrapError(errorCode);\n\t}\n\tconst normalized = [...new Set(values)];\n\tfor (const value of normalized) {\n\t\tif (!isMcpClientOAuthScopeToken(value)) {\n\t\t\tthrow bootstrapError(errorCode);\n\t\t}\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction normalizeMetadataList(values: readonly string[] | undefined): readonly string[] {\n\tif (values === undefined) return Object.freeze([]);\n\tif (!Array.isArray(values) || values.length > MAX_METADATA_LIST_LENGTH) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t}\n\tconst normalized = [...new Set(values)];\n\tfor (const value of normalized) {\n\t\tif (\n\t\t\ttypeof value !== \"string\" ||\n\t\t\tvalue.length === 0 ||\n\t\t\tvalue.length > MAX_METADATA_VALUE_LENGTH ||\n\t\t\tcontainsControlCharacter(value)\n\t\t) {\n\t\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t\t}\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction normalizeOptionalLegacyRegistrationEndpoint(\n\tvalue: string | undefined,\n): string | undefined {\n\tif (value === undefined) return undefined;\n\ttry {\n\t\treturn requireSecureUrl(value, true).href;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction freezeSelectionRequired(\n\tresource: McpClientOAuthBootstrapResource,\n\tscopes: readonly string[] | undefined,\n\tissuers: readonly string[],\n): McpClientOAuthBootstrapSelectionRequired {\n\treturn Object.freeze({\n\t\tkind: \"authorization-server-selection-required\",\n\t\tresource: copyResource(resource),\n\t\t...(scopes === undefined ? {} : { scopes: Object.freeze([...scopes]) }),\n\t\tcandidates: Object.freeze(\n\t\t\tissuers.map(\n\t\t\t\t(issuer) => Object.freeze({ issuer }) satisfies McpClientOAuthBootstrapIssuerCandidate,\n\t\t\t),\n\t\t),\n\t});\n}\n\nfunction freezeStrictUnsupported(\n\tresource: McpClientOAuthBootstrapResource,\n\tscopes: readonly string[] | undefined,\n\tissuer: string,\n\tissues: readonly McpClientOAuthStrictCompatibilityIssue[],\n): McpClientOAuthBootstrapStrictProtocolUnsupported {\n\treturn Object.freeze({\n\t\tkind: \"strict-protocol-unsupported\",\n\t\tresource: copyResource(resource),\n\t\t...(scopes === undefined ? {} : { scopes: Object.freeze([...scopes]) }),\n\t\tissuer,\n\t\tissues: Object.freeze([...issues]),\n\t});\n}\n\nfunction freezeReady(\n\tresource: McpClientOAuthBootstrapResource,\n\tscopes: readonly string[] | undefined,\n\tcandidate: McpClientOAuthBootstrapCandidate,\n): McpClientOAuthBootstrapReady {\n\treturn Object.freeze({\n\t\tkind: \"ready\",\n\t\tresource: copyResource(resource),\n\t\t...(scopes === undefined ? {} : { scopes: Object.freeze([...scopes]) }),\n\t\tcandidate: Object.freeze({\n\t\t\tauthority: copyAuthority(candidate.authority),\n\t\t\tclientIdMetadataDocumentSupported: candidate.clientIdMetadataDocumentSupported,\n\t\t\t...(candidate.legacyDynamicRegistrationEndpoint === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tlegacyDynamicRegistrationEndpoint: candidate.legacyDynamicRegistrationEndpoint,\n\t\t\t\t\t}),\n\t\t}),\n\t});\n}\n\nfunction copyResource(resource: McpClientOAuthBootstrapResource): McpClientOAuthBootstrapResource {\n\treturn Object.freeze({\n\t\tserverUrl: resource.serverUrl,\n\t\tresource: resource.resource,\n\t\tresourceMetadataUrl: resource.resourceMetadataUrl,\n\t\t...(resource.scopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { scopesSupported: Object.freeze([...resource.scopesSupported]) }),\n\t});\n}\n\nfunction copyAuthority(authority: McpClientOAuthAuthority): McpClientOAuthAuthority {\n\treturn Object.freeze({\n\t\tserverUrl: authority.serverUrl,\n\t\tresource: authority.resource,\n\t\tissuer: authority.issuer,\n\t\tauthorizationEndpoint: authority.authorizationEndpoint,\n\t\ttokenEndpoint: authority.tokenEndpoint,\n\t\tresponseTypesSupported: Object.freeze([...authority.responseTypesSupported]),\n\t\tcodeChallengeMethodsSupported: Object.freeze([...authority.codeChallengeMethodsSupported]),\n\t\ttokenEndpointAuthMethodsSupported: Object.freeze([\n\t\t\t...authority.tokenEndpointAuthMethodsSupported,\n\t\t]),\n\t\t...(authority.grantTypesSupported === undefined\n\t\t\t? {}\n\t\t\t: { grantTypesSupported: Object.freeze([...authority.grantTypesSupported]) }),\n\t\t...(authority.resourceScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { resourceScopesSupported: Object.freeze([...authority.resourceScopesSupported]) }),\n\t\t...(authority.authorizationScopesSupported === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tauthorizationScopesSupported: Object.freeze([...authority.authorizationScopesSupported]),\n\t\t\t\t}),\n\t\tauthorizationResponseIssuerParameterSupported:\n\t\t\tauthority.authorizationResponseIssuerParameterSupported,\n\t});\n}\n\nfunction normalizeProtocolVersion(value: string): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_PROTOCOL_VERSION_LENGTH ||\n\t\tcontainsControlCharacter(value)\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n\t}\n\treturn value;\n}\n\nfunction requireSecureUrl(value: string, query: boolean): URL {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > MAX_URL_LENGTH) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t}\n\tif (\n\t\turl.protocol !== \"https:\" ||\n\t\turl.username.length > 0 ||\n\t\turl.password.length > 0 ||\n\t\turl.hash.length > 0 ||\n\t\t(!query && url.search.length > 0)\n\t) {\n\t\tthrow bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);\n\t}\n\treturn url;\n}\n\nfunction isExactResponseUrl(value: string, expected: string): boolean {\n\ttry {\n\t\treturn new URL(value).href === expected;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction combineAbortSignals(\n\toperationSignal: AbortSignal | undefined,\n\trequestSignal: AbortSignal | null | undefined,\n): AbortSignal | undefined {\n\tif (operationSignal === undefined) return requestSignal ?? undefined;\n\tif (requestSignal === undefined || requestSignal === null || requestSignal === operationSignal) {\n\t\treturn operationSignal;\n\t}\n\treturn AbortSignal.any([operationSignal, requestSignal]);\n}\n\nfunction awaitWithSignal<Value>(\n\tpromise: PromiseLike<Value>,\n\tsignal: AbortSignal | undefined,\n): Promise<Value> {\n\tif (signal === undefined) return Promise.resolve(promise);\n\tsignal.throwIfAborted();\n\treturn new Promise<Value>((resolve, reject) => {\n\t\tconst onAbort = (): void => reject(signal.reason);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tPromise.resolve(promise).then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tsignal?.throwIfAborted();\n}\n\nfunction containsControlCharacter(value: string): boolean {\n\tfor (const character of value) {\n\t\tconst point = character.codePointAt(0);\n\t\tif (point !== undefined && (point <= 0x1f || (point >= 0x7f && point <= 0x9f))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction findBearerChallenge(value: string): string | undefined {\n\tlet quoted = false;\n\tlet escaped = false;\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst character = value[index];\n\t\tif (quoted) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') quoted = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquoted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (value.slice(index, index + 6).toLowerCase() !== \"bearer\") continue;\n\t\tlet boundary = index - 1;\n\t\twhile (boundary >= 0 && /\\s/u.test(value[boundary] ?? \"\")) boundary -= 1;\n\t\tconst before = boundary < 0 ? undefined : value[boundary];\n\t\tconst after = value[index + 6];\n\t\tif ((before === undefined || before === \",\") && /\\s/u.test(after ?? \"\")) {\n\t\t\tlet parameterStart = index + 6;\n\t\t\twhile (parameterStart < value.length && /\\s/u.test(value[parameterStart] ?? \"\")) {\n\t\t\t\tparameterStart += 1;\n\t\t\t}\n\t\t\tconst challengeEnd = findAuthenticationChallengeEnd(value, parameterStart);\n\t\t\treturn value.slice(parameterStart, challengeEnd).trimEnd();\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction findAuthenticationChallengeEnd(value: string, start: number): number {\n\tlet quoted = false;\n\tlet escaped = false;\n\tfor (let index = start; index < value.length; index += 1) {\n\t\tconst character = value[index];\n\t\tif (quoted) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') quoted = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquoted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character !== \",\") continue;\n\t\tlet cursor = index + 1;\n\t\twhile (cursor < value.length && /\\s/u.test(value[cursor] ?? \"\")) cursor += 1;\n\t\tconst tokenStart = cursor;\n\t\twhile (cursor < value.length && isAuthenticationTokenCharacter(value[cursor])) cursor += 1;\n\t\tif (cursor === tokenStart) continue;\n\t\twhile (cursor < value.length && /\\s/u.test(value[cursor] ?? \"\")) cursor += 1;\n\t\t// An auth-param is followed by `=`; another token begins the next challenge.\n\t\tif (value[cursor] !== \"=\") return index;\n\t}\n\treturn value.length;\n}\n\nfunction isAuthenticationTokenCharacter(value: string | undefined): boolean {\n\treturn value !== undefined && /^[!#$%&'*+\\-.^_`|~A-Za-z0-9]$/u.test(value);\n}\n\ninterface ParsedBearerParameters {\n\treadonly resourceMetadataUrl?: string;\n\treadonly scope?: string;\n}\n\n/** `null` means the Bearer credential was malformed or repeated a security-relevant field. */\nfunction parseBearerParameters(bearerParameters: string): ParsedBearerParameters | null {\n\tlet offset = 0;\n\tlet resourceMetadataUrl: string | undefined;\n\tlet scope: string | undefined;\n\n\twhile (offset < bearerParameters.length) {\n\t\twhile (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) {\n\t\t\toffset += 1;\n\t\t}\n\t\tconst nameStart = offset;\n\t\twhile (\n\t\t\toffset < bearerParameters.length &&\n\t\t\tisAuthenticationTokenCharacter(bearerParameters[offset])\n\t\t) {\n\t\t\toffset += 1;\n\t\t}\n\t\tif (offset === nameStart) return null;\n\t\tconst name = bearerParameters.slice(nameStart, offset).toLowerCase();\n\n\t\twhile (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) {\n\t\t\toffset += 1;\n\t\t}\n\t\tif (bearerParameters[offset] !== \"=\") return null;\n\t\toffset += 1;\n\t\twhile (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) {\n\t\t\toffset += 1;\n\t\t}\n\n\t\tlet value = \"\";\n\t\tif (bearerParameters[offset] === '\"') {\n\t\t\toffset += 1;\n\t\t\tlet closed = false;\n\t\t\twhile (offset < bearerParameters.length) {\n\t\t\t\tconst character = bearerParameters[offset];\n\t\t\t\toffset += 1;\n\t\t\t\tif (character === \"\\t\") return null;\n\t\t\t\tif (character === \"\\\\\") {\n\t\t\t\t\tconst escaped = bearerParameters[offset];\n\t\t\t\t\tif (escaped === undefined || escaped === \"\\t\") return null;\n\t\t\t\t\tvalue += escaped;\n\t\t\t\t\toffset += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (character === '\"') {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (character === undefined) return null;\n\t\t\t\tvalue += character;\n\t\t\t}\n\t\t\tif (!closed) return null;\n\t\t} else {\n\t\t\tconst valueStart = offset;\n\t\t\twhile (\n\t\t\t\toffset < bearerParameters.length &&\n\t\t\t\t!isOptionalWhitespace(bearerParameters[offset]) &&\n\t\t\t\tbearerParameters[offset] !== \",\"\n\t\t\t) {\n\t\t\t\toffset += 1;\n\t\t\t}\n\t\t\tvalue = bearerParameters.slice(valueStart, offset);\n\t\t}\n\n\t\tif (value.length === 0 && (name === \"resource_metadata\" || name === \"scope\")) return null;\n\t\tif (name === \"resource_metadata\") {\n\t\t\tif (resourceMetadataUrl !== undefined) return null;\n\t\t\tresourceMetadataUrl = value;\n\t\t} else if (name === \"scope\") {\n\t\t\tif (scope !== undefined) return null;\n\t\t\tscope = value;\n\t\t}\n\n\t\twhile (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) {\n\t\t\toffset += 1;\n\t\t}\n\t\tif (offset === bearerParameters.length) break;\n\t\tif (bearerParameters[offset] !== \",\") return null;\n\t\toffset += 1;\n\t\twhile (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) {\n\t\t\toffset += 1;\n\t\t}\n\t\tif (offset === bearerParameters.length) return null;\n\t}\n\n\treturn Object.freeze({\n\t\t...(resourceMetadataUrl === undefined ? {} : { resourceMetadataUrl }),\n\t\t...(scope === undefined ? {} : { scope }),\n\t});\n}\n\nfunction isOptionalWhitespace(value: string | undefined): boolean {\n\treturn value === \" \" || value === \"\\t\";\n}\n\nfunction containsForbiddenHeaderCharacter(value: string): boolean {\n\tfor (const character of value) {\n\t\tconst point = character.codePointAt(0);\n\t\tif (\n\t\t\tpoint !== undefined &&\n\t\t\t((point <= 0x1f && point !== 0x09) || (point >= 0x7f && point <= 0x9f))\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction bootstrapError(code: McpClientOAuthBootstrapErrorCode): McpClientOAuthBootstrapError {\n\treturn new McpClientOAuthBootstrapError(code);\n}\n\nfunction bootstrapErrorMessage(code: McpClientOAuthBootstrapErrorCode): string {\n\tswitch (code) {\n\t\tcase McpClientOAuthBootstrapErrorCode.InvalidOptions:\n\t\t\treturn \"The OAuth bootstrap options are invalid.\";\n\t\tcase McpClientOAuthBootstrapErrorCode.EndpointRejected:\n\t\t\treturn \"An OAuth bootstrap endpoint was rejected.\";\n\t\tcase McpClientOAuthBootstrapErrorCode.DiscoveryFailed:\n\t\t\treturn \"OAuth bootstrap discovery failed.\";\n\t\tcase McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid:\n\t\t\treturn \"The OAuth protected-resource metadata is invalid.\";\n\t\tcase McpClientOAuthBootstrapErrorCode.AuthorityInvalid:\n\t\t\treturn \"The OAuth authorization-server metadata is invalid.\";\n\t\tdefault:\n\t\t\treturn \"OAuth bootstrap failed.\";\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport {\n\tMcpClientOAuthCredentialInvalidationReason,\n\tcreateMcpClientOAuthCredentialSnapshot,\n\tisMcpClientOAuthCredentialRevision,\n\tnextMcpClientOAuthCredentialRevision,\n\ttype McpClientOAuthCredentialInvalidationResult,\n\ttype McpClientOAuthCredentialRevision,\n\ttype McpClientOAuthCredentialSnapshot,\n\ttype McpClientOAuthCredentialStore,\n\ttype McpClientOAuthCredentialStoreContext,\n\ttype McpClientOAuthRefreshClaimId,\n\ttype McpClientOAuthRefreshClaimReleaseResult,\n\ttype McpClientOAuthRefreshClaimResult,\n\ttype McpClientOAuthRefreshCommitResult,\n\ttype McpClientOAuthTerminalRefreshReason,\n} from \"./credential-store.ts\";\nimport { isInternalMcpClientOAuthProtocolError } from \"./protocol-error-brand.ts\";\nimport { McpClientOAuthProtocolErrorCode } from \"./protocol.ts\";\n\nconst DEFAULT_MAX_IN_FLIGHT_KEYS = 100;\nconst CALLER_ABORTED = Symbol(\"caller-aborted\");\nconst GENERATION_RETIRED = Symbol(\"generation-retired\");\n\n/** Stable, secret-free refresh-coordinator failures. */\nexport const McpClientOAuthRefreshErrorCode = {\n\tInvalidOptions: \"MCP_CLIENT_OAUTH_REFRESH_INVALID_OPTIONS\",\n\tClosed: \"MCP_CLIENT_OAUTH_REFRESH_COORDINATOR_CLOSED\",\n\tCapacityExceeded: \"MCP_CLIENT_OAUTH_REFRESH_CAPACITY_EXCEEDED\",\n\tRevisionInFlight: \"MCP_CLIENT_OAUTH_REFRESH_REVISION_IN_FLIGHT\",\n\tCredentialMissing: \"MCP_CLIENT_OAUTH_CREDENTIAL_MISSING\",\n\tCredentialInvalidated: \"MCP_CLIENT_OAUTH_CREDENTIAL_INVALIDATED\",\n\tRevisionMismatch: \"MCP_CLIENT_OAUTH_CREDENTIAL_REVISION_MISMATCH\",\n\tRefreshFailed: \"MCP_CLIENT_OAUTH_REFRESH_FAILED\",\n\tStoreFailed: \"MCP_CLIENT_OAUTH_CREDENTIAL_STORE_FAILED\",\n\tInvalidStoreResult: \"MCP_CLIENT_OAUTH_CREDENTIAL_STORE_RESULT_INVALID\",\n\tInvalidationHookFailed: \"MCP_CLIENT_OAUTH_INVALIDATION_HOOK_FAILED\",\n\tCallerAborted: \"MCP_CLIENT_OAUTH_REFRESH_CALLER_ABORTED\",\n\tInternalFailure: \"MCP_CLIENT_OAUTH_REFRESH_INTERNAL_FAILURE\",\n} as const;\n\nexport type McpClientOAuthRefreshErrorCode =\n\t(typeof McpClientOAuthRefreshErrorCode)[keyof typeof McpClientOAuthRefreshErrorCode];\n\n/**\n * Public coordinator error. Errors emitted across coordinator boundaries are rematerialized by\n * code so their fixed messages never retain identity, credential, or caught error data.\n */\nexport class McpClientOAuthRefreshError extends Error {\n\treadonly code: McpClientOAuthRefreshErrorCode;\n\n\tconstructor(code: McpClientOAuthRefreshErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"McpClientOAuthRefreshError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface McpClientOAuthRefreshContext {\n\t/** Shared operation cancellation; never tied to one caller waiting for the result. */\n\treadonly signal: AbortSignal;\n}\n\nexport interface McpClientOAuthRefreshOperationOptions {\n\t/** Cancels only this caller's wait and never the shared refresh or persistence mutation. */\n\treadonly signal?: AbortSignal;\n}\n\nexport interface McpClientOAuthInvalidateOptions extends McpClientOAuthRefreshOperationOptions {\n\treadonly reason?: McpClientOAuthCredentialInvalidationReason;\n}\n\n/** Explicitly states whether a caught refresh failure can safely reuse the exact generation. */\nexport type McpClientOAuthRefreshFailureDisposition =\n\t| { readonly kind: \"retry-safe\" }\n\t| {\n\t\t\treadonly kind: \"terminal\";\n\t\t\treadonly reason: McpClientOAuthTerminalRefreshReason;\n\t };\n\nexport interface McpClientOAuthInvalidatedContext {\n\treadonly revision: McpClientOAuthCredentialRevision;\n\treadonly reason: McpClientOAuthCredentialInvalidationReason;\n}\n\nexport interface McpClientOAuthRefreshCoordinatorOptions<Identity, Credential extends object> {\n\treadonly store: McpClientOAuthCredentialStore<Identity, Credential>;\n\t/**\n\t * Exchanges the complete current credential set for one complete replacement set.\n\t * The identity must be a stable, non-secret binding chosen by the host application.\n\t * It may perform at most one credentialed token exchange per invocation; neither it nor its\n\t * fetch middleware may retry a token POST. An ambiguous outcome must be thrown for terminal\n\t * settlement.\n\t */\n\treadonly refresh: (\n\t\tidentity: Identity,\n\t\tcurrent: McpClientOAuthCredentialSnapshot<Credential>,\n\t\tcontext: McpClientOAuthRefreshContext,\n\t) => Promise<Readonly<Credential>> | Readonly<Credential>;\n\t/**\n\t * Classifies a caught refresh failure. Returning `retry-safe` is an assertion that no\n\t * credentialed refresh request was dispatched; throws and invalid results fail terminally.\n\t */\n\treadonly classifyRefreshFailure?: (error: unknown) => McpClientOAuthRefreshFailureDisposition;\n\t/**\n\t * Called only when the exact generation is unusable: after durable or observed invalidation,\n\t * external disappearance, or local fail-closed retirement when durable state is uncertain.\n\t * Successful local rotation and observation of a newer generation follow that binding without\n\t * eviction. Delivery is at most once for one in-process coalesced settlement; this is not a\n\t * durable or cross-process exactly-once guarantee. `ObservedExternal` proves absence; a terminal\n\t * reason may instead represent durable invalidation or local fail-closed retirement.\n\t * The hook is awaited and must only initiate lease retirement; it must never await active-lease\n\t * drain, because refresh may be settling a 401 from that same lease.\n\t */\n\treadonly onInvalidated?: (\n\t\tidentity: Identity,\n\t\tcontext: McpClientOAuthInvalidatedContext,\n\t) => Promise<void> | void;\n\t/** Hard bound over distinct opaque identities with accepted work or local fail-closed fences. */\n\treadonly maxInFlightKeys?: number;\n}\n\n/** Aggregate diagnostics deliberately omit identities, credentials, revisions, and failures. */\nexport interface McpClientOAuthRefreshCoordinatorSnapshot {\n\treadonly closed: boolean;\n\treadonly maxInFlightKeys: number;\n\treadonly inFlightKeyCount: number;\n\treadonly refreshCount: number;\n\treadonly invalidationCount: number;\n\treadonly waiterCount: number;\n}\n\nexport type McpClientOAuthInvalidateResult =\n\t| { readonly status: \"invalidated\" }\n\t| { readonly status: \"superseded\" }\n\t| { readonly status: \"missing\" }\n\t| { readonly status: \"conflict\" };\n\ntype RefreshPhase = \"loading\" | \"refreshing\" | \"committing\" | \"settling\" | \"done\";\n\ninterface RefreshEntry<Credential extends object> {\n\treadonly token: symbol;\n\treadonly revision: McpClientOAuthCredentialRevision;\n\treadonly claimId: McpClientOAuthRefreshClaimId;\n\treadonly workController: AbortController;\n\treadonly settlementController: AbortController;\n\treadonly retirementController: AbortController;\n\tphase: RefreshPhase;\n\tsettlementOwnsInvalidation: boolean;\n\twaiterCount: number;\n\tretirementError: McpClientOAuthRefreshError | undefined;\n\ttask: Promise<RefreshOutcome<Credential>> | undefined;\n}\n\ninterface InvalidationEntry {\n\treadonly token: symbol;\n\treadonly revision: McpClientOAuthCredentialRevision;\n\treadonly reason: McpClientOAuthCredentialInvalidationReason;\n\treadonly controller: AbortController;\n\twaiterCount: number;\n\ttask: Promise<InvalidationOutcome> | undefined;\n}\n\ntype RefreshOutcome<Credential extends object> =\n\t| { readonly status: \"success\"; readonly snapshot: McpClientOAuthCredentialSnapshot<Credential> }\n\t| { readonly status: \"error\"; readonly error: McpClientOAuthRefreshError };\n\ntype InvalidationOutcome =\n\t| { readonly status: \"success\"; readonly result: McpClientOAuthInvalidateResult }\n\t| { readonly status: \"error\"; readonly error: McpClientOAuthRefreshError };\n\ninterface AbortWait<Result extends symbol> {\n\treadonly promise: Promise<Result>;\n\tdetach(): void;\n}\n\n/**\n * Bounded, framework-neutral refresh ownership keyed by an opaque, non-secret identity.\n *\n * Calls for the same identity and exact revision share one refresh. A different revision is never\n * joined to existing work. A durable pre-dispatch claim prevents multiple coordinators from\n * sending the same refresh token. Only the holder's exact claim can commit the complete next\n * generation. Commit loss reloads the authoritative winner and never retries the old token.\n * Closing drains accepted mutations; it does not abandon a claimed generation.\n */\nexport class McpClientOAuthRefreshCoordinator<\n\tIdentity,\n\tCredential extends object,\n> implements AsyncDisposable {\n\treadonly #store: McpClientOAuthCredentialStore<Identity, Credential>;\n\treadonly #refreshCredential: McpClientOAuthRefreshCoordinatorOptions<\n\t\tIdentity,\n\t\tCredential\n\t>[\"refresh\"];\n\treadonly #classifyRefreshFailure: NonNullable<\n\t\tMcpClientOAuthRefreshCoordinatorOptions<Identity, Credential>[\"classifyRefreshFailure\"]\n\t>;\n\treadonly #onInvalidated:\n\t\tMcpClientOAuthRefreshCoordinatorOptions<Identity, Credential>[\"onInvalidated\"] | undefined;\n\treadonly #maxInFlightKeys: number;\n\treadonly #refreshes = new Map<Identity, RefreshEntry<Credential>>();\n\treadonly #invalidations = new Map<Identity, InvalidationEntry>();\n\treadonly #retiredRevisions = new Map<Identity, McpClientOAuthCredentialRevision>();\n\t#closed = false;\n\t#closeTask: Promise<void> | undefined;\n\n\tconstructor(options: McpClientOAuthRefreshCoordinatorOptions<Identity, Credential>) {\n\t\tif (!isObjectLike(options)) throw invalidOptionsError();\n\n\t\tlet store: McpClientOAuthCredentialStore<Identity, Credential>;\n\t\tlet refreshCredential: McpClientOAuthRefreshCoordinatorOptions<Identity, Credential>[\"refresh\"];\n\t\tlet classifyRefreshFailure:\n\t\t\t| McpClientOAuthRefreshCoordinatorOptions<Identity, Credential>[\"classifyRefreshFailure\"]\n\t\t\t| undefined;\n\t\tlet onInvalidated:\n\t\t\tMcpClientOAuthRefreshCoordinatorOptions<Identity, Credential>[\"onInvalidated\"] | undefined;\n\t\tlet maxInFlightKeys: number;\n\t\ttry {\n\t\t\tstore = options.store;\n\t\t\trefreshCredential = options.refresh;\n\t\t\tclassifyRefreshFailure = options.classifyRefreshFailure;\n\t\t\tonInvalidated = options.onInvalidated;\n\t\t\tmaxInFlightKeys = options.maxInFlightKeys ?? DEFAULT_MAX_IN_FLIGHT_KEYS;\n\t\t} catch {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\n\t\tif (!isCredentialStore(store) || typeof refreshCredential !== \"function\") {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tif (classifyRefreshFailure !== undefined && typeof classifyRefreshFailure !== \"function\") {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tif (onInvalidated !== undefined && typeof onInvalidated !== \"function\") {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\t\tif (!Number.isSafeInteger(maxInFlightKeys) || maxInFlightKeys <= 0) {\n\t\t\tthrow invalidOptionsError();\n\t\t}\n\n\t\tthis.#store = store;\n\t\tthis.#refreshCredential = refreshCredential;\n\t\tthis.#classifyRefreshFailure = classifyRefreshFailure ?? classifyMcpClientOAuthRefreshFailure;\n\t\tthis.#onInvalidated = onInvalidated;\n\t\tthis.#maxInFlightKeys = maxInFlightKeys;\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed;\n\t}\n\n\tsnapshot(): McpClientOAuthRefreshCoordinatorSnapshot {\n\t\tlet waiterCount = 0;\n\t\tfor (const entry of this.#refreshes.values()) waiterCount += entry.waiterCount;\n\t\tfor (const entry of this.#invalidations.values()) waiterCount += entry.waiterCount;\n\n\t\treturn Object.freeze({\n\t\t\tclosed: this.#closed,\n\t\t\tmaxInFlightKeys: this.#maxInFlightKeys,\n\t\t\tinFlightKeyCount: this.#inFlightKeyCount(),\n\t\t\trefreshCount: this.#refreshes.size,\n\t\t\tinvalidationCount: this.#invalidations.size,\n\t\t\twaiterCount,\n\t\t});\n\t}\n\n\tasync refresh(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\toptions: McpClientOAuthRefreshOperationOptions = {},\n\t): Promise<McpClientOAuthCredentialSnapshot<Credential>> {\n\t\tthis.#assertOpen();\n\t\tassertRevision(expectedRevision);\n\t\tthrowIfCallerAborted(options.signal);\n\n\t\tconst invalidation = this.#invalidations.get(identity);\n\t\tif (invalidation !== undefined) throw credentialInvalidatedError();\n\t\tthis.#assertGenerationUsable(identity, expectedRevision);\n\n\t\tconst existing = this.#refreshes.get(identity);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.revision !== expectedRevision) throw revisionInFlightError();\n\t\t\treturn this.#waitForRefresh(existing, options.signal);\n\t\t}\n\n\t\tthis.#assertCapacity(identity);\n\t\tconst entry = this.#createRefreshEntry(identity, expectedRevision);\n\t\treturn this.#waitForRefresh(entry, options.signal);\n\t}\n\n\tasync invalidate(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\toptions: McpClientOAuthInvalidateOptions = {},\n\t): Promise<McpClientOAuthInvalidateResult> {\n\t\tthis.#assertOpen();\n\t\tassertRevision(expectedRevision);\n\t\tthrowIfCallerAborted(options.signal);\n\t\tconst reason = options.reason ?? McpClientOAuthCredentialInvalidationReason.Explicit;\n\t\tassertInvalidationReason(reason);\n\n\t\tconst existing = this.#invalidations.get(identity);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.revision !== expectedRevision || existing.reason !== reason) {\n\t\t\t\tthrow revisionInFlightError();\n\t\t\t}\n\t\t\treturn this.#waitForInvalidation(existing, options.signal);\n\t\t}\n\n\t\tthis.#assertCapacity(identity);\n\t\tconst refreshEntry = this.#refreshes.get(identity);\n\t\tconst matchingRefresh = refreshEntry?.revision === expectedRevision ? refreshEntry : undefined;\n\t\tif (\n\t\t\tmatchingRefresh?.phase === \"settling\" &&\n\t\t\tmatchingRefresh.settlementOwnsInvalidation &&\n\t\t\tmatchingRefresh.retirementError === undefined\n\t\t) {\n\t\t\treturn this.#waitForSettlingInvalidation(matchingRefresh, options.signal);\n\t\t}\n\t\tconst entry = this.#createInvalidationEntry(\n\t\t\tidentity,\n\t\t\texpectedRevision,\n\t\t\treason,\n\t\t\tmatchingRefresh,\n\t\t);\n\t\tif (matchingRefresh !== undefined) this.#retireRefresh(matchingRefresh);\n\t\treturn this.#waitForInvalidation(entry, options.signal);\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#closed = true;\n\t\tconst tasks = [\n\t\t\t...[...this.#refreshes.values()].map(requireRefreshTask),\n\t\t\t...[...this.#invalidations.values()].map(requireInvalidationTask),\n\t\t];\n\t\tthis.#closeTask = Promise.all(tasks).then(() => {\n\t\t\tthis.#retiredRevisions.clear();\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\t#createRefreshEntry(\n\t\tidentity: Identity,\n\t\trevision: McpClientOAuthCredentialRevision,\n\t): RefreshEntry<Credential> {\n\t\tconst entry: RefreshEntry<Credential> = {\n\t\t\ttoken: Symbol(\"mcp-client-oauth-refresh\"),\n\t\t\trevision,\n\t\t\tclaimId: createRefreshClaimId(),\n\t\t\tworkController: new AbortController(),\n\t\t\tsettlementController: new AbortController(),\n\t\t\tretirementController: new AbortController(),\n\t\t\tphase: \"loading\",\n\t\t\tsettlementOwnsInvalidation: false,\n\t\t\twaiterCount: 0,\n\t\t\tretirementError: undefined,\n\t\t\ttask: undefined,\n\t\t};\n\t\tthis.#refreshes.set(identity, entry);\n\t\tentry.task = Promise.resolve()\n\t\t\t.then(async () => this.#executeRefresh(identity, entry))\n\t\t\t.catch(() => refreshErrorOutcome(internalFailureError()));\n\t\tvoid entry.task.then(() => {\n\t\t\tentry.phase = \"done\";\n\t\t\tif (this.#refreshes.get(identity)?.token === entry.token) {\n\t\t\t\tthis.#refreshes.delete(identity);\n\t\t\t}\n\t\t});\n\t\treturn entry;\n\t}\n\n\t#createInvalidationEntry(\n\t\tidentity: Identity,\n\t\trevision: McpClientOAuthCredentialRevision,\n\t\treason: McpClientOAuthCredentialInvalidationReason,\n\t\tmatchingRefresh: RefreshEntry<Credential> | undefined,\n\t): InvalidationEntry {\n\t\tconst entry: InvalidationEntry = {\n\t\t\ttoken: Symbol(\"mcp-client-oauth-invalidation\"),\n\t\t\trevision,\n\t\t\treason,\n\t\t\tcontroller: new AbortController(),\n\t\t\twaiterCount: 0,\n\t\t\ttask: undefined,\n\t\t};\n\t\tthis.#invalidations.set(identity, entry);\n\t\tconst refreshTask =\n\t\t\tmatchingRefresh === undefined ? undefined : requireRefreshTask(matchingRefresh);\n\t\tentry.task = Promise.resolve()\n\t\t\t.then(async () => this.#executeInvalidation(identity, entry, refreshTask))\n\t\t\t.catch(() => invalidationErrorOutcome(internalFailureError()));\n\t\tvoid entry.task.then(() => {\n\t\t\tif (this.#invalidations.get(identity)?.token === entry.token) {\n\t\t\t\tthis.#invalidations.delete(identity);\n\t\t\t}\n\t\t});\n\t\treturn entry;\n\t}\n\n\tasync #executeRefresh(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tlet claim: McpClientOAuthRefreshClaimResult<Credential>;\n\t\ttry {\n\t\t\tclaim = await this.#claimRefresh(identity, entry, entry.workController.signal);\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\tentry.phase = \"settling\";\n\t\t\treturn this.#settleClaimUncertainty(identity, entry, sanitizeCoordinatorError(error));\n\t\t}\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\t\tif (claim.status !== \"claimed\") {\n\t\t\tentry.phase = \"settling\";\n\t\t\treturn this.#settleUnclaimed(identity, entry, claim.status);\n\t\t}\n\t\tconst current = claim.snapshot;\n\t\tthis.#clearRetiredRevision(identity, current.revision);\n\n\t\tentry.phase = \"refreshing\";\n\t\tlet replacement: Readonly<Credential>;\n\t\ttry {\n\t\t\treplacement = await this.#refreshCredential(identity, current, {\n\t\t\t\tsignal: entry.workController.signal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\treturn this.#handleRefreshFailure(identity, entry, error);\n\t\t}\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\t\tif (!isObjectLike(replacement)) {\n\t\t\treturn this.#retireGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry,\n\t\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\t);\n\t\t}\n\n\t\tentry.phase = \"committing\";\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.#commitRefresh(\n\t\t\t\tidentity,\n\t\t\t\tentry,\n\t\t\t\treplacement,\n\t\t\t\tentry.settlementController.signal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\tentry.phase = \"settling\";\n\t\t\treturn this.#settleCommitUncertainty(\n\t\t\t\tidentity,\n\t\t\t\tentry,\n\t\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\t\tsanitizeCoordinatorError(error),\n\t\t\t);\n\t\t}\n\t\tif (result.status === \"applied\") return refreshSuccessOutcome(result.snapshot);\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\n\t\tentry.phase = \"settling\";\n\t\treturn this.#settleCommitUncertainty(\n\t\t\tidentity,\n\t\t\tentry,\n\t\t\tMcpClientOAuthCredentialInvalidationReason.ObservedExternal,\n\t\t\trevisionMismatchError(),\n\t\t);\n\t}\n\n\tasync #handleRefreshFailure(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\terror: unknown,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tlet disposition: McpClientOAuthRefreshFailureDisposition;\n\t\ttry {\n\t\t\tdisposition = this.#classifyRefreshFailure(error);\n\t\t} catch {\n\t\t\tdisposition = terminalRefreshFailureDisposition();\n\t\t}\n\t\tconst normalized = normalizeRefreshFailureDisposition(disposition);\n\t\tif (normalized.kind === \"retry-safe\") {\n\t\t\treturn this.#releaseRetrySafeClaim(identity, entry);\n\t\t}\n\t\treturn this.#retireGeneration(identity, entry, normalized.reason);\n\t}\n\n\tasync #releaseRetrySafeClaim(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tentry.phase = \"settling\";\n\t\tlet result: McpClientOAuthRefreshClaimReleaseResult;\n\t\ttry {\n\t\t\tresult = await this.#releaseRefreshClaim(identity, entry, entry.settlementController.signal);\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t}\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\t\tif (result.status === \"released\") return refreshErrorOutcome(refreshFailedError());\n\n\t\tlet current: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\tcurrent = await this.#load(identity, entry.settlementController.signal);\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t}\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\t\tif (current === undefined) {\n\t\t\tentry.settlementOwnsInvalidation = true;\n\t\t\ttry {\n\t\t\t\tawait this.#notifyInvalidated(\n\t\t\t\t\tidentity,\n\t\t\t\t\tentry.revision,\n\t\t\t\t\tMcpClientOAuthCredentialInvalidationReason.ObservedExternal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(credentialInvalidatedError());\n\t\t}\n\t\tif (current.revision > entry.revision) return refreshSuccessOutcome(current);\n\t\tif (current.revision === entry.revision) return refreshErrorOutcome(refreshFailedError());\n\t\treturn refreshErrorOutcome(invalidStoreResultError());\n\t}\n\n\tasync #retireGeneration(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\treason: McpClientOAuthTerminalRefreshReason,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tentry.phase = \"settling\";\n\t\tentry.settlementOwnsInvalidation = true;\n\t\tlet result: McpClientOAuthCredentialInvalidationResult;\n\t\ttry {\n\t\t\tresult = await this.#invalidateStored(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\treason,\n\t\t\t\tentry.settlementController.signal,\n\t\t\t);\n\t\t} catch (storeError) {\n\t\t\treturn this.#failClosedGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\treason,\n\t\t\t\tsanitizeCoordinatorError(storeError),\n\t\t\t);\n\t\t}\n\t\tif (result.status === \"applied\") {\n\t\t\tthis.#clearRetiredRevision(identity, entry.revision);\n\t\t\ttry {\n\t\t\t\tawait this.#notifyInvalidated(identity, entry.revision, reason);\n\t\t\t} catch (hookError) {\n\t\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(hookError));\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(credentialInvalidatedError());\n\t\t}\n\n\t\treturn this.#reloadAfterInvalidationConflict(identity, entry, reason);\n\t}\n\n\tasync #settleClaimUncertainty(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tclaimFailure: McpClientOAuthRefreshError,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\treturn this.#settleCommitUncertainty(\n\t\t\tidentity,\n\t\t\tentry,\n\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\tclaimFailure,\n\t\t);\n\t}\n\n\tasync #settleUnclaimed(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tstatus: \"busy\" | \"conflict\",\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tlet current: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\tcurrent = await this.#load(identity, entry.settlementController.signal);\n\t\t} catch (error) {\n\t\t\tif (entry.retirementError !== undefined) {\n\t\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t}\n\t\tif (entry.retirementError !== undefined) {\n\t\t\treturn refreshErrorOutcome(entry.retirementError);\n\t\t}\n\t\tif (current === undefined) {\n\t\t\tentry.settlementOwnsInvalidation = true;\n\t\t\ttry {\n\t\t\t\tawait this.#notifyInvalidated(\n\t\t\t\t\tidentity,\n\t\t\t\t\tentry.revision,\n\t\t\t\t\tMcpClientOAuthCredentialInvalidationReason.ObservedExternal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(credentialMissingError());\n\t\t}\n\t\tif (current.revision > entry.revision) {\n\t\t\tthis.#clearRetiredRevision(identity, current.revision);\n\t\t\treturn refreshSuccessOutcome(current);\n\t\t}\n\t\tif (current.revision === entry.revision) {\n\t\t\tthis.#clearRetiredRevision(identity, current.revision);\n\t\t\treturn refreshErrorOutcome(\n\t\t\t\tstatus === \"busy\" ? revisionInFlightError() : revisionMismatchError(),\n\t\t\t);\n\t\t}\n\t\treturn refreshErrorOutcome(invalidStoreResultError());\n\t}\n\n\tasync #settleCommitUncertainty(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tmissingReason:\n\t\t\t| typeof McpClientOAuthCredentialInvalidationReason.ObservedExternal\n\t\t\t| McpClientOAuthTerminalRefreshReason,\n\t\tloadFailure: McpClientOAuthRefreshError,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tentry.settlementOwnsInvalidation = true;\n\t\tlet winner: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\twinner = await this.#load(identity, entry.settlementController.signal);\n\t\t} catch (error) {\n\t\t\treturn this.#failClosedGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\t\tsanitizeCoordinatorError(error),\n\t\t\t);\n\t\t}\n\t\tif (winner === undefined) {\n\t\t\tthis.#clearRetiredRevision(identity, entry.revision);\n\t\t\ttry {\n\t\t\t\tawait this.#notifyInvalidated(identity, entry.revision, missingReason);\n\t\t\t} catch (error) {\n\t\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(credentialInvalidatedError());\n\t\t}\n\t\tif (winner.revision > entry.revision) {\n\t\t\tthis.#clearRetiredRevision(identity, winner.revision);\n\t\t\treturn refreshSuccessOutcome(winner);\n\t\t}\n\t\tif (winner.revision === entry.revision) {\n\t\t\treturn this.#retireGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry,\n\t\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\t);\n\t\t}\n\t\treturn this.#failClosedGeneration(\n\t\t\tidentity,\n\t\t\tentry.revision,\n\t\t\tMcpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n\t\t\tloadFailure.code === McpClientOAuthRefreshErrorCode.InvalidStoreResult\n\t\t\t\t? loadFailure\n\t\t\t\t: invalidStoreResultError(),\n\t\t);\n\t}\n\n\tasync #reloadAfterInvalidationConflict(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\treason: McpClientOAuthTerminalRefreshReason,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tlet winner: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\twinner = await this.#load(identity, entry.settlementController.signal);\n\t\t} catch (error) {\n\t\t\treturn this.#failClosedGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\treason,\n\t\t\t\tsanitizeCoordinatorError(error),\n\t\t\t);\n\t\t}\n\t\tif (winner === undefined) {\n\t\t\tthis.#clearRetiredRevision(identity, entry.revision);\n\t\t\ttry {\n\t\t\t\tawait this.#notifyInvalidated(identity, entry.revision, reason);\n\t\t\t} catch (error) {\n\t\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(error));\n\t\t\t}\n\t\t\treturn refreshErrorOutcome(credentialInvalidatedError());\n\t\t}\n\t\tif (winner.revision > entry.revision) {\n\t\t\tthis.#clearRetiredRevision(identity, winner.revision);\n\t\t\treturn refreshSuccessOutcome(winner);\n\t\t}\n\t\tif (winner.revision === entry.revision) {\n\t\t\treturn this.#failClosedGeneration(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\treason,\n\t\t\t\tcredentialInvalidatedError(),\n\t\t\t);\n\t\t}\n\t\treturn this.#failClosedGeneration(identity, entry.revision, reason, invalidStoreResultError());\n\t}\n\n\tasync #failClosedGeneration(\n\t\tidentity: Identity,\n\t\trevision: McpClientOAuthCredentialRevision,\n\t\treason: McpClientOAuthTerminalRefreshReason,\n\t\terror: McpClientOAuthRefreshError,\n\t): Promise<RefreshOutcome<Credential>> {\n\t\tthis.#retireRevision(identity, revision);\n\t\ttry {\n\t\t\tawait this.#notifyInvalidated(identity, revision, reason);\n\t\t} catch (hookError) {\n\t\t\treturn refreshErrorOutcome(sanitizeCoordinatorError(hookError));\n\t\t}\n\t\treturn refreshErrorOutcome(error);\n\t}\n\n\tasync #executeInvalidation(\n\t\tidentity: Identity,\n\t\tentry: InvalidationEntry,\n\t\trefreshTask: Promise<RefreshOutcome<Credential>> | undefined,\n\t): Promise<InvalidationOutcome> {\n\t\tlet outcome: InvalidationOutcome;\n\t\ttry {\n\t\t\tconst result = await this.#invalidateStored(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\tentry.reason,\n\t\t\t\tentry.controller.signal,\n\t\t\t);\n\t\t\tif (result.status === \"applied\") {\n\t\t\t\tthis.#clearRetiredRevision(identity, entry.revision);\n\t\t\t\tawait this.#notifyInvalidated(identity, entry.revision, entry.reason);\n\t\t\t\toutcome = invalidationSuccessOutcome(\"invalidated\");\n\t\t\t} else {\n\t\t\t\tconst current = await this.#load(identity, entry.controller.signal);\n\t\t\t\tif (current === undefined) {\n\t\t\t\t\tthis.#clearRetiredRevision(identity, entry.revision);\n\t\t\t\t\tawait this.#notifyInvalidated(identity, entry.revision, entry.reason);\n\t\t\t\t\toutcome = invalidationSuccessOutcome(\"missing\");\n\t\t\t\t} else if (current.revision > entry.revision) {\n\t\t\t\t\tthis.#clearRetiredRevision(identity, current.revision);\n\t\t\t\t\toutcome = invalidationSuccessOutcome(\"superseded\");\n\t\t\t\t} else if (current.revision === entry.revision) {\n\t\t\t\t\toutcome = invalidationSuccessOutcome(\"conflict\");\n\t\t\t\t} else outcome = invalidationErrorOutcome(invalidStoreResultError());\n\t\t\t}\n\t\t} catch (error) {\n\t\t\toutcome = invalidationErrorOutcome(sanitizeCoordinatorError(error));\n\t\t}\n\n\t\tif (refreshTask !== undefined) await refreshTask;\n\t\treturn outcome;\n\t}\n\n\tasync #load(\n\t\tidentity: Identity,\n\t\tsignal: AbortSignal,\n\t): Promise<McpClientOAuthCredentialSnapshot<Credential> | undefined> {\n\t\tlet value: McpClientOAuthCredentialSnapshot<Credential> | undefined;\n\t\ttry {\n\t\t\tvalue = await this.#store.load(identity, storeContext(signal));\n\t\t} catch {\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\tif (value === undefined) return undefined;\n\t\treturn normalizeCredentialSnapshot<Credential>(value);\n\t}\n\n\tasync #claimRefresh(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tsignal: AbortSignal,\n\t): Promise<McpClientOAuthRefreshClaimResult<Credential>> {\n\t\tlet value: McpClientOAuthRefreshClaimResult<Credential>;\n\t\ttry {\n\t\t\tvalue = await this.#store.claimRefresh(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\tentry.claimId,\n\t\t\t\tstoreContext(signal),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\treturn normalizeRefreshClaimResult(value, entry.revision);\n\t}\n\n\tasync #commitRefresh(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tcredential: Readonly<Credential>,\n\t\tsignal: AbortSignal,\n\t): Promise<\n\t\t| {\n\t\t\t\treadonly status: \"applied\";\n\t\t\t\treadonly snapshot: McpClientOAuthCredentialSnapshot<Credential>;\n\t\t }\n\t\t| { readonly status: \"conflict\" }\n\t> {\n\t\tlet value: McpClientOAuthRefreshCommitResult<Credential>;\n\t\ttry {\n\t\t\tvalue = await this.#store.commitRefresh(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\tentry.claimId,\n\t\t\t\tcredential,\n\t\t\t\tstoreContext(signal),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\treturn normalizeRefreshCommitResult<Credential>(value, entry.revision);\n\t}\n\n\tasync #releaseRefreshClaim(\n\t\tidentity: Identity,\n\t\tentry: RefreshEntry<Credential>,\n\t\tsignal: AbortSignal,\n\t): Promise<McpClientOAuthRefreshClaimReleaseResult> {\n\t\tlet value: McpClientOAuthRefreshClaimReleaseResult;\n\t\ttry {\n\t\t\tvalue = await this.#store.releaseRefreshClaim(\n\t\t\t\tidentity,\n\t\t\t\tentry.revision,\n\t\t\t\tentry.claimId,\n\t\t\t\tstoreContext(signal),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\treturn normalizeRefreshClaimReleaseResult(value);\n\t}\n\n\tasync #invalidateStored(\n\t\tidentity: Identity,\n\t\texpectedRevision: McpClientOAuthCredentialRevision,\n\t\treason: McpClientOAuthCredentialInvalidationReason,\n\t\tsignal: AbortSignal,\n\t): Promise<McpClientOAuthCredentialInvalidationResult> {\n\t\tlet value: McpClientOAuthCredentialInvalidationResult;\n\t\ttry {\n\t\t\tvalue = await this.#store.invalidate(\n\t\t\t\tidentity,\n\t\t\t\texpectedRevision,\n\t\t\t\treason,\n\t\t\t\tstoreContext(signal),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow storeFailedError();\n\t\t}\n\t\treturn normalizeInvalidationResult(value);\n\t}\n\n\tasync #notifyInvalidated(\n\t\tidentity: Identity,\n\t\trevision: McpClientOAuthCredentialRevision,\n\t\treason: McpClientOAuthCredentialInvalidationReason,\n\t): Promise<void> {\n\t\tif (this.#onInvalidated === undefined) return;\n\t\ttry {\n\t\t\tawait this.#onInvalidated(identity, Object.freeze({ revision, reason }));\n\t\t} catch {\n\t\t\tthrow invalidationHookFailedError();\n\t\t}\n\t}\n\n\t#retireRefresh(entry: RefreshEntry<Credential>): void {\n\t\tif (entry.retirementError !== undefined) return;\n\t\tentry.retirementError = credentialInvalidatedError();\n\t\tentry.retirementController.abort(generationInvalidatedAbortReason());\n\t\tif (entry.phase === \"loading\" || entry.phase === \"refreshing\") {\n\t\t\tentry.workController.abort(generationInvalidatedAbortReason());\n\t\t}\n\t}\n\n\tasync #waitForRefresh(\n\t\tentry: RefreshEntry<Credential>,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<McpClientOAuthCredentialSnapshot<Credential>> {\n\t\tentry.waiterCount += 1;\n\t\tconst caller = signal === undefined ? undefined : waitForAbort(signal, CALLER_ABORTED);\n\t\tconst retired = waitForAbort(entry.retirementController.signal, GENERATION_RETIRED);\n\t\ttry {\n\t\t\tconst result = await Promise.race([\n\t\t\t\trequireRefreshTask(entry),\n\t\t\t\tretired.promise,\n\t\t\t\t...(caller === undefined ? [] : [caller.promise]),\n\t\t\t]);\n\t\t\tif (result === CALLER_ABORTED) throw callerAbortedError();\n\t\t\tif (result === GENERATION_RETIRED) {\n\t\t\t\tthrow entry.retirementError ?? credentialInvalidatedError();\n\t\t\t}\n\t\t\tif (result.status === \"error\") throw result.error;\n\t\t\treturn result.snapshot;\n\t\t} finally {\n\t\t\tentry.waiterCount -= 1;\n\t\t\tcaller?.detach();\n\t\t\tretired.detach();\n\t\t}\n\t}\n\n\tasync #waitForInvalidation(\n\t\tentry: InvalidationEntry,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<McpClientOAuthInvalidateResult> {\n\t\tentry.waiterCount += 1;\n\t\tconst caller = signal === undefined ? undefined : waitForAbort(signal, CALLER_ABORTED);\n\t\ttry {\n\t\t\tconst result = await Promise.race([\n\t\t\t\trequireInvalidationTask(entry),\n\t\t\t\t...(caller === undefined ? [] : [caller.promise]),\n\t\t\t]);\n\t\t\tif (result === CALLER_ABORTED) throw callerAbortedError();\n\t\t\tif (result.status === \"error\") throw result.error;\n\t\t\treturn result.result;\n\t\t} finally {\n\t\t\tentry.waiterCount -= 1;\n\t\t\tcaller?.detach();\n\t\t}\n\t}\n\n\tasync #waitForSettlingInvalidation(\n\t\tentry: RefreshEntry<Credential>,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<McpClientOAuthInvalidateResult> {\n\t\tentry.waiterCount += 1;\n\t\tconst caller = signal === undefined ? undefined : waitForAbort(signal, CALLER_ABORTED);\n\t\ttry {\n\t\t\tconst outcome = await Promise.race([\n\t\t\t\trequireRefreshTask(entry),\n\t\t\t\t...(caller === undefined ? [] : [caller.promise]),\n\t\t\t]);\n\t\t\tif (outcome === CALLER_ABORTED) throw callerAbortedError();\n\t\t\tif (outcome.status === \"success\") return createInvalidationResult(\"superseded\");\n\t\t\tif (outcome.error.code === McpClientOAuthRefreshErrorCode.CredentialInvalidated) {\n\t\t\t\treturn createInvalidationResult(\"invalidated\");\n\t\t\t}\n\t\t\tif (outcome.error.code === McpClientOAuthRefreshErrorCode.CredentialMissing) {\n\t\t\t\treturn createInvalidationResult(\"missing\");\n\t\t\t}\n\t\t\tif (outcome.error.code === McpClientOAuthRefreshErrorCode.RevisionMismatch) {\n\t\t\t\treturn createInvalidationResult(\"conflict\");\n\t\t\t}\n\t\t\tthrow outcome.error;\n\t\t} finally {\n\t\t\tentry.waiterCount -= 1;\n\t\t\tcaller?.detach();\n\t\t}\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#closed) throw coordinatorClosedError();\n\t}\n\n\t#assertCapacity(identity: Identity): void {\n\t\tif (\n\t\t\tthis.#refreshes.has(identity) ||\n\t\t\tthis.#invalidations.has(identity) ||\n\t\t\tthis.#retiredRevisions.has(identity)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.#inFlightKeyCount() >= this.#maxInFlightKeys) throw capacityExceededError();\n\t}\n\n\t#inFlightKeyCount(): number {\n\t\tconst identities = new Set(this.#refreshes.keys());\n\t\tfor (const identity of this.#invalidations.keys()) identities.add(identity);\n\t\tfor (const identity of this.#retiredRevisions.keys()) identities.add(identity);\n\t\treturn identities.size;\n\t}\n\n\t#assertGenerationUsable(identity: Identity, revision: McpClientOAuthCredentialRevision): void {\n\t\tconst retiredRevision = this.#retiredRevisions.get(identity);\n\t\tif (retiredRevision === undefined) return;\n\t\tif (revision <= retiredRevision) throw credentialInvalidatedError();\n\t}\n\n\t#retireRevision(identity: Identity, revision: McpClientOAuthCredentialRevision): void {\n\t\tconst current = this.#retiredRevisions.get(identity);\n\t\tif (current === undefined || revision > current) this.#retiredRevisions.set(identity, revision);\n\t}\n\n\t#clearRetiredRevision(\n\t\tidentity: Identity,\n\t\tauthoritativeRevision: McpClientOAuthCredentialRevision,\n\t): void {\n\t\tconst current = this.#retiredRevisions.get(identity);\n\t\tif (current !== undefined && current <= authoritativeRevision) {\n\t\t\tthis.#retiredRevisions.delete(identity);\n\t\t}\n\t}\n}\n\n/**\n * Fails terminally by default. Only internally branded strict-protocol errors with a definitive\n * pre-dispatch outcome are retry-safe; public constructor/code lookalikes are not.\n */\nexport function classifyMcpClientOAuthRefreshFailure(\n\terror: unknown,\n): McpClientOAuthRefreshFailureDisposition {\n\tif (!isInternalMcpClientOAuthProtocolError(error)) {\n\t\treturn terminalRefreshFailureDisposition();\n\t}\n\n\tswitch (readStringProperty(error, \"code\")) {\n\t\tcase McpClientOAuthProtocolErrorCode.InvalidGrant:\n\t\t\treturn terminalRefreshFailureDisposition(\n\t\t\t\tMcpClientOAuthCredentialInvalidationReason.InvalidGrant,\n\t\t\t);\n\t\tcase McpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown:\n\t\tcase McpClientOAuthProtocolErrorCode.InvalidClient:\n\t\t\treturn terminalRefreshFailureDisposition();\n\t\tcase McpClientOAuthProtocolErrorCode.InvalidOptions:\n\t\tcase McpClientOAuthProtocolErrorCode.EndpointRejected:\n\t\tcase McpClientOAuthProtocolErrorCode.DiscoveryFailed:\n\t\tcase McpClientOAuthProtocolErrorCode.AuthorityInvalid:\n\t\tcase McpClientOAuthProtocolErrorCode.ClientUnsupported:\n\t\tcase McpClientOAuthProtocolErrorCode.TransactionInvalid:\n\t\tcase McpClientOAuthProtocolErrorCode.AuthorizationDenied:\n\t\tcase McpClientOAuthProtocolErrorCode.AuthorizationFailed:\n\t\tcase McpClientOAuthProtocolErrorCode.TokenExchangeFailed:\n\t\tcase McpClientOAuthProtocolErrorCode.TokenRefreshFailed:\n\t\t\treturn retrySafeRefreshFailureDisposition();\n\t\tdefault:\n\t\t\treturn terminalRefreshFailureDisposition();\n\t}\n}\n\nfunction normalizeCredentialSnapshot<Credential extends object>(\n\tvalue: McpClientOAuthCredentialSnapshot<Credential>,\n): McpClientOAuthCredentialSnapshot<Credential> {\n\ttry {\n\t\tif (!isObjectLike(value)) throw invalidStoreResultError();\n\t\tconst { credential, revision } = value;\n\t\tif (!isMcpClientOAuthCredentialRevision(revision) || !isObjectLike(credential)) {\n\t\t\tthrow invalidStoreResultError();\n\t\t}\n\t\treturn createMcpClientOAuthCredentialSnapshot<Credential>(revision, credential);\n\t} catch (error) {\n\t\tthrow sanitizeInvalidStoreResult(error);\n\t}\n}\n\nfunction normalizeRefreshClaimResult<Credential extends object>(\n\tvalue: McpClientOAuthRefreshClaimResult<Credential>,\n\texpectedRevision: McpClientOAuthCredentialRevision,\n): McpClientOAuthRefreshClaimResult<Credential> {\n\ttry {\n\t\tif (!isObjectLike(value)) throw invalidStoreResultError();\n\t\tconst { status } = value;\n\t\tif (status === \"busy\" || status === \"conflict\") return Object.freeze({ status });\n\t\tif (status !== \"claimed\") throw invalidStoreResultError();\n\t\tconst snapshot = normalizeCredentialSnapshot<Credential>(value.snapshot);\n\t\tif (snapshot.revision !== expectedRevision) throw invalidStoreResultError();\n\t\treturn Object.freeze({ status, snapshot });\n\t} catch (error) {\n\t\tthrow sanitizeInvalidStoreResult(error);\n\t}\n}\n\nfunction normalizeRefreshCommitResult<Credential extends object>(\n\tvalue: McpClientOAuthRefreshCommitResult<Credential>,\n\texpectedRevision: McpClientOAuthCredentialRevision,\n):\n\t| {\n\t\t\treadonly status: \"applied\";\n\t\t\treadonly snapshot: McpClientOAuthCredentialSnapshot<Credential>;\n\t }\n\t| { readonly status: \"conflict\" } {\n\ttry {\n\t\tif (!isObjectLike(value)) throw invalidStoreResultError();\n\t\tconst { status } = value;\n\t\tif (status === \"conflict\") return Object.freeze({ status });\n\t\tif (status !== \"applied\") throw invalidStoreResultError();\n\t\tconst snapshot = normalizeCredentialSnapshot<Credential>(value.snapshot);\n\t\tif (snapshot.revision !== nextMcpClientOAuthCredentialRevision(expectedRevision)) {\n\t\t\tthrow invalidStoreResultError();\n\t\t}\n\t\treturn Object.freeze({ status, snapshot });\n\t} catch (error) {\n\t\tthrow sanitizeInvalidStoreResult(error);\n\t}\n}\n\nfunction normalizeRefreshClaimReleaseResult(\n\tvalue: McpClientOAuthRefreshClaimReleaseResult,\n): McpClientOAuthRefreshClaimReleaseResult {\n\ttry {\n\t\tif (!isObjectLike(value)) throw invalidStoreResultError();\n\t\tconst { status } = value;\n\t\tif (status !== \"released\" && status !== \"conflict\") throw invalidStoreResultError();\n\t\treturn Object.freeze({ status });\n\t} catch (error) {\n\t\tthrow sanitizeInvalidStoreResult(error);\n\t}\n}\n\nfunction normalizeInvalidationResult(\n\tvalue: McpClientOAuthCredentialInvalidationResult,\n): McpClientOAuthCredentialInvalidationResult {\n\ttry {\n\t\tif (!isObjectLike(value)) throw invalidStoreResultError();\n\t\tconst { status } = value;\n\t\tif (status !== \"applied\" && status !== \"conflict\") throw invalidStoreResultError();\n\t\treturn Object.freeze({ status });\n\t} catch (error) {\n\t\tthrow sanitizeInvalidStoreResult(error);\n\t}\n}\n\nfunction refreshSuccessOutcome<Credential extends object>(\n\tsnapshot: McpClientOAuthCredentialSnapshot<Credential>,\n): RefreshOutcome<Credential> {\n\treturn Object.freeze({ status: \"success\", snapshot });\n}\n\nfunction refreshErrorOutcome<Credential extends object>(\n\terror: McpClientOAuthRefreshError,\n): RefreshOutcome<Credential> {\n\treturn Object.freeze({ status: \"error\", error });\n}\n\nfunction invalidationSuccessOutcome(\n\tstatus: McpClientOAuthInvalidateResult[\"status\"],\n): InvalidationOutcome {\n\treturn Object.freeze({ status: \"success\", result: createInvalidationResult(status) });\n}\n\nfunction createInvalidationResult(\n\tstatus: McpClientOAuthInvalidateResult[\"status\"],\n): McpClientOAuthInvalidateResult {\n\treturn Object.freeze({ status });\n}\n\nfunction invalidationErrorOutcome(error: McpClientOAuthRefreshError): InvalidationOutcome {\n\treturn Object.freeze({ status: \"error\", error });\n}\n\nfunction requireRefreshTask<Credential extends object>(\n\tentry: RefreshEntry<Credential>,\n): Promise<RefreshOutcome<Credential>> {\n\tif (entry.task === undefined) throw internalFailureError();\n\treturn entry.task;\n}\n\nfunction requireInvalidationTask(entry: InvalidationEntry): Promise<InvalidationOutcome> {\n\tif (entry.task === undefined) throw internalFailureError();\n\treturn entry.task;\n}\n\nfunction storeContext(signal: AbortSignal): McpClientOAuthCredentialStoreContext {\n\treturn Object.freeze({ signal });\n}\n\nfunction waitForAbort<Result extends symbol>(\n\tsignal: AbortSignal,\n\tresult: Result,\n): AbortWait<Result> {\n\tif (signal.aborted) return { promise: Promise.resolve(result), detach: noop };\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\nfunction throwIfCallerAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted === true) throw callerAbortedError();\n}\n\nfunction assertRevision(value: unknown): asserts value is McpClientOAuthCredentialRevision {\n\tif (!isMcpClientOAuthCredentialRevision(value)) throw invalidOptionsError();\n}\n\nfunction createRefreshClaimId(): McpClientOAuthRefreshClaimId {\n\ttry {\n\t\treturn Object.freeze({ value: randomUUID() });\n\t} catch {\n\t\tthrow internalFailureError();\n\t}\n}\n\nfunction retrySafeRefreshFailureDisposition(): McpClientOAuthRefreshFailureDisposition {\n\treturn Object.freeze({ kind: \"retry-safe\" });\n}\n\nfunction terminalRefreshFailureDisposition(\n\treason: McpClientOAuthTerminalRefreshReason = McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure,\n): McpClientOAuthRefreshFailureDisposition {\n\treturn Object.freeze({ kind: \"terminal\", reason });\n}\n\nfunction normalizeRefreshFailureDisposition(\n\tvalue: unknown,\n): McpClientOAuthRefreshFailureDisposition {\n\ttry {\n\t\tif (!isObjectLike(value)) return terminalRefreshFailureDisposition();\n\t\tconst { kind } = value as { readonly kind?: unknown };\n\t\tif (kind === \"retry-safe\") return retrySafeRefreshFailureDisposition();\n\t\tif (kind !== \"terminal\") return terminalRefreshFailureDisposition();\n\t\tconst { reason } = value as { readonly reason?: unknown };\n\t\treturn isTerminalRefreshReason(reason)\n\t\t\t? terminalRefreshFailureDisposition(reason)\n\t\t\t: terminalRefreshFailureDisposition();\n\t} catch {\n\t\treturn terminalRefreshFailureDisposition();\n\t}\n}\n\nfunction assertInvalidationReason(\n\tvalue: unknown,\n): asserts value is McpClientOAuthCredentialInvalidationReason {\n\tif (\n\t\tvalue !== McpClientOAuthCredentialInvalidationReason.Explicit &&\n\t\tvalue !== McpClientOAuthCredentialInvalidationReason.ObservedExternal &&\n\t\t!isTerminalRefreshReason(value)\n\t) {\n\t\tthrow invalidOptionsError();\n\t}\n}\n\nfunction isTerminalRefreshReason(value: unknown): value is McpClientOAuthTerminalRefreshReason {\n\treturn (\n\t\tvalue === McpClientOAuthCredentialInvalidationReason.InvalidGrant ||\n\t\tvalue === McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure\n\t);\n}\n\nfunction isCredentialStore(\n\tvalue: unknown,\n): value is McpClientOAuthCredentialStore<unknown, object> {\n\tif (!isObjectLike(value)) return false;\n\ttry {\n\t\treturn (\n\t\t\ttypeof Reflect.get(value, \"load\") === \"function\" &&\n\t\t\ttypeof Reflect.get(value, \"claimRefresh\") === \"function\" &&\n\t\t\ttypeof Reflect.get(value, \"commitRefresh\") === \"function\" &&\n\t\t\ttypeof Reflect.get(value, \"releaseRefreshClaim\") === \"function\" &&\n\t\t\ttypeof Reflect.get(value, \"compareAndSwap\") === \"function\" &&\n\t\t\ttypeof Reflect.get(value, \"invalidate\") === \"function\"\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isObjectLike(value: unknown): value is object {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\");\n}\n\nfunction readStringProperty(value: unknown, property: string): string | undefined {\n\tif (!isObjectLike(value)) return undefined;\n\ttry {\n\t\tconst result = Reflect.get(value, property) as unknown;\n\t\treturn typeof result === \"string\" ? result : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction sanitizeCoordinatorError(error: unknown): McpClientOAuthRefreshError {\n\ttry {\n\t\tif (!(error instanceof McpClientOAuthRefreshError)) return internalFailureError();\n\t} catch {\n\t\treturn internalFailureError();\n\t}\n\n\tswitch (readStringProperty(error, \"code\")) {\n\t\tcase McpClientOAuthRefreshErrorCode.InvalidOptions:\n\t\t\treturn invalidOptionsError();\n\t\tcase McpClientOAuthRefreshErrorCode.Closed:\n\t\t\treturn coordinatorClosedError();\n\t\tcase McpClientOAuthRefreshErrorCode.CapacityExceeded:\n\t\t\treturn capacityExceededError();\n\t\tcase McpClientOAuthRefreshErrorCode.RevisionInFlight:\n\t\t\treturn revisionInFlightError();\n\t\tcase McpClientOAuthRefreshErrorCode.CredentialMissing:\n\t\t\treturn credentialMissingError();\n\t\tcase McpClientOAuthRefreshErrorCode.CredentialInvalidated:\n\t\t\treturn credentialInvalidatedError();\n\t\tcase McpClientOAuthRefreshErrorCode.RevisionMismatch:\n\t\t\treturn revisionMismatchError();\n\t\tcase McpClientOAuthRefreshErrorCode.RefreshFailed:\n\t\t\treturn refreshFailedError();\n\t\tcase McpClientOAuthRefreshErrorCode.StoreFailed:\n\t\t\treturn storeFailedError();\n\t\tcase McpClientOAuthRefreshErrorCode.InvalidStoreResult:\n\t\t\treturn invalidStoreResultError();\n\t\tcase McpClientOAuthRefreshErrorCode.InvalidationHookFailed:\n\t\t\treturn invalidationHookFailedError();\n\t\tcase McpClientOAuthRefreshErrorCode.CallerAborted:\n\t\t\treturn callerAbortedError();\n\t\tcase McpClientOAuthRefreshErrorCode.InternalFailure:\n\t\tdefault:\n\t\t\treturn internalFailureError();\n\t}\n}\n\nfunction sanitizeInvalidStoreResult(_error: unknown): McpClientOAuthRefreshError {\n\treturn invalidStoreResultError();\n}\n\nfunction invalidOptionsError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.InvalidOptions,\n\t\t\"The OAuth refresh coordinator options are invalid.\",\n\t);\n}\n\nfunction coordinatorClosedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.Closed,\n\t\t\"The OAuth refresh coordinator is closed and cannot accept new work.\",\n\t);\n}\n\nfunction capacityExceededError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.CapacityExceeded,\n\t\t\"The OAuth refresh coordinator is at capacity.\",\n\t);\n}\n\nfunction revisionInFlightError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.RevisionInFlight,\n\t\t\"A different OAuth credential revision already has accepted work.\",\n\t);\n}\n\nfunction credentialMissingError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.CredentialMissing,\n\t\t\"The OAuth credential generation is unavailable.\",\n\t);\n}\n\nfunction credentialInvalidatedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.CredentialInvalidated,\n\t\t\"The OAuth credential generation is no longer usable.\",\n\t);\n}\n\nfunction revisionMismatchError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.RevisionMismatch,\n\t\t\"The OAuth credential revision changed before refresh could be committed.\",\n\t);\n}\n\nfunction refreshFailedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.RefreshFailed,\n\t\t\"The OAuth credential refresh failed.\",\n\t);\n}\n\nfunction storeFailedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.StoreFailed,\n\t\t\"The OAuth credential store operation failed.\",\n\t);\n}\n\nfunction invalidStoreResultError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.InvalidStoreResult,\n\t\t\"The OAuth credential store returned an invalid result.\",\n\t);\n}\n\nfunction invalidationHookFailedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.InvalidationHookFailed,\n\t\t\"The OAuth credential invalidation hook failed.\",\n\t);\n}\n\nfunction callerAbortedError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.CallerAborted,\n\t\t\"The caller stopped waiting for OAuth credential work.\",\n\t);\n}\n\nfunction internalFailureError(): McpClientOAuthRefreshError {\n\treturn new McpClientOAuthRefreshError(\n\t\tMcpClientOAuthRefreshErrorCode.InternalFailure,\n\t\t\"The OAuth refresh coordinator could not complete the operation.\",\n\t);\n}\n\nfunction generationInvalidatedAbortReason(): DOMException {\n\treturn new DOMException(\"The OAuth credential generation was invalidated.\", \"AbortError\");\n}\n\nfunction noop(): void {}\n","import {\n\tparseMcpClientOAuthBootstrapDiscoveryResult,\n\ttype McpClientOAuthBootstrapReady,\n} from \"./bootstrap.ts\";\nimport type { McpClientOAuthClientAuthentication } from \"./protocol.ts\";\nimport { isMcpClientOAuthScopeToken } from \"./scope.ts\";\nimport {\n\tassertOAuthSnapshotKeys,\n\toauthSnapshotBoolean,\n\toauthSnapshotString,\n\toauthSnapshotStrings,\n\tparseOAuthSnapshot,\n} from \"./snapshot-data.ts\";\n\n/** Public provenance only. Credentials and the identity of the host's record stay with the host. */\nexport interface McpClientOAuthExistingClient {\n\treadonly clientId: string;\n\treadonly serverUrl: string;\n\treadonly issuer: string;\n\treadonly resource: string;\n\treadonly provisioningMethod: \"manual\" | \"client_id_metadata\" | \"dynamic_registration\";\n\treadonly authenticationMethod: McpClientOAuthClientAuthentication[\"method\"];\n\t/** Whether the host can supply the secret or signing key required by this method. */\n\treadonly authenticationAvailable: boolean;\n\t/** Required for automatic-client reuse; manual clients retain host-managed redirect policy. */\n\treadonly redirectUri?: string;\n\t/** Configured manual scopes or the original registered allowance, not a previous access token grant. */\n\treadonly scopes: readonly string[];\n}\n\nexport type McpClientOAuthProvisioningStrategy =\n\t\"reuse\" | \"client_id_metadata\" | \"dynamic_registration\";\nexport type McpClientOAuthExistingClientStatus =\n\t\"absent\" | \"incompatible\" | \"scope_insufficient\" | \"reusable\";\n\nexport interface McpClientOAuthProvisioningInput {\n\treadonly discovery: McpClientOAuthBootstrapReady;\n\treadonly redirectUri: string;\n\treadonly clientIdMetadataUrl?: string;\n\treadonly existingClient?: McpClientOAuthExistingClient;\n\t/** Explicit host preference order. Omitting a strategy prohibits selecting it. */\n\treadonly strategies: readonly McpClientOAuthProvisioningStrategy[];\n\t/** Defaults to false: an insufficient existing registration cannot silently cause another one. */\n\treadonly allowRegistrationAfterScopeExpansion?: boolean;\n}\n\nexport interface McpClientOAuthProvisioningPlan {\n\treadonly kind:\n\t\t| \"reuse\"\n\t\t| \"client_id_metadata\"\n\t\t| \"dynamic_registration\"\n\t\t| \"registration_scope_insufficient\"\n\t\t| \"manual_client_required\";\n\treadonly existingClientStatus: McpClientOAuthExistingClientStatus;\n\t/** Exact scopes to request. Empty means request no scopes, including after narrower rediscovery. */\n\treadonly authorizationScopes: readonly string[];\n}\n\n/**\n * Pure provisioning decision over captured protocol facts and explicit host preferences.\n * Performs no I/O, registration, decryption, authorization or persistence. A registration plan\n * is only a capability result; hosts must obtain consent and fence dispatch independently.\n */\nexport function planMcpClientOAuthProvisioning(\n\tinput: McpClientOAuthProvisioningInput,\n): McpClientOAuthProvisioningPlan {\n\tconst discovery = parseMcpClientOAuthBootstrapDiscoveryResult(input.discovery);\n\tif (discovery.kind !== \"ready\") throw invalidOptions();\n\tconst applicationType = getMcpClientOAuthApplicationType(input.redirectUri);\n\tif (applicationType === undefined) throw invalidOptions();\n\tconst strategies = [...input.strategies];\n\tif (\n\t\tstrategies.length > 3 ||\n\t\tnew Set(strategies).size !== strategies.length ||\n\t\tstrategies.some(\n\t\t\t(value) =>\n\t\t\t\tvalue !== \"reuse\" && value !== \"client_id_metadata\" && value !== \"dynamic_registration\",\n\t\t) ||\n\t\t(input.allowRegistrationAfterScopeExpansion !== undefined &&\n\t\t\ttypeof input.allowRegistrationAfterScopeExpansion !== \"boolean\")\n\t)\n\t\tthrow invalidOptions();\n\tconst clientIdMetadataUrl = input.clientIdMetadataUrl;\n\tif (\n\t\tclientIdMetadataUrl !== undefined &&\n\t\tgetMcpClientOAuthApplicationType(clientIdMetadataUrl) !== \"web\"\n\t)\n\t\tthrow invalidOptions();\n\tconst existing =\n\t\tinput.existingClient === undefined ? undefined : captureExistingClient(input.existingClient);\n\tconst status = existingClientStatus(existing, discovery, input.redirectUri, clientIdMetadataUrl);\n\tconst scopes = Object.freeze([...(discovery.scopes ?? [])]);\n\tconst result = (\n\t\tkind: McpClientOAuthProvisioningPlan[\"kind\"],\n\t\tauthorizationScopes = scopes,\n\t): McpClientOAuthProvisioningPlan =>\n\t\tObject.freeze({ kind, existingClientStatus: status, authorizationScopes });\n\tconst publicClient =\n\t\tdiscovery.candidate.authority.tokenEndpointAuthMethodsSupported.includes(\"none\");\n\tfor (const strategy of strategies) {\n\t\tif (strategy === \"reuse\" && status === \"reusable\" && existing !== undefined) {\n\t\t\treturn result(\"reuse\", existing.provisioningMethod === \"manual\" ? existing.scopes : scopes);\n\t\t}\n\t\tif (\n\t\t\tstrategy === \"client_id_metadata\" &&\n\t\t\tpublicClient &&\n\t\t\tapplicationType === \"web\" &&\n\t\t\tdiscovery.candidate.clientIdMetadataDocumentSupported &&\n\t\t\tclientIdMetadataUrl !== undefined\n\t\t)\n\t\t\treturn result(\"client_id_metadata\");\n\t\tif (\n\t\t\tstrategy === \"dynamic_registration\" &&\n\t\t\tpublicClient &&\n\t\t\tdiscovery.candidate.legacyDynamicRegistrationEndpoint !== undefined\n\t\t) {\n\t\t\tif (status === \"scope_insufficient\" && input.allowRegistrationAfterScopeExpansion !== true)\n\t\t\t\treturn result(\"registration_scope_insufficient\");\n\t\t\treturn result(\"dynamic_registration\");\n\t\t}\n\t}\n\treturn result(\n\t\tstatus === \"scope_insufficient\" ? \"registration_scope_insufficient\" : \"manual_client_required\",\n\t);\n}\n\n/** Canonical HTTPS web callback or RFC 8252 loopback HTTP native callback; no network admission. */\nexport function getMcpClientOAuthApplicationType(value: string): \"web\" | \"native\" | undefined {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > 4_096) return undefined;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.href !== value || url.username !== \"\" || url.password !== \"\" || url.hash !== \"\")\n\t\t\treturn undefined;\n\t\tif (url.protocol === \"https:\") return \"web\";\n\t\tif (\n\t\t\turl.protocol === \"http:\" &&\n\t\t\t(url.hostname === \"localhost\" ||\n\t\t\t\turl.hostname === \"[::1]\" ||\n\t\t\t\t/^127\\.\\d+\\.\\d+\\.\\d+$/u.test(url.hostname))\n\t\t)\n\t\t\treturn \"native\";\n\t} catch {\n\t\t/* Invalid URLs are not provisioning capabilities. */\n\t}\n\treturn undefined;\n}\n\n/** Empty or absent discovery asks for no scopes; it never expands a registered allowance. */\nexport function mcpClientOAuthScopesCover(\n\tavailable: readonly string[],\n\trequested: readonly string[] = [],\n): boolean {\n\tvalidateScopes(available);\n\tvalidateScopes(requested);\n\tconst allowed = new Set(available);\n\treturn requested.every((scope) => allowed.has(scope));\n}\n\nfunction existingClientStatus(\n\texisting: McpClientOAuthExistingClient | undefined,\n\tready: McpClientOAuthBootstrapReady,\n\tredirectUri: string,\n\tmetadataUrl: string | undefined,\n): McpClientOAuthExistingClientStatus {\n\tif (existing === undefined) return \"absent\";\n\tif (\n\t\texisting.serverUrl !== ready.resource.serverUrl ||\n\t\texisting.issuer !== ready.candidate.authority.issuer ||\n\t\texisting.resource !== ready.resource.resource ||\n\t\t(existing.provisioningMethod !== \"manual\" && existing.redirectUri !== redirectUri) ||\n\t\t(existing.provisioningMethod === \"client_id_metadata\" &&\n\t\t\t(!ready.candidate.clientIdMetadataDocumentSupported ||\n\t\t\t\tmetadataUrl === undefined ||\n\t\t\t\texisting.clientId !== metadataUrl)) ||\n\t\t!ready.candidate.authority.tokenEndpointAuthMethodsSupported.includes(\n\t\t\texisting.authenticationMethod,\n\t\t) ||\n\t\t(existing.authenticationMethod !== \"none\" && !existing.authenticationAvailable)\n\t)\n\t\treturn \"incompatible\";\n\treturn existing.provisioningMethod === \"dynamic_registration\" &&\n\t\t!mcpClientOAuthScopesCover(existing.scopes, ready.scopes)\n\t\t? \"scope_insufficient\"\n\t\t: \"reusable\";\n}\n\nfunction captureExistingClient(value: McpClientOAuthExistingClient): McpClientOAuthExistingClient {\n\treturn parseOAuthSnapshot(value, {}, (record) => {\n\t\tassertOAuthSnapshotKeys(record, [\n\t\t\t\"clientId\",\n\t\t\t\"serverUrl\",\n\t\t\t\"issuer\",\n\t\t\t\"resource\",\n\t\t\t\"provisioningMethod\",\n\t\t\t\"authenticationMethod\",\n\t\t\t\"authenticationAvailable\",\n\t\t\t\"redirectUri\",\n\t\t\t\"scopes\",\n\t\t]);\n\t\tconst method = record.provisioningMethod;\n\t\tconst authentication = record.authenticationMethod;\n\t\tif (method !== \"manual\" && method !== \"client_id_metadata\" && method !== \"dynamic_registration\")\n\t\t\tthrow invalidOptions();\n\t\tif (\n\t\t\tauthentication !== \"none\" &&\n\t\t\tauthentication !== \"client_secret_basic\" &&\n\t\t\tauthentication !== \"client_secret_post\" &&\n\t\t\tauthentication !== \"private_key_jwt\"\n\t\t)\n\t\t\tthrow invalidOptions();\n\t\tconst scopes = oauthSnapshotStrings(record.scopes, 128);\n\t\tvalidateScopes(scopes);\n\t\treturn Object.freeze({\n\t\t\tclientId: oauthSnapshotString(record.clientId, 2_048),\n\t\t\tserverUrl: oauthSnapshotString(record.serverUrl, 4_096),\n\t\t\tissuer: oauthSnapshotString(record.issuer, 4_096),\n\t\t\tresource: oauthSnapshotString(record.resource, 4_096),\n\t\t\tprovisioningMethod: method,\n\t\t\tauthenticationMethod: authentication,\n\t\t\tauthenticationAvailable: oauthSnapshotBoolean(record.authenticationAvailable),\n\t\t\t...(record.redirectUri === undefined\n\t\t\t\t? {}\n\t\t\t\t: { redirectUri: oauthSnapshotString(record.redirectUri, 4_096) }),\n\t\t\tscopes: Object.freeze([...scopes]),\n\t\t});\n\t});\n}\n\nfunction validateScopes(value: readonly string[]): void {\n\tif (\n\t\t!Array.isArray(value) ||\n\t\tvalue.length > 128 ||\n\t\t!value.every(isMcpClientOAuthScopeToken) ||\n\t\tvalue.join(\" \").length > 4_096\n\t)\n\t\tthrow invalidOptions();\n}\n\nfunction invalidOptions(): TypeError {\n\treturn new TypeError(\"The MCP OAuth provisioning options are invalid.\");\n}\n","import type { FetchLike } from \"@modelcontextprotocol/client\";\nimport { McpClientOAuthBootstrapError, McpClientOAuthBootstrapErrorCode } from \"./bootstrap.ts\";\n\nexport interface McpClientOAuthChallengeProbeInput {\n\treadonly serverUrl: string;\n\t/** Already admitted, unauthenticated fetch. The host owns DNS/redirect/response limits and lease cleanup. */\n\treadonly fetch: FetchLike;\n\t/** Host deadline and cancellation. Fetch must honor it; this helper owns no transport. */\n\treadonly signal: AbortSignal;\n}\n\n/** One non-credentialed GET. Pass its bounded raw header to bootstrap.discover({ wwwAuthenticate }). */\nexport async function probeMcpClientOAuthChallenge(\n\tinput: McpClientOAuthChallengeProbeInput,\n): Promise<string | undefined> {\n\tconst { fetch, signal, serverUrl } = input;\n\tif (typeof fetch !== \"function\" || typeof serverUrl !== \"string\" || serverUrl.length > 4_096)\n\t\tthrow invalidOptions();\n\tlet endpoint: URL;\n\ttry {\n\t\tendpoint = new URL(serverUrl);\n\t} catch {\n\t\tthrow invalidOptions();\n\t}\n\tif (\n\t\t(endpoint.protocol !== \"https:\" && endpoint.protocol !== \"http:\") ||\n\t\tendpoint.username !== \"\" ||\n\t\tendpoint.password !== \"\" ||\n\t\tendpoint.hash !== \"\"\n\t)\n\t\tthrow invalidOptions();\n\tsignal.throwIfAborted();\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(serverUrl, {\n\t\t\tcache: \"no-store\",\n\t\t\tcredentials: \"omit\",\n\t\t\theaders: { Accept: \"text/event-stream\", \"Cache-Control\": \"no-store\" },\n\t\t\tmethod: \"GET\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal,\n\t\t});\n\t} catch {\n\t\tsignal.throwIfAborted();\n\t\tthrow new McpClientOAuthBootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);\n\t}\n\ttry {\n\t\tsignal.throwIfAborted();\n\t\tconst challenge =\n\t\t\tresponse.status === 401 ? (response.headers.get(\"www-authenticate\") ?? undefined) : undefined;\n\t\tif (challenge !== undefined && challenge.length > 8_192) throw invalidOptions();\n\t\treturn challenge;\n\t} finally {\n\t\ttry {\n\t\t\tawait response.body?.cancel();\n\t\t} catch {\n\t\t\t/* The host still closes the admitted fetch lease. */\n\t\t}\n\t}\n}\n\nfunction invalidOptions(): McpClientOAuthBootstrapError {\n\treturn new McpClientOAuthBootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);\n}\n","import {\n\tClient,\n\tStreamableHTTPClientTransport,\n\ttype FetchLike,\n} from \"@modelcontextprotocol/client\";\n\nimport {\n\tMcpClientOAuthBootstrap,\n\tMcpClientOAuthBootstrapError,\n\tparseMcpClientOAuthBootstrapChallenge,\n\ttype McpClientOAuthBootstrapDiscoveryResult,\n\ttype McpClientOAuthBootstrapEndpointPolicy,\n\ttype McpClientOAuthBootstrapErrorCode,\n} from \"./bootstrap.ts\";\n\nexport interface McpClientAuthenticationDetectionInput {\n\treadonly serverUrl: string;\n\t/** Already admitted, credential-free fetch. The host owns DNS pinning and network policy. */\n\treadonly fetch: FetchLike;\n\t/** Guarded OAuth metadata fetch; defaults to fetch. Useful with an endpoint-only MCP lease. */\n\treadonly discoveryFetch?: FetchLike;\n\t/** The same policy used by OAuth bootstrap, including all generated discovery URLs. */\n\treadonly endpointPolicy: McpClientOAuthBootstrapEndpointPolicy;\n\t/** Host cancellation/deadline, preserved as a rejection with its original reason. */\n\treadonly signal: AbortSignal;\n\t/** Whole detection budget, default 10 seconds, at most 60 seconds. Cleanup adds at most 1 second. */\n\treadonly timeoutMs?: number;\n\t/** Aggregate response bytes, including SSE framing and metadata. Default 256 KiB, at most 1 MiB. */\n\treadonly maxResponseBytes?: number;\n}\n\nexport type McpClientAuthenticationDetectionReason =\n\t| \"invalid-options\"\n\t| \"endpoint-rejected\"\n\t| \"network-error\"\n\t| \"invalid-response\"\n\t| \"response-too-large\"\n\t| \"request-limit\"\n\t| \"timeout\"\n\t| \"http-error\"\n\t| \"unsupported-authentication\"\n\t| \"oauth-discovery-failed\"\n\t| \"cleanup-failed\";\n\nexport type McpClientAuthenticationDetectionResult =\n\t| {\n\t\t\t/** A credential-free MCP connection succeeded; later operations may still require OAuth. */\n\t\t\treadonly kind: \"anonymous\";\n\t\t\treadonly protocolVersion: string;\n\t\t\treadonly protocolEra: \"modern\" | \"legacy\";\n\t\t\t/** Schema-validated, bounded, self-reported display data; never an identity attestation. */\n\t\t\treadonly serverInfo?: {\n\t\t\t\treadonly name: string;\n\t\t\t\treadonly version: string;\n\t\t\t\treadonly title?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\t/** Authorization was denied and OAuth bootstrap validated the advertised resource. */\n\t\t\treadonly kind: \"oauth-required\";\n\t\t\t/** Enrollment, issuer selection, and strict-protocol compatibility remain host decisions. */\n\t\t\treadonly discovery: McpClientOAuthBootstrapDiscoveryResult;\n\t }\n\t| {\n\t\t\treadonly kind: \"indeterminate\";\n\t\t\treadonly reason: McpClientAuthenticationDetectionReason;\n\t\t\treadonly httpStatus?: number;\n\t\t\treadonly discoveryErrorCode?: McpClientOAuthBootstrapErrorCode;\n\t };\n\n/**\n * Passive Streamable HTTP detection using the SDK's modern discovery / legacy handshake.\n * No credentials, registration, browser navigation, token requests, or feature invocation.\n * Never infer anonymous access from a status code or missing OAuth metadata. HTTP+SSE (2024)\n * endpoints are not followed. The caller must always release its admitted network lease.\n */\nexport async function detectMcpClientAuthentication(\n\tinput: McpClientAuthenticationDetectionInput,\n): Promise<McpClientAuthenticationDetectionResult> {\n\tif (typeof input !== \"object\" || input === null || !(input.signal instanceof AbortSignal))\n\t\treturn indeterminate(\"invalid-options\");\n\tinput.signal.throwIfAborted();\n\tconst timeoutMs = input.timeoutMs ?? 10_000;\n\tconst maxResponseBytes = input.maxResponseBytes ?? 262_144;\n\tlet endpoint: URL;\n\ttry {\n\t\tendpoint = new URL(input.serverUrl);\n\t\tif (\n\t\t\ttypeof input.serverUrl !== \"string\" ||\n\t\t\tinput.serverUrl.length > 4_096 ||\n\t\t\t![\"http:\", \"https:\"].includes(endpoint.protocol) ||\n\t\t\tendpoint.username !== \"\" ||\n\t\t\tendpoint.password !== \"\" ||\n\t\t\tendpoint.hash !== \"\" ||\n\t\t\ttypeof input.fetch !== \"function\" ||\n\t\t\t(input.discoveryFetch !== undefined && typeof input.discoveryFetch !== \"function\") ||\n\t\t\ttypeof input.endpointPolicy !== \"function\" ||\n\t\t\t!Number.isSafeInteger(timeoutMs) ||\n\t\t\ttimeoutMs < 1 ||\n\t\t\ttimeoutMs > 60_000 ||\n\t\t\t!Number.isSafeInteger(maxResponseBytes) ||\n\t\t\tmaxResponseBytes < 1 ||\n\t\t\tmaxResponseBytes > 1_048_576\n\t\t)\n\t\t\treturn indeterminate(\"invalid-options\");\n\t} catch {\n\t\treturn indeterminate(\"invalid-options\");\n\t}\n\n\tconst scope = new DetectionScope(input, maxResponseBytes);\n\tconst timer = setTimeout(() => scope.stop(\"timeout\"), timeoutMs);\n\tlet denied: { status: number; header?: string } | undefined;\n\tlet accepting = true;\n\tconst pendingGets = new Set<Promise<Response>>();\n\tconst transportFetch: FetchLike = (url, init) => {\n\t\tconst request = (async () => {\n\t\t\tif (!accepting || denied !== undefined) throw new DetectionFailure(\"http-error\");\n\t\t\tif (String(url) !== endpoint.href) throw new DetectionFailure(\"endpoint-rejected\");\n\t\t\tconst method = init?.method;\n\t\t\tconst rpcMethod = method === \"POST\" ? outgoingMethod(init?.body) : undefined;\n\t\t\tif (\n\t\t\t\tmethod !== \"GET\" &&\n\t\t\t\t(method !== \"POST\" ||\n\t\t\t\t\t![\"server/discover\", \"initialize\", \"notifications/initialized\"].includes(rpcMethod ?? \"\"))\n\t\t\t) {\n\t\t\t\tscope.stop(\"invalid-response\");\n\t\t\t\tthrow new DetectionFailure(\"invalid-response\");\n\t\t\t}\n\t\t\tconst response = await scope.fetch(url, init);\n\t\t\tif (response.status === 401 || response.status === 403) {\n\t\t\t\tconst header = response.headers.get(\"www-authenticate\");\n\t\t\t\tdenied = { status: response.status, ...(header === null ? {} : { header }) };\n\t\t\t\tscope.cancel(response);\n\t\t\t\tthrow new DetectionFailure(\"http-error\");\n\t\t\t}\n\t\t\tif (method === \"GET\") {\n\t\t\t\t// The SDK opens the optional legacy GET stream after initialized. Only its\n\t\t\t\t// headers matter here; do not wait for a stream that is designed to stay open.\n\t\t\t\tscope.cancel(response);\n\t\t\t\tif (!response.ok && response.status !== 405) {\n\t\t\t\t\tscope.stop(\"http-error\");\n\t\t\t\t\tthrow new DetectionFailure(\"http-error\");\n\t\t\t\t}\n\t\t\t\treturn new Response(null, { status: response.status, headers: response.headers });\n\t\t\t}\n\t\t\tif (!response.ok && ![400, 404, 405].includes(response.status)) {\n\t\t\t\tscope.cancel(response);\n\t\t\t\tscope.stop(\"http-error\");\n\t\t\t\tthrow new DetectionFailure(\"http-error\");\n\t\t\t}\n\t\t\tif (rpcMethod === \"notifications/initialized\" && response.ok) {\n\t\t\t\tscope.cancel(response);\n\t\t\t\tif (response.status !== 202) {\n\t\t\t\t\tscope.stop(\"invalid-response\");\n\t\t\t\t\tthrow new DetectionFailure(\"invalid-response\");\n\t\t\t\t}\n\t\t\t\treturn new Response(null, { status: 202, headers: response.headers });\n\t\t\t}\n\t\t\treturn response;\n\t\t})();\n\t\tif (init?.method === \"GET\") pendingGets.add(request);\n\t\treturn request;\n\t};\n\tconst transport = new StreamableHTTPClientTransport(endpoint, {\n\t\tfetch: transportFetch,\n\t\treconnectionOptions: {\n\t\t\tmaxRetries: 0,\n\t\t\tinitialReconnectionDelay: 1_000,\n\t\t\tmaxReconnectionDelay: 1_000,\n\t\t\treconnectionDelayGrowFactor: 1,\n\t\t},\n\t});\n\tconst client = new Client(\n\t\t{ name: \"nest-mcp-authentication-detection\", version: \"1\" },\n\t\t{ capabilities: {}, versionNegotiation: { mode: \"auto\", probe: { timeoutMs, maxRetries: 0 } } },\n\t);\n\tlet result: McpClientAuthenticationDetectionResult;\n\ttry {\n\t\ttry {\n\t\t\tawait withSignal(\n\t\t\t\tclient.connect(transport, { signal: scope.signal, timeout: timeoutMs }),\n\t\t\t\tscope.signal,\n\t\t\t);\n\t\t\tawait withSignal(Promise.all(pendingGets), scope.signal);\n\t\t\tif (denied !== undefined) throw new DetectionFailure(\"http-error\");\n\t\t\tconst protocolVersion = client.getNegotiatedProtocolVersion();\n\t\t\tconst protocolEra = client.getProtocolEra();\n\t\t\tif (protocolVersion === undefined || protocolEra === undefined)\n\t\t\t\tthrow new DetectionFailure(\"invalid-response\");\n\t\t\tconst serverInfo = boundedServerInfo(client.getServerVersion());\n\t\t\tresult = Object.freeze({\n\t\t\t\tkind: \"anonymous\",\n\t\t\t\tprotocolVersion,\n\t\t\t\tprotocolEra,\n\t\t\t\t...(serverInfo === undefined ? {} : { serverInfo }),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (denied === undefined || scope.signal.aborted) throw error;\n\t\t\tconst { status, header } = denied;\n\t\t\tlet bearer;\n\t\t\ttry {\n\t\t\t\tbearer = header === undefined ? undefined : parseMcpClientOAuthBootstrapChallenge(header);\n\t\t\t} catch {\n\t\t\t\tthrow new DetectionFailure(\"unsupported-authentication\");\n\t\t\t}\n\t\t\t// A bare 401 supports well-known discovery. Basic/API-key auth and bare\n\t\t\t// 403 (including origin rejection) do not establish an OAuth challenge.\n\t\t\tif (\n\t\t\t\t(header !== undefined && bearer === undefined) ||\n\t\t\t\t(status === 403 && bearer === undefined)\n\t\t\t) {\n\t\t\t\tthrow new DetectionFailure(\"unsupported-authentication\");\n\t\t\t}\n\t\t\tconst bootstrap = new McpClientOAuthBootstrap({\n\t\t\t\tfetch: scope.discoveryFetch,\n\t\t\t\tendpointPolicy: input.endpointPolicy,\n\t\t\t});\n\t\t\tconst discovery = await withSignal(\n\t\t\t\tbootstrap.discover({\n\t\t\t\t\tserverUrl: endpoint.href,\n\t\t\t\t\t...(header === undefined ? {} : { wwwAuthenticate: header }),\n\t\t\t\t\tsignal: scope.signal,\n\t\t\t\t}),\n\t\t\t\tscope.signal,\n\t\t\t);\n\t\t\tresult = Object.freeze({ kind: \"oauth-required\", discovery });\n\t\t}\n\t} catch (error) {\n\t\tresult = indeterminate(\n\t\t\tscope.failure ??\n\t\t\t\t(error instanceof DetectionFailure\n\t\t\t\t\t? error.reason\n\t\t\t\t\t: error instanceof McpClientOAuthBootstrapError\n\t\t\t\t\t\t? \"oauth-discovery-failed\"\n\t\t\t\t\t\t: \"invalid-response\"),\n\t\t\tdenied?.status ?? scope.httpStatus,\n\t\t\terror instanceof McpClientOAuthBootstrapError ? error.code : undefined,\n\t\t);\n\t} finally {\n\t\taccepting = false;\n\t\tclearTimeout(timer);\n\t}\n\n\t// The SDK's close() only aborts streams; it does not terminate legacy sessions.\n\t// Use a fresh bounded cleanup signal because connect() may already have closed\n\t// the SDK transport on error. Never outlive cancellation supplied by the host.\n\tconst cleaned = await scope.close(client, transport, endpoint);\n\tinput.signal.throwIfAborted();\n\tif (!cleaned && result.kind === \"anonymous\") return indeterminate(\"cleanup-failed\");\n\treturn result;\n}\n\nclass DetectionFailure extends Error {\n\tconstructor(readonly reason: McpClientAuthenticationDetectionReason) {\n\t\tsuper(\"MCP authentication detection did not complete.\");\n\t}\n}\n\nclass DetectionScope {\n\treadonly #controller = new AbortController();\n\treadonly signal: AbortSignal;\n\treadonly #cancellations = new Set<Promise<unknown>>();\n\treadonly #readers = new Map<Response, () => void>();\n\t#bytes = 0;\n\t#requests = 0;\n\tfailure: McpClientAuthenticationDetectionReason | undefined;\n\thttpStatus: number | undefined;\n\n\tconstructor(\n\t\treadonly input: McpClientAuthenticationDetectionInput,\n\t\treadonly maximum: number,\n\t) {\n\t\tthis.signal = AbortSignal.any([input.signal, this.#controller.signal]);\n\t}\n\n\tstop(reason: McpClientAuthenticationDetectionReason): void {\n\t\tthis.failure ??= reason;\n\t\tthis.#controller.abort(new DetectionFailure(reason));\n\t}\n\n\tfetch: FetchLike = (url, init) => this.#fetch(this.input.fetch, url, init);\n\tdiscoveryFetch: FetchLike = (url, init) =>\n\t\tthis.#fetch(this.input.discoveryFetch ?? this.input.fetch, url, init);\n\n\tasync #fetch(\n\t\tfetch: FetchLike,\n\t\turl: Parameters<FetchLike>[0],\n\t\tinit: RequestInit | undefined,\n\t): Promise<Response> {\n\t\tthis.signal.throwIfAborted();\n\t\tif (++this.#requests > 12) {\n\t\t\tthis.stop(\"request-limit\");\n\t\t\tthrow new DetectionFailure(\"request-limit\");\n\t\t}\n\t\tconst signal = AbortSignal.any([this.signal, ...(init?.signal == null ? [] : [init.signal])]);\n\t\tconst pending = Promise.resolve().then(() => {\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn fetch(url, credentialFreeInit(init, signal));\n\t\t});\n\t\t// A host fetch that settles after cancellation must still have its body cancelled.\n\t\tconst request = Promise.resolve(pending).then((response) => {\n\t\t\tif (signal.aborted) {\n\t\t\t\tthis.#cancelBody(response);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\treturn response;\n\t\t});\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await withSignal(request, signal);\n\t\t} catch {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.stop(\"network-error\");\n\t\t\tthrow new DetectionFailure(\"network-error\");\n\t\t}\n\t\tif (\n\t\t\tresponse.redirected ||\n\t\t\t(response.status >= 300 && response.status < 400) ||\n\t\t\t(response.url !== \"\" && response.url !== String(url))\n\t\t) {\n\t\t\tthis.#cancelBody(response);\n\t\t\tthis.stop(\"endpoint-rejected\");\n\t\t\tthrow new DetectionFailure(\"endpoint-rejected\");\n\t\t}\n\t\tthis.httpStatus = response.status;\n\t\tif (\n\t\t\t(response.headers.get(\"www-authenticate\")?.length ?? 0) > 8_192 ||\n\t\t\t(response.headers.get(\"mcp-session-id\")?.length ?? 0) > 1_024\n\t\t) {\n\t\t\tthis.#cancelBody(response);\n\t\t\tthis.stop(\"response-too-large\");\n\t\t\tthrow new DetectionFailure(\"response-too-large\");\n\t\t}\n\t\tconst sessionId = response.headers.get(\"mcp-session-id\");\n\t\tif (sessionId !== null && !/^[\\x21-\\x7e]+$/.test(sessionId)) {\n\t\t\tthis.#cancelBody(response);\n\t\t\tthis.stop(\"invalid-response\");\n\t\t\tthrow new DetectionFailure(\"invalid-response\");\n\t\t}\n\t\treturn this.#bounded(response, signal);\n\t}\n\n\tcancel(response: Response): void {\n\t\tthis.#readers.get(response)?.();\n\t}\n\n\t#cancelBody(response: Response): void {\n\t\tif (response.body !== null) this.#cancellations.add(response.body.cancel().catch(() => {}));\n\t}\n\n\t#bounded(response: Response, signal: AbortSignal): Response {\n\t\tif (response.body === null) return response;\n\t\tconst reader = response.body.getReader();\n\t\tlet ended = false;\n\t\tlet wrapped: Response;\n\t\tlet controller: ReadableStreamDefaultController<Uint8Array>;\n\t\tconst detach = () => {\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t\tthis.#readers.delete(wrapped);\n\t\t};\n\t\tconst cancel = () => {\n\t\t\tif (ended) return;\n\t\t\tended = true;\n\t\t\tdetach();\n\t\t\tcontroller.close();\n\t\t\tthis.#cancellations.add(\n\t\t\t\treader\n\t\t\t\t\t.cancel()\n\t\t\t\t\t.catch(() => {})\n\t\t\t\t\t.finally(() => reader.releaseLock()),\n\t\t\t);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tif (ended) return;\n\t\t\tcontroller.error(new DetectionFailure(this.failure ?? \"invalid-response\"));\n\t\t\tended = true;\n\t\t\tdetach();\n\t\t\tthis.#cancellations.add(\n\t\t\t\treader\n\t\t\t\t\t.cancel()\n\t\t\t\t\t.catch(() => {})\n\t\t\t\t\t.finally(() => reader.releaseLock()),\n\t\t\t);\n\t\t};\n\t\tconst stream = new ReadableStream<Uint8Array>(\n\t\t\t{\n\t\t\t\tstart(value) {\n\t\t\t\t\tcontroller = value;\n\t\t\t\t},\n\t\t\t\tpull: async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst chunk = await reader.read();\n\t\t\t\t\t\tif (ended) return;\n\t\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\t\tended = true;\n\t\t\t\t\t\t\tdetach();\n\t\t\t\t\t\t\treader.releaseLock();\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.#bytes += chunk.value.byteLength;\n\t\t\t\t\t\tif (this.#bytes > this.maximum) {\n\t\t\t\t\t\t\tthis.stop(\"response-too-large\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk.value);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (!ended) this.stop(\"network-error\");\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcancel: () => {\n\t\t\t\t\tif (!ended) {\n\t\t\t\t\t\tended = true;\n\t\t\t\t\t\tdetach();\n\t\t\t\t\t\tthis.#cancellations.add(\n\t\t\t\t\t\t\treader\n\t\t\t\t\t\t\t\t.cancel()\n\t\t\t\t\t\t\t\t.catch(() => {})\n\t\t\t\t\t\t\t\t.finally(() => reader.releaseLock()),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ highWaterMark: 0 },\n\t\t);\n\t\twrapped = new Response(stream, { status: response.status, headers: response.headers });\n\t\tthis.#readers.set(wrapped, cancel);\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal.aborted) abort();\n\t\treturn wrapped;\n\t}\n\n\tasync close(\n\t\tclient: Client,\n\t\ttransport: StreamableHTTPClientTransport,\n\t\tendpoint: URL,\n\t): Promise<boolean> {\n\t\tconst cleanup = new AbortController();\n\t\tconst timer = setTimeout(() => cleanup.abort(), 1_000);\n\t\tconst signal = AbortSignal.any([this.input.signal, cleanup.signal]);\n\t\ttry {\n\t\t\tconst sessionId = transport.sessionId;\n\t\t\t// Close streams immediately, before waiting for session termination.\n\t\t\tthis.#controller.abort();\n\t\t\t// Initiate both closes even when the host signal is already aborted: during\n\t\t\t// negotiation the raw transport has not yet been attached to Client.\n\t\t\tawait withSignal(Promise.all([client.close(), transport.close()]), signal);\n\t\t\tif (sessionId !== undefined && /^[\\x21-\\x7e]{1,1024}$/.test(sessionId)) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tconst headers = new Headers({ \"mcp-session-id\": sessionId });\n\t\t\t\tif (transport.protocolVersion !== undefined)\n\t\t\t\t\theaders.set(\"mcp-protocol-version\", transport.protocolVersion);\n\t\t\t\tconst request = Promise.resolve(\n\t\t\t\t\tthis.input.fetch(endpoint, credentialFreeInit({ method: \"DELETE\", headers }, signal)),\n\t\t\t\t).then((response) => {\n\t\t\t\t\tthis.#cancelBody(response);\n\t\t\t\t\treturn response;\n\t\t\t\t});\n\t\t\t\tconst response = await withSignal(request, signal);\n\t\t\t\tif (\n\t\t\t\t\tresponse.redirected ||\n\t\t\t\t\t(response.url !== \"\" && response.url !== endpoint.href) ||\n\t\t\t\t\t(!response.ok && response.status !== 405)\n\t\t\t\t)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\tawait withSignal(Promise.all(this.#cancellations), signal);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t} finally {\n\t\t\tcleanup.abort();\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n}\n\nfunction credentialFreeInit(init: RequestInit | undefined, signal: AbortSignal): RequestInit {\n\tconst headers = new Headers(init?.headers);\n\tfor (const name of [\"authorization\", \"proxy-authorization\", \"cookie\"]) headers.delete(name);\n\treturn { ...init, headers, signal, credentials: \"omit\", redirect: \"error\", cache: \"no-store\" };\n}\n\nfunction outgoingMethod(body: unknown): string | undefined {\n\tif (typeof body !== \"string\") return undefined;\n\tconst value: unknown = JSON.parse(body);\n\treturn typeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"method\" in value &&\n\t\ttypeof value.method === \"string\"\n\t\t? value.method\n\t\t: undefined;\n}\n\nfunction boundedServerInfo(info: ReturnType<Client[\"getServerVersion\"]>) {\n\tif (info === undefined || info.name.length > 256 || info.version.length > 128) return undefined;\n\treturn Object.freeze({\n\t\tname: info.name,\n\t\tversion: info.version,\n\t\t...(info.title === undefined || info.title.length > 256 ? {} : { title: info.title }),\n\t});\n}\n\nfunction indeterminate(\n\treason: McpClientAuthenticationDetectionReason,\n\thttpStatus?: number,\n\tdiscoveryErrorCode?: McpClientOAuthBootstrapErrorCode,\n): McpClientAuthenticationDetectionResult {\n\treturn Object.freeze({\n\t\tkind: \"indeterminate\",\n\t\treason,\n\t\t...(httpStatus === undefined ? {} : { httpStatus }),\n\t\t...(discoveryErrorCode === undefined ? {} : { discoveryErrorCode }),\n\t});\n}\n\nfunction withSignal<Value>(promise: Promise<Value>, signal: AbortSignal): Promise<Value> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst aborted = () => reject(signal.reason);\n\t\tsignal.addEventListener(\"abort\", aborted, { once: true });\n\t\tif (signal.aborted) aborted();\n\t\tpromise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", aborted));\n\t});\n}\n"],"mappings":";;;;;;AAaA,MAAa,6CAA6C;CACzD,UAAU;CACV,cAAc;;CAEd,kBAAkB;CAClB,wBAAwB;AACzB;;AAwJA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