@mcp-use/client 2.2.3 → 2.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +1 -1
- package/dist/.tsbuildinfo +0 -1
- package/dist/auth/browser.d.ts +0 -218
- package/dist/auth/browser.d.ts.map +0 -1
- package/dist/auth/callback.d.ts +0 -9
- package/dist/auth/callback.d.ts.map +0 -1
- package/dist/auth/flow.d.ts +0 -32
- package/dist/auth/flow.d.ts.map +0 -1
- package/dist/auth/node.d.ts +0 -212
- package/dist/auth/node.d.ts.map +0 -1
- package/dist/auth/popup.d.ts +0 -67
- package/dist/auth/popup.d.ts.map +0 -1
- package/dist/auth/session-store.d.ts +0 -125
- package/dist/auth/session-store.d.ts.map +0 -1
- package/dist/auth/storage-file.d.ts +0 -18
- package/dist/auth/storage-file.d.ts.map +0 -1
- package/dist/auth/storage.d.ts +0 -34
- package/dist/auth/storage.d.ts.map +0 -1
- package/dist/auth/url.d.ts +0 -17
- package/dist/auth/url.d.ts.map +0 -1
- package/dist/code-mode/connector.d.ts +0 -27
- package/dist/code-mode/connector.d.ts.map +0 -1
- package/dist/code-mode/executor-e2b.d.ts +0 -46
- package/dist/code-mode/executor-e2b.d.ts.map +0 -1
- package/dist/code-mode/executor-vm.d.ts +0 -39
- package/dist/code-mode/executor-vm.d.ts.map +0 -1
- package/dist/code-mode/executor.d.ts +0 -81
- package/dist/code-mode/executor.d.ts.map +0 -1
- package/dist/core/base.d.ts +0 -423
- package/dist/core/base.d.ts.map +0 -1
- package/dist/core/browser.d.ts +0 -32
- package/dist/core/browser.d.ts.map +0 -1
- package/dist/core/config.d.ts +0 -225
- package/dist/core/config.d.ts.map +0 -1
- package/dist/core/node.d.ts +0 -437
- package/dist/core/node.d.ts.map +0 -1
- package/dist/core/session.d.ts +0 -792
- package/dist/core/session.d.ts.map +0 -1
- package/dist/core/skills.d.ts +0 -47
- package/dist/core/skills.d.ts.map +0 -1
- package/dist/index-browser.d.ts +0 -26
- package/dist/index-browser.d.ts.map +0 -1
- package/dist/index-browser.js +0 -4767
- package/dist/index-browser.js.map +0 -1
- package/dist/index.d.ts +0 -23
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -6105
- package/dist/index.js.map +0 -1
- package/dist/react/McpClientProvider.d.ts +0 -254
- package/dist/react/McpClientProvider.d.ts.map +0 -1
- package/dist/react/index.d.ts +0 -39
- package/dist/react/index.d.ts.map +0 -1
- package/dist/react/index.js +0 -9444
- package/dist/react/index.js.map +0 -1
- package/dist/react/rpc-logger.d.ts +0 -47
- package/dist/react/rpc-logger.d.ts.map +0 -1
- package/dist/react/storage.d.ts +0 -98
- package/dist/react/storage.d.ts.map +0 -1
- package/dist/react/token-expiry.d.ts +0 -9
- package/dist/react/token-expiry.d.ts.map +0 -1
- package/dist/react/types.d.ts +0 -727
- package/dist/react/types.d.ts.map +0 -1
- package/dist/react/useMcp-helpers.d.ts +0 -99
- package/dist/react/useMcp-helpers.d.ts.map +0 -1
- package/dist/react/useMcp-operations.d.ts +0 -180
- package/dist/react/useMcp-operations.d.ts.map +0 -1
- package/dist/react/useMcp.d.ts +0 -48
- package/dist/react/useMcp.d.ts.map +0 -1
- package/dist/react/useMcpServerQueues.d.ts +0 -403
- package/dist/react/useMcpServerQueues.d.ts.map +0 -1
- package/dist/react/view/ViewRenderer.d.ts +0 -20
- package/dist/react/view/ViewRenderer.d.ts.map +0 -1
- package/dist/react/view/ext-apps-bridge.d.ts +0 -3
- package/dist/react/view/ext-apps-bridge.d.ts.map +0 -1
- package/dist/react/view/initialized-sync.d.ts +0 -13
- package/dist/react/view/initialized-sync.d.ts.map +0 -1
- package/dist/react/view/inject-openai-file-apis.d.ts +0 -9
- package/dist/react/view/inject-openai-file-apis.d.ts.map +0 -1
- package/dist/react/view/parse-custom-props.d.ts +0 -10
- package/dist/react/view/parse-custom-props.d.ts.map +0 -1
- package/dist/react/view/resolve-view-resource.d.ts +0 -22
- package/dist/react/view/resolve-view-resource.d.ts.map +0 -1
- package/dist/react/view/sandbox-blob-url.d.ts +0 -27
- package/dist/react/view/sandbox-blob-url.d.ts.map +0 -1
- package/dist/react/view/types.d.ts +0 -220
- package/dist/react/view/types.d.ts.map +0 -1
- package/dist/react/view/use-display-mode.d.ts +0 -19
- package/dist/react/view/use-display-mode.d.ts.map +0 -1
- package/dist/react/view/view-detection.d.ts +0 -22
- package/dist/react/view/view-detection.d.ts.map +0 -1
- package/dist/react/view/view-host-policy.d.ts +0 -61
- package/dist/react/view/view-host-policy.d.ts.map +0 -1
- package/dist/sandbox.d.ts +0 -2
- package/dist/sandbox.d.ts.map +0 -1
- package/dist/sandbox.js +0 -288
- package/dist/sandbox.js.map +0 -1
- package/dist/telemetry/client-telemetry.d.ts +0 -13
- package/dist/telemetry/client-telemetry.d.ts.map +0 -1
- package/dist/telemetry/configure-browser.d.ts +0 -2
- package/dist/telemetry/configure-browser.d.ts.map +0 -1
- package/dist/telemetry/configure-node.d.ts +0 -2
- package/dist/telemetry/configure-node.d.ts.map +0 -1
- package/dist/telemetry/connector-telemetry.d.ts +0 -8
- package/dist/telemetry/connector-telemetry.d.ts.map +0 -1
- package/dist/telemetry/events.d.ts +0 -91
- package/dist/telemetry/events.d.ts.map +0 -1
- package/dist/telemetry/index.d.ts +0 -3
- package/dist/telemetry/index.d.ts.map +0 -1
- package/dist/telemetry/tel-fetch.d.ts +0 -19
- package/dist/telemetry/tel-fetch.d.ts.map +0 -1
- package/dist/telemetry/telemetry-browser.d.ts +0 -6
- package/dist/telemetry/telemetry-browser.d.ts.map +0 -1
- package/dist/telemetry/telemetry-node.d.ts +0 -8
- package/dist/telemetry/telemetry-node.d.ts.map +0 -1
- package/dist/telemetry/telemetry.d.ts +0 -75
- package/dist/telemetry/telemetry.d.ts.map +0 -1
- package/dist/transport/base.d.ts +0 -656
- package/dist/transport/base.d.ts.map +0 -1
- package/dist/transport/connection-manager.d.ts +0 -59
- package/dist/transport/connection-manager.d.ts.map +0 -1
- package/dist/transport/http.d.ts +0 -137
- package/dist/transport/http.d.ts.map +0 -1
- package/dist/transport/stdio.d.ts +0 -97
- package/dist/transport/stdio.d.ts.map +0 -1
- package/dist/utils/elicitation.d.ts +0 -54
- package/dist/utils/elicitation.d.ts.map +0 -1
- package/dist/utils/favicon.d.ts +0 -6
- package/dist/utils/favicon.d.ts.map +0 -1
- package/dist/utils/json-schema-validator.d.ts +0 -13
- package/dist/utils/json-schema-validator.d.ts.map +0 -1
- package/dist/utils/logging.d.ts +0 -33
- package/dist/utils/logging.d.ts.map +0 -1
- package/dist/utils/version.d.ts +0 -9
- package/dist/utils/version.d.ts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/telemetry/client-telemetry.ts","../src/telemetry/connector-telemetry.ts","../src/utils/logging.ts","../src/utils/version.ts","../src/telemetry/events.ts","../src/telemetry/tel-fetch.ts","../src/telemetry/telemetry.ts","../src/telemetry/configure-browser.ts","../src/auth/browser.ts","../src/auth/storage.ts","../src/auth/session-store.ts","../src/auth/url.ts","../src/auth/callback.ts","../src/auth/popup.ts","../src/auth/flow.ts","../src/index-browser.ts","../src/transport/http.ts","../src/utils/json-schema-validator.ts","../src/transport/base.ts","../src/core/config.ts","../src/core/skills.ts","../src/core/session.ts","../src/core/base.ts","../src/core/browser.ts","../src/utils/favicon.ts"],"sourcesContent":["import type { ServerConfig } from \"../core/config.js\";\n\ninterface ClientTelemetryTracker {\n addServer(name: string, config: ServerConfig): Promise<void> | void;\n removeServer(name: string): Promise<void> | void;\n}\n\nlet tracker: ClientTelemetryTracker | undefined;\n\n/** @internal Configures the runtime-specific client telemetry sink. */\nexport function setClientTelemetryTracker(\n nextTracker: ClientTelemetryTracker | undefined\n): void {\n tracker = nextTracker;\n}\n\n/** @internal Records that a configured server was added. */\nexport function trackClientAddServer(name: string, config: ServerConfig): void {\n void tracker?.addServer(name, config);\n}\n\n/** @internal Records that a configured server was removed. */\nexport function trackClientRemoveServer(name: string): void {\n void tracker?.removeServer(name);\n}\n","import type { ConnectorInitEventData } from \"./events.js\";\n\ntype ConnectorTracker = (data: ConnectorInitEventData) => Promise<void> | void;\n\nlet tracker: ConnectorTracker | undefined;\n\n/** @internal Configures the runtime-specific connector telemetry sink. */\nexport function setConnectorTelemetryTracker(\n nextTracker: ConnectorTracker | undefined\n): void {\n tracker = nextTracker;\n}\n\n/** @internal Sends connector telemetry when the active runtime configured it. */\nexport function trackConnectorTelemetry(data: ConnectorInitEventData): void {\n void tracker?.(data);\n}\n","export type LogLevel =\n | \"silent\"\n | \"error\"\n | \"warn\"\n | \"info\"\n | \"http\"\n | \"verbose\"\n | \"debug\"\n | \"silly\";\n\ntype LogFormat = \"minimal\" | \"detailed\" | \"emoji\";\n\nconst LEVELS = [\n \"silent\",\n \"error\",\n \"warn\",\n \"info\",\n \"http\",\n \"verbose\",\n \"debug\",\n \"silly\",\n] as const satisfies readonly LogLevel[];\n\nconst EMOJI: Record<LogLevel, string> = {\n silent: \"\",\n error: \"❌\",\n warn: \"⚠️\",\n info: \"ℹ️\",\n http: \"🌐\",\n verbose: \"📝\",\n debug: \"🔍\",\n silly: \"🤪\",\n};\n\nfunction envLevel(): LogLevel {\n let raw: string | undefined;\n try {\n raw =\n typeof process !== \"undefined\"\n ? (process.env?.MCP_USE_LOG_LEVEL ?? process.env?.DEBUG)\n : undefined;\n } catch {\n // Deno may deny env access.\n }\n const v = raw?.trim().toLowerCase();\n if (v === \"2\") return \"debug\";\n if (v && (LEVELS as readonly string[]).includes(v)) return v as LogLevel;\n return \"info\";\n}\n\nclass SimpleConsoleLogger {\n constructor(\n private name = \"mcp-use\",\n public level: LogLevel = \"info\",\n public format: LogFormat = \"minimal\"\n ) {}\n\n private write(level: LogLevel, message: string, args: unknown[]): void {\n if (\n this.level === \"silent\" ||\n LEVELS.indexOf(level) > LEVELS.indexOf(this.level)\n ) {\n return;\n }\n const extra = args\n .map((a) => {\n if (typeof a === \"string\") return a;\n try {\n return JSON.stringify(a);\n } catch {\n return String(a);\n }\n })\n .join(\" \");\n const full = extra ? `${message} ${extra}` : message;\n const ts = new Date().toLocaleTimeString(\"en-US\", { hour12: false });\n const label = this.format === \"minimal\" ? level : level.toUpperCase();\n const emoji = this.format === \"emoji\" ? ` ${EMOJI[level]}` : \"\";\n const line = `${ts} [${this.name}]${emoji} ${label}: ${full}`;\n const fn =\n level === \"error\"\n ? console.error\n : level === \"warn\"\n ? console.warn\n : level === \"info\"\n ? console.info\n : level === \"debug\"\n ? console.debug\n : console.log;\n fn(line);\n }\n\n error = (m: string, ...a: unknown[]) => this.write(\"error\", m, a);\n warn = (m: string, ...a: unknown[]) => this.write(\"warn\", m, a);\n info = (m: string, ...a: unknown[]) => this.write(\"info\", m, a);\n debug = (m: string, ...a: unknown[]) => this.write(\"debug\", m, a);\n http = (m: string, ...a: unknown[]) => this.write(\"http\", m, a);\n verbose = (m: string, ...a: unknown[]) => this.write(\"verbose\", m, a);\n silly = (m: string, ...a: unknown[]) => this.write(\"silly\", m, a);\n\n setFormat(format: LogFormat): void {\n this.format = format;\n }\n}\n\nexport class Logger {\n private static instances: Record<string, SimpleConsoleLogger> = {};\n private static currentFormat: LogFormat = \"minimal\";\n private static currentLevel: LogLevel | undefined;\n\n static get(name = \"mcp-use\"): SimpleConsoleLogger {\n return (this.instances[name] ??= new SimpleConsoleLogger(\n name,\n this.currentLevel ?? envLevel(),\n this.currentFormat\n ));\n }\n\n static configure({\n level = envLevel(),\n format = \"minimal\",\n }: { level?: LogLevel; format?: LogFormat } = {}): void {\n this.currentLevel = level;\n this.currentFormat = format;\n for (const log of Object.values(this.instances)) {\n log.level = level;\n log.format = format;\n }\n }\n\n static setDebug(enabled: boolean | 0 | 1 | 2): void {\n const level: LogLevel =\n enabled === 2 || enabled === true ? \"debug\" : \"info\";\n this.currentLevel = level;\n for (const log of Object.values(this.instances)) log.level = level;\n try {\n if (typeof process !== \"undefined\" && process.env) {\n process.env.MCP_USE_LOG_LEVEL = level;\n }\n } catch {\n // optional\n }\n }\n\n static setFormat(format: LogFormat): void {\n this.configure({ format });\n }\n}\n\n/** Default package logger used by client and connector operations. */\nexport const logger = Logger.get();\n","declare const __MCP_USE_PACKAGE_VERSION__: string;\n\n/** Installed `@mcp-use/client` package version. */\nexport const VERSION = __MCP_USE_PACKAGE_VERSION__;\n\n/**\n * Returns the installed `@mcp-use/client` package version.\n *\n * @returns Package version string.\n */\nexport function getPackageVersion(): string {\n return VERSION;\n}\n","export abstract class BaseTelemetryEvent {\n abstract get name(): string;\n abstract get properties(): Record<string, any>;\n}\n\n// ============================================================================\n// MCPAgentExecutionEvent\n// ============================================================================\n\nexport interface MCPAgentExecutionEventData {\n // Execution method and context\n executionMethod: string; // \"run\" or \"astream\"\n query: string; // The actual user query\n success: boolean;\n\n // Agent configuration\n modelProvider: string;\n modelName: string;\n serverCount: number;\n serverIdentifiers: Array<Record<string, string>>;\n totalToolsAvailable: number;\n toolsAvailableNames: string[];\n maxStepsConfigured: number;\n memoryEnabled: boolean;\n useServerManager: boolean;\n\n // Execution PARAMETERS\n maxStepsUsed: number | null;\n manageConnector: boolean;\n externalHistoryUsed: boolean;\n\n // Execution results\n stepsTaken?: number | null;\n toolsUsedCount?: number | null;\n toolsUsedNames?: string[] | null;\n response?: string | null; // The actual response\n executionTimeMs?: number | null;\n errorType?: string | null;\n\n // Context\n conversationHistoryLength?: number | null;\n}\n\nexport class MCPAgentExecutionEvent extends BaseTelemetryEvent {\n constructor(private data: MCPAgentExecutionEventData) {\n super();\n }\n\n get name(): string {\n return \"mcp_agent_execution\";\n }\n\n get properties(): Record<string, any> {\n return {\n // Core execution info\n execution_method: this.data.executionMethod,\n query_length: this.data.query.length,\n success: this.data.success,\n // Agent configuration\n model_provider: this.data.modelProvider,\n model_name: this.data.modelName,\n server_count: this.data.serverCount,\n total_tools_available: this.data.totalToolsAvailable,\n max_steps_configured: this.data.maxStepsConfigured,\n memory_enabled: this.data.memoryEnabled,\n use_server_manager: this.data.useServerManager,\n // Execution parameters (always include, even if null)\n max_steps_used: this.data.maxStepsUsed,\n manage_connector: this.data.manageConnector,\n external_history_used: this.data.externalHistoryUsed,\n // Execution results (always include, even if null)\n steps_taken: this.data.stepsTaken ?? null,\n tools_used_count: this.data.toolsUsedCount ?? null,\n response_length: this.data.response ? this.data.response.length : null,\n execution_time_ms: this.data.executionTimeMs ?? null,\n error_type: this.data.errorType ?? null,\n conversation_history_length: this.data.conversationHistoryLength ?? null,\n };\n }\n}\n\n// ============================================================================\n// MCPClientInitEvent\n// ============================================================================\n\nexport interface MCPClientInitEventData {\n codeMode: boolean;\n sandbox: boolean;\n allCallbacks: boolean;\n verify: boolean;\n servers: string[];\n numServers: number;\n isBrowser: boolean; // true for BrowserMCPClient, false for Node.js MCPClient\n}\n\nexport class MCPClientInitEvent extends BaseTelemetryEvent {\n constructor(private data: MCPClientInitEventData) {\n super();\n }\n\n get name(): string {\n return \"mcpclient_init\";\n }\n\n get properties(): Record<string, any> {\n return {\n code_mode: this.data.codeMode,\n sandbox: this.data.sandbox,\n all_callbacks: this.data.allCallbacks,\n verify: this.data.verify,\n servers: this.data.servers,\n num_servers: this.data.numServers,\n is_browser: this.data.isBrowser,\n };\n }\n}\n\n// ============================================================================\n// ConnectorInitEvent\n// ============================================================================\n\nexport interface ConnectorInitEventData {\n connectorType: string;\n serverCommand?: string | null;\n serverArgs?: string[] | null;\n serverUrl?: string | null;\n publicIdentifier?: string | null;\n}\n\nexport class ConnectorInitEvent extends BaseTelemetryEvent {\n constructor(private data: ConnectorInitEventData) {\n super();\n }\n\n get name(): string {\n return \"connector_init\";\n }\n\n get properties(): Record<string, any> {\n return {\n connector_type: this.data.connectorType,\n server_command: this.data.serverCommand ?? null,\n server_args: this.data.serverArgs ?? null,\n server_url: this.data.serverUrl ?? null,\n public_identifier: this.data.publicIdentifier ?? null,\n };\n }\n}\n\n// ============================================================================\n// ClientAddServerEvent\n// ============================================================================\n\n/**\n * Raw input data for tracking server addition.\n * The event class will extract the necessary properties.\n */\ninterface ClientAddServerEventInput {\n serverName: string;\n serverConfig: Record<string, any>;\n}\n\nexport class ClientAddServerEvent extends BaseTelemetryEvent {\n constructor(private data: ClientAddServerEventInput) {\n super();\n }\n\n get name(): string {\n return \"client_add_server\";\n }\n\n get properties(): Record<string, any> {\n const { serverName, serverConfig } = this.data;\n const url = serverConfig.url;\n\n return {\n server_name: serverName,\n server_url_domain: url ? this._extractHostname(url) : null,\n transport: serverConfig.transport ?? null,\n has_auth: !!(serverConfig.authToken || serverConfig.authProvider),\n };\n }\n\n private _extractHostname(url: string): string | null {\n try {\n return new URL(url).hostname;\n } catch {\n return null;\n }\n }\n}\n\n// ============================================================================\n// ClientRemoveServerEvent\n// ============================================================================\n\n/**\n * Raw input data for tracking server removal.\n */\ninterface ClientRemoveServerEventInput {\n serverName: string;\n}\n\nexport class ClientRemoveServerEvent extends BaseTelemetryEvent {\n constructor(private data: ClientRemoveServerEventInput) {\n super();\n }\n\n get name(): string {\n return \"client_remove_server\";\n }\n\n get properties(): Record<string, any> {\n return {\n server_name: this.data.serverName,\n };\n }\n}\n","/**\n * Fire-and-forget telemetry HTTP request. Never surfaces network/HTTP failures\n * to the host app — telemetry must not log or throw into user code.\n */\nexport async function telFetch(url: string, init?: RequestInit): Promise<void> {\n try {\n await fetch(url, init);\n } catch {\n // Telemetry must never break or log into the host app.\n }\n}\n\nexport const POSTHOG_HOST = \"https://eu.i.posthog.com\";\nexport const POSTHOG_API_KEY =\n \"phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI\";\n\nconst CONTENT_PROPERTY =\n /(^|_)(arguments?|args|body|command|headers?|location|message|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i;\nconst IDENTIFYING_PROPERTY =\n /(^|_)(server_identifiers?|server_names?|servers|tool_names?|tools_(available|used)_names)(_|$)/i;\nconst AGGREGATE_PROPERTY =\n /(_count|_length|_duration(?:_ms)?|_time_ms|(^|_)num_[a-z0-9_]+)$/i;\n\nfunction normalizePropertyKey(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[^a-z0-9_$]+/gi, \"_\")\n .toLowerCase();\n}\n\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n throw new TypeError(\"Cyclic telemetry properties are not supported\");\n }\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n if (\n value !== null &&\n typeof value === \"object\" &&\n (Object.getPrototypeOf(value) === Object.prototype ||\n Object.getPrototypeOf(value) === null)\n ) {\n if (seen.has(value)) {\n throw new TypeError(\"Cyclic telemetry properties are not supported\");\n }\n seen.add(value);\n const sanitized = sanitizeProperties(\n value as Record<string, unknown>,\n seen\n );\n seen.delete(value);\n return sanitized;\n }\n\n return value;\n}\n\nfunction sanitizeProperties(\n properties: Record<string, unknown>,\n seen = new WeakSet<object>()\n): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(properties)) {\n const normalizedKey = normalizePropertyKey(key);\n if (AGGREGATE_PROPERTY.test(normalizedKey)) {\n if (value === null || typeof value === \"number\") {\n sanitized[key] = value;\n }\n continue;\n }\n if (\n IDENTIFYING_PROPERTY.test(normalizedKey) ||\n CONTENT_PROPERTY.test(normalizedKey)\n ) {\n continue;\n }\n sanitized[key] = sanitizeValue(value, seen);\n }\n return sanitized;\n}\n\n/**\n * Send a single event to PostHog's public capture endpoint using `fetch` only\n * (no `posthog-js` / `posthog-node` SDK dependency). Errors are swallowed.\n */\nexport async function capturePostHog(params: {\n host?: string;\n apiKey?: string;\n event: string;\n distinctId: string;\n properties: Record<string, unknown>;\n}): Promise<void> {\n try {\n const host = params.host ?? POSTHOG_HOST;\n const apiKey = params.apiKey ?? POSTHOG_API_KEY;\n const body = JSON.stringify({\n api_key: apiKey,\n event: params.event,\n distinct_id: params.distinctId,\n properties: sanitizeProperties(params.properties),\n timestamp: new Date().toISOString(),\n });\n await telFetch(`${host}/i/v0/e/`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n body,\n });\n } catch {\n // Invalid telemetry data must never surface into host application code.\n }\n}\n","/**\n * Cross-compatible telemetry: PostHog via fetch, Web Crypto, feature-detected\n * opt-out. Optional {@link TelemetryStorage} (fs from node entry, localStorage\n * when available) for durable user ids.\n */\nimport { logger } from \"../utils/logging.js\";\nimport { getPackageVersion } from \"../utils/version.js\";\nimport type {\n BaseTelemetryEvent,\n ConnectorInitEventData,\n MCPAgentExecutionEventData,\n MCPClientInitEventData,\n} from \"./events.js\";\nimport {\n ClientAddServerEvent,\n ClientRemoveServerEvent,\n ConnectorInitEvent,\n MCPAgentExecutionEvent,\n MCPClientInitEvent,\n} from \"./events.js\";\nimport { capturePostHog } from \"./tel-fetch.js\";\n\nfunction generateUUID(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction secureRandomString(): string {\n const array = new Uint8Array(8);\n globalThis.crypto.getRandomValues(array);\n return Array.from(array, (v) => v.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport type TelemetryStorage = {\n getUserId(): string | null;\n setUserId(id: string): void;\n};\n\ntype RuntimeEnvironment =\n | \"browser\"\n | \"node\"\n | \"cloudflare-workers\"\n | \"edge\"\n | \"deno\"\n | \"bun\"\n | \"unknown\";\n\ntype StorageCapability = \"persistent\" | \"session-only\";\n\nconst USER_ID_STORAGE_KEY = \"mcp_use_user_id\";\nconst PROJECT_API_KEY = \"phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI\";\nconst HOST = \"https://eu.i.posthog.com\";\n\n/** Install before first `getInstance()` — node entry wires fs storage here. */\nlet configuredStorage: TelemetryStorage | null = null;\n\nexport function configureTelemetryStorage(storage: TelemetryStorage): void {\n configuredStorage = storage;\n}\n\nfunction isLocalStorageFunctional(): boolean {\n return (\n typeof localStorage !== \"undefined\" &&\n typeof localStorage.getItem === \"function\" &&\n typeof localStorage.setItem === \"function\" &&\n typeof localStorage.removeItem === \"function\"\n );\n}\n\nfunction createLocalStorageBackend(): TelemetryStorage | null {\n if (!isLocalStorageFunctional()) return null;\n try {\n localStorage.setItem(\"__mcp_use_test__\", \"1\");\n localStorage.removeItem(\"__mcp_use_test__\");\n } catch {\n return null;\n }\n return {\n getUserId() {\n try {\n return localStorage.getItem(USER_ID_STORAGE_KEY);\n } catch {\n return null;\n }\n },\n setUserId(id: string) {\n try {\n localStorage.setItem(USER_ID_STORAGE_KEY, id);\n } catch {\n // ignore\n }\n },\n };\n}\n\nfunction detectRuntimeEnvironment(): RuntimeEnvironment {\n try {\n if (typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\") {\n return \"bun\";\n }\n if (typeof (globalThis as { Deno?: unknown }).Deno !== \"undefined\") {\n return \"deno\";\n }\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent?.includes(\"Cloudflare-Workers\")\n ) {\n return \"cloudflare-workers\";\n }\n if (\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime !==\n \"undefined\"\n ) {\n return \"edge\";\n }\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n return \"browser\";\n }\n if (\n typeof process !== \"undefined\" &&\n typeof process.versions?.node !== \"undefined\"\n ) {\n return \"node\";\n }\n return \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction readSourceHint(): string | undefined {\n if (typeof process !== \"undefined\" && process.env?.MCP_USE_TELEMETRY_SOURCE) {\n return process.env.MCP_USE_TELEMETRY_SOURCE;\n }\n try {\n if (isLocalStorageFunctional()) {\n return localStorage.getItem(\"MCP_USE_TELEMETRY_SOURCE\") ?? undefined;\n }\n } catch {\n // ignore\n }\n return undefined;\n}\n\nfunction isTelemetryDisabled(): boolean {\n if (\n typeof window !== \"undefined\" &&\n (window as unknown as { __MCP_USE_ANONYMIZED_TELEMETRY__?: boolean })\n .__MCP_USE_ANONYMIZED_TELEMETRY__ === false\n ) {\n return true;\n }\n if (\n typeof process !== \"undefined\" &&\n process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === \"false\"\n ) {\n return true;\n }\n try {\n if (\n isLocalStorageFunctional() &&\n localStorage.getItem(\"MCP_USE_ANONYMIZED_TELEMETRY\") === \"false\"\n ) {\n return true;\n }\n } catch {\n // ignore\n }\n return false;\n}\n\nfunction sessionId(): string {\n try {\n return `session-${generateUUID()}`;\n } catch {\n return `session-${Date.now()}-${secureRandomString()}`;\n }\n}\n\n/**\n * Shared telemetry singleton for node and browser.\n *\n * Usage: `Tel.getInstance().trackMCPClientInit(...)`\n */\nexport class Telemetry {\n private static instance: Telemetry | null = null;\n\n private readonly UNKNOWN_USER_ID = \"UNKNOWN_USER_ID\";\n\n private _currUserId: string | null = null;\n private _telemetryEnabled = false;\n private _pending = new Set<Promise<void>>();\n private _runtimeEnvironment: RuntimeEnvironment;\n private _storageCapability: StorageCapability;\n private _storage: TelemetryStorage | null;\n private _source: string;\n private _productVersion?: string;\n\n private constructor() {\n this._runtimeEnvironment = detectRuntimeEnvironment();\n this._storage = configuredStorage ?? createLocalStorageBackend() ?? null;\n this._storageCapability = this._storage ? \"persistent\" : \"session-only\";\n this._source = readSourceHint() || this._runtimeEnvironment;\n\n const disabled = isTelemetryDisabled();\n const canSupport = this._runtimeEnvironment !== \"unknown\";\n\n if (disabled) {\n this._telemetryEnabled = false;\n logger.debug(\"Telemetry disabled via opt-out\");\n } else if (!canSupport) {\n this._telemetryEnabled = false;\n logger.debug(\n `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`\n );\n } else {\n logger.debug(\n \"Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.\"\n );\n this._telemetryEnabled = true;\n }\n }\n\n get runtimeEnvironment(): RuntimeEnvironment {\n return this._runtimeEnvironment;\n }\n\n get storageCapability(): StorageCapability {\n return this._storageCapability;\n }\n\n static getInstance(): Telemetry {\n if (!Telemetry.instance) {\n Telemetry.instance = new Telemetry();\n }\n return Telemetry.instance;\n }\n\n setSource(source: string): void {\n this._source = source;\n try {\n if (isLocalStorageFunctional()) {\n localStorage.setItem(\"MCP_USE_TELEMETRY_SOURCE\", source);\n }\n } catch {\n // ignore\n }\n logger.debug(`Telemetry source set to: ${source}`);\n }\n\n getSource(): string {\n return this._source;\n }\n\n setProductVersion(version: string): void {\n this._productVersion = version;\n }\n\n get isEnabled(): boolean {\n return this._telemetryEnabled;\n }\n\n get userId(): string {\n if (this._currUserId) return this._currUserId;\n\n try {\n if (this._storage) {\n const existing = this._storage.getUserId();\n if (existing) {\n this._currUserId = existing;\n return existing;\n }\n const id = generateUUID();\n this._storage.setUserId(id);\n this._currUserId = id;\n return id;\n }\n this._currUserId = sessionId();\n } catch {\n this._currUserId = this.UNKNOWN_USER_ID;\n }\n return this._currUserId;\n }\n\n async capture(event: BaseTelemetryEvent): Promise<void> {\n if (!this._telemetryEnabled) return;\n\n const currentUserId = this.userId;\n const properties: Record<string, unknown> = {\n ...event.properties,\n mcp_use_version: this._productVersion ?? getPackageVersion(),\n language: \"typescript\",\n source: this._source,\n runtime: this._runtimeEnvironment,\n };\n\n const p = capturePostHog({\n host: HOST,\n apiKey: PROJECT_API_KEY,\n event: event.name,\n distinctId: currentUserId,\n properties,\n });\n this._pending.add(p);\n void p.finally(() => this._pending.delete(p));\n }\n\n async trackAgentExecution(data: MCPAgentExecutionEventData): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture(new MCPAgentExecutionEvent(data));\n }\n\n async trackMCPClientInit(data: MCPClientInitEventData): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture(new MCPClientInitEvent(data));\n }\n\n async trackConnectorInit(data: ConnectorInitEventData): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture(new ConnectorInitEvent(data));\n }\n\n async trackClientAddServer(\n serverName: string,\n serverConfig: Record<string, any>\n ): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture(new ClientAddServerEvent({ serverName, serverConfig }));\n }\n\n async trackClientRemoveServer(serverName: string): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture(new ClientRemoveServerEvent({ serverName }));\n }\n\n async trackUseMcpConnection(data: {\n url: string;\n transportType: string;\n success: boolean;\n errorType?: string | null;\n connectionTimeMs?: number | null;\n hasOAuth: boolean;\n hasSampling: boolean;\n hasElicitation: boolean;\n }): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture({\n name: \"usemcp_connection\",\n properties: {\n url_domain: new URL(data.url).hostname,\n transport_type: data.transportType,\n success: data.success,\n error_type: data.errorType ?? null,\n connection_time_ms: data.connectionTimeMs ?? null,\n has_oauth: data.hasOAuth,\n has_sampling: data.hasSampling,\n has_elicitation: data.hasElicitation,\n },\n });\n }\n\n async trackUseMcpToolCall(data: {\n toolName: string;\n success: boolean;\n errorType?: string | null;\n executionTimeMs?: number | null;\n }): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture({\n name: \"usemcp_tool_call\",\n properties: {\n tool_name: data.toolName,\n success: data.success,\n error_type: data.errorType ?? null,\n execution_time_ms: data.executionTimeMs ?? null,\n },\n });\n }\n\n async trackUseMcpResourceRead(data: {\n resourceUri: string;\n success: boolean;\n errorType?: string | null;\n }): Promise<void> {\n if (!this.isEnabled) return;\n await this.capture({\n name: \"usemcp_resource_read\",\n properties: {\n resource_uri_scheme: data.resourceUri.split(\":\")[0],\n success: data.success,\n error_type: data.errorType ?? null,\n },\n });\n }\n\n identify(userId: string, properties?: Record<string, unknown>): void {\n this._currUserId = userId;\n this._storage?.setUserId(userId);\n if (this._telemetryEnabled) {\n void capturePostHog({\n host: HOST,\n apiKey: PROJECT_API_KEY,\n event: \"$identify\",\n distinctId: userId,\n properties: { $set: properties ?? {} },\n });\n }\n }\n\n reset(): void {\n this._currUserId = null;\n }\n\n flush(): void {\n void Promise.allSettled([...this._pending]);\n }\n\n async shutdown(): Promise<void> {\n try {\n await Promise.allSettled([...this._pending]);\n logger.debug(\"Telemetry fetch captures flushed\");\n } catch (e) {\n logger.debug(`Error flushing telemetry captures: ${e}`);\n }\n }\n}\n\n/**\n * Backward-compatible name for {@link Telemetry}.\n *\n * @alias\n */\nexport const Tel = Telemetry;\n\nexport function setTelemetrySource(source: string): void {\n Tel.getInstance().setSource(source);\n}\n\nexport function setProductVersion(version: string): void {\n Tel.getInstance().setProductVersion(version);\n}\n","import { setClientTelemetryTracker } from \"./client-telemetry.js\";\nimport { setConnectorTelemetryTracker } from \"./connector-telemetry.js\";\nimport { Telemetry } from \"./telemetry-browser.js\";\n\nsetClientTelemetryTracker({\n addServer: (name, config) =>\n Telemetry.getInstance()\n .trackClientAddServer(name, config)\n .catch(() => undefined),\n removeServer: (name) =>\n Telemetry.getInstance()\n .trackClientRemoveServer(name)\n .catch(() => undefined),\n});\n\nsetConnectorTelemetryTracker((data) =>\n Telemetry.getInstance()\n .trackConnectorInit(data)\n .catch(() => undefined)\n);\n","// browser-provider.ts\nimport {\n extractWWWAuthenticateParams,\n type OAuthClientInformation,\n type OAuthClientInformationContext,\n type OAuthClientMetadata,\n type OAuthClientProvider,\n type OAuthDiscoveryState,\n type OAuthTokens,\n} from \"@modelcontextprotocol/client\";\nimport { LocalStorageKVStore } from \"./storage.js\";\nimport { OAuthSessionStore } from \"./session-store.js\";\n\n/**\n * Serialize request body for proxying\n */\nasync function serializeBody(body: BodyInit): Promise<any> {\n if (typeof body === \"string\") return body;\n if (body instanceof URLSearchParams || body instanceof FormData) {\n return Object.fromEntries(body.entries());\n }\n if (body instanceof Blob) return await body.text();\n return body;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) {\n end--;\n }\n return value.slice(0, end);\n}\n\n/** Options for the browser implementation of the SDK `OAuthClientProvider`. */\nexport interface BrowserOAuthOptions {\n /** Prefix used for persisted OAuth keys. */\n storageKeyPrefix?: string;\n /** Human-readable OAuth client name. */\n clientName?: string;\n /** Public website describing the OAuth client. */\n clientUri?: string;\n /** Public OAuth client logo URL. */\n logoUri?: string;\n /** OAuth redirect URI. */\n callbackUrl?: string;\n /** Whether initial connection waits for an explicit authentication action. */\n preventAutoAuth?: boolean;\n /** Whether authorization uses a full-page redirect instead of a popup. */\n useRedirectFlow?: boolean;\n /** Same-origin proxy endpoint for OAuth HTTP requests. */\n oauthProxyUrl?: string;\n /** MCP proxy URL the transport connected to, used to re-anchor discovery. */\n connectionUrl?: string;\n /** HTTPS URL serving this public client's metadata document for CIMD. */\n clientMetadataUrl?: string;\n /**\n * When true (default), OAuth requests (.well-known metadata, token,\n * registration, revocation, and introspection) are routed through\n * `oauthProxyUrl` to bypass CORS.\n * The routing is applied only to the scoped fetch returned by\n * {@link BrowserOAuthClientProvider.getProxyFetch}; it never mutates the\n * global `fetch`. Set to false to connect directly even when an OAuth proxy\n * URL is available (e.g. when the MCP gateway already proxies OAuth).\n */\n proxyOAuthRequests?: boolean;\n /**\n * Pre-registered OAuth client information. When set, the SDK skips\n * Dynamic Client Registration and uses this client_id directly.\n * Required for proxy-mode auth servers (e.g. Slack, WorkOS proxy)\n * that strip `registration_endpoint` from metadata.\n */\n staticClientInfo?: OAuthClientInformation;\n /** OAuth scope string forwarded to the SDK via clientMetadata.scope. */\n scope?: string;\n /** Called immediately before the provider opens an authorization popup. */\n onPopupWindow?: (\n url: string,\n features: string,\n window: globalThis.Window | null\n ) => void;\n}\n\n/**\n * Browser-compatible OAuth client provider for MCP using localStorage.\n */\nexport class BrowserOAuthClientProvider implements OAuthClientProvider {\n /** Protected MCP server URL associated with this provider. */\n readonly serverUrl: string;\n /** Pre-registered public client information, when configured. */\n readonly staticClientInfo?: OAuthClientInformation;\n private session: OAuthSessionStore;\n private readonly storage: LocalStorageKVStore;\n\n // Browser-only state\n /** Whether initial connection waits for explicit authentication. */\n readonly preventAutoAuth?: boolean;\n private useRedirectFlow?: boolean;\n private oauthProxyUrl?: string;\n private connectionUrl?: string;\n private proxyOAuthRequests: boolean;\n private lastAttemptedAuthUrl: string | null = null;\n private authorizationPending = false;\n /** Latest protected-resource metadata URL advertised by an MCP 401. */\n private challengedResourceMetadataUrl: string | undefined;\n /** Callback invoked immediately before an authorization popup opens. */\n readonly onPopupWindow:\n | ((\n url: string,\n features: string,\n window: globalThis.Window | null\n ) => void)\n | undefined;\n\n constructor(serverUrl: string, options: BrowserOAuthOptions = {}) {\n if (options.staticClientInfo?.client_secret) {\n throw new Error(\n \"Browser OAuth clients must be public clients; staticClientInfo.client_secret is not allowed.\"\n );\n }\n this.serverUrl = serverUrl;\n this.storage = new LocalStorageKVStore();\n this.session = new OAuthSessionStore(\n serverUrl,\n { ...options, allowClientSecret: false },\n this.storage\n );\n this.preventAutoAuth = options.preventAutoAuth;\n this.useRedirectFlow = options.useRedirectFlow;\n this.oauthProxyUrl = options.oauthProxyUrl;\n this.connectionUrl = options.connectionUrl;\n this.proxyOAuthRequests = options.proxyOAuthRequests ?? true;\n this.staticClientInfo = options.staticClientInfo;\n this.onPopupWindow = options.onPopupWindow;\n }\n\n // --- Identity / key fields exposed for callback handling ---\n\n /** Prefix used for persisted OAuth keys. */\n get storageKeyPrefix(): string {\n return this.session.storageKeyPrefix;\n }\n\n /** Stable hash used to namespace storage for this server. */\n get serverUrlHash(): string {\n return this.session.serverUrlHash;\n }\n\n /** Human-readable OAuth client name. */\n get clientName(): string {\n return this.session.clientName;\n }\n\n /** Public website describing the OAuth client. */\n get clientUri(): string {\n return this.session.clientUri;\n }\n\n /** Public OAuth client logo URL. */\n get logoUri(): string {\n return this.session.logoUri;\n }\n\n /** OAuth redirect URI. */\n get callbackUrl(): string {\n return this.session.callbackUrl;\n }\n\n /** Space-delimited OAuth scopes requested by the client. */\n get scope(): string | undefined {\n return this.session.scope;\n }\n\n get clientMetadataUrl(): string | undefined {\n return this.session.clientMetadataUrl;\n }\n\n /**\n * Returns a provider-scoped storage key.\n *\n * @param keySuffix - Suffix identifying the stored value.\n * @returns Namespaced storage key.\n */\n getKey(keySuffix: string): string {\n return this.session.getKey(keySuffix);\n }\n\n /** Whether an authorization flow is awaiting completion. */\n get hasPendingFlow(): boolean {\n return this.authorizationPending;\n }\n\n /** Marks the current authorization flow as complete. */\n markFlowComplete(): void {\n this.authorizationPending = false;\n }\n\n /**\n * Re-anchor an SDK-derived OAuth discovery URL from the MCP connection\n * (proxy) origin onto the actual MCP server.\n *\n * When MCP traffic is tunneled through a gateway/inspector proxy, the SDK\n * transport derives `/.well-known/*` URLs from the URL it connected to (the\n * proxy) whenever no `resource_metadata` hint is available — the SSE\n * transport's EventSource cannot read `WWW-Authenticate`, and token refresh\n * runs without a 401 response at hand. The proxy origin serves no OAuth\n * metadata, so discovery would fail and the server would be misclassified\n * as \"does not support OAuth\". Rewriting reproduces what a direct\n * connection would have requested: the same well-known document, anchored\n * on the server origin, with the RFC 8414 §3.1 / RFC 9728 §3.1 path\n * insertion using the server's path instead of the proxy's.\n */\n private reanchorWellKnownUrl(url: string): string {\n if (!this.connectionUrl) return url;\n try {\n const requested = new URL(url);\n const connection = new URL(this.connectionUrl);\n if (requested.origin !== connection.origin) return url;\n if (!requested.pathname.startsWith(\"/.well-known/\")) return url;\n\n const target = new URL(this.serverUrl);\n const rest = requested.pathname.slice(\"/.well-known/\".length);\n const [doc, ...suffixParts] = rest.split(\"/\");\n if (!doc) return url;\n\n const suffix = suffixParts.length ? `/${suffixParts.join(\"/\")}` : \"\";\n const connectionPath = trimTrailingSlashes(connection.pathname);\n const targetPath = trimTrailingSlashes(target.pathname);\n // Path-insertion form: swap the proxy's inserted path for the server's.\n // Root form (no suffix) stays root. Unrelated suffixes are preserved.\n const newSuffix =\n suffix && suffix === connectionPath ? targetPath : suffix;\n\n return `${target.origin}/.well-known/${doc}${newSuffix}${requested.search}`;\n } catch {\n return url;\n }\n }\n\n private rememberResourceMetadataChallenge(response: Response): boolean {\n if (response.status !== 401) return false;\n const { resourceMetadataUrl } = extractWWWAuthenticateParams(response);\n if (!resourceMetadataUrl) return false;\n this.challengedResourceMetadataUrl = resourceMetadataUrl.toString();\n return true;\n }\n\n /**\n * Returns a `fetch` function, scoped to this provider, that routes OAuth\n * metadata and non-browser OAuth endpoint requests through the configured\n * `oauthProxyUrl` to bypass CORS. Authorization endpoints are navigated by\n * the browser and all unrelated requests pass through unchanged.\n *\n * Unlike patching the global `fetch`, the returned function only affects the\n * transport/auth calls it is explicitly handed to (via the SDK transport's\n * `fetch` option or `auth({ fetchFn })`). Connecting one server \"Via Proxy\"\n * therefore never alters fetch behavior for other servers, other\n * connections, or the rest of the page.\n *\n * OAuth metadata is always fetched with `cache: \"no-store\"`, including in\n * direct mode. Authorization servers commonly vary CORS headers by Origin;\n * bypassing the browser HTTP cache prevents a revalidated response cached\n * for another localhost origin from poisoning discovery. When OAuth proxying\n * is disabled or no `oauthProxyUrl` is configured, all requests still go\n * directly to their original URLs.\n *\n * @param baseFetch - The fetch used for non-OAuth requests and for the\n * underlying proxy calls. Defaults to the global `fetch`.\n */\n getProxyFetch(baseFetch?: typeof fetch): typeof fetch | undefined {\n const base: typeof fetch = baseFetch ?? globalThis.fetch.bind(globalThis);\n const oauthProxyUrl =\n this.proxyOAuthRequests && this.oauthProxyUrl\n ? this.oauthProxyUrl\n : undefined;\n const discoveredEndpoints = new Set<string>();\n let restoredDiscovery = false;\n\n // Create scoped fetch\n return async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const requestedUrl =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n\n // The SDK derives discovery URLs from the transport URL. Re-anchor URLs\n // derived from an MCP proxy onto the actual MCP server before routing.\n const url = this.reanchorWellKnownUrl(requestedUrl);\n\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return await base(input, init);\n }\n const isMetadata = pathname.includes(\"/.well-known/\");\n\n // Metadata responses can carry Origin-specific CORS headers. Never let\n // the browser reuse or revalidate a response cached for another origin.\n // This is scoped to discovery; MCP traffic and OAuth endpoint POSTs keep\n // their caller-provided cache behavior.\n if (!oauthProxyUrl) {\n const response = await base(\n isMetadata ? url : input,\n isMetadata ? { ...init, cache: \"no-store\" } : init\n );\n if (!isMetadata) this.rememberResourceMetadataChallenge(response);\n return response;\n }\n\n if (!restoredDiscovery) {\n restoredDiscovery = true;\n const metadata = (await this.discoveryState())\n ?.authorizationServerMetadata as Record<string, unknown> | undefined;\n for (const key of [\n \"registration_endpoint\",\n \"token_endpoint\",\n \"revocation_endpoint\",\n \"introspection_endpoint\",\n ]) {\n if (typeof metadata?.[key] === \"string\") {\n discoveredEndpoints.add(metadata[key]);\n }\n }\n }\n const isProxiedEndpoint =\n discoveredEndpoints.has(url) ||\n /\\/(?:register|registration|token|revoke|revocation|introspect|introspection)\\/?$/.test(\n pathname\n );\n\n if (!isMetadata && !isProxiedEndpoint) {\n const response = await base(input, init);\n if (this.rememberResourceMetadataChallenge(response)) {\n // Endpoints restored before the MCP request may belong to discovery\n // that the fresh challenge has just made stale. Fresh metadata will\n // repopulate this routing set as the SDK rediscovers it.\n discoveredEndpoints.clear();\n }\n return response;\n }\n\n // Don't intercept requests already going to our OAuth proxy (avoid circular proxying)\n // Check if the URL is pointing to our OAuth proxy endpoint\n try {\n const urlObj = new URL(url);\n const proxyUrlObj = new URL(oauthProxyUrl);\n // If the request is going to the same origin and path as our OAuth proxy, don't intercept\n if (\n urlObj.origin === proxyUrlObj.origin &&\n (urlObj.pathname.startsWith(proxyUrlObj.pathname) ||\n url.includes(\"/inspector/api/oauth\"))\n ) {\n return await base(input, init);\n }\n } catch {\n // If URL parsing fails, continue with interception (better safe than sorry)\n }\n\n const proxyEndpoint = isMetadata\n ? `${oauthProxyUrl}/metadata?serverUrl=${encodeURIComponent(\n this.serverUrl\n )}&url=${encodeURIComponent(url)}`\n : `${oauthProxyUrl}/proxy`;\n\n if (isMetadata) {\n const response = await base(proxyEndpoint, {\n ...init,\n method: \"GET\",\n cache: \"no-store\",\n });\n try {\n const metadata = (await response.clone().json()) as Record<\n string,\n unknown\n >;\n for (const key of [\n \"registration_endpoint\",\n \"token_endpoint\",\n \"revocation_endpoint\",\n \"introspection_endpoint\",\n ]) {\n if (typeof metadata[key] === \"string\") {\n discoveredEndpoints.add(metadata[key]);\n }\n }\n } catch {\n // The SDK owns metadata validation and will reject malformed responses.\n }\n return response;\n }\n\n const inputRequest = input instanceof Request ? input : undefined;\n const method = init?.method ?? inputRequest?.method ?? \"POST\";\n const requestHeaders = init?.headers ?? inputRequest?.headers;\n let body: unknown;\n if (init?.body !== undefined && init.body !== null) {\n body = await serializeBody(init.body);\n } else if (inputRequest?.body && method !== \"GET\" && method !== \"HEAD\") {\n body = await inputRequest.clone().text();\n }\n const response = await base(proxyEndpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n serverUrl: this.serverUrl,\n url,\n method,\n headers: requestHeaders\n ? Object.fromEntries(new Headers(requestHeaders as HeadersInit))\n : {},\n body,\n }),\n });\n const data = (await response.json()) as {\n status?: unknown;\n statusText?: unknown;\n headers?: unknown;\n body?: unknown;\n };\n if (!response.ok || typeof data.status !== \"number\") {\n return new Response(JSON.stringify(data), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return new Response(JSON.stringify(data.body), {\n status: data.status,\n statusText:\n typeof data.statusText === \"string\" ? data.statusText : undefined,\n headers: new Headers(\n data.headers && typeof data.headers === \"object\"\n ? (data.headers as HeadersInit)\n : undefined\n ),\n });\n };\n }\n\n // --- SDK Interface Methods (delegated) ---\n\n get redirectUrl(): string {\n return this.session.redirectUrl;\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this.session.clientMetadata;\n }\n\n tokens(\n ctx?: OAuthClientInformationContext\n ): Promise<OAuthTokens | undefined> {\n return this.session.tokens(ctx);\n }\n\n saveTokens(\n tokens: OAuthTokens,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n this.lastAttemptedAuthUrl = null;\n this.authorizationPending = false;\n return this.session.saveTokens(tokens, ctx);\n }\n\n /**\n * Returns the configured or dynamically registered OAuth client information.\n *\n * @param ctx - Optional registration context.\n * @returns OAuth client information, or `undefined` when not registered.\n */\n async clientInformation(\n ctx?: OAuthClientInformationContext\n ): Promise<OAuthClientInformation | undefined> {\n // Pre-registered client info (proxy-mode servers like Slack/WorkOS proxy\n // strip registration_endpoint, so DCR is not an option). When set, this\n // bypasses any stored DCR result so a stale localStorage entry can't\n // shadow the configured client_id.\n if (this.staticClientInfo) return this.staticClientInfo;\n return this.session.clientInformation(ctx);\n }\n\n /**\n * Persists public OAuth client registration information.\n *\n * Static client configuration takes precedence, and browser providers discard\n * any client secret returned for a public client.\n *\n * @param clientInformation - Registration information to save.\n * @param ctx - Optional registration context.\n */\n async saveClientInformation(\n clientInformation: OAuthClientInformation,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n // When a pre-registered client_id is configured, never persist DCR results\n // — the static client_id is the source of truth.\n if (this.staticClientInfo) return;\n\n // Browser clients always register as public clients\n // (`token_endpoint_auth_method: \"none\"`). Some authorization servers,\n // including Auth0 DCR, still include a generated client_secret in the\n // registration response even though the public client must not use or\n // retain it. Persist only the public portion of the response. Keep the\n // session store's secret rejection intact as a defense-in-depth guard for\n // every other browser persistence path.\n const { client_secret: discardedClientSecret, ...publicClientInformation } =\n clientInformation;\n if (discardedClientSecret) {\n console.info(\n `[${this.storageKeyPrefix}] Discarded client_secret returned for a public browser OAuth client.`\n );\n }\n return this.session.saveClientInformation(\n publicClientInformation as OAuthClientInformation,\n ctx\n );\n }\n\n codeVerifier(): Promise<string> {\n return this.session.codeVerifier();\n }\n\n saveCodeVerifier(codeVerifier: string): Promise<void> {\n return this.session.saveCodeVerifier(codeVerifier);\n }\n\n invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"\n ): Promise<void> {\n return this.session.invalidateCredentials(scope);\n }\n\n /**\n * Persist OAuth discovery state (SEP-2352). Delegated to the session store;\n * implementing this silences the SDK's per-callback warning and enables the\n * authorization-server mix-up defense on the callback leg.\n */\n saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n return this.session.saveDiscoveryState(state);\n }\n\n /** Return previously saved OAuth discovery state, or `undefined`. */\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const state = await this.session.discoveryState();\n const challengedUrl = this.challengedResourceMetadataUrl;\n this.challengedResourceMetadataUrl = undefined;\n\n if (challengedUrl && state) {\n // A fresh MCP challenge is authoritative. RFC 9728 section 5.2 says it\n // can indicate that protected-resource metadata has changed even when\n // the metadata URL itself is unchanged. Always rediscover after such a\n // challenge instead of trusting a complete-but-stale persisted document.\n // Let the SDK rediscover from the challenge while preserving issuer-keyed\n // tokens and client registrations until normal issuer validation decides\n // whether either credential is reusable.\n await this.session.invalidateCredentials(\"discovery\");\n return undefined;\n }\n\n return state;\n }\n\n /**\n * Return the token endpoint from the SDK's persisted discovery state.\n * Returns `null` before a successful authorization discovery.\n */\n getTokenEndpoint(): Promise<string | null> {\n return this.session.getTokenEndpoint();\n }\n\n /** Return the protected-resource URL selected during OAuth discovery. */\n getResource(): Promise<string | null> {\n return this.session.getResource();\n }\n\n /**\n * Return the stored public OAuth client ID. Browser providers do not retain\n * client secrets.\n */\n async getClientCredentials(): Promise<{\n /** Public OAuth client identifier. */\n client_id: string;\n } | null> {\n const info = await this.clientInformation();\n return info?.client_id ? { client_id: info.client_id } : null;\n }\n\n /**\n * Generates and persists `StoredState` for an authorization request,\n * and returns the sanitized URL with the `state` param appended. Does NOT\n * open a popup or redirect —\n * use `redirectToAuthorization` for that.\n */\n async prepareAuthorizationUrl(authorizationUrl: URL): Promise<string> {\n const prepared = await this.session.storeAuthorizationState(\n authorizationUrl,\n {\n extraProviderOptions: {\n oauthProxyUrl: this.oauthProxyUrl,\n ...(this.clientMetadataUrl\n ? { clientMetadataUrl: this.clientMetadataUrl }\n : {}),\n ...(this.staticClientInfo\n ? { staticClientInfo: this.staticClientInfo }\n : {}),\n ...(this.scope ? { scope: this.scope } : {}),\n },\n flowType: this.useRedirectFlow ? \"redirect\" : \"popup\",\n returnUrl:\n typeof window !== \"undefined\" ? window.location.href : undefined,\n }\n );\n this.lastAttemptedAuthUrl = prepared;\n this.authorizationPending = true;\n return prepared;\n }\n\n /**\n * Redirects the user agent to the authorization URL, storing necessary state.\n * @param authorizationUrl - The fully constructed authorization URL from the SDK.\n */\n async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n await this.prepareAuthorizationUrl(authorizationUrl);\n\n // If auto-auth is prevented, just store the URL but don't redirect/popup\n if (this.preventAutoAuth) {\n console.info(\n `[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`\n );\n return;\n }\n\n this.startAuthorization();\n }\n\n /**\n * Open the authorization URL prepared by the official SDK.\n *\n * This is the explicit-user-action counterpart to `preventAutoAuth`: the\n * provider still lets the SDK own discovery and PKCE state, while a host can\n * launch the stored authorization request later from an Authenticate button.\n */\n startAuthorization(): void {\n const authorizationUrl = this.lastAttemptedAuthUrl;\n if (!authorizationUrl) {\n throw new Error(\"No prepared OAuth authorization is available\");\n }\n\n // Use redirect flow if enabled (avoids popup blockers)\n if (this.useRedirectFlow) {\n console.info(\n `[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`\n );\n window.location.href = authorizationUrl;\n return;\n }\n\n // Otherwise, use popup flow (legacy behavior)\n const popupFeatures =\n \"width=600,height=700,resizable=yes,scrollbars=yes,status=yes\";\n try {\n const popup = window.open(\n authorizationUrl,\n `mcp_auth_${this.serverUrlHash}`,\n popupFeatures\n );\n\n if (this.onPopupWindow) {\n this.onPopupWindow(authorizationUrl, popupFeatures, popup);\n }\n\n if (!popup || popup.closed || typeof popup.closed === \"undefined\") {\n console.warn(\n `[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`\n );\n } else {\n popup.focus();\n console.info(\n `[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`\n );\n }\n } catch (e) {\n console.error(\n `[${this.storageKeyPrefix}] Error opening popup window:`,\n e\n );\n }\n }\n\n /**\n * Retrieves the last URL passed to `redirectToAuthorization`. Useful for manual fallback.\n */\n getLastAttemptedAuthUrl(): string | null {\n return this.lastAttemptedAuthUrl;\n }\n\n /**\n * Removes OAuth state stored for this server.\n *\n * @returns The number of storage entries removed.\n */\n clearStorage(): number {\n this.lastAttemptedAuthUrl = null;\n this.authorizationPending = false;\n const prefixPattern = `${this.storageKeyPrefix}_${this.serverUrlHash}_`;\n const keysToRemove: string[] = [];\n let count = 0;\n\n for (const key of this.storage.keys()) {\n if (key.startsWith(prefixPattern)) {\n keysToRemove.push(key);\n }\n }\n\n const uniqueKeysToRemove = [...new Set(keysToRemove)];\n uniqueKeysToRemove.forEach((key) => {\n this.storage.remove(key);\n count++;\n });\n return count;\n }\n}\n\n/**\n * Creates the browser OAuth provider used by the root client entry.\n */\nexport async function createOAuthProvider(\n serverUrl: string,\n options: BrowserOAuthOptions = {}\n): Promise<OAuthClientProvider> {\n return new BrowserOAuthClientProvider(serverUrl, options);\n}\n\nexport type { BrowserOAuthOptions as OAuthProviderOptions };\n","/**\n * Minimal key/value storage abstraction used by OAuthSessionStore.\n *\n * Browser-safe module — Node filesystem KV lives in `storage-file.ts`.\n *\n * @internal\n */\nexport interface KVStore {\n get(key: string): Promise<string | null> | string | null;\n set(key: string, value: string): Promise<void> | void;\n remove(key: string): Promise<void> | void;\n keys(): Promise<string[]> | string[];\n}\n\ntype EncryptedEnvelope = {\n v: 1;\n alg: \"A256GCM\";\n iv: string;\n ciphertext: string;\n};\n\nconst AUTH_CRYPTO_DATABASE = \"mcp-use-oauth-crypto\";\nconst AUTH_CRYPTO_STORE = \"keys\";\nconst AUTH_CRYPTO_KEY = \"aes-gcm-v1\";\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Encrypted `KVStore` backed by `globalThis.localStorage`.\n *\n * Values use AES-256-GCM with a non-extractable origin key held by IndexedDB.\n * Legacy plaintext values are encrypted on first read. When durable browser\n * cryptography is unavailable, the store removes plaintext and falls back to\n * memory for the lifetime of this instance.\n *\n * @internal\n */\nexport class LocalStorageKVStore implements KVStore {\n private readonly fallback = new Map<string, string>();\n private keyPromise: Promise<CryptoKey> | undefined;\n private durable = true;\n\n async get(key: string): Promise<string | null> {\n if (!this.durable) return this.fallback.get(key) ?? null;\n\n let stored: string | null;\n try {\n stored = localStorage.getItem(key);\n } catch {\n this.durable = false;\n return this.fallback.get(key) ?? null;\n }\n if (stored === null) return null;\n\n const envelope = parseEncryptedEnvelope(stored);\n if (!envelope) {\n await this.set(key, stored);\n return stored;\n }\n\n try {\n const cryptoKey = await this.getCryptoKey();\n const plaintext = await globalThis.crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: decodeBase64(envelope.iv),\n additionalData: textEncoder.encode(key),\n },\n cryptoKey,\n decodeBase64(envelope.ciphertext)\n );\n return textDecoder.decode(plaintext);\n } catch {\n await this.remove(key);\n return null;\n }\n }\n\n async set(key: string, value: string): Promise<void> {\n if (!this.durable) {\n this.fallback.set(key, value);\n return;\n }\n\n try {\n const cryptoKey = await this.getCryptoKey();\n const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = await globalThis.crypto.subtle.encrypt(\n {\n name: \"AES-GCM\",\n iv,\n additionalData: textEncoder.encode(key),\n },\n cryptoKey,\n textEncoder.encode(value)\n );\n const envelope: EncryptedEnvelope = {\n v: 1,\n alg: \"A256GCM\",\n iv: encodeBase64(iv),\n ciphertext: encodeBase64(new Uint8Array(ciphertext)),\n };\n localStorage.setItem(key, JSON.stringify(envelope));\n this.fallback.delete(key);\n } catch {\n this.durable = false;\n try {\n localStorage.removeItem(key);\n } catch {\n // Storage may be disabled entirely.\n }\n this.fallback.set(key, value);\n }\n }\n\n remove(key: string): void {\n this.fallback.delete(key);\n try {\n localStorage.removeItem(key);\n } catch {\n this.durable = false;\n }\n }\n\n keys(): string[] {\n const out = new Set(this.fallback.keys());\n if (this.durable) {\n try {\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key) out.add(key);\n }\n } catch {\n this.durable = false;\n }\n }\n return [...out];\n }\n\n private getCryptoKey(): Promise<CryptoKey> {\n this.keyPromise ??= getOrCreateCryptoKey();\n return this.keyPromise;\n }\n}\n\nfunction parseEncryptedEnvelope(value: string): EncryptedEnvelope | undefined {\n try {\n const parsed: unknown = JSON.parse(value);\n if (\n !parsed ||\n typeof parsed !== \"object\" ||\n !(\"v\" in parsed) ||\n parsed.v !== 1 ||\n !(\"alg\" in parsed) ||\n parsed.alg !== \"A256GCM\" ||\n !(\"iv\" in parsed) ||\n typeof parsed.iv !== \"string\" ||\n !(\"ciphertext\" in parsed) ||\n typeof parsed.ciphertext !== \"string\"\n ) {\n return undefined;\n }\n return parsed as EncryptedEnvelope;\n } catch {\n return undefined;\n }\n}\n\nasync function getOrCreateCryptoKey(): Promise<CryptoKey> {\n if (!globalThis.crypto?.subtle || typeof indexedDB === \"undefined\") {\n throw new Error(\"Durable browser cryptography is unavailable\");\n }\n\n const candidate = await globalThis.crypto.subtle.generateKey(\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n const database = await openCryptoDatabase();\n try {\n return await new Promise<CryptoKey>((resolve, reject) => {\n const transaction = database.transaction(AUTH_CRYPTO_STORE, \"readwrite\");\n const store = transaction.objectStore(AUTH_CRYPTO_STORE);\n const request = store.get(AUTH_CRYPTO_KEY);\n let selected: CryptoKey | undefined;\n\n request.onsuccess = () => {\n selected = request.result as CryptoKey | undefined;\n if (!selected) {\n selected = candidate;\n store.put(candidate, AUTH_CRYPTO_KEY);\n }\n };\n request.onerror = () => reject(request.error);\n transaction.oncomplete = () => {\n if (selected) resolve(selected);\n else reject(new Error(\"OAuth encryption key was not initialized\"));\n };\n transaction.onerror = () => reject(transaction.error);\n transaction.onabort = () => reject(transaction.error);\n });\n } finally {\n database.close();\n }\n}\n\nfunction openCryptoDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(AUTH_CRYPTO_DATABASE, 1);\n request.onupgradeneeded = () => {\n const database = request.result;\n if (!database.objectStoreNames.contains(AUTH_CRYPTO_STORE)) {\n database.createObjectStore(AUTH_CRYPTO_STORE);\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n request.onblocked = () =>\n reject(new Error(\"OAuth encryption database is blocked\"));\n });\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array<ArrayBuffer> {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n","import type {\n OAuthClientInformation,\n OAuthClientInformationContext,\n OAuthClientMetadata,\n OAuthDiscoveryState,\n StoredOAuthTokens,\n} from \"@modelcontextprotocol/client\";\nimport { validateClientMetadataUrl } from \"@modelcontextprotocol/client\";\nimport { sanitizeUrl } from \"./url.js\";\nimport type { KVStore } from \"./storage.js\";\n\n/**\n * Internal type for storing OAuth state during the OAuth flow.\n * @internal\n */\nexport interface StoredState {\n expiry: number;\n serverUrlHash: string;\n providerOptions: {\n serverUrl: string;\n storageKeyPrefix: string;\n clientName: string;\n clientUri: string;\n callbackUrl: string;\n oauthProxyUrl?: string;\n clientMetadataUrl?: string;\n staticClientInfo?: OAuthClientInformation;\n scope?: string;\n };\n flowType?: \"popup\" | \"redirect\";\n returnUrl?: string;\n}\n\n/**\n * Common options for OAuthSessionStore.\n *\n * @internal\n */\nexport interface OAuthSessionStoreOptions {\n /** Prefix used for persisted OAuth keys. */\n storageKeyPrefix?: string;\n /** Human-readable OAuth client name. */\n clientName?: string;\n /** Public website describing the OAuth client. */\n clientUri?: string;\n /** Public OAuth client logo URL. */\n logoUri?: string;\n /** OAuth redirect URI. */\n callbackUrl?: string;\n /** OAuth Client ID Metadata Document URL. */\n clientMetadataUrl?: string;\n /** Whether this platform may persist confidential-client credentials. */\n allowClientSecret?: boolean;\n /** OAuth scope string forwarded to the SDK via clientMetadata.scope. */\n scope?: string;\n}\n\n/**\n * Options passed by the platform provider when persisting an authorization\n * request prior to redirecting the user agent.\n *\n * @internal\n */\ninterface StoreAuthorizationStateOptions {\n /**\n * Platform-specific provider options that should round-trip through the\n * stored state so the callback handler can rebuild the provider.\n */\n extraProviderOptions?: Record<string, unknown>;\n flowType?: \"popup\" | \"redirect\";\n returnUrl?: string;\n}\n\n/**\n * Platform-neutral helper that owns OAuth session persistence and refresh\n * logic. Used by `BrowserOAuthClientProvider` and `NodeOAuthClientProvider`\n * — each platform provider implements `OAuthClientProvider` directly and\n * delegates the generic methods here.\n *\n * @internal\n */\nexport class OAuthSessionStore {\n readonly serverUrl: string;\n readonly storageKeyPrefix: string;\n readonly serverUrlHash: string;\n readonly clientName: string;\n readonly clientUri: string;\n readonly logoUri: string;\n readonly callbackUrl: string;\n readonly clientMetadataUrl?: string;\n readonly scope?: string;\n\n private store: KVStore;\n private allowClientSecret: boolean;\n\n constructor(\n serverUrl: string,\n options: OAuthSessionStoreOptions,\n store: KVStore\n ) {\n validateClientMetadataUrl(options.clientMetadataUrl);\n this.serverUrl = serverUrl;\n this.storageKeyPrefix = options.storageKeyPrefix || \"mcp:auth\";\n this.serverUrlHash = OAuthSessionStore.hashString(serverUrl);\n this.clientName = options.clientName || \"mcp-use\";\n this.clientUri =\n options.clientUri ||\n (typeof window !== \"undefined\"\n ? window.location.origin\n : \"https://mcp-use.com\");\n this.logoUri = options.logoUri || \"https://mcp-use.com/logo.png\";\n this.callbackUrl = sanitizeUrl(\n options.callbackUrl ||\n (typeof window !== \"undefined\"\n ? new URL(\"/oauth/callback\", window.location.origin).toString()\n : \"/oauth/callback\")\n );\n this.clientMetadataUrl = options.clientMetadataUrl;\n this.scope = options.scope;\n this.store = store;\n this.allowClientSecret = options.allowClientSecret ?? true;\n }\n\n getKey(keySuffix: string): string {\n return `${this.storageKeyPrefix}_${this.serverUrlHash}_${keySuffix}`;\n }\n\n static hashString(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n return Math.abs(hash).toString(16);\n }\n\n // --- SDK Interface Methods (delegated) ---\n\n get redirectUrl(): string {\n return this.callbackUrl;\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.redirectUrl],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n client_name: this.clientName,\n client_uri: this.clientUri,\n logo_uri: this.logoUri,\n ...(this.scope ? { scope: this.scope } : {}),\n };\n }\n\n private credentialKey(\n kind: \"client_info\" | \"tokens\",\n ctx?: OAuthClientInformationContext\n ): string {\n return ctx\n ? this.getKey(`${kind}_${encodeURIComponent(ctx.issuer)}`)\n : this.getKey(kind);\n }\n\n private async readCredential<T extends { issuer?: string }>(\n kind: \"client_info\" | \"tokens\",\n ctx?: OAuthClientInformationContext\n ): Promise<{ key: string; value: T } | undefined> {\n const key = this.credentialKey(kind, ctx);\n const data = await this.store.get(key);\n if (!data && ctx) {\n const legacyKey = this.credentialKey(kind);\n const legacyData = await this.store.get(legacyKey);\n if (legacyData) {\n try {\n const legacyValue = JSON.parse(legacyData) as T;\n if (!legacyValue.issuer || legacyValue.issuer === ctx.issuer) {\n const migratedValue = {\n ...legacyValue,\n issuer: ctx.issuer,\n };\n const migratedData = JSON.stringify(migratedValue);\n await this.store.set(key, migratedData);\n await this.store.set(legacyKey, migratedData);\n return { key, value: migratedValue };\n }\n } catch {\n await this.store.remove(legacyKey);\n }\n }\n return undefined;\n }\n if (!data) return undefined;\n try {\n return { key, value: JSON.parse(data) as T };\n } catch (e) {\n console.warn(\n `[${this.storageKeyPrefix}] Failed to parse ${kind.replace(\"_\", \" \")}:`,\n e\n );\n await this.store.remove(key);\n return undefined;\n }\n }\n\n async tokens(\n ctx?: OAuthClientInformationContext\n ): Promise<StoredOAuthTokens | undefined> {\n return (await this.readCredential<StoredOAuthTokens>(\"tokens\", ctx))?.value;\n }\n\n async saveTokens(\n tokens: StoredOAuthTokens,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n // Persist tokens BEFORE clearing the verifier / last_auth_url so a failed\n // write can't strand the auth flow with no way to recover.\n const serialized = JSON.stringify(tokens);\n await this.store.set(this.credentialKey(\"tokens\", ctx), serialized);\n // The no-context SDK read is the transport's latest bearer token lookup.\n if (ctx) await this.store.set(this.credentialKey(\"tokens\"), serialized);\n await this.store.remove(this.getKey(\"code_verifier\"));\n await this.store.remove(this.getKey(\"last_auth_url\"));\n await this.store.remove(this.getKey(\"last_auth_callback_url\"));\n }\n\n async clientInformation(\n ctx?: OAuthClientInformationContext\n ): Promise<OAuthClientInformation | undefined> {\n if (!this.allowClientSecret) {\n const registeredRedirectUri = await this.store.get(\n this.getKey(\"client_info_redirect_uri\")\n );\n if (registeredRedirectUri !== this.redirectUrl) {\n await this.invalidateCredentials(\"registration\");\n console.info(\n `[${this.storageKeyPrefix}] Re-registering browser OAuth client after its Inspector callback changed or could not be verified.`\n );\n return undefined;\n }\n }\n\n const stored = await this.readCredential<\n OAuthClientInformation & {\n issuer?: string;\n redirect_uris?: string[];\n client_secret?: string;\n }\n >(\"client_info\", ctx);\n if (!stored) return undefined;\n const { key, value: clientInfo } = stored;\n try {\n if (!this.allowClientSecret && clientInfo.client_secret) {\n await this.invalidateCredentials(\"registration\");\n console.warn(\n `[${this.storageKeyPrefix}] Recovered stale browser OAuth credentials containing a client_secret.`\n );\n return undefined;\n }\n const storedRedirectUris = Array.isArray(clientInfo.redirect_uris)\n ? clientInfo.redirect_uris\n : [];\n // Node clients can retain registrations from servers that omit\n // redirect_uris. Browser clients cannot: the same origin may serve both\n // embedded and standalone Inspectors at different callback paths.\n const hasMatchingRedirect =\n (storedRedirectUris.length === 0 && this.allowClientSecret) ||\n storedRedirectUris.includes(this.redirectUrl);\n\n if (!hasMatchingRedirect) {\n console.info(\n `[${this.storageKeyPrefix}] Recovering cached OAuth credentials after a redirect URI change.`\n );\n await this.invalidateCredentials(\"registration\");\n return undefined;\n }\n\n return clientInfo;\n } catch {\n await this.store.remove(key);\n return undefined;\n }\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformation,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n const info = clientInformation as OAuthClientInformation & {\n client_secret?: string;\n };\n if (!this.allowClientSecret && info.client_secret) {\n await this.store.remove(this.credentialKey(\"client_info\", ctx));\n if (ctx) await this.store.remove(this.credentialKey(\"client_info\"));\n throw new Error(\n \"Browser OAuth clients must be public clients; client_secret persistence is not allowed.\"\n );\n }\n const persistedClientInformation =\n !this.allowClientSecret &&\n (!(\"redirect_uris\" in clientInformation) ||\n !Array.isArray(\n (clientInformation as { redirect_uris?: unknown }).redirect_uris\n ) ||\n (clientInformation as { redirect_uris: unknown[] }).redirect_uris\n .length === 0)\n ? { ...clientInformation, redirect_uris: [this.redirectUrl] }\n : clientInformation;\n const serialized = JSON.stringify(persistedClientInformation);\n await this.store.set(this.credentialKey(\"client_info\", ctx), serialized);\n if (ctx) {\n await this.store.set(this.credentialKey(\"client_info\"), serialized);\n }\n if (!this.allowClientSecret) {\n await this.store.set(\n this.getKey(\"client_info_redirect_uri\"),\n this.redirectUrl\n );\n }\n }\n\n async saveCodeVerifier(codeVerifier: string): Promise<void> {\n await this.store.set(this.getKey(\"code_verifier\"), codeVerifier);\n }\n\n async codeVerifier(): Promise<string> {\n const key = this.getKey(\"code_verifier\");\n const verifier = await this.store.get(key);\n if (!verifier) {\n throw new Error(\n `[${this.storageKeyPrefix}] Code verifier not found in storage for key ${key}. Auth flow likely corrupted or timed out.`\n );\n }\n return verifier;\n }\n\n async invalidateCredentials(\n scope:\n | \"all\"\n | \"registration\"\n | \"client\"\n | \"tokens\"\n | \"verifier\"\n | \"discovery\"\n ): Promise<void> {\n const removeCredentialKeys = async (\n kind: \"client_info\" | \"tokens\"\n ): Promise<void> => {\n const prefix = `${this.getKey(kind)}_`;\n for (const key of await this.store.keys()) {\n if (key === this.getKey(kind) || key.startsWith(prefix)) {\n await this.store.remove(key);\n }\n }\n };\n\n switch (scope) {\n case \"registration\":\n // The SDK saves freshly discovered issuer metadata before it asks for\n // client information. Preserve that callback-leg binding while\n // replacing stale browser registration and authorization artifacts.\n await removeCredentialKeys(\"tokens\");\n await removeCredentialKeys(\"client_info\");\n await this.store.remove(this.getKey(\"code_verifier\"));\n await this.store.remove(this.getKey(\"last_auth_url\"));\n await this.store.remove(this.getKey(\"last_auth_callback_url\"));\n await this.store.remove(this.getKey(\"client_info_redirect_uri\"));\n await this.store.remove(this.getKey(\"token_endpoint\"));\n break;\n case \"all\":\n await removeCredentialKeys(\"tokens\");\n await removeCredentialKeys(\"client_info\");\n await this.store.remove(this.getKey(\"code_verifier\"));\n await this.store.remove(this.getKey(\"last_auth_url\"));\n await this.store.remove(this.getKey(\"last_auth_callback_url\"));\n await this.store.remove(this.getKey(\"client_info_redirect_uri\"));\n await this.store.remove(this.getKey(\"discovery_state\"));\n await this.store.remove(this.getKey(\"token_endpoint\"));\n break;\n case \"client\":\n await removeCredentialKeys(\"client_info\");\n break;\n case \"tokens\":\n await removeCredentialKeys(\"tokens\");\n break;\n case \"verifier\":\n await this.store.remove(this.getKey(\"code_verifier\"));\n break;\n case \"discovery\":\n await this.store.remove(this.getKey(\"discovery_state\"));\n break;\n default:\n break;\n }\n }\n\n /**\n * Persist the OAuth discovery state (authorization-server metadata resolved\n * during the auth flow). Stored with the same durability as the code\n * verifier so the callback leg can verify it is exchanging the code at the\n * same authorization server the redirect targeted (SEP-2352 mix-up defense).\n */\n async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n await this.store.set(this.getKey(\"discovery_state\"), JSON.stringify(state));\n }\n\n /** Return the previously saved discovery state, or `undefined`. */\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const data = await this.store.get(this.getKey(\"discovery_state\"));\n if (!data) return undefined;\n try {\n return JSON.parse(data) as OAuthDiscoveryState;\n } catch {\n await this.store.remove(this.getKey(\"discovery_state\"));\n return undefined;\n }\n }\n\n // --- Helper / non-SDK methods ---\n\n /**\n * Generates and persists `StoredState` for an authorization request,\n * appends the `state` query param to the URL, and persists the sanitized\n * URL to `last_auth_url` so it can be replayed on popup-blocker fallback.\n *\n * @returns The sanitized authorization URL string with the `state` param appended.\n */\n async storeAuthorizationState(\n authorizationUrl: URL,\n opts: StoreAuthorizationStateOptions = {}\n ): Promise<string> {\n const state = globalThis.crypto.randomUUID();\n const stateKey = `${this.storageKeyPrefix}_${this.serverUrlHash}_state_${state}`;\n\n const stateData: StoredState = {\n serverUrlHash: this.serverUrlHash,\n expiry: Date.now() + 1000 * 60 * 10, // State expires in 10 minutes\n providerOptions: {\n serverUrl: this.serverUrl,\n storageKeyPrefix: this.storageKeyPrefix,\n clientName: this.clientName,\n clientUri: this.clientUri,\n callbackUrl: this.callbackUrl,\n ...(this.clientMetadataUrl\n ? { clientMetadataUrl: this.clientMetadataUrl }\n : {}),\n ...(opts.extraProviderOptions ?? {}),\n },\n flowType: opts.flowType,\n returnUrl: opts.returnUrl,\n };\n\n authorizationUrl.searchParams.set(\"state\", state);\n const sanitizedAuthUrl = sanitizeUrl(authorizationUrl.toString());\n\n // Persist the state record BEFORE the last_auth_url so a partial failure\n // can't leave behind an auth URL whose state has no backing record.\n await this.store.set(stateKey, JSON.stringify(stateData));\n await this.store.set(\n this.getKey(\"last_auth_callback_url\"),\n this.redirectUrl\n );\n await this.store.set(this.getKey(\"last_auth_url\"), sanitizedAuthUrl);\n\n return sanitizedAuthUrl;\n }\n\n /**\n * Return the token endpoint from SDK-managed discovery state. The SDK\n * persists this state during `auth()`, avoiding a second discovery flow.\n */\n async getTokenEndpoint(): Promise<string | null> {\n return (\n (await this.discoveryState())?.authorizationServerMetadata\n ?.token_endpoint ?? null\n );\n }\n\n /**\n * Return the protected-resource URL selected during OAuth discovery.\n * Consumers can persist it and reuse it for server-side refresh exchanges.\n */\n async getResource(): Promise<string | null> {\n const resource = (await this.discoveryState())?.resourceMetadata?.resource;\n return typeof resource === \"string\" ? resource : null;\n }\n}\n","/**\n * URL sanitization utility\n *\n * Sanitizes URLs to prevent security issues by:\n * - Restricting to http/https protocols only\n * - Encoding URL components properly\n * - Validating hostnames\n */\n\n/**\n * Sanitizes a URL string by encoding all components and validating the protocol.\n *\n * @param raw - The raw URL string to sanitize\n * @returns The sanitized URL as a string\n * @throws Error if the URL is invalid or uses an unsupported protocol\n */\nexport function sanitizeUrl(raw: string): string {\n const abort = () => {\n throw new Error(`Invalid url to pass to open(): ${raw}`);\n };\n\n let url!: URL;\n\n try {\n url = new URL(raw);\n } catch (_) {\n abort();\n }\n\n // Don't allow any other scheme than http(s)\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") abort();\n\n // Hostnames can't be updated, but let's reject if they contain anything suspicious\n if (url.hostname !== encodeURIComponent(url.hostname)) abort();\n\n // Forcibly sanitise all the pieces of the URL\n if (url.username) url.username = encodeURIComponent(url.username);\n if (url.password) url.password = encodeURIComponent(url.password);\n url.pathname =\n url.pathname.slice(0, 1) +\n encodeURIComponent(url.pathname.slice(1)).replace(/%2f/gi, \"/\");\n url.search =\n url.search.slice(0, 1) +\n Array.from(url.searchParams.entries()).map(sanitizeParam).join(\"&\");\n url.hash = url.hash.slice(0, 1) + encodeURIComponent(url.hash.slice(1));\n\n return url.href;\n}\n\n/**\n * Helper function to sanitize URL search parameters\n */\nfunction sanitizeParam([k, v]: [string, string]): string {\n return `${encodeURIComponent(k)}${v.length > 0 ? `=${encodeURIComponent(v)}` : \"\"}`;\n}\n","import { StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\";\nimport { BrowserOAuthClientProvider } from \"./browser.js\";\nimport {\n MCP_AUTH_BROADCAST_CHANNEL,\n MCP_AUTH_CALLBACK_MESSAGE_TYPE,\n type McpAuthCallbackMessage,\n} from \"./popup.js\";\nimport type { StoredState } from \"./session-store.js\";\nimport { LocalStorageKVStore } from \"./storage.js\";\n\ninterface AuthCallbackMeta {\n state?: string | null;\n serverUrlHash?: string | null;\n}\n\nlet inFlightCallback: Promise<void> | null = null;\n\nfunction isMcpAuthPopupWindow(): boolean {\n return typeof window !== \"undefined\" && window.name.startsWith(\"mcp_auth_\");\n}\n\nfunction buildCallbackPayload(\n success: boolean,\n error: string | undefined,\n meta: AuthCallbackMeta\n): McpAuthCallbackMessage {\n return {\n type: MCP_AUTH_CALLBACK_MESSAGE_TYPE,\n success,\n ...(success ? {} : { error: error ?? \"Unknown error\" }),\n ...(meta.state ? { state: meta.state } : {}),\n ...(meta.serverUrlHash ? { serverUrlHash: meta.serverUrlHash } : {}),\n };\n}\n\nfunction broadcastCallback(payload: McpAuthCallbackMessage): void {\n if (typeof BroadcastChannel === \"undefined\") return;\n\n let channel: BroadcastChannel | undefined;\n try {\n channel = new BroadcastChannel(MCP_AUTH_BROADCAST_CHANNEL);\n channel.postMessage(payload);\n } catch (error) {\n console.warn(\"[mcp-callback] Failed to broadcast callback result:\", error);\n } finally {\n if (channel) {\n setTimeout(() => {\n try {\n channel?.close();\n } catch {\n // Best-effort signaling only.\n }\n }, 0);\n }\n }\n}\n\nfunction renderResult(\n title: string,\n message: string,\n error: boolean,\n returnUrl?: string\n): void {\n if (typeof document === \"undefined\") return;\n\n document.body.innerHTML = \"\";\n const container = document.createElement(\"div\");\n container.style.fontFamily = \"sans-serif\";\n container.style.padding = \"20px\";\n\n const heading = document.createElement(\"h1\");\n heading.textContent = title;\n container.appendChild(heading);\n\n const text = document.createElement(\"p\");\n text.textContent = message;\n if (error) {\n text.style.color = \"red\";\n text.style.backgroundColor = \"#ffebeb\";\n text.style.border = \"1px solid red\";\n text.style.padding = \"10px\";\n text.style.borderRadius = \"4px\";\n }\n container.appendChild(text);\n\n const close = document.createElement(\"a\");\n close.href = \"#\";\n close.textContent = \"Close this window\";\n close.onclick = (event) => {\n event.preventDefault();\n window.close();\n return false;\n };\n container.appendChild(close);\n\n if (returnUrl) {\n const separator = document.createTextNode(\" or \");\n const back = document.createElement(\"a\");\n back.href = returnUrl;\n back.textContent = \"return to the app\";\n container.append(separator, back);\n }\n\n document.body.appendChild(container);\n}\n\nasync function findStoredState(state: string): Promise<{\n key: string;\n value: StoredState;\n store: LocalStorageKVStore;\n}> {\n const store = new LocalStorageKVStore();\n const legacySuffix = `:state_${state}`;\n const scopedSuffix = `_state_${state}`;\n const key = (await store.keys()).find(\n (candidate) =>\n candidate.endsWith(legacySuffix) || candidate.endsWith(scopedSuffix)\n );\n const serialized = key ? await store.get(key) : null;\n if (!key || !serialized) {\n throw new Error(`Invalid or expired OAuth state \"${state}\".`);\n }\n\n let value: StoredState;\n try {\n value = JSON.parse(serialized) as StoredState;\n } catch {\n await store.remove(key);\n throw new Error(\"Failed to parse stored OAuth state.\");\n }\n\n return { key, value, store };\n}\n\nfunction redirectWithError(returnUrl: string, message: string): void {\n const url = new URL(returnUrl);\n url.searchParams.set(\"auth_error\", \"oauth_callback_failed\");\n url.searchParams.set(\"auth_error_description\", message);\n window.location.href = url.toString();\n}\n\nfunction signalResult(\n success: boolean,\n error: string | undefined,\n storedState: StoredState | null,\n meta: AuthCallbackMeta\n): void {\n const payload = buildCallbackPayload(success, error, meta);\n const returnUrl = storedState?.returnUrl;\n const popup = storedState?.flowType === \"popup\" || isMcpAuthPopupWindow();\n\n if (storedState?.flowType === \"redirect\" && returnUrl) {\n if (success) window.location.href = returnUrl;\n else redirectWithError(returnUrl, error ?? \"Authentication failed.\");\n return;\n }\n\n if (window.opener && !window.opener.closed) {\n window.opener.postMessage(payload, window.location.origin);\n window.close();\n return;\n }\n\n if (popup) {\n broadcastCallback(payload);\n renderResult(\n success ? \"Authentication Successful!\" : \"Authentication Error\",\n success\n ? \"You're authenticated. You can close this window and return to the app.\"\n : (error ?? \"Authentication failed.\"),\n !success,\n returnUrl\n );\n try {\n window.close();\n } catch {\n // The browser may forbid closing after a COOP browsing-context swap.\n }\n return;\n }\n\n if (returnUrl) {\n if (success) window.location.href = returnUrl;\n else redirectWithError(returnUrl, error ?? \"Authentication failed.\");\n return;\n }\n\n if (!success) {\n renderResult(\n \"Authentication Error\",\n error ?? \"Authentication failed.\",\n true\n );\n return;\n }\n\n window.location.href = \"/\";\n}\n\n/**\n * Completes the browser OAuth callback once per page load.\n *\n * This host validates the CSRF state and restores the browser provider. The MCP\n * SDK transport owns callback parameter parsing, issuer validation, OAuth error\n * handling, and the authorization-code exchange.\n */\nexport function onMcpAuthorization(): Promise<void> {\n if (!inFlightCallback) inFlightCallback = completeAuthorization();\n return inFlightCallback;\n}\n\nasync function completeAuthorization(): Promise<void> {\n const callbackParams = new URLSearchParams(window.location.search);\n const state = callbackParams.get(\"state\");\n let stateKey: string | null = null;\n let stateStore: LocalStorageKVStore | null = null;\n let storedState: StoredState | null = null;\n let provider: BrowserOAuthClientProvider | null = null;\n\n try {\n if (!state) {\n throw new Error(\"OAuth callback is missing the state parameter.\");\n }\n\n const stored = await findStoredState(state);\n stateKey = stored.key;\n stateStore = stored.store;\n storedState = stored.value;\n\n if (!storedState.expiry || storedState.expiry < Date.now()) {\n await stateStore.remove(stateKey);\n throw new Error(\n \"OAuth state has expired. Please start authentication again.\"\n );\n }\n\n if (!storedState.providerOptions) {\n throw new Error(\"Stored OAuth state is missing provider options.\");\n }\n\n const { serverUrl, ...providerOptions } = storedState.providerOptions;\n provider = new BrowserOAuthClientProvider(serverUrl, providerOptions);\n\n const transport = new StreamableHTTPClientTransport(new URL(serverUrl), {\n authProvider: provider,\n fetch: provider.getProxyFetch(),\n });\n\n await transport.finishAuth(callbackParams);\n await stateStore.remove(stateKey);\n signalResult(true, undefined, storedState, {\n state,\n serverUrlHash: storedState.serverUrlHash,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\"[mcp-callback] OAuth callback failed:\", error);\n\n if (stateKey && stateStore) await stateStore.remove(stateKey);\n if (provider) {\n await (stateStore ?? new LocalStorageKVStore()).remove(\n provider.getKey(\"last_auth_url\")\n );\n }\n\n signalResult(false, message, storedState, {\n state,\n serverUrlHash: storedState?.serverUrlHash,\n });\n }\n}\n","// popup-runner.ts\n//\n// Opener-owned OAuth popup runner. Models the pattern used by mature browser\n// OAuth libraries (auth0-spa-js `runPopup`, oidc-client-ts `AbstractChildWindow`,\n// msal-browser popup clients): the window that OPENED the popup owns a promise\n// that settles on exactly one of four terminal outcomes, so the caller can never\n// be left waiting forever.\n//\n// A flow settles on the first of:\n// 1. An `mcp_auth_callback` result message (postMessage from the popup's\n// `window.opener`, or a same-origin `BroadcastChannel` when the opener was\n// severed by COOP / cross-origin redirects / tab grouping), matched to this\n// flow by its OAuth `state` parameter.\n// 2. The popup being closed (`popup.closed` poll). Before declaring the flow\n// cancelled we check whether tokens already landed in storage — the popup\n// may have completed the exchange and closed before its message dispatched.\n// 3. A `storage` event for this flow's tokens key. This is the most robust\n// signal: the popup always persists tokens to localStorage before notifying,\n// and `storage` events fire cross-window even when message channels are\n// severed or partitioned (the MSAL \"redirect bridge partition\" gotcha).\n// 4. A timeout. Same tokens check as the close path before declaring timeout.\n\n/** Channel name shared by the popup callback notifier and every listener. */\nexport const MCP_AUTH_BROADCAST_CHANNEL = \"mcp_auth_callback\";\n\n/** Result message type posted by the OAuth callback page. */\nexport const MCP_AUTH_CALLBACK_MESSAGE_TYPE = \"mcp_auth_callback\";\n\n/**\n * Payload shape posted by the OAuth callback page over `postMessage` /\n * `BroadcastChannel`. `state` and `serverUrlHash` are used to scope a result\n * to the flow / server that initiated it; both are optional for backward\n * compatibility with callback pages built against older versions.\n */\nexport interface McpAuthCallbackMessage {\n type?: string;\n success?: boolean;\n error?: string;\n /** OAuth `state` parameter of the originating authorization request. */\n state?: string;\n /** Hash of the server URL the flow authenticated against. */\n serverUrlHash?: string;\n}\n\n/** Terminal outcome of an opener-owned popup flow. */\ntype AuthPopupResult =\n | { kind: \"success\" }\n | { kind: \"error\"; error: string }\n | { kind: \"cancelled\" }\n | { kind: \"timeout\" };\n\ninterface RunAuthPopupOptions {\n /**\n * The popup window handle returned by `window.open`. May be `null` when the\n * popup was blocked or opened out-of-band (e.g. a manual fallback link); the\n * runner then relies on the message / storage / timeout signals only.\n */\n popup: globalThis.Window | null;\n /** OAuth `state` parameter for this flow. Used to ignore unrelated results. */\n state: string | null;\n /** localStorage key under which the flow's tokens are persisted on success. */\n tokensKey: string;\n /** Overall flow timeout. Default 5 minutes. */\n timeoutMs?: number;\n /** Interval for the `popup.closed` poll. Default 1s (matches auth0-spa-js). */\n closePollMs?: number;\n /**\n * How long to keep waiting for a result after the popup reports closed\n * without tokens, before settling `cancelled`. COOP browsing-context-group\n * swaps (popup navigating cross-origin) make `popup.closed` report `true`\n * while the real window is still open mid-flow, so a closed signal is only\n * a soft hint — message/storage listeners stay alive during this grace\n * window and can still settle `success`. Default 20s.\n */\n closeGraceMs?: number;\n /**\n * Origin to accept `postMessage` results from. Defaults to the current\n * window origin. BroadcastChannel results are same-origin by definition.\n */\n expectedOrigin?: string;\n}\n\nfunction hasStoredTokens(tokensKey: string): boolean {\n try {\n return (\n typeof localStorage !== \"undefined\" && !!localStorage.getItem(tokensKey)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Run an opener-owned OAuth popup flow and resolve once it reaches a terminal\n * outcome. Never rejects — all failure modes map to an {@link AuthPopupResult}.\n */\nexport function runAuthPopup({\n popup,\n state,\n tokensKey,\n timeoutMs = 5 * 60_000,\n closePollMs = 1000,\n closeGraceMs = 20_000,\n expectedOrigin = typeof window !== \"undefined\" ? window.location.origin : \"\",\n}: RunAuthPopupOptions): Promise<AuthPopupResult> {\n return new Promise<AuthPopupResult>((resolve) => {\n let settled = false;\n let closeTimer: ReturnType<typeof setInterval> | null = null;\n let timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n let graceTimer: ReturnType<typeof setTimeout> | null = null;\n let broadcastChannel: BroadcastChannel | null = null;\n\n const cleanup = () => {\n if (closeTimer) {\n clearInterval(closeTimer);\n closeTimer = null;\n }\n if (timeoutTimer) {\n clearTimeout(timeoutTimer);\n timeoutTimer = null;\n }\n if (graceTimer) {\n clearTimeout(graceTimer);\n graceTimer = null;\n }\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"message\", messageHandler);\n window.removeEventListener(\"storage\", storageHandler);\n }\n if (broadcastChannel) {\n try {\n broadcastChannel.removeEventListener(\"message\", broadcastHandler);\n broadcastChannel.close();\n } catch {\n /* ignore */\n }\n broadcastChannel = null;\n }\n };\n\n const settle = (result: AuthPopupResult) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(result);\n };\n\n // Shared handler for postMessage + BroadcastChannel result payloads.\n const handlePayload = (payload: McpAuthCallbackMessage | undefined) => {\n if (!payload || payload.type !== MCP_AUTH_CALLBACK_MESSAGE_TYPE) return;\n // State-keyed: ignore results from a different concurrent flow. Payloads\n // without a `state` (older callback pages) are accepted for back-compat.\n if (payload.state && state && payload.state !== state) return;\n if (payload.success) {\n settle({ kind: \"success\" });\n } else {\n settle({\n kind: \"error\",\n error: payload.error ?? \"Authentication failed in callback.\",\n });\n }\n };\n\n const messageHandler = (event: globalThis.MessageEvent) => {\n if (expectedOrigin && event.origin !== expectedOrigin) return;\n handlePayload(event.data as McpAuthCallbackMessage | undefined);\n };\n\n const broadcastHandler = (event: globalThis.MessageEvent) => {\n handlePayload(event.data as McpAuthCallbackMessage | undefined);\n };\n\n const storageHandler = (event: globalThis.StorageEvent) => {\n if (event.key !== tokensKey) return;\n // A non-null new value means the popup just persisted fresh tokens.\n if (event.newValue) settle({ kind: \"success\" });\n };\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", messageHandler);\n window.addEventListener(\"storage\", storageHandler);\n }\n\n if (typeof BroadcastChannel !== \"undefined\") {\n try {\n broadcastChannel = new BroadcastChannel(MCP_AUTH_BROADCAST_CHANNEL);\n broadcastChannel.addEventListener(\"message\", broadcastHandler);\n } catch {\n broadcastChannel = null;\n }\n }\n\n // Poll for popup closure. The user may close it without completing, or it\n // may complete and close before its result message is delivered.\n if (popup) {\n closeTimer = setInterval(() => {\n if (settled) return;\n let closed = false;\n try {\n closed = popup.closed;\n } catch {\n // Cross-origin access to `.closed` can throw under some engines;\n // treat as not-closed and keep waiting for other signals.\n closed = false;\n }\n if (!closed) return;\n if (closeTimer) {\n clearInterval(closeTimer);\n closeTimer = null;\n }\n if (hasStoredTokens(tokensKey)) {\n settle({ kind: \"success\" });\n return;\n }\n // Soft-close grace window: `popup.closed` is unreliable under COOP —\n // a cross-origin navigation swaps the browsing context group and the\n // original WindowProxy reports closed while the real window is still\n // open mid-consent (observed in the field: closed at ~3s, tokens\n // landing ~7s later). Keep the message/storage listeners alive and\n // only settle `cancelled` if nothing arrives within the grace window.\n graceTimer = setTimeout(() => {\n settle(\n hasStoredTokens(tokensKey)\n ? { kind: \"success\" }\n : { kind: \"cancelled\" }\n );\n }, closeGraceMs);\n }, closePollMs);\n }\n\n timeoutTimer = setTimeout(() => {\n settle(\n hasStoredTokens(tokensKey) ? { kind: \"success\" } : { kind: \"timeout\" }\n );\n }, timeoutMs);\n });\n}\n","import {\n auth,\n InsufficientScopeError,\n UnauthorizedError,\n type OAuthClientProvider,\n} from \"@modelcontextprotocol/client\";\nimport type { NodeOAuthAuthorizationResponse } from \"./node.js\";\nimport { runAuthPopup } from \"./popup.js\";\n\nconst DEFAULT_AUTH_TIMEOUT_MS = 5 * 60_000;\n\n/** Provider extras used by the Node loopback and browser popup flows. */\ntype FlowProvider = OAuthClientProvider & {\n serverUrlHash?: string;\n hasPendingFlow?: boolean;\n getAuthorizationResponse?: () => Promise<NodeOAuthAuthorizationResponse>;\n getAuthorizationCode?: () => Promise<string>;\n getProxyFetch?: (baseFetch?: typeof fetch) => typeof fetch | undefined;\n getKey?: (keySuffix: string) => string;\n getLastAttemptedAuthUrl?: () => string | null;\n markFlowComplete?: () => void;\n preventAutoAuth?: boolean;\n startAuthorization?: () => void;\n useRedirectFlow?: boolean;\n};\n\n/** Host callback used to complete the official transport's pending OAuth flow. */\ntype FinishOAuthAuthorization = (code: string, iss?: string) => Promise<void>;\n\n/**\n * True if the error (or a wrapped cause) is an HTTP 401 / UnauthorizedError\n * that should trigger the OAuth completion dance.\n */\nexport function isUnauthorized(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n if (err instanceof UnauthorizedError) return true;\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n if (code === 401) return true;\n if (err.name === \"UnauthorizedError\") return true;\n const message = err.message ?? \"\";\n if (message.includes(\"401\") || message.includes(\"Unauthorized\")) {\n return true;\n }\n if (err.cause && isUnauthorized(err.cause, depth + 1)) return true;\n const data = (err as { data?: { cause?: unknown } }).data;\n if (data?.cause && isUnauthorized(data.cause, depth + 1)) return true;\n }\n return false;\n}\n\n/**\n * True when the official SDK has started an interactive OAuth flow that the\n * host must finish before retrying the logical MCP operation.\n */\nexport function isOAuthInteractionRequired(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n if (\n err instanceof InsufficientScopeError ||\n err instanceof UnauthorizedError\n ) {\n return true;\n }\n if (err instanceof Error) {\n if (\n err.name === \"InsufficientScopeError\" ||\n err.name === \"UnauthorizedError\"\n ) {\n return true;\n }\n if (err.cause && isOAuthInteractionRequired(err.cause, depth + 1)) {\n return true;\n }\n const data = (err as { data?: { cause?: unknown } }).data;\n if (data?.cause && isOAuthInteractionRequired(data.cause, depth + 1)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Complete an in-progress or required OAuth authorization for `provider`.\n *\n * - Node loopback providers expose `getAuthorizationCode()`; we await the\n * code and finish the token exchange.\n * - Browser providers open a popup/redirect; we wait for the callback page\n * (`onMcpAuthorization`) to exchange the code and signal success over\n * `BroadcastChannel` / `postMessage`.\n *\n * Safe to call when the SDK transport already invoked `auth()` on a 401\n * (Node: `hasPendingFlow`; we skip a duplicate `auth()` in that case).\n */\nexport async function completeOAuthFlow(\n provider: OAuthClientProvider,\n serverUrl: string,\n options: {\n timeoutMs?: number;\n fetchFn?: typeof fetch;\n finishAuthorization?: FinishOAuthAuthorization;\n } = {}\n): Promise<void> {\n const flowProvider = provider as FlowProvider;\n const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;\n const fetchFn =\n options.fetchFn ?? flowProvider.getProxyFetch?.() ?? undefined;\n\n if (!flowProvider.hasPendingFlow) {\n const result = await auth(provider, { serverUrl, fetchFn });\n if (result === \"AUTHORIZED\") return;\n if (result !== \"REDIRECT\") {\n throw new Error(`Unexpected OAuth auth() result: ${result}`);\n }\n }\n\n // With preventAutoAuth, redirectToAuthorization() deliberately only stores\n // the SDK-prepared URL. An explicit authenticate() call is the user gesture\n // that should launch that already-prepared request.\n if (\n flowProvider.preventAutoAuth === true &&\n typeof flowProvider.startAuthorization === \"function\"\n ) {\n flowProvider.startAuthorization();\n }\n\n if (\n typeof flowProvider.getAuthorizationResponse === \"function\" ||\n typeof flowProvider.getAuthorizationCode === \"function\"\n ) {\n const response =\n typeof flowProvider.getAuthorizationResponse === \"function\"\n ? await flowProvider.getAuthorizationResponse()\n : { code: await flowProvider.getAuthorizationCode!() };\n if (options.finishAuthorization) {\n await options.finishAuthorization(response.code, response.iss);\n } else {\n // Connect-time authorization may no longer have its failed transport.\n // Keep the official top-level helper as the fallback for that case.\n await auth(provider, {\n serverUrl,\n authorizationCode: response.code,\n ...(response.iss !== undefined ? { iss: response.iss } : {}),\n fetchFn,\n });\n }\n return;\n }\n\n await waitForBrowserAuthComplete(flowProvider, timeoutMs);\n}\n\nasync function waitForBrowserAuthComplete(\n provider: FlowProvider,\n timeoutMs: number\n): Promise<void> {\n if (typeof window === \"undefined\") {\n throw new Error(\n \"OAuth redirect requires a browser environment or a provider with getAuthorizationCode()\"\n );\n }\n\n if (provider.useRedirectFlow) {\n // Do not return to the caller and retry the MCP connection before the\n // full-page navigation replaces this JavaScript context.\n await new Promise<void>(() => {});\n return;\n }\n\n const tokensKey = provider.getKey?.(\"tokens\");\n if (!tokensKey) {\n throw new Error(\n \"Browser OAuth provider must expose getKey() for token storage\"\n );\n }\n\n let state: string | null = null;\n const authUrl = provider.getLastAttemptedAuthUrl?.();\n if (authUrl) {\n try {\n state = new URL(authUrl).searchParams.get(\"state\");\n } catch {\n // state-less fallback is supported by runAuthPopup\n }\n }\n\n try {\n const result = await runAuthPopup({\n popup: null,\n state,\n tokensKey,\n timeoutMs,\n });\n\n switch (result.kind) {\n case \"success\":\n return;\n case \"cancelled\":\n throw new Error(\"OAuth authentication was cancelled.\");\n case \"timeout\":\n throw new Error(\n `OAuth callback not received within ${timeoutMs}ms. Ensure /oauth/callback calls onMcpAuthorization().`\n );\n case \"error\":\n throw new Error(result.error);\n default:\n throw new Error(\"Unexpected OAuth popup result\");\n }\n } finally {\n provider.markFlowComplete?.();\n }\n}\n","/**\n * Browser, worker, Bun, and Deno entry point for `@mcp-use/client`.\n *\n * This module intentionally exposes the same HTTP connection API as the Node\n * entry while excluding process spawning, filesystem configuration, and local\n * code execution.\n */\n\nimport \"./telemetry/configure-browser.js\";\n\nexport {\n createOAuthProvider,\n type OAuthProviderOptions,\n} from \"./auth/browser.js\";\nexport {\n BrowserOAuthClientProvider,\n type BrowserOAuthOptions,\n} from \"./auth/browser.js\";\nexport { onMcpAuthorization } from \"./auth/callback.js\";\nexport {\n completeOAuthFlow,\n isOAuthInteractionRequired,\n isUnauthorized,\n} from \"./auth/flow.js\";\nexport { auth, UnauthorizedError } from \"@modelcontextprotocol/client\";\n/** Browser-compatible MCP client for HTTP servers. */\nexport { BrowserMCPClient as MCPClient } from \"./core/browser.js\";\nexport * from \"./core/session.js\";\nexport * from \"./core/config.js\";\n\nexport * from \"./transport/base.js\";\nexport * from \"./transport/http.js\";\nexport * from \"./utils/json-schema-validator.js\";\n\nexport { logger } from \"./utils/logging.js\";\nexport {\n Tel,\n Telemetry,\n setTelemetrySource,\n setProductVersion,\n} from \"./telemetry/telemetry-browser.js\";\nexport {\n telFetch,\n capturePostHog,\n POSTHOG_HOST,\n POSTHOG_API_KEY,\n} from \"./telemetry/tel-fetch.js\";\nexport { getPackageVersion, VERSION } from \"./utils/version.js\";\nexport { detectFavicon } from \"./utils/favicon.js\";\n","import {\n Client,\n discoverOAuthProtectedResourceMetadata,\n SdkError,\n SdkHttpError,\n StreamableHTTPClientTransport,\n UnauthorizedError,\n type ClientOptions,\n type OAuthClientProvider,\n type VersionNegotiationMode,\n} from \"@modelcontextprotocol/client\";\nimport { completeOAuthFlow, isOAuthInteractionRequired } from \"../auth/flow.js\";\nimport type { MCPAuthorizationInfo } from \"../core/session.js\";\nimport { DialectJsonSchemaValidator } from \"../utils/json-schema-validator.js\";\nimport { logger } from \"../utils/logging.js\";\nimport type { ConnectorInitOptions } from \"./base.js\";\nimport { BaseConnector } from \"./base.js\";\n\nconst MIXED_AUTH_DISCOVERY_TIMEOUT_MS = 2_000;\n\n/**\n * Detect a 401 anywhere in an error / cause chain. Under\n * `versionNegotiation: \"auto\"` a connect-time 401 can surface wrapped as\n * `SdkError(EraNegotiationFailed)` with the `UnauthorizedError` at\n * `error.data.cause` (rather than a bare `SdkHttpError`), so we walk the chain.\n */\nfunction detectUnauthorized(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n if (err instanceof UnauthorizedError) return true;\n if (err instanceof SdkHttpError && err.status === 401) return true;\n if (err instanceof Error) {\n if (err.cause) {\n if (detectUnauthorized(err.cause, depth + 1)) return true;\n }\n const data = err instanceof SdkError ? (err.data as any) : undefined;\n if (data?.cause && detectUnauthorized(data.cause, depth + 1)) return true;\n }\n return false;\n}\n\n/** Client identity advertised to an MCP server during connection setup. */\nexport type ClientInfo = {\n /** Stable programmatic client name. */\n name: string;\n /** Optional human-readable client title. */\n title?: string;\n /** Client version string. */\n version: string;\n /** Human-readable client description. */\n description?: string;\n /** Icons representing the client. */\n icons?: Array<{\n /** Icon URL. */\n src: string;\n /** Icon media type. */\n mimeType?: string;\n /** Supported icon sizes, such as `\"48x48\"`. */\n sizes?: string[];\n }>;\n /** Public website describing the client. */\n websiteUrl?: string;\n};\n\n/** HTTP-specific connector options. */\ninterface HttpConnectorOptions extends ConnectorInitOptions {\n /** Bearer token added to the `Authorization` header. */\n authToken?: string;\n /** Fetch implementation used by transport requests. */\n fetch?: typeof fetch;\n /** Additional transport request headers. */\n headers?: Record<string, string>;\n /** Connection timeout in milliseconds. Defaults to `10000`. */\n timeout?: number;\n /** Client identity advertised to the server. */\n clientInfo?: ClientInfo;\n /**\n * Protocol version negotiation mode passed to the SDK `Client`.\n * - `\"auto\"` (mcp-use HTTP default): probe with `server/discover`, falling\n * back to the 2025 handshake against legacy servers.\n * - `\"legacy\"`: classic 2025 `initialize` handshake, no probe. This matches\n * the official SDK's default when used directly.\n * - In auto mode, the probe performs OAuth discovery on auth-required\n * servers and can fail on servers whose\n * authorization-server issuer differs from the server URL (RFC 8414 §3.3),\n * which would otherwise mask the normal 401 → auth flow.\n * - `{ pin: \"2026-07-28\" }`: modern era only, no fallback.\n */\n protocolNegotiation?: VersionNegotiationMode;\n /** Gateway endpoint through which MCP transport requests are routed. */\n gatewayUrl?: string;\n /** Server identifier forwarded to the gateway for observability. */\n serverId?: string;\n /** Retry settings for streamable HTTP reconnection. */\n reconnectionOptions?: {\n /** Maximum delay between reconnection attempts in milliseconds. */\n maxReconnectionDelay?: number;\n /** Delay before the first reconnection attempt in milliseconds. */\n initialReconnectionDelay?: number;\n /** Multiplier applied after each failed attempt. */\n reconnectionDelayGrowFactor?: number;\n /** Maximum number of reconnection attempts. */\n maxRetries?: number;\n };\n /** Detect RFC 9728 metadata after anonymous connection. Defaults to true. */\n detectMixedAuth?: boolean;\n}\n\ntype StreamableHttpFailure = {\n fallbackReason: string;\n is401Error: boolean;\n httpStatusCode?: number;\n};\n\nfunction isOAuthClientProvider(\n provider: ConnectorInitOptions[\"authProvider\"]\n): provider is OAuthClientProvider {\n return Boolean(\n provider &&\n \"redirectToAuthorization\" in provider &&\n typeof provider.redirectToAuthorization === \"function\" &&\n \"tokens\" in provider &&\n typeof provider.tokens === \"function\"\n );\n}\n\nfunction createMcpProxyFetch(\n logicalServerUrl: string,\n proxyUrl: string,\n baseFetch: typeof fetch,\n serverId?: string\n): typeof fetch {\n const logical = new URL(logicalServerUrl);\n const proxy = proxyUrl.replace(/\\/$/, \"\");\n\n return async (input, init) => {\n const request = new Request(input, init);\n const requestUrl = new URL(request.url);\n const isMcpTransportRequest =\n requestUrl.origin === logical.origin &&\n requestUrl.pathname === logical.pathname;\n\n // OAuth discovery/token requests deliberately keep their own URLs so a\n // separately injected OAuth BFF fetch can handle them.\n if (!isMcpTransportRequest) {\n return baseFetch(request);\n }\n\n const headers = new Headers(request.headers);\n headers.set(\"X-Target-URL\", request.url);\n if (serverId) headers.set(\"X-Server-Id\", serverId);\n\n const body =\n request.method === \"GET\" || request.method === \"HEAD\"\n ? undefined\n : await request.clone().arrayBuffer();\n\n return baseFetch(\n new Request(proxy, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: \"manual\",\n })\n );\n };\n}\n\nfunction createDeadlineFetch(\n baseFetch: typeof fetch,\n deadlineSignal: AbortSignal\n): typeof fetch {\n return async (input, init) => {\n const requestSignal = init?.signal;\n if (!requestSignal) {\n return baseFetch(input, { ...init, signal: deadlineSignal });\n }\n\n const controller = new AbortController();\n const abortFromRequest = () => controller.abort(requestSignal.reason);\n const abortFromDeadline = () => controller.abort(deadlineSignal.reason);\n\n if (requestSignal.aborted) abortFromRequest();\n else\n requestSignal.addEventListener(\"abort\", abortFromRequest, { once: true });\n\n if (deadlineSignal.aborted) abortFromDeadline();\n else\n deadlineSignal.addEventListener(\"abort\", abortFromDeadline, {\n once: true,\n });\n\n try {\n return await baseFetch(input, { ...init, signal: controller.signal });\n } finally {\n requestSignal.removeEventListener(\"abort\", abortFromRequest);\n deadlineSignal.removeEventListener(\"abort\", abortFromDeadline);\n }\n };\n}\n\n/**\n * Connects to an MCP server using streamable HTTP.\n *\n * The connector negotiates modern and legacy protocol eras by default and can\n * route transport requests through an HTTP gateway.\n */\nexport class HttpConnector extends BaseConnector {\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n private readonly timeout: number;\n private readonly customFetch?: typeof fetch;\n private readonly clientInfo: ClientInfo;\n private readonly protocolNegotiation: VersionNegotiationMode;\n private readonly gatewayUrl?: string;\n private readonly serverId?: string;\n private readonly reconnectionOptions?: HttpConnectorOptions[\"reconnectionOptions\"];\n private readonly detectMixedAuth: boolean;\n private transportType: \"streamable-http\" | null = null;\n private streamableTransport: StreamableHTTPClientTransport | null = null;\n private hadAccessTokenAtConnect = false;\n private pendingOAuthCompletion: Promise<void> | null = null;\n private authorizationDiscovery: Promise<\n MCPAuthorizationInfo | undefined\n > | null = null;\n\n /**\n * Creates an HTTP connector.\n *\n * @param baseUrl - MCP endpoint URL.\n * @param opts - Authentication, transport, SDK, and reconnection options.\n */\n constructor(baseUrl: string, opts: HttpConnectorOptions = {}) {\n super(opts);\n\n const originalUrl = baseUrl.replace(/\\/$/, \"\");\n this.baseUrl = originalUrl;\n this.headers = { ...(opts.headers ?? {}) };\n this.gatewayUrl = opts.gatewayUrl;\n this.serverId = opts.serverId;\n\n // Add auth token if provided\n if (opts.authToken) {\n this.headers.Authorization = `Bearer ${opts.authToken}`;\n }\n\n this.timeout = opts.timeout ?? 10000; // Default 10 seconds\n const baseFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.customFetch = this.gatewayUrl\n ? createMcpProxyFetch(\n originalUrl,\n this.gatewayUrl,\n baseFetch,\n this.serverId\n )\n : opts.fetch;\n this.clientInfo = opts.clientInfo ?? {\n name: \"http-connector\",\n version: \"1.0.0\",\n };\n // Negotiate the most capable protocol available. The SDK safely falls back\n // to the 2025 sessionful era for v1 servers while using v2's sessionless\n // server/discover flow when it is available.\n this.protocolNegotiation = opts.protocolNegotiation ?? \"auto\";\n this.reconnectionOptions = opts.reconnectionOptions;\n this.detectMixedAuth = opts.detectMixedAuth ?? true;\n }\n\n private get oauthProvider(): OAuthClientProvider | undefined {\n return isOAuthClientProvider(this.opts.authProvider)\n ? this.opts.authProvider\n : undefined;\n }\n\n private async completeInteractiveAuthorization(): Promise<void> {\n const provider = this.oauthProvider;\n if (!provider) {\n throw new Error(\"No OAuth client provider is configured\");\n }\n if (!this.pendingOAuthCompletion) {\n this.pendingOAuthCompletion = completeOAuthFlow(provider, this.baseUrl, {\n fetchFn: this.customFetch,\n finishAuthorization: async (code, iss) => {\n const transport = this.streamableTransport;\n if (!transport) {\n throw new Error(\"OAuth transport is no longer connected\");\n }\n await transport.finishAuth(code, iss);\n },\n })\n .then(() => {\n this.authorizationCache = {\n ...(this.authorizationCache ?? { mode: \"mixed\" }),\n authenticated: true,\n };\n })\n .finally(() => {\n this.pendingOAuthCompletion = null;\n });\n }\n await this.pendingOAuthCompletion;\n }\n\n protected override async executeRequest<T>(\n operation: () => Promise<T>\n ): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n const provider = this.oauthProvider as\n | (OAuthClientProvider & { preventAutoAuth?: boolean })\n | undefined;\n if (\n !provider ||\n provider.preventAutoAuth === true ||\n !isOAuthInteractionRequired(error)\n ) {\n throw error;\n }\n await this.completeInteractiveAuthorization();\n if (!this.connected || !this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n return operation();\n }\n }\n\n /** Authenticate an already-connected server without requiring a 401 first. */\n override async authenticate(): Promise<void> {\n if (!this.connected || !this.streamableTransport) {\n throw new Error(\"MCP client is not connected\");\n }\n await this.completeInteractiveAuthorization();\n }\n\n override async discoverAuthorization(): Promise<\n MCPAuthorizationInfo | undefined\n > {\n if (\n !this.detectMixedAuth ||\n !this.oauthProvider ||\n this.hadAccessTokenAtConnect\n ) {\n return this.authorizationCache;\n }\n\n if (this.authorizationDiscovery) return this.authorizationDiscovery;\n\n this.authorizationDiscovery = this.discoverMixedAuthorization().then(\n (authorization) => {\n // A missing or temporarily unavailable RFC 9728 endpoint must not be\n // cached for the lifetime of an otherwise healthy MCP connection.\n if (!authorization) this.authorizationDiscovery = null;\n return authorization;\n }\n );\n return this.authorizationDiscovery;\n }\n\n private async discoverMixedAuthorization(): Promise<\n MCPAuthorizationInfo | undefined\n > {\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const discoveryTimeout = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n const error = new Error(\n `Mixed-auth metadata discovery timed out after ${MIXED_AUTH_DISCOVERY_TIMEOUT_MS}ms`\n );\n controller.abort(error);\n reject(error);\n }, MIXED_AUTH_DISCOVERY_TIMEOUT_MS);\n });\n const baseFetch = this.customFetch ?? globalThis.fetch.bind(globalThis);\n\n try {\n const metadata = await Promise.race([\n discoverOAuthProtectedResourceMetadata(\n this.baseUrl,\n { protocolVersion: this.negotiatedProtocolVersion },\n createDeadlineFetch(baseFetch, controller.signal)\n ),\n discoveryTimeout,\n ]);\n this.authorizationCache = {\n mode: \"mixed\",\n authenticated: false,\n ...(metadata.resource ? { resource: metadata.resource } : {}),\n ...(metadata.scopes_supported\n ? { scopesSupported: [...metadata.scopes_supported] }\n : {}),\n };\n logger.info(\n \"OAuth protected-resource metadata found after anonymous connection; server uses mixed auth\"\n );\n } catch (error) {\n // RFC 9728 metadata is optional for anonymous servers. Discovery is a\n // best-effort classification and must never turn a valid MCP connection\n // into a failure.\n logger.debug(\"Mixed-auth metadata was not discovered:\", error);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n return this.authorizationCache;\n }\n\n private buildClientOptions(): ClientOptions {\n return {\n ...(this.opts.clientOptions || {}),\n jsonSchemaValidator:\n this.opts.clientOptions?.jsonSchemaValidator ??\n new DialectJsonSchemaValidator(),\n versionNegotiation: {\n // Allow a caller-supplied versionNegotiation in clientOptions to win.\n mode: this.protocolNegotiation,\n ...(this.opts.clientOptions?.versionNegotiation ?? {}),\n },\n listChanged: {\n tools: {\n autoRefresh: true,\n onChanged: (error, tools) =>\n void this.handleListChanged(\n \"notifications/tools/list_changed\",\n error,\n tools\n ),\n },\n resources: {\n autoRefresh: false,\n onChanged: (error) =>\n void this.handleListChanged(\n \"notifications/resources/list_changed\",\n error\n ),\n },\n prompts: {\n autoRefresh: false,\n onChanged: (error) =>\n void this.handleListChanged(\n \"notifications/prompts/list_changed\",\n error\n ),\n },\n ...(this.opts.clientOptions?.listChanged ?? {}),\n },\n capabilities: {\n ...(this.opts.clientOptions?.capabilities || {}),\n roots: { listChanged: true },\n ...(this.opts.onSampling ? { sampling: {} } : {}),\n ...(this.opts.onElicitation\n ? { elicitation: { form: {}, url: {} } }\n : {}),\n },\n };\n }\n\n // In v2 HTTP transport errors are thrown as SdkHttpError (subclass of\n // SdkError) with a numeric `.status` accessor, replacing v1's\n // StreamableHTTPError (which carried the status on `.code`).\n private unwrapStreamableError(err: unknown): SdkHttpError | null {\n if (err instanceof SdkHttpError) {\n return err;\n }\n if (err instanceof Error && err.cause instanceof SdkHttpError) {\n return err.cause;\n }\n return null;\n }\n\n private classifyStreamableHttpFailure(err: unknown): StreamableHttpFailure {\n let fallbackReason = \"Unknown error\";\n let is401Error = false;\n let httpStatusCode: number | undefined;\n\n const streamableErr = this.unwrapStreamableError(err);\n if (streamableErr) {\n const status = streamableErr.status;\n is401Error = status === 401;\n httpStatusCode = status;\n\n if (\n status === 400 &&\n streamableErr.message.includes(\"Missing session ID\")\n ) {\n fallbackReason = \"Server requires session ID\";\n logger.warn(`⚠️ ${fallbackReason}`);\n } else if (status === 404 || status === 405) {\n fallbackReason = `Server returned ${status} - server likely doesn't support streamable HTTP`;\n logger.debug(fallbackReason);\n } else {\n fallbackReason = `Server returned ${status}: ${streamableErr.message}`;\n logger.debug(fallbackReason);\n }\n\n return { fallbackReason, is401Error, httpStatusCode };\n }\n\n if (err instanceof Error) {\n const errorStr = err.toString();\n const errorMsg = err.message || \"\";\n is401Error =\n detectUnauthorized(err) ||\n errorStr.includes(\"401\") ||\n errorMsg.includes(\"Unauthorized\");\n\n if (\n errorStr.includes(\"Missing session ID\") ||\n errorStr.includes(\"Bad Request: Missing session ID\") ||\n errorMsg.includes(\"FastMCP session ID error\")\n ) {\n fallbackReason = \"Server requires session ID\";\n logger.warn(`⚠️ ${fallbackReason}`);\n } else if (\n errorStr.includes(\"405 Method Not Allowed\") ||\n errorStr.includes(\"404 Not Found\")\n ) {\n fallbackReason = \"Server doesn't support streamable HTTP (405/404)\";\n logger.debug(fallbackReason);\n } else {\n fallbackReason = `Streamable HTTP failed: ${err.message}`;\n logger.debug(fallbackReason);\n }\n }\n\n return { fallbackReason, is401Error, httpStatusCode };\n }\n\n /**\n * Establishes a streamable HTTP connection to the MCP server.\n *\n * @returns A promise that resolves after protocol negotiation completes.\n * @throws An error with `code: 401` when authentication is required.\n */\n async connect(): Promise<void> {\n if (this.connected) {\n logger.debug(\"Already connected to MCP implementation\");\n return;\n }\n\n const baseUrl = this.baseUrl;\n logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);\n\n const oauthProvider = this.oauthProvider;\n if (oauthProvider) {\n try {\n this.hadAccessTokenAtConnect = Boolean(\n (await oauthProvider.tokens())?.access_token\n );\n } catch {\n this.hadAccessTokenAtConnect = false;\n }\n }\n\n try {\n await this.connectWithStreamableHttp(baseUrl);\n logger.debug(\"✅ Successfully connected via streamable HTTP\");\n } catch (err: unknown) {\n logger.debug(\"Streamable HTTP connect failed\", err);\n const { fallbackReason, is401Error, httpStatusCode } =\n this.classifyStreamableHttpFailure(err);\n\n await this.cleanupResources();\n\n if (is401Error) {\n logger.info(\"Authentication required\");\n const authError = new Error(\"Authentication required\") as any;\n authError.code = 401;\n throw authError;\n }\n\n const finalError = new Error(\n `Could not connect via streamable HTTP: ${fallbackReason}`\n );\n if (httpStatusCode !== undefined) {\n Object.defineProperty(finalError, \"code\", {\n value: httpStatusCode,\n writable: false,\n enumerable: true,\n configurable: true,\n });\n }\n throw finalError;\n }\n }\n\n /**\n * Tee an SSE response so v2 MRTR progress can be correlated even when the\n * upstream SDK does not carry the original callback to retry request IDs.\n */\n private observeSseProgress(response: Response): Response {\n if (\n !response.body ||\n !response.headers.get(\"content-type\")?.includes(\"text/event-stream\")\n ) {\n return response;\n }\n const [body, observed] = response.body.tee();\n void (async () => {\n const reader = observed.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const events = buffer.split(/\\r?\\n\\r?\\n/);\n buffer = events.pop() ?? \"\";\n for (const event of events) {\n for (const line of event.split(/\\r?\\n/)) {\n if (!line.startsWith(\"data:\")) continue;\n try {\n const message = JSON.parse(line.slice(5).trim()) as {\n method?: string;\n params?: unknown;\n };\n if (message.method === \"notifications/progress\") {\n this.forwardRoundProgress(message.params);\n }\n } catch {\n // Ignore malformed/non-JSON SSE data; the SDK remains authoritative.\n }\n }\n }\n }\n } catch (error) {\n if (!(error instanceof DOMException && error.name === \"AbortError\")) {\n logger.debug(\"Progress observer stream ended:\", error);\n }\n } finally {\n reader.releaseLock();\n }\n })();\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n private async connectWithStreamableHttp(baseUrl: string): Promise<void> {\n try {\n logger.debug(\"[HttpConnector] Connecting with Streamable HTTP\", {\n baseUrl,\n originalUrl: this.baseUrl,\n gatewayUrl: this.gatewayUrl || \"none\",\n authProviderUrl:\n this.opts.authProvider &&\n \"serverUrl\" in this.opts.authProvider &&\n typeof this.opts.authProvider.serverUrl === \"string\"\n ? this.opts.authProvider.serverUrl\n : \"none\",\n headers: this.headers,\n });\n\n const baseFetch = this.customFetch ?? globalThis.fetch.bind(globalThis);\n const observedFetch: typeof fetch = async (input, init) => {\n const response = await baseFetch(input, init);\n const requestHeaders = new Headers(\n input instanceof Request ? input.headers : undefined\n );\n new Headers(init?.headers).forEach((value, key) => {\n requestHeaders.set(key, value);\n });\n // subscriptions/listen owns its SSE reader and acknowledgement state.\n // Re-wrapping that response breaks the SDK's per-request stream hooks;\n // the progress observer is only for ordinary request/response calls.\n return requestHeaders.get(\"mcp-method\") === \"subscriptions/listen\"\n ? response\n : this.observeSseProgress(response);\n };\n\n // Create StreamableHTTPClientTransport directly\n // The official SDK's StreamableHTTPClientTransport automatically handles session IDs\n // when client.connect() is called - it sends initialize, gets session ID from response header,\n // and opens the SSE stream with that session ID\n const streamableTransport = new StreamableHTTPClientTransport(\n new URL(baseUrl),\n {\n authProvider: this.opts.authProvider, // ← Pass OAuth provider to SDK\n fetch: observedFetch,\n requestInit: {\n headers: this.headers,\n },\n reconnectionOptions: {\n maxReconnectionDelay: 30000,\n initialReconnectionDelay: 1000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 2,\n ...this.reconnectionOptions,\n },\n // Don't pass sessionId - let the SDK generate it automatically during connect()\n }\n );\n\n // Store transport for cleanup (we'll create ConnectionManager later if needed for reconnection)\n let transport: StreamableHTTPClientTransport = streamableTransport;\n\n // Wrap transport if wrapper is provided\n if (this.opts.wrapTransport) {\n const serverId = this.baseUrl; // Use URL as server ID for now\n transport = this.opts.wrapTransport(\n transport,\n serverId\n ) as StreamableHTTPClientTransport;\n }\n\n // Create and connect the client\n // This performs both initialize AND initialized notification\n // Always advertise roots capability - server may query roots/list even if client has no roots\n const clientOptions = this.buildClientOptions();\n logger.debug(\n `Creating Client with capabilities:`,\n JSON.stringify(clientOptions.capabilities, null, 2)\n );\n this.client = new Client(this.clientInfo, clientOptions);\n\n // Register inbound handlers BEFORE connect() so they are available for the\n // entire connection lifetime (including reverse RPC during/after initialize).\n this.setupRootsHandler();\n this.setupSamplingHandler();\n this.setupElicitationHandler();\n this.setupNotificationHandler();\n logger.debug(\n \"Roots/sampling/elicitation/notification handlers registered before connect\"\n );\n\n try {\n // The SDK's StreamableHTTPClientTransport should automatically:\n // 1. Send POST initialize request\n // 2. Extract mcp-session-id from response header\n // 3. Open GET SSE stream with that session ID in header\n //\n // Keep the connection timeout outside the SDK request options so it\n // cannot leak onto streams opened during connection setup.\n let connectTimeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this.client.connect(transport),\n new Promise<never>((_, reject) => {\n connectTimeout = setTimeout(\n () =>\n reject(\n new Error(`MCP connection timed out after ${this.timeout}ms`)\n ),\n this.timeout\n );\n }),\n ]).finally(() => {\n if (connectTimeout !== undefined) clearTimeout(connectTimeout);\n });\n\n // The official SDK opens the optional v1 standalone GET stream in the\n // background after initialization. Do not gate ordinary request/response\n // readiness on that long-lived stream: proxies may buffer its headers,\n // while tools/list and other client operations are already usable.\n // Inbound request and notification handlers are registered above before\n // connect(), so the stream can attach later without racing handler setup.\n\n // Streamable HTTP servers may optionally assign a session ID.\n const sessionId = streamableTransport.sessionId;\n if (sessionId) {\n logger.debug(`Session ID obtained: ${sessionId}`);\n }\n } catch (connectErr) {\n // Check if the error is due to missing session ID during connection handshake\n if (connectErr instanceof Error) {\n const errMsg = connectErr.message || connectErr.toString();\n if (\n errMsg.includes(\"Missing session ID\") ||\n errMsg.includes(\"Bad Request: Missing session ID\") ||\n errMsg.includes(\"Mcp-Session-Id header is required\")\n ) {\n // Wrap it in a more specific error so the outer catch can detect it\n const wrappedError = new Error(\n `Session ID error: ${errMsg}. The SDK should automatically extract session ID from initialize response.`\n );\n wrappedError.cause = connectErr;\n throw wrappedError;\n }\n }\n throw connectErr;\n }\n\n // Store the transport for later cleanup\n this.streamableTransport = streamableTransport;\n // Create a minimal connection manager wrapper for cleanup purposes.\n // Note: terminateSession() is invoked from cleanupResources() *before*\n // the SDK's client.close() aborts the transport's abort controller.\n // Calling terminateSession() here would race the abort and surface a\n // spurious AbortError on every clean shutdown.\n this.connectionManager = {\n stop: async () => {\n if (this.streamableTransport) {\n try {\n await this.streamableTransport.close();\n } catch (e) {\n logger.warn(`Error closing Streamable HTTP transport: ${e}`);\n } finally {\n this.streamableTransport = null;\n }\n }\n },\n } as any;\n\n this.connected = true;\n this.transportType = \"streamable-http\";\n // Inbound request handlers (roots/sampling/elicitation) were registered before connect()\n logger.debug(\n `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`\n );\n\n // Track connector initialization\n this.trackConnectorInit({\n serverUrl: this.baseUrl,\n publicIdentifier: `${this.baseUrl} (streamable-http)`,\n });\n } catch (err) {\n // Clean up partial resources before throwing\n await this.cleanupResources();\n throw err;\n }\n }\n\n /**\n * Returns fields that identify the endpoint and negotiated transport.\n *\n * @returns HTTP connector identity metadata.\n */\n get publicIdentifier(): Record<string, string> {\n return {\n type: \"http\",\n url: this.baseUrl,\n transport: this.transportType || \"unknown\",\n protocolEra: this.protocolEra ?? \"unknown\",\n };\n }\n\n /**\n * Returns the active transport type.\n *\n * @returns `\"streamable-http\"` after connection, otherwise `null`.\n */\n getTransportType(): \"streamable-http\" | null {\n return this.transportType;\n }\n\n // Send the streamable-HTTP DELETE *before* super.cleanupResources() invokes\n // client.close(). The SDK's transport.close() aborts the shared abort\n // controller, and terminateSession()'s DELETE fetch reuses that signal —\n // running it after close() rejects immediately with AbortError.\n protected async cleanupResources(): Promise<void> {\n // Only legacy (2025-era) connections carry an Mcp-Session-Id worth\n // terminating. Modern (2026-07-28) connections are stateless per-request,\n // so there is no session DELETE to issue.\n if (this.streamableTransport && this.protocolEra !== \"modern\") {\n let terminationTimeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const terminated = await Promise.race([\n this.streamableTransport.terminateSession().then(() => true),\n new Promise<false>(\n (resolve) =>\n (terminationTimeout = setTimeout(\n () => resolve(false),\n Math.min(this.timeout, 5000)\n ))\n ),\n ]);\n if (!terminated) {\n logger.debug(\n \"Timed out terminating legacy HTTP session; closing transport\"\n );\n }\n } catch (e) {\n logger.debug(`Error terminating Streamable HTTP session: ${e}`);\n } finally {\n if (terminationTimeout) clearTimeout(terminationTimeout);\n }\n }\n await super.cleanupResources();\n this.authorizationDiscovery = null;\n }\n}\n","import type {\n JsonSchemaType,\n jsonSchemaValidator,\n} from \"@modelcontextprotocol/client\";\nimport {\n CfWorkerJsonSchemaValidator,\n type CfWorkerSchemaDraft,\n} from \"@modelcontextprotocol/client/validators/cf-worker\";\n\nconst DRAFT_04_URI = \"http://json-schema.org/draft-04/schema\";\nconst DRAFT_07_URIS = new Set([\n \"http://json-schema.org/draft-07/schema\",\n \"https://json-schema.org/draft-07/schema\",\n]);\nconst DRAFT_2019_09_URIS = new Set([\n \"https://json-schema.org/draft/2019-09/schema\",\n \"http://json-schema.org/draft/2019-09/schema\",\n]);\nconst DRAFT_2020_12_URIS = new Set([\n \"https://json-schema.org/draft/2020-12/schema\",\n \"http://json-schema.org/draft/2020-12/schema\",\n]);\n\nfunction resolveDraft(schema: JsonSchemaType): CfWorkerSchemaDraft | undefined {\n if (!(\"$schema\" in schema) || typeof schema.$schema !== \"string\") {\n return \"2020-12\";\n }\n\n const normalized = schema.$schema.replace(/#$/, \"\");\n\n if (normalized === DRAFT_04_URI) return \"4\";\n if (DRAFT_07_URIS.has(normalized)) return \"7\";\n if (DRAFT_2019_09_URIS.has(normalized)) return \"2019-09\";\n if (DRAFT_2020_12_URIS.has(normalized)) return \"2020-12\";\n\n return undefined;\n}\n\n/**\n * JSON Schema validator that maps common `$schema` dialect URIs to the\n * matching `@cfworker/json-schema` draft. The v2 SDK default rejects any\n * schema not declaring JSON Schema 2020-12 as an \"unsupported dialect\", which\n * breaks `tools/call` against v1-era servers that emit draft-04/-07/2019-09\n * `$schema` on tool `outputSchema` (mcp-use#1839). Unknown `$schema` URIs\n * still fail fast via the SDK's strict default validator.\n */\nexport class DialectJsonSchemaValidator implements jsonSchemaValidator {\n getValidator<T>(schema: JsonSchemaType) {\n const draft = resolveDraft(schema);\n const delegate =\n draft !== undefined\n ? new CfWorkerJsonSchemaValidator({ draft })\n : new CfWorkerJsonSchemaValidator();\n return delegate.getValidator<T>(schema);\n }\n}\n","import type {\n CallToolResult,\n Client,\n ClientOptions,\n CompleteRequestParams,\n CompleteResult,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n AuthProvider,\n JSONRPCMessage,\n Notification,\n OAuthClientProvider,\n ProtocolEra,\n RequestOptions,\n Root,\n Tool,\n} from \"@modelcontextprotocol/client\";\nimport { logger } from \"../utils/logging.js\";\nimport { isOAuthInteractionRequired } from \"../auth/flow.js\";\nimport type {\n SamplingCreateMessageParams,\n SamplingCreateMessageResult,\n} from \"../core/config.js\";\n\n/**\n * Accept-anything Standard Schema used for raw passthrough requests whose\n * method string is arbitrary (possibly non-spec). v2's `Protocol.request()`\n * requires a result schema for non-spec methods; this preserves the v1\n * \"return whatever the server sent\" behavior without importing Zod here.\n */\nconst passthroughResultSchema = {\n \"~standard\": {\n version: 1 as const,\n vendor: \"mcp-use\",\n validate: (value: unknown) => ({ value }),\n },\n};\n\nimport type { ConnectionManager } from \"./connection-manager.js\";\nimport type { ConnectorInitEventData } from \"../telemetry/events.js\";\nimport { trackConnectorTelemetry } from \"../telemetry/connector-telemetry.js\";\nimport type { MCPAuthorizationInfo, MCPServerInfo } from \"../core/session.js\";\n\n/**\n * Handles a notification received from an MCP server.\n *\n * @param notification - Notification envelope supplied by the server.\n */\nexport type NotificationHandler = (\n notification: Notification\n) => void | Promise<void>;\n\n/** Shared initialization options for all connector transports. */\nexport interface ConnectorInitOptions {\n /**\n * Options forwarded to the underlying MCP `Client` instance.\n *\n * By default, all connectors (HTTP and stdio) use `DialectJsonSchemaValidator`\n * to support common `$schema` dialects (draft-04, draft-07, 2019-09, 2020-12)\n * for cross-version compatibility with v1-era servers. Override with\n * `clientOptions.jsonSchemaValidator` if stricter validation is needed.\n */\n clientOptions?: ClientOptions;\n /**\n * Arbitrary request options (timeouts, cancellation, etc.) used by helper\n * methods when they issue SDK requests. Can be overridden per‑call.\n */\n defaultRequestOptions?: RequestOptions;\n /**\n * OAuth client provider for automatic authentication\n */\n authProvider?: AuthProvider | OAuthClientProvider;\n /**\n * Optional callback to wrap the transport before passing it to the Client.\n * Useful for logging, monitoring, or other transport-level interceptors.\n */\n wrapTransport?: (transport: any, serverId: string) => any;\n /**\n * Initial roots to provide to the server.\n * Roots allow the server to know which directories/files the client has access to.\n */\n roots?: Root[];\n /**\n * Optional callback function to handle sampling requests from servers.\n * When provided, the client will declare sampling capability and handle\n * `sampling/createMessage` requests by calling this callback.\n *\n * @deprecated Sampling is deprecated by the 2026 protocol. Retained for v1\n * push requests and v2 multi-round-trip compatibility.\n */\n onSampling?: (\n params: SamplingCreateMessageParams\n ) => Promise<SamplingCreateMessageResult>;\n /**\n * Optional callback function to handle elicitation requests from servers.\n * When provided, the client will declare elicitation capability and handle\n * `elicitation/create` requests by calling this callback.\n *\n * Elicitation allows servers to request additional information from users:\n * - Form mode: Collect structured data with JSON schema validation\n * - URL mode: Direct users to external URLs for sensitive interactions\n */\n onElicitation?: (\n params: ElicitRequestFormParams | ElicitRequestURLParams\n ) => Promise<ElicitResult>;\n /**\n * Optional callback for server notifications.\n * When provided, registered as initial notification handler.\n */\n onNotification?: NotificationHandler;\n /**\n * Reconnection options for streamable HTTP transport.\n * Controls retry behavior of the underlying `StreamableHTTPClientTransport`.\n */\n reconnectionOptions?: {\n /** Maximum delay between reconnection attempts in milliseconds. */\n maxReconnectionDelay?: number;\n /** Delay before the first reconnection attempt in milliseconds. */\n initialReconnectionDelay?: number;\n /** Multiplier applied to the delay after each failed attempt. */\n reconnectionDelayGrowFactor?: number;\n /** Maximum number of reconnection attempts. */\n maxRetries?: number;\n };\n}\n\n/**\n * Implements protocol operations shared by MCP transport connectors.\n *\n * Subclasses provide transport-specific connection setup and a public\n * identifier. Call {@link BaseConnector.connect}, then\n * {@link BaseConnector.initialize}, before invoking protocol operations.\n */\nexport abstract class BaseConnector {\n protected client: Client | null = null;\n protected connectionManager: ConnectionManager<any> | null = null;\n protected toolsCache: Tool[] | null = null;\n protected capabilitiesCache: Record<string, unknown> | null = null;\n protected serverInfoCache: MCPServerInfo | null = null;\n protected authorizationCache: MCPAuthorizationInfo | undefined;\n protected connected = false;\n protected readonly opts: ConnectorInitOptions;\n protected notificationHandlers: NotificationHandler[] = [];\n protected rootsCache: Root[] = [];\n private activeProgressHandlers = new Set<\n NonNullable<RequestOptions[\"onprogress\"]>\n >();\n\n /**\n * Creates a connector with shared SDK and callback options.\n *\n * @param opts - Connector initialization options.\n */\n constructor(opts: ConnectorInitOptions = {}) {\n this.opts = opts;\n // Initialize roots from options\n if (opts.roots) {\n this.rootsCache = [...opts.roots];\n }\n // Register initial notification handler if provided\n if (opts.onNotification) {\n this.notificationHandlers.push(opts.onNotification);\n }\n }\n\n /**\n * Track connector initialization event\n * Should be called by subclasses after successful connection\n */\n protected trackConnectorInit(\n data: Omit<ConnectorInitEventData, \"connectorType\">\n ): void {\n const connectorType = this.constructor.name;\n trackConnectorTelemetry({ connectorType, ...data });\n }\n\n /**\n * Register a handler for server notifications\n *\n * @param handler - Function to call when a notification is received\n *\n * @example\n * ```typescript\n * connector.onNotification((notification) => {\n * console.log(`Received: ${notification.method}`, notification.params);\n * });\n * ```\n */\n onNotification(handler: NotificationHandler): void {\n this.notificationHandlers.push(handler);\n // Wire up to SDK client if already connected\n if (this.client) {\n this.setupNotificationHandler();\n }\n }\n\n /** Forward a normalized notification to every registered consumer. */\n protected async forwardNotification(\n notification: Notification\n ): Promise<void> {\n for (const handler of this.notificationHandlers) {\n try {\n await handler(notification);\n } catch (err) {\n logger.error(\"Error in notification handler:\", err);\n }\n }\n }\n\n /** Handle SDK list-change callbacks identically on v1 and v2 connections. */\n protected async handleListChanged(\n method:\n | \"notifications/tools/list_changed\"\n | \"notifications/resources/list_changed\"\n | \"notifications/prompts/list_changed\",\n error: Error | null,\n tools?: Tool[] | null\n ): Promise<void> {\n if (error) {\n logger.warn(`[Auto] ${method} refresh failed:`, error);\n return;\n }\n if (method === \"notifications/tools/list_changed\" && tools) {\n this.toolsCache = [...tools];\n }\n await this.forwardNotification({ method } as Notification);\n }\n\n /**\n * Internal: wire notification handlers to the SDK client\n * Includes automatic handling for list_changed notifications per MCP spec\n */\n protected setupNotificationHandler(): void {\n if (!this.client) return;\n\n // Use fallbackNotificationHandler to catch all notifications\n this.client.fallbackNotificationHandler = async (\n notification: Notification\n ) => {\n // Auto-handle list_changed notifications per MCP spec\n // Clients SHOULD re-fetch the list when receiving these notifications\n switch (notification.method) {\n case \"notifications/tools/list_changed\":\n await this.refreshToolsCache();\n break;\n case \"notifications/resources/list_changed\":\n await this.onResourcesListChanged();\n break;\n case \"notifications/prompts/list_changed\":\n await this.onPromptsListChanged();\n break;\n default:\n break;\n }\n\n await this.forwardNotification(notification);\n };\n\n // The SDK registers specific handlers for progress and cancelled notifications\n // that bypass fallbackNotificationHandler entirely. Override them to also\n // forward to user-registered handlers so they appear in notification UIs.\n const client = this.client as any;\n const handlersMap = client._notificationHandlers as Map<\n string,\n (notification: Notification) => Promise<void>\n >;\n\n for (const method of [\n \"notifications/progress\",\n \"notifications/cancelled\",\n ]) {\n const originalHandler = handlersMap.get(method);\n if (originalHandler) {\n handlersMap.set(method, async (notification: Notification) => {\n await originalHandler(notification);\n await this.forwardNotification(notification);\n });\n }\n }\n }\n\n /**\n * Forward v2 MRTR progress whose retry request IDs are not associated with\n * the original call callback by the current SDK beta.\n *\n * ponytail: fallback is enabled only when exactly one progress-aware call is\n * active; remove it when the upstream SDK propagates handlers to MRTR rounds.\n */\n protected setupRoundProgressForwarding(): void {\n if (!this.client) return;\n const sdkClient = this.client as unknown as {\n _onnotification: (message: JSONRPCMessage) => void | Promise<void>;\n _progressHandlers?: Map<unknown, unknown>;\n };\n const original = sdkClient._onnotification.bind(this.client);\n sdkClient._onnotification = async (message: JSONRPCMessage) => {\n if (\n message &&\n typeof message === \"object\" &&\n (message as { method?: unknown }).method === \"notifications/progress\"\n ) {\n this.forwardRoundProgress((message as { params?: unknown }).params);\n }\n await original?.(message);\n };\n }\n\n /** Forward progress parsed from a transport stream to the active call. */\n protected forwardRoundProgress(params: unknown): void {\n if (this.activeProgressHandlers.size === 1) {\n const [handler] = this.activeProgressHandlers;\n handler?.(\n params as Parameters<NonNullable<RequestOptions[\"onprogress\"]>>[0]\n );\n }\n }\n\n /**\n * Auto-refresh tools cache when server sends tools/list_changed notification\n */\n protected async refreshToolsCache(): Promise<void> {\n if (!this.client) return;\n try {\n logger.debug(\n \"[Auto] Refreshing tools cache due to list_changed notification\"\n );\n const result = await this.client.listTools();\n this.toolsCache = (result.tools ?? []) as Tool[];\n logger.debug(\n `[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`\n );\n } catch (err) {\n logger.warn(\"[Auto] Failed to refresh tools cache:\", err);\n }\n }\n\n /**\n * Called when server sends resources/list_changed notification\n * Resources aren't cached by default, but we log for user awareness\n */\n protected async onResourcesListChanged(): Promise<void> {\n logger.debug(\n \"[Auto] Resources list changed - clients should re-fetch if needed\"\n );\n }\n\n /**\n * Called when server sends prompts/list_changed notification\n * Prompts aren't cached by default, but we log for user awareness\n */\n protected async onPromptsListChanged(): Promise<void> {\n logger.debug(\n \"[Auto] Prompts list changed - clients should re-fetch if needed\"\n );\n }\n\n /**\n * Set roots and notify the server.\n * Roots represent directories or files that the client has access to.\n *\n * @param roots - Array of Root objects with `uri` (must start with \"file://\") and optional `name`\n *\n * @deprecated Roots are retained only for v1 compatibility.\n *\n * @example\n * ```typescript\n * await connector.setRoots([\n * { uri: \"file:///home/user/project\", name: \"My Project\" },\n * { uri: \"file:///home/user/data\" }\n * ]);\n * ```\n */\n async setRoots(roots: Root[]): Promise<void> {\n this.rootsCache = [...roots];\n if (this.client) {\n logger.debug(\n `Sending roots/list_changed notification with ${roots.length} root(s)`\n );\n await this.client.sendRootsListChanged();\n }\n }\n\n /**\n * Returns the roots currently advertised to the server.\n *\n * @returns A copy of the configured roots.\n */\n getRoots(): Root[] {\n return [...this.rootsCache];\n }\n\n /**\n * Internal: set up roots/list request handler.\n * Must be registered after Client construction and before connect() so the\n * handler is available during initialize / reverse RPC for the full session.\n */\n protected setupRootsHandler(): void {\n if (!this.client) return;\n\n // Handle roots/list requests from the server\n this.client.setRequestHandler(\"roots/list\", async () => {\n logger.debug(\n `Server requested roots list, returning ${this.rootsCache.length} root(s)`\n );\n return { roots: this.rootsCache };\n });\n }\n\n /**\n * Internal: set up sampling/createMessage request handler.\n * Must be registered after Client construction and before connect().\n */\n protected setupSamplingHandler(): void {\n if (!this.client) {\n logger.debug(\"setupSamplingHandler: No client available\");\n return;\n }\n const samplingCallback = this.opts.onSampling;\n if (!samplingCallback) {\n logger.debug(\"setupSamplingHandler: No sampling callback provided\");\n return;\n }\n\n logger.debug(\"setupSamplingHandler: Setting up sampling request handler\");\n // Handle sampling/createMessage requests from the server\n this.client.setRequestHandler(\"sampling/createMessage\", async (request) => {\n logger.debug(\"Server requested sampling, forwarding to callback\");\n return await samplingCallback(request.params);\n });\n logger.debug(\n \"setupSamplingHandler: Sampling handler registered successfully\"\n );\n }\n\n /**\n * Internal: set up elicitation/create request handler.\n * Must be registered after Client construction and before connect().\n */\n protected setupElicitationHandler(): void {\n if (!this.client) {\n logger.debug(\"setupElicitationHandler: No client available\");\n return;\n }\n const elicitationCallback = this.opts.onElicitation;\n if (!elicitationCallback) {\n logger.debug(\"setupElicitationHandler: No elicitation callback provided\");\n return;\n }\n\n logger.debug(\n \"setupElicitationHandler: Setting up elicitation request handler\"\n );\n // Handle elicitation/create requests from the server\n this.client.setRequestHandler(\"elicitation/create\", async (request) => {\n logger.debug(\"Server requested elicitation, forwarding to callback\");\n return await elicitationCallback(\n request.params as ElicitRequestFormParams | ElicitRequestURLParams\n );\n });\n logger.debug(\n \"setupElicitationHandler: Elicitation handler registered successfully\"\n );\n }\n\n /**\n * Establishes the transport connection and creates the SDK client.\n *\n * @returns A promise that resolves when the connector is connected.\n */\n abstract connect(): Promise<void>;\n\n /**\n * Returns transport-specific fields suitable for logs and telemetry.\n *\n * @returns A record identifying the connector without exposing credentials.\n */\n abstract get publicIdentifier(): Record<string, string>;\n\n /**\n * Run one logical MCP operation. HTTP connectors override this host seam to\n * finish an SDK-started interactive OAuth flow and retry exactly once.\n */\n protected async executeRequest<T>(operation: () => Promise<T>): Promise<T> {\n return operation();\n }\n\n /** OAuth state discovered for the active connection, when available. */\n get authorization(): MCPAuthorizationInfo | undefined {\n return this.authorizationCache;\n }\n\n /**\n * Discover optional authorization metadata without delaying connection\n * readiness. HTTP connectors override this with RFC 9728 discovery.\n */\n async discoverAuthorization(): Promise<MCPAuthorizationInfo | undefined> {\n return this.authorization;\n }\n\n /** Start optional OAuth for a connected mixed-auth server. */\n async authenticate(): Promise<void> {\n throw new Error(\"This connector does not support interactive OAuth\");\n }\n\n /**\n * Disconnects the SDK client and releases transport resources.\n *\n * @returns A promise that resolves after cleanup completes.\n */\n async disconnect(): Promise<void> {\n if (!this.connected) {\n logger.debug(\"Not connected to MCP implementation\");\n return;\n }\n\n logger.debug(\"Disconnecting from MCP implementation\");\n await this.cleanupResources();\n this.connected = false;\n logger.debug(\"Disconnected from MCP implementation\");\n }\n\n /** Whether an SDK client currently exists for this connector. */\n get isClientConnected(): boolean {\n return this.client != null;\n }\n\n /**\n * Initialise the MCP session **after** `connect()` has succeeded.\n *\n * In the SDK, `Client.connect(transport)` automatically performs the\n * protocol‑level `initialize` handshake, so we only need to cache the list of\n * tools and expose some server info.\n *\n * @param defaultRequestOptions - Options used while fetching the initial tool list.\n * @returns The capabilities advertised by the server.\n * @throws When {@link BaseConnector.connect} has not completed.\n */\n async initialize(\n defaultRequestOptions: RequestOptions = this.opts.defaultRequestOptions ??\n {}\n ): Promise<ReturnType<Client[\"getServerCapabilities\"]>> {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(\"Caching server capabilities & tools\");\n\n // Cache server capabilities for callers who need them.\n const capabilities = this.client.getServerCapabilities();\n this.capabilitiesCache = (capabilities as Record<string, unknown>) || null;\n\n // The SDK normalizes identity from legacy initialize responses and modern\n // result metadata. Modern servers may remain anonymous.\n const serverInfo = this.client.getServerVersion();\n this.serverInfoCache = serverInfo\n ? {\n name: serverInfo.name,\n version: serverInfo.version,\n title: serverInfo.title,\n description: serverInfo.description,\n websiteUrl: serverInfo.websiteUrl,\n icons: serverInfo.icons,\n }\n : null;\n\n // Fetch and cache tools\n // Gracefully handle servers that don't implement tools/list or have no tools\n try {\n const listToolsRes = await this.executeRequest(() =>\n this.client!.listTools(undefined, defaultRequestOptions)\n );\n this.toolsCache = (listToolsRes.tools ?? []) as Tool[];\n logger.debug(`Fetched ${this.toolsCache.length} tools from server`);\n } catch (err: unknown) {\n if (isOAuthInteractionRequired(err)) throw err;\n const error = err as Error & { code?: number };\n // If tools/list is not implemented or fails, assume no tools\n // This commonly happens with blank servers that have no tools registered\n if (error.code === -32601) {\n logger.debug(\"Server does not implement tools/list, assuming no tools\");\n } else {\n logger.debug(\"Failed to list tools, assuming empty:\", error.message);\n }\n this.toolsCache = [];\n }\n\n logger.debug(\"Server capabilities:\", capabilities);\n logger.debug(\"Server info:\", serverInfo);\n return capabilities;\n }\n\n /**\n * Returns the tool list cached during initialization.\n *\n * @throws When {@link BaseConnector.initialize} has not completed.\n */\n get tools(): Tool[] {\n if (!this.toolsCache) {\n throw new Error(\"MCP client is not initialized; call initialize() first\");\n }\n return this.toolsCache;\n }\n\n /** Capabilities cached during initialization, or an empty object. */\n get serverCapabilities(): Record<string, unknown> {\n return this.capabilitiesCache || {};\n }\n\n /** Server identity cached during initialization, or `null`. */\n get serverInfo(): MCPServerInfo | null {\n return this.serverInfoCache;\n }\n\n /** Instructions supplied by the connected server, if any. */\n get instructions(): string | undefined {\n return this.client?.getInstructions?.();\n }\n\n /**\n * The negotiated protocol era for the active connection.\n * - `\"legacy\"` — 2025-era server, sessionful `initialize` handshake.\n * - `\"modern\"` — 2026-era server, stateless per-request.\n * `undefined` before the connection has negotiated.\n */\n get protocolEra(): ProtocolEra | undefined {\n return this.client?.getProtocolEra?.();\n }\n\n /** The protocol version string negotiated for the active connection. */\n get negotiatedProtocolVersion(): string | undefined {\n return this.client?.getNegotiatedProtocolVersion?.();\n }\n\n /**\n * Calls a tool on the connected server.\n *\n * @param name - Tool name.\n * @param args - Tool arguments.\n * @param options - Per-request timeout, cancellation, and progress options.\n * @returns The tool result returned by the server.\n * @throws When the connector is not connected or the tool call fails.\n */\n async callTool(\n name: string,\n args: Record<string, any>,\n options?: RequestOptions\n ): Promise<CallToolResult> {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n // If resetTimeoutOnProgress is enabled but no onprogress callback is provided,\n // add a no-op callback to trigger the SDK to add progressToken to the request.\n // The SDK only adds progressToken when onprogress is present, which is required\n // for the server to send progress notifications that reset the timeout.\n const enhancedOptions = options ? { ...options } : undefined;\n if (\n enhancedOptions?.resetTimeoutOnProgress &&\n !enhancedOptions.onprogress\n ) {\n // Add no-op progress callback to trigger progressToken addition\n enhancedOptions.onprogress = () => {\n // No-op: progress notifications are handled by the SDK's timeout reset logic\n };\n logger.debug(\n `[BaseConnector] Added onprogress callback for tool '${name}' to enable progressToken`\n );\n }\n\n logger.debug(`Calling tool '${name}' with args`, args);\n const progressHandler = enhancedOptions?.onprogress;\n if (progressHandler) this.activeProgressHandlers.add(progressHandler);\n try {\n const res = await this.executeRequest(() =>\n this.client!.callTool({ name, arguments: args }, enhancedOptions)\n );\n logger.debug(`Tool '${name}' returned`, res);\n return res as CallToolResult;\n } finally {\n if (progressHandler) this.activeProgressHandlers.delete(progressHandler);\n }\n }\n\n /**\n * List all available tools from the MCP server.\n * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.\n *\n * @param options - Optional request options\n * @returns Array of available tools\n */\n async listTools(options?: RequestOptions): Promise<Tool[]> {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n logger.debug(\"[listTools] Fetching fresh tools from server...\");\n const result = await this.executeRequest(() =>\n this.client!.listTools(undefined, options)\n );\n // Create a new array to ensure React detects the change (avoid reference equality issues)\n const tools = result.tools ? [...result.tools] : [];\n logger.debug(\n `[listTools] Returned ${tools.length} tools:`,\n tools.map((t) => t.name)\n );\n return tools;\n }\n\n /**\n * List resources from the server with optional pagination\n *\n * @param cursor - Optional cursor for pagination\n * @param options - Request options\n * @returns Resource list with optional nextCursor for pagination\n */\n async listResources(cursor?: string, options?: RequestOptions) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(\"Listing resources\", cursor ? `with cursor: ${cursor}` : \"\");\n return await this.executeRequest(() =>\n this.client!.listResources({ cursor }, options)\n );\n }\n\n /**\n * List all resources from the server, automatically handling pagination\n *\n * @param options - Request options\n * @returns Complete list of all resources\n */\n async listAllResources(options?: RequestOptions): Promise<{\n /** Resources returned across all result pages. */\n resources: any[];\n }> {\n // Held across the pagination loop below: `disconnect()` clears\n // `this.client`, and re-reading it once per page would dereference null\n // mid-listing instead of failing on the closed transport.\n const client = this.client;\n if (!client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n // Check if server advertises resources capability\n if (!this.capabilitiesCache?.resources) {\n logger.debug(\"Server does not advertise resources capability, skipping\");\n return { resources: [] };\n }\n\n try {\n logger.debug(\"Listing all resources (with auto-pagination)\");\n return await this.executeRequest(async () => {\n const allResources: any[] = [];\n let cursor: string | undefined = undefined;\n\n do {\n const result: { resources?: any[]; nextCursor?: string } =\n await client.listResources({ cursor }, options);\n allResources.push(...(result.resources || []));\n cursor = result.nextCursor;\n } while (cursor);\n\n return { resources: allResources };\n });\n } catch (err: unknown) {\n const error = err as Error & { code?: number };\n // Gracefully handle if server advertises but doesn't actually support it\n if (error.code === -32601) {\n logger.debug(\"Server advertised resources but method not found\");\n return { resources: [] };\n }\n throw err;\n }\n }\n\n /**\n * List resource templates from the server\n *\n * @param options - Request options\n * @returns List of available resource templates\n */\n async listResourceTemplates(options?: RequestOptions) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(\"Listing resource templates\");\n return await this.executeRequest(() =>\n this.client!.listResourceTemplates(undefined, options)\n );\n }\n\n /**\n * Request completion suggestions for a prompt or resource template argument\n *\n * @param params - Completion request parameters\n * @param options - Request options\n * @returns Completion suggestions from the server\n */\n async complete(\n params: CompleteRequestParams,\n options?: RequestOptions\n ): Promise<CompleteResult> {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n logger.debug(\"[complete] Requesting completions for:\", params.ref);\n const result = await this.executeRequest(() =>\n this.client!.complete(params, options)\n );\n logger.debug(\n `[complete] Received ${result.completion.values.length} suggestions`\n );\n return result;\n }\n\n /**\n * Reads a resource by URI.\n *\n * @param uri - Resource URI to read.\n * @param options - Per-request options.\n * @returns The resource contents returned by the server.\n */\n async readResource(uri: string, options?: RequestOptions) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(`Reading resource ${uri}`);\n const res = await this.executeRequest(() =>\n this.client!.readResource({ uri }, options)\n );\n return res;\n }\n\n /**\n * Subscribe to resource updates\n *\n * @param uri - URI of the resource to subscribe to\n * @param options - Request options\n */\n async subscribeToResource(uri: string, options?: RequestOptions) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(`Subscribing to resource: ${uri}`);\n return await this.executeRequest(() =>\n this.client!.subscribeResource({ uri }, options)\n );\n }\n\n /**\n * Unsubscribe from resource updates\n *\n * @param uri - URI of the resource to unsubscribe from\n * @param options - Request options\n */\n async unsubscribeFromResource(uri: string, options?: RequestOptions) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(`Unsubscribing from resource: ${uri}`);\n return await this.executeRequest(() =>\n this.client!.unsubscribeResource({ uri }, options)\n );\n }\n\n /**\n * Lists prompts exposed by the server.\n *\n * @returns The prompt list, or an empty list when prompts are unsupported.\n */\n async listPrompts() {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n // Check if server advertises prompts capability\n if (!this.capabilitiesCache?.prompts) {\n logger.debug(\"Server does not advertise prompts capability, skipping\");\n return { prompts: [] };\n }\n\n try {\n logger.debug(\"Listing prompts\");\n return await this.executeRequest(() => this.client!.listPrompts());\n } catch (err: unknown) {\n const error = err as Error & { code?: number };\n // Gracefully handle if server advertises but doesn't actually support it\n if (error.code === -32601) {\n logger.debug(\"Server advertised prompts but method not found\");\n return { prompts: [] };\n }\n throw err;\n }\n }\n\n /**\n * Gets a prompt with the supplied arguments.\n *\n * @param name - Prompt name.\n * @param args - Prompt arguments.\n * @param options - Per-request timeout, cancellation, and progress options.\n * @returns The rendered prompt returned by the server.\n */\n async getPrompt(\n name: string,\n args: Record<string, any>,\n options?: RequestOptions\n ) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(`Getting prompt ${name}`);\n return await this.executeRequest(() =>\n this.client!.getPrompt({ name, arguments: args }, options)\n );\n }\n\n /**\n * Sends a raw, potentially non-standard request through the SDK client.\n *\n * @param method - JSON-RPC method name.\n * @param params - Request parameters. Defaults to an empty object.\n * @param options - Per-request options.\n * @returns The unvalidated result returned by the server.\n */\n async request(\n method: string,\n params: Record<string, any> | null = null,\n options?: RequestOptions\n ) {\n if (!this.client) {\n throw new Error(\"MCP client is not connected\");\n }\n\n logger.debug(`Sending raw request '${method}' with params`, params);\n // v2 requires a result schema for non-spec methods; a passthrough schema\n // preserves the v1 behavior of returning the raw server result for any\n // method string.\n return await this.executeRequest(() =>\n this.client!.request(\n { method, params: params ?? {} },\n passthroughResultSchema,\n options\n )\n );\n }\n\n /**\n * Helper to tear down the client & connection manager safely.\n */\n protected async cleanupResources(): Promise<void> {\n const issues: string[] = [];\n\n if (this.client) {\n try {\n if (typeof this.client.close === \"function\") {\n await this.client.close();\n }\n } catch (e) {\n const msg = `Error closing client: ${e}`;\n logger.warn(msg);\n issues.push(msg);\n } finally {\n this.client = null;\n }\n }\n\n if (this.connectionManager) {\n try {\n await this.connectionManager.stop();\n } catch (e) {\n const msg = `Error stopping connection manager: ${e}`;\n logger.warn(msg);\n issues.push(msg);\n } finally {\n this.connectionManager = null;\n }\n }\n\n this.toolsCache = null;\n this.authorizationCache = undefined;\n if (issues.length) {\n logger.warn(`Resource cleanup finished with ${issues.length} issue(s)`);\n }\n }\n}\n","import type {\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n Notification,\n AuthProvider,\n OAuthClientInformation,\n OAuthClientProvider,\n Root,\n RequestTypeMap,\n RequestOptions,\n ResultTypeMap,\n ClientOptions,\n VersionNegotiationMode,\n} from \"@modelcontextprotocol/client\";\nimport type { BaseConnector, ConnectorInitOptions } from \"../transport/base.js\";\nimport type { ClientInfo } from \"../transport/http.js\";\nimport { HttpConnector } from \"../transport/http.js\";\nimport type { StdioStderrMode } from \"../transport/stdio.js\";\nimport { getPackageVersion } from \"../utils/version.js\";\n\n/** Parameters accepted by the MCP `sampling/createMessage` request. */\nexport type SamplingCreateMessageParams =\n RequestTypeMap[\"sampling/createMessage\"][\"params\"];\n\n/** Result returned for the MCP `sampling/createMessage` request. */\nexport type SamplingCreateMessageResult =\n ResultTypeMap[\"sampling/createMessage\"];\n\n/**\n * Handles a sampling request initiated by an MCP server.\n *\n * @param params - Sampling request parameters supplied by the server.\n * @returns The model-generated sampling result.\n */\nexport type OnSamplingCallback = (\n params: SamplingCreateMessageParams\n) => Promise<SamplingCreateMessageResult>;\n\n/**\n * Handles a form or URL elicitation request initiated by an MCP server.\n *\n * @param params - Elicitation request parameters supplied by the server.\n * @returns The user's elicitation decision and optional content.\n */\nexport type OnElicitationCallback = (\n params: ElicitRequestFormParams | ElicitRequestURLParams\n) => Promise<ElicitResult>;\n\n/**\n * Handles a notification sent by an MCP server.\n *\n * @param notification - The notification envelope supplied by the server.\n */\nexport type OnNotificationCallback = (\n notification: Notification\n) => void | Promise<void>;\n\n/**\n * Callback options shared by per-server config and global defaults.\n */\nexport interface CallbackConfig {\n /**\n * Callback for sampling input.\n *\n * @deprecated Sampling is deprecated by the 2026 protocol. Retained for v1\n * push requests and the v2 `input_required` compatibility window.\n */\n onSampling?: OnSamplingCallback;\n /** Callback for elicitation requests from servers. */\n onElicitation?: OnElicitationCallback;\n /** Callback for notifications from servers. */\n onNotification?: OnNotificationCallback;\n}\n\n/**\n * Resolves callback handlers, preferring per-server values over global values.\n *\n * @param perServer - Callback overrides for one server.\n * @param globalDefaults - Fallback callbacks shared by all servers.\n * @returns The effective callbacks for the server.\n */\nexport function resolveCallbacks(\n perServer: CallbackConfig | undefined,\n globalDefaults: CallbackConfig | undefined\n): {\n /** Effective sampling callback. */\n onSampling?: OnSamplingCallback;\n /** Effective elicitation callback. */\n onElicitation?: OnElicitationCallback;\n /** Effective notification callback. */\n onNotification?: OnNotificationCallback;\n} {\n const pickSampling = perServer?.onSampling ?? globalDefaults?.onSampling;\n const pickElicitation =\n perServer?.onElicitation ?? globalDefaults?.onElicitation;\n const pickNotification =\n perServer?.onNotification ?? globalDefaults?.onNotification;\n\n return {\n onSampling: pickSampling,\n onElicitation: pickElicitation,\n onNotification: pickNotification,\n };\n}\n\n/**\n * Base server configuration with common optional fields\n */\n/** Options shared by HTTP and stdio server configurations. */\ninterface BaseServerConfig extends CallbackConfig {\n /** Client identity advertised to the server. */\n clientInfo?: ClientInfo;\n /** Initial roots advertised to the server. */\n roots?: Root[];\n /** Options forwarded to the official MCP SDK Client. */\n clientOptions?: ClientOptions;\n /** Default timeout/cancellation options for requests. */\n defaultRequestOptions?: RequestOptions;\n}\n\n/**\n * Configures a local MCP server launched over standard input and output.\n */\nexport interface StdioServerConfig extends BaseServerConfig {\n /** Executable used to start the server. */\n command: string;\n /** Arguments passed to {@link StdioServerConfig.command}. */\n args: string[];\n /** Environment variables merged with the current process environment. */\n env?: Record<string, string>;\n /** Working directory used to launch the server process. */\n cwd?: string;\n /**\n * How the server process's standard error is handled. Defaults to `\"pipe\"`,\n * which forwards it to the connector's `errlog`. Use `\"inherit\"` to give the\n * child the parent's stderr file descriptor instead, preserving TTY\n * detection and colorization, or `\"ignore\"` to discard it.\n */\n stderr?: StdioStderrMode;\n /**\n * Protocol version negotiation mode. Defaults to `\"legacy\"` for stdio (the\n * SDK advises against probing for spawn-per-invocation tools). See\n * {@link StdioConnector}.\n */\n protocolNegotiation?: VersionNegotiationMode;\n}\n\n/**\n * Options forwarded to the platform `createOAuthProvider` when the client\n * auto-provisions OAuth for an HTTP server. Platform-specific fields\n * (e.g. Node `openBrowser`, browser `oauthProxyUrl`) are accepted and ignored\n * by the other runtime.\n */\nexport interface AutoOAuthOptions {\n /** Prefix used for persisted OAuth session keys. */\n storageKeyPrefix?: string;\n /** OAuth client display name. */\n clientName?: string;\n /** Public URL describing the OAuth client. */\n clientUri?: string;\n /** Public URL for the OAuth client logo. */\n logoUri?: string;\n /** OAuth redirect URI. The platform provider supplies a default when omitted. */\n callbackUrl?: string;\n /** URL of an OAuth Client ID Metadata Document. */\n clientMetadataUrl?: string;\n /** Space-delimited OAuth scopes to request. */\n scope?: string;\n /** Pre-registered public client id (skips DCR). */\n staticClientInfo?: OAuthClientInformation;\n /** Preferred Node loopback port. Defaults to `33418`. */\n preferredPort?: number;\n /** Number of Node loopback ports to try. Defaults to `10`. */\n portRange?: number;\n /** Node loopback callback timeout in milliseconds. Defaults to five minutes. */\n authTimeoutMs?: number;\n /** Node: override browser launch (CLI prints the URL instead). */\n openBrowser?: (url: string) => void | Promise<void>;\n /** Browser: wait for explicit authenticate() instead of auto popup. */\n preventAutoAuth?: boolean;\n /** Browser: full-page redirect instead of popup. */\n useRedirectFlow?: boolean;\n /** Browser: same-origin OAuth BFF base URL. */\n oauthProxyUrl?: string;\n /** Whether browser OAuth HTTP uses `oauthProxyUrl`. Defaults to `true` when the URL is set. */\n proxyOAuthRequests?: boolean;\n}\n\n/**\n * Configures a remote MCP server accessed with streamable HTTP.\n */\nexport interface HttpServerConfig extends BaseServerConfig {\n /** MCP endpoint URL. */\n url: string;\n /** Headers included with MCP transport requests. */\n headers?: Record<string, string>;\n /** Fetch implementation used by the HTTP transport. */\n fetch?: typeof fetch;\n /** Bearer token added as the `Authorization` header. */\n authToken?: string;\n /** Connection timeout in milliseconds. */\n timeout?: number;\n /** OAuth provider used when the server requires authorization. */\n authProvider?: AuthProvider | OAuthClientProvider;\n /**\n * Auto-OAuth options for HTTP servers.\n * - omit / `{}`: client creates the platform provider on connect\n * - `false`: disable auto-OAuth (e.g. CLI `--no-oauth`)\n * - object: forwarded to `createOAuthProvider`\n *\n * Ignored when `authProvider` or `authToken` is set, or when `headers`\n * already includes `Authorization`.\n */\n oauth?: AutoOAuthOptions | false;\n /**\n * Detect mixed-auth servers after an anonymous connection by using the\n * official SDK's RFC 9728 protected-resource metadata discovery.\n * @defaultValue true\n */\n detectMixedAuth?: boolean;\n /**\n * Protocol version negotiation mode. Defaults to `\"auto\"` to negotiate both\n * v1 and v2 MCP servers. See {@link HttpConnector}.\n */\n protocolNegotiation?: VersionNegotiationMode;\n}\n\n/**\n * Tests whether the client should create an OAuth provider for an HTTP server.\n *\n * @param serverConfig - Server configuration to inspect.\n * @returns `true` for an HTTP configuration without explicit authorization.\n */\nexport function shouldAutoProvisionOAuth(\n serverConfig: ServerConfig\n): serverConfig is HttpServerConfig {\n if (!(\"url\" in serverConfig) || typeof serverConfig.url !== \"string\") {\n return false;\n }\n if (serverConfig.authProvider) return false;\n if (serverConfig.authToken) return false;\n if (serverConfig.oauth === false) return false;\n const headers = serverConfig.headers;\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"authorization\") return false;\n }\n }\n return true;\n}\n\n/**\n * Configuration for either a local stdio server or a remote HTTP server.\n */\nexport type ServerConfig = StdioServerConfig | HttpServerConfig;\n\n/**\n * Top-level MCP client configuration.\n *\n * Callback and client identity values act as defaults for individual servers.\n */\nexport interface MCPClientConfigShape extends CallbackConfig {\n /** Default client identity for all servers; overridable per server. */\n clientInfo?: ClientInfo;\n /** Server configurations keyed by the name used in client methods. */\n mcpServers?: Record<string, ServerConfig>;\n}\n\n/**\n * Default clientInfo for mcp-use\n */\nfunction getDefaultClientInfo(): ClientInfo {\n return {\n name: \"mcp-use\",\n title: \"mcp-use\",\n version: getPackageVersion(),\n description:\n \"mcp-use is a complete TypeScript framework for building and using MCP\",\n icons: [\n {\n src: \"https://mcp-use.com/logo.png\",\n },\n ],\n websiteUrl: \"https://mcp-use.com\",\n };\n}\n\n/**\n * Normalizes a client identity and fills optional metadata with package defaults.\n *\n * @param input - Candidate client identity.\n * @returns The supplied identity merged with defaults, or the complete default\n * identity when `input` does not contain both `name` and `version`.\n */\nexport function normalizeClientInfo(input: unknown): ClientInfo {\n const fallback = getDefaultClientInfo();\n if (!input || typeof input !== \"object\") return fallback;\n const ci = input as Partial<ClientInfo>;\n // Require name + version (SDK/client contract)\n if (!ci.name || !ci.version) return fallback;\n return { ...fallback, ...ci };\n}\n\n/**\n * Expands the `capabilities.views` shorthand into the MCP Apps extension.\n *\n * @param clientOptions - SDK client options to normalize.\n * @returns Normalized options, or `undefined` when no options were supplied.\n */\nexport function resolveClientOptions(\n clientOptions: ClientOptions | undefined\n): ClientOptions | undefined {\n const capabilities = clientOptions?.capabilities as\n | Record<string, unknown>\n | undefined;\n if (!capabilities || capabilities.views !== true) return clientOptions;\n\n const { views: _views, ...capsWithoutViews } = capabilities;\n const extensions =\n capsWithoutViews.extensions &&\n typeof capsWithoutViews.extensions === \"object\" &&\n !Array.isArray(capsWithoutViews.extensions)\n ? { ...(capsWithoutViews.extensions as Record<string, unknown>) }\n : {};\n\n return {\n ...clientOptions,\n capabilities: {\n ...capsWithoutViews,\n extensions: {\n ...extensions,\n \"io.modelcontextprotocol/ui\": {\n mimeTypes: [\"text/html;profile=mcp-app\"],\n },\n },\n },\n };\n}\n\n/**\n * Creates an HTTP connector from a runtime-neutral server configuration.\n *\n * @param serverConfig - Server configuration to convert.\n * @param connectorOptions - Connector options that override derived values.\n * @returns An HTTP connector for the configured endpoint.\n * @throws When `serverConfig` is a stdio configuration or has no recognized transport.\n */\nexport function createConnectorFromConfig(\n serverConfig: ServerConfig,\n connectorOptions?: Partial<ConnectorInitOptions>\n): BaseConnector {\n // Normalize clientInfo to ensure required fields are present\n const clientInfo = normalizeClientInfo(serverConfig.clientInfo);\n\n if (\"command\" in serverConfig && \"args\" in serverConfig) {\n throw new Error(\n \"Stdio connector is not supported in this environment. \" +\n \"Stdio connections require Node.js and are only available in the Node.js MCPClient.\"\n );\n }\n\n if (\"url\" in serverConfig) {\n return new HttpConnector(serverConfig.url, {\n headers: serverConfig.headers,\n fetch: serverConfig.fetch,\n authToken: serverConfig.authToken,\n authProvider: serverConfig.authProvider,\n detectMixedAuth: serverConfig.detectMixedAuth,\n protocolNegotiation: serverConfig.protocolNegotiation,\n timeout: serverConfig.timeout,\n roots: serverConfig.roots,\n clientOptions: resolveClientOptions(serverConfig.clientOptions),\n defaultRequestOptions: serverConfig.defaultRequestOptions,\n clientInfo,\n ...connectorOptions,\n });\n }\n\n throw new Error(\"Cannot determine connector type from config\");\n}\n","/** Experimental Skills over MCP extension identifier. */\nexport const SKILLS_EXTENSION_ID = \"io.modelcontextprotocol/skills\" as const;\n\n/** One immutable resource advertised by a remote skill. */\nexport interface SkillResource {\n /** Absolute MCP resource URI. */\n uri: string;\n /** SHA-256 digest of the raw resource bytes. */\n digest: string;\n}\n\n/** One skill catalog entry returned by `skills/list` or `skills/get`. */\nexport interface Skill {\n /** URI of the skill's root `SKILL.md`. */\n uri: string;\n /** Verbatim parsed YAML frontmatter. */\n frontmatter: Record<string, unknown>;\n /** Complete resource manifest when the server exposes a static skill. */\n resources?: SkillResource[];\n}\n\n/** Paginated result returned by `skills/list`. */\nexport interface SkillsListResult {\n /** Skills on this page, in server order. */\n skills: Skill[];\n /** Cursor for the next page, absent on the final page. */\n nextCursor?: string;\n}\n\n/** Result returned by `skills/get`. */\nexport interface SkillGetResult {\n /** The requested skill. */\n skill: Skill;\n}\n\n/** One child returned by `resources/directory/read`. */\nexport interface SkillDirectoryEntry {\n /** Resource URI of the child. */\n uri: string;\n /** Display name of the child when the server provides one. */\n name?: string;\n /** MIME type of the child when the server provides one. */\n mimeType?: string;\n}\n\n/** Paginated result returned by `resources/directory/read`. */\nexport interface SkillDirectoryReadResult {\n /** Directory children on this page, in server order. */\n resources: SkillDirectoryEntry[];\n /** Cursor for the next page, absent on the final page. */\n nextCursor?: string;\n}\n","import type {\n CallToolResult,\n CompleteRequestParams,\n CompleteResult,\n MetaObject,\n Notification,\n ProtocolEra,\n RequestOptions,\n Root,\n Tool,\n} from \"@modelcontextprotocol/client\";\nimport type { BaseConnector, NotificationHandler } from \"../transport/base.js\";\n\n/** Negotiated protocol era: `\"legacy\"` or `\"modern\"`. */\nexport type MCPProtocolEra = ProtocolEra;\n\n/** OAuth availability inferred after an anonymous MCP connection succeeds. */\nexport interface MCPAuthorizationInfo {\n /** Mixed auth means public MCP operations succeeded while OAuth is available. */\n mode: \"mixed\";\n /** Whether this client currently has OAuth access tokens. */\n authenticated: boolean;\n /** Canonical protected-resource identifier from RFC 9728 metadata. */\n resource?: string;\n /** Scopes advertised by the protected resource, when provided. */\n scopesSupported?: string[];\n}\n\n/**\n * Server information normalized across legacy sessionful and modern sessionless\n * MCP protocols.\n */\nexport interface MCPServerInfo {\n /** Stable server name. */\n name: string;\n /** Server version reported during initialization. */\n version?: string;\n /** Optional human-readable server title. */\n title?: string;\n /** Optional human-readable server description. */\n description?: string;\n /** Public website describing the server. */\n websiteUrl?: string;\n /** Icons advertised by the server. */\n icons?: Array<{\n /** Icon URL. */\n src: string;\n /** Icon media type. */\n mimeType?: string;\n /** Supported icon sizes, such as `\"48x48\"`. */\n sizes?: string[];\n }>;\n}\n\n/**\n * Connection metadata available after the MCP SDK has negotiated a protocol.\n *\n * `extensions` retains protocol-specific extensions without requiring\n * callers to branch on the negotiated era.\n */\nexport interface MCPConnectionInfo {\n /** Negotiated protocol era. */\n protocolEra: MCPProtocolEra;\n /** Negotiated MCP protocol version. */\n protocolVersion: string;\n /** Server identity reported during negotiation, when provided. */\n server?: MCPServerInfo;\n /** Capabilities advertised by the server. */\n capabilities: Record<string, unknown>;\n /** Instructions advertised by the server. */\n instructions?: string;\n /** Protocol extension metadata advertised by the server. */\n extensions: Record<string, unknown>;\n /** Optional OAuth state discovered without forcing authentication. */\n authorization?: MCPAuthorizationInfo;\n}\n\n/**\n * A ready connection to an MCP server.\n *\n * The connection has the same public API for legacy, sessionful MCP servers\n * and modern, sessionless MCP servers. The underlying SDK owns the lifecycle\n * distinction and protocol negotiation.\n *\n * Sessions handle:\n * - Connection lifecycle (connect, disconnect, initialize)\n * - Tool invocation\n * - Resource access\n * - Prompt retrieval\n * - Notification handling\n * - Root directory management\n *\n * Sessions are typically created by `MCPClient.createSession()` rather than\n * being instantiated directly.\n *\n * @example\n * ```typescript\n * // Create via client\n * const client = new MCPClient('./config.json');\n * const session = await client.createSession('my-server');\n *\n * // Use the session\n * const tools = await session.listTools();\n * const result = await session.callTool('my-tool', { arg: 'value' });\n * ```\n *\n * @example\n * ```typescript\n * // Manual creation (advanced)\n * import { StdioConnector } from \"@mcp-use/client\";\n *\n * const connector = new StdioConnector({\n * command: 'node',\n * args: ['server.js']\n * });\n * const session = new MCPSession(connector);\n * await session.initialize();\n * ```\n *\n * @see {@link BaseConnector} for connector implementations\n */\nexport class MCPConnection {\n /**\n * The underlying connector managing the transport layer.\n * This is the Stdio, HTTP, or WebSocket connector handling actual communication.\n */\n readonly connector: BaseConnector;\n\n /**\n * Whether to automatically connect when initializing.\n * @internal\n */\n private autoConnect: boolean;\n\n /**\n * Creates a new MCP session.\n *\n * @param connector - The connector to use for communication (Stdio, HTTP, WebSocket)\n * @param autoConnect - Whether to automatically connect during initialization (default: true)\n *\n * @example\n * ```typescript\n * const connector = new HttpConnector({ url: 'http://localhost:3000/mcp' });\n * const session = new MCPSession(connector);\n * await session.initialize(); // Auto-connects and initializes\n * ```\n *\n * @example\n * ```typescript\n * // Manual connection control\n * const session = new MCPSession(connector, false);\n * await session.connect();\n * await session.initialize();\n * ```\n */\n constructor(connector: BaseConnector, autoConnect = true) {\n this.connector = connector;\n this.autoConnect = autoConnect;\n }\n\n /**\n * Establishes the connection to the MCP server.\n *\n * This method starts the underlying transport (spawns process for Stdio,\n * opens WebSocket, etc.) but does not perform the MCP initialization\n * handshake. Call {@link initialize} after connecting.\n *\n * @returns Promise that resolves when connected\n *\n * @example\n * ```typescript\n * await session.connect();\n * await session.initialize();\n * ```\n *\n * @see {@link initialize} for performing the MCP handshake\n * @see {@link disconnect} for closing the connection\n */\n async connect(): Promise<void> {\n await this.connector.connect();\n }\n\n /**\n * Closes the connection to the MCP server.\n *\n * This method gracefully shuts down the transport and cleans up resources.\n * After disconnecting, the session cannot be used until reconnected.\n *\n * @returns Promise that resolves when disconnected\n *\n * @example\n * ```typescript\n * await session.disconnect();\n * console.log('Session closed');\n * ```\n *\n * @see {@link connect} for establishing connections\n */\n async disconnect(): Promise<void> {\n await this.connector.disconnect();\n }\n\n /**\n * Initializes the MCP session with the server.\n *\n * This method performs the MCP initialization handshake, exchanging\n * capabilities and metadata with the server. If `autoConnect` is true\n * and the session is not yet connected, it will connect first.\n *\n * After initialization, you can list and call tools, read resources, etc.\n *\n * @returns Promise that resolves when initialized\n *\n * @example\n * ```typescript\n * const session = await client.createSession('my-server', false);\n * await session.connect();\n * await session.initialize();\n * // Now ready to use\n * const tools = await session.listTools();\n * ```\n *\n * @see {@link connect} for establishing the connection first\n */\n async initialize(): Promise<void> {\n if (!this.isConnected && this.autoConnect) {\n await this.connect();\n }\n await this.connector.initialize();\n }\n\n /**\n * Checks if the session is currently connected to the server.\n *\n * @returns True if connected, false otherwise\n *\n * @example\n * ```typescript\n * if (session.isConnected) {\n * const tools = await session.listTools();\n * }\n * ```\n */\n get isConnected(): boolean {\n return this.connector && this.connector.isClientConnected;\n }\n\n /**\n * Register an event handler for session events\n *\n * @param event - The event type to listen for\n * @param handler - The handler function to call when the event occurs\n *\n * @example\n * ```typescript\n * session.on(\"notification\", async (notification) => {\n * console.log(`Received: ${notification.method}`, notification.params);\n *\n * if (notification.method === \"notifications/tools/list_changed\") {\n * // Refresh tools list\n * }\n * });\n * ```\n */\n on(event: \"notification\", handler: NotificationHandler): void {\n if (event === \"notification\") {\n this.connector.onNotification(handler);\n }\n }\n\n /**\n * Set roots and notify the server.\n * Roots represent directories or files that the client has access to.\n *\n * @param roots - Array of Root objects with `uri` (must start with \"file://\") and optional `name`\n *\n * @deprecated Roots are a v1 compatibility feature and are not part of the\n * sessionless v2 protocol.\n *\n * @example\n * ```typescript\n * await session.setRoots([\n * { uri: \"file:///home/user/project\", name: \"My Project\" },\n * { uri: \"file:///home/user/data\" }\n * ]);\n * ```\n */\n async setRoots(roots: Root[]): Promise<void> {\n return this.connector.setRoots(roots);\n }\n\n /**\n * Gets the current roots advertised to the server.\n *\n * Roots represent directories or files that the client has provided access to.\n * The server may use this information to scope its operations.\n *\n * @returns Array of Root objects\n *\n * @example\n * ```typescript\n * const roots = session.getRoots();\n * console.log(`Current roots: ${roots.map(r => r.uri).join(', ')}`);\n * ```\n *\n * @see {@link setRoots} for updating roots\n */\n getRoots(): Root[] {\n return this.connector.getRoots();\n }\n\n /**\n * Get the cached list of tools from the server.\n *\n * @returns Array of available tools\n *\n * @example\n * ```typescript\n * const tools = session.tools;\n * console.log(`Available tools: ${tools.map(t => t.name).join(\", \")}`);\n * ```\n */\n get tools(): Tool[] {\n return this.connector.tools;\n }\n\n /**\n * List all available tools from the MCP server.\n * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.\n *\n * @param options - Optional request options\n * @returns Array of available tools\n *\n * @example\n * ```typescript\n * const tools = await session.listTools();\n * console.log(`Available tools: ${tools.map(t => t.name).join(\", \")}`);\n * ```\n */\n async listTools(options?: RequestOptions): Promise<Tool[]> {\n return this.connector.listTools(options);\n }\n\n /**\n * Get the server capabilities advertised during initialization.\n *\n * @returns Server capabilities object\n */\n get serverCapabilities(): Record<string, unknown> {\n return this.connector.serverCapabilities;\n }\n\n /**\n * Get the server information (name and version).\n *\n * @returns Server info object or null if not available\n */\n get serverInfo(): MCPServerInfo | null {\n return this.connector.serverInfo;\n }\n\n /** OAuth state discovered for this connection, when available. */\n get authorization(): MCPAuthorizationInfo | undefined {\n return this.connector.authorization;\n }\n\n /** Discover optional OAuth metadata without delaying MCP readiness. */\n async discoverAuthorization(): Promise<MCPAuthorizationInfo | undefined> {\n return this.connector.discoverAuthorization();\n }\n\n /** Authenticate an already-connected mixed-auth server. */\n async authenticate(): Promise<void> {\n await this.connector.authenticate();\n }\n\n /**\n * The negotiated protocol era for this session's connection:\n * `\"legacy\"` (2025-era) or `\"modern\"` (2026-07-28-era).\n * `undefined` before the connection has negotiated.\n */\n get protocolEra(): MCPProtocolEra | undefined {\n return this.connector.protocolEra;\n }\n\n /** The negotiated protocol version string for this session's connection. */\n get negotiatedProtocolVersion(): string | undefined {\n return this.connector.negotiatedProtocolVersion;\n }\n\n /**\n * Normalized server metadata for this ready connection.\n *\n * @throws When called before protocol negotiation completes.\n */\n get info(): MCPConnectionInfo {\n const protocolEra = this.protocolEra;\n const protocolVersion = this.negotiatedProtocolVersion;\n const server = this.serverInfo;\n\n if (!protocolEra || !protocolVersion) {\n throw new Error(\"MCP connection is not initialized\");\n }\n\n const capabilities = this.serverCapabilities;\n const extensions =\n capabilities.extensions &&\n typeof capabilities.extensions === \"object\" &&\n !Array.isArray(capabilities.extensions)\n ? (capabilities.extensions as Record<string, unknown>)\n : {};\n\n return {\n protocolEra,\n protocolVersion,\n ...(server ? { server } : {}),\n capabilities,\n instructions: this.connector.instructions,\n extensions,\n ...(this.authorization ? { authorization: this.authorization } : {}),\n };\n }\n\n /**\n * Whether the server advertised a named MCP capability.\n *\n * @param capability - A top-level capability name such as `\"tools\"` or\n * `\"resources\"`.\n */\n supports(capability: string): boolean {\n return capability in this.serverCapabilities;\n }\n\n /**\n * Call a tool on the server.\n *\n * @param name - Name of the tool to call\n * @param args - Arguments to pass to the tool (defaults to empty object)\n * @param options - Optional request options (timeout, progress handlers, etc.)\n * @returns Result from the tool execution\n *\n * @example\n * ```typescript\n * const result = await session.callTool(\"add\", { a: 5, b: 3 });\n * console.log(`Result: ${result.content[0].text}`);\n * ```\n */\n async callTool(\n name: string,\n args: Record<string, any> = {},\n options?: RequestOptions\n ): Promise<CallToolResult> {\n return this.connector.callTool(name, args, options);\n }\n\n /**\n * List resources from the server with optional pagination.\n *\n * @param cursor - Optional cursor for pagination\n * @param options - Request options\n * @returns Resource list with optional nextCursor for pagination\n *\n * @example\n * ```typescript\n * const result = await session.listResources();\n * console.log(`Found ${result.resources.length} resources`);\n * ```\n */\n async listResources(cursor?: string, options?: RequestOptions) {\n return this.connector.listResources(cursor, options);\n }\n\n /**\n * List all resources from the server, automatically handling pagination.\n *\n * @param options - Request options\n * @returns Complete list of all resources\n *\n * @example\n * ```typescript\n * const result = await session.listAllResources();\n * console.log(`Total resources: ${result.resources.length}`);\n * ```\n */\n async listAllResources(options?: RequestOptions) {\n return this.connector.listAllResources(options);\n }\n\n /**\n * List resource templates from the server.\n *\n * @param options - Request options\n * @returns List of available resource templates\n *\n * @example\n * ```typescript\n * const result = await session.listResourceTemplates();\n * console.log(`Available templates: ${result.resourceTemplates.length}`);\n * ```\n */\n async listResourceTemplates(options?: RequestOptions) {\n return this.connector.listResourceTemplates(options);\n }\n\n /**\n * Request completion suggestions for a prompt or resource template argument.\n *\n * @param params - Completion request parameters\n * @param options - Request options\n * @returns Completion suggestions from the server\n *\n * @example\n * ```typescript\n * // Complete a prompt argument\n * const result = await session.complete({\n * ref: { type: \"ref/prompt\", name: \"my-prompt\" },\n * argument: { name: \"language\", value: \"py\" }\n * });\n * console.log(result.completion.values); // [\"python\"]\n * ```\n */\n async complete(\n params: CompleteRequestParams,\n options?: RequestOptions\n ): Promise<CompleteResult> {\n return this.connector.complete(params, options);\n }\n\n /**\n * Read a resource by URI.\n *\n * @param uri - URI of the resource to read\n * @param options - Request options\n * @returns Resource content\n *\n * @example\n * ```typescript\n * const resource = await session.readResource(\"file:///path/to/file.txt\");\n * console.log(resource.contents);\n * ```\n */\n async readResource(uri: string, options?: RequestOptions) {\n return this.connector.readResource(uri, options);\n }\n\n /**\n * Subscribe to resource updates.\n *\n * @param uri - URI of the resource to subscribe to\n * @param options - Request options\n *\n * @example\n * ```typescript\n * await session.subscribeToResource(\"file:///path/to/file.txt\");\n * // Now you'll receive notifications when this resource changes\n * ```\n */\n async subscribeToResource(uri: string, options?: RequestOptions) {\n return this.connector.subscribeToResource(uri, options);\n }\n\n /**\n * Unsubscribe from resource updates.\n *\n * @param uri - URI of the resource to unsubscribe from\n * @param options - Request options\n *\n * @example\n * ```typescript\n * await session.unsubscribeFromResource(\"file:///path/to/file.txt\");\n * ```\n */\n async unsubscribeFromResource(uri: string, options?: RequestOptions) {\n return this.connector.unsubscribeFromResource(uri, options);\n }\n\n /**\n * List available prompts from the server.\n *\n * @returns List of available prompts\n *\n * @example\n * ```typescript\n * const result = await session.listPrompts();\n * console.log(`Available prompts: ${result.prompts.length}`);\n * ```\n */\n async listPrompts() {\n return this.connector.listPrompts();\n }\n\n /**\n * Get a specific prompt with arguments.\n *\n * @param name - Name of the prompt to get\n * @param args - Arguments for the prompt\n * @param options - Per-request timeout, cancellation, and progress options\n * @returns Prompt result\n *\n * @example\n * ```typescript\n * const prompt = await session.getPrompt(\"greeting\", { name: \"Alice\" });\n * console.log(prompt.messages);\n * ```\n */\n async getPrompt(\n name: string,\n args: Record<string, any>,\n options?: RequestOptions\n ) {\n return this.connector.getPrompt(name, args, options);\n }\n\n /**\n * Send a raw request through the client.\n *\n * @param method - MCP method name\n * @param params - Request parameters\n * @param options - Request options\n * @returns Response from the server\n *\n * @example\n * ```typescript\n * const result = await session.request(\"custom/method\", { key: \"value\" });\n * ```\n */\n async request(\n method: string,\n params: Record<string, any> | null = null,\n options?: RequestOptions\n ) {\n return this.connector.request(method, params, options);\n }\n\n /** List one page of skills advertised through the experimental extension. */\n async listSkills(cursor?: string, options?: RequestOptions) {\n return (await this.request(\n \"skills/list\",\n cursor === undefined ? {} : { cursor },\n options\n )) as import(\"./skills.js\").SkillsListResult;\n }\n\n /** List the complete skill catalog, following pagination defensively. */\n async listAllSkills(options?: RequestOptions) {\n const skills: import(\"./skills.js\").Skill[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = await this.listSkills(cursor, options);\n skills.push(...(Array.isArray(page.skills) ? page.skills : []));\n cursor = page.nextCursor;\n if (cursor !== undefined) {\n if (seenCursors.has(cursor)) {\n throw new Error(\"skills/list returned a repeated pagination cursor\");\n }\n seenCursors.add(cursor);\n }\n } while (cursor !== undefined);\n return { skills };\n }\n\n /** Get one skill by its canonical `SKILL.md` URI. */\n async getSkill(uri: string, options?: RequestOptions) {\n return (await this.request(\n \"skills/get\",\n { uri },\n options\n )) as import(\"./skills.js\").SkillGetResult;\n }\n\n /** Read one non-recursive skill directory. */\n async readResourceDirectory(\n uri: string,\n cursor?: string,\n options?: RequestOptions\n ) {\n return (await this.request(\n \"resources/directory/read\",\n cursor === undefined ? { uri } : { uri, cursor },\n options\n )) as import(\"./skills.js\").SkillDirectoryReadResult;\n }\n}\n\n/** @deprecated Use {@link MCPConnection}. */\nexport { MCPConnection as MCPSession };\n\n// Re-export types for convenience\nexport type { CallToolResult, MetaObject, Notification, Root, Tool };\nexport type {\n Skill,\n SkillDirectoryEntry,\n SkillDirectoryReadResult,\n SkillGetResult,\n SkillResource,\n SkillsListResult,\n} from \"./skills.js\";\nexport { SKILLS_EXTENSION_ID } from \"./skills.js\";\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/client\";\nimport type { BaseConnector } from \"../transport/base.js\";\nimport type {\n AutoOAuthOptions,\n HttpServerConfig,\n MCPClientConfigShape,\n ServerConfig,\n} from \"./config.js\";\nimport { shouldAutoProvisionOAuth } from \"./config.js\";\nimport { completeOAuthFlow, isUnauthorized } from \"../auth/flow.js\";\nimport { logger } from \"../utils/logging.js\";\nimport { MCPSession } from \"./session.js\";\nimport type { MCPConnection } from \"./session.js\";\nimport {\n trackClientAddServer,\n trackClientRemoveServer,\n} from \"../telemetry/client-telemetry.js\";\n\nfunction isOAuthClientProvider(\n provider: unknown\n): provider is OAuthClientProvider {\n return (\n !!provider &&\n typeof provider === \"object\" &&\n \"redirectUrl\" in provider &&\n \"clientMetadata\" in provider\n );\n}\n\n/**\n * Base MCPClient class with shared functionality across all environments.\n *\n * This abstract class provides the core client logic for managing MCP servers,\n * sessions, and configurations. It works in both Node.js and browser environments\n * by delegating platform-specific operations to concrete implementations.\n *\n * Platform-specific implementations such as the Node.js `MCPClient` should\n * extend this class and override the abstract {@link createConnectorFromConfig}\n * method to provide environment-specific connector creation.\n *\n * @example\n * ```typescript\n * // Typically used through concrete implementations\n * import { MCPClient } from \"@mcp-use/client\";\n *\n * const client = new MCPClient({\n * mcpServers: {\n * 'my-server': {\n * command: 'node',\n * args: ['server.js']\n * }\n * }\n * });\n * ```\n *\n * @see {@link MCPSession} for session management\n */\nexport abstract class BaseMCPClient {\n /**\n * Internal configuration object containing MCP server definitions.\n */\n protected config: MCPClientConfigShape = {};\n\n /**\n * Map of server names to their active sessions.\n */\n protected sessions: Record<string, MCPSession> = {};\n\n /**\n * Tracks teardown by session identity so overlapping cleanup paths share the\n * same disconnect. In particular, createSession() can replace a session while\n * closeSession() is already disconnecting it.\n */\n private readonly sessionDisconnects = new WeakMap<\n MCPSession,\n Promise<void>\n >();\n\n /**\n * List of server names that have active sessions.\n * This array is kept in sync with the sessions map and can be used\n * to iterate over active connections.\n *\n * @example\n * ```typescript\n * console.log(`Active servers: ${client.activeSessions.join(', ')}`);\n * ```\n */\n public activeSessions: string[] = [];\n\n /**\n * Creates a new BaseMCPClient instance.\n *\n * @param config - Optional configuration object with MCP server definitions\n *\n * @example\n * ```typescript\n * const client = new MCPClient({\n * mcpServers: {\n * 'example': {\n * command: 'node',\n * args: ['server.js']\n * }\n * }\n * });\n * ```\n */\n constructor(config?: MCPClientConfigShape) {\n if (config) {\n this.config = config;\n }\n }\n\n private disconnectSession(session: MCPSession): Promise<void> {\n const existingDisconnect = this.sessionDisconnects.get(session);\n if (existingDisconnect) {\n return existingDisconnect;\n }\n\n // Install the promise before invoking the connector so even synchronous\n // re-entry observes and reuses this teardown.\n const disconnect = Promise.resolve().then(() => session.disconnect());\n this.sessionDisconnects.set(session, disconnect);\n return disconnect;\n }\n\n /**\n * Creates a client instance from a configuration dictionary.\n *\n * This static factory method must be implemented by concrete subclasses\n * to provide proper type information and platform-specific initialization.\n *\n * @param _cfg - Configuration dictionary\n * @returns Client instance\n * @throws If called on the base class instead of a concrete implementation\n *\n * @example\n * ```typescript\n * const client = MCPClient.fromDict({\n * mcpServers: {\n * 'my-server': { command: 'node', args: ['server.js'] }\n * }\n * });\n * ```\n */\n public static fromDict(_cfg: MCPClientConfigShape): BaseMCPClient {\n // This will be overridden by concrete implementations\n throw new Error(\"fromDict must be implemented by concrete class\");\n }\n\n /**\n * Adds a new MCP server configuration to the client.\n *\n * This method adds or updates a server configuration dynamically without\n * needing to restart the client. The server can then be used to create\n * new sessions.\n *\n * @param name - Unique name for the server\n * @param serverConfig - Server configuration object (connector type, command, args, etc.)\n *\n * @example\n * ```typescript\n * client.addServer('new-server', {\n * command: 'python',\n * args: ['server.py']\n * });\n *\n * // Now you can create a session\n * const session = await client.createSession('new-server');\n * ```\n *\n * @see {@link removeServer} for removing servers\n * @see {@link getServerConfig} for retrieving configurations\n */\n public addServer(name: string, serverConfig: ServerConfig): void {\n this.config.mcpServers = this.config.mcpServers || {};\n this.config.mcpServers[name] = serverConfig;\n trackClientAddServer(name, serverConfig);\n }\n\n /**\n * Removes an MCP server configuration from the client.\n *\n * This method removes a server configuration and cleans up any active\n * sessions associated with that server. If there's an active session,\n * it will be removed from the active sessions list.\n *\n * @param name - Name of the server to remove\n *\n * @example\n * ```typescript\n * // Remove a server configuration\n * await client.removeServer('old-server');\n *\n * // The server name will no longer appear in getServerNames()\n * console.log(client.getServerNames()); // 'old-server' is gone\n * ```\n *\n * @see {@link addServer} for adding servers\n * @see {@link closeSession} for properly closing sessions before removal\n */\n public async removeServer(name: string): Promise<void> {\n if (!this.config.mcpServers?.[name]) return;\n\n await this.closeSession(name);\n delete this.config.mcpServers[name];\n trackClientRemoveServer(name);\n }\n\n /**\n * Gets the names of all configured MCP servers.\n *\n * @returns Array of server names defined in the configuration\n *\n * @example\n * ```typescript\n * const serverNames = client.getServerNames();\n * console.log(`Configured servers: ${serverNames.join(', ')}`);\n *\n * // Create sessions for all servers\n * for (const name of serverNames) {\n * await client.createSession(name);\n * }\n * ```\n *\n * @see {@link activeSessions} for servers with active sessions\n */\n public getServerNames(): string[] {\n return Object.keys(this.config.mcpServers ?? {});\n }\n\n /**\n * Gets the configuration for a specific MCP server.\n *\n * @param name - Name of the server\n * @returns Server configuration object, or undefined if not found\n *\n * @example\n * ```typescript\n * const config = client.getServerConfig('my-server');\n * if (config) {\n * console.log(`Command: ${config.command}`);\n * console.log(`Args: ${config.args.join(' ')}`);\n * }\n * ```\n *\n * @see {@link getConfig} for retrieving the entire configuration\n */\n public getServerConfig(name: string): ServerConfig | undefined {\n return this.config.mcpServers?.[name];\n }\n\n /**\n * Gets the complete client configuration.\n *\n * @returns Complete configuration object including all server definitions\n *\n * @example\n * ```typescript\n * const config = client.getConfig();\n * console.log(`Total servers: ${Object.keys(config.mcpServers).length}`);\n * ```\n *\n * @see {@link getServerConfig} for retrieving individual server configurations\n */\n public getConfig(): MCPClientConfigShape {\n return this.config ?? {};\n }\n\n /**\n * Creates a connector from server configuration.\n *\n * This abstract method must be implemented by platform-specific subclasses\n * to create the appropriate connector type (Stdio, HTTP, WebSocket, etc.)\n * based on the server configuration and runtime environment.\n *\n * @param serverConfig - Server configuration object\n * @returns Platform-specific connector instance\n */\n protected abstract createConnectorFromConfig(\n serverConfig: ServerConfig\n ): BaseConnector | Promise<BaseConnector>;\n\n /**\n * Platform OAuth provider used when an HTTP server has no bearer token /\n * `authProvider`. Node and browser entries implement this via their\n * `createOAuthProvider` export.\n */\n protected abstract createDefaultOAuthProvider(\n serverUrl: string,\n options?: AutoOAuthOptions\n ): Promise<OAuthClientProvider>;\n\n /**\n * Creates a new session for connecting to an MCP server.\n *\n * @deprecated Use {@link connect}; modern MCP servers are sessionless.\n *\n * This method initializes a connection to the specified server using the\n * configuration provided during client construction. Sessions manage the\n * lifecycle of connections and provide methods for calling tools, listing\n * resources, and more.\n *\n * If a session already exists for the server, it will be replaced with a new\n * one and the previous session is disconnected; any previously returned\n * reference to it becomes unusable.\n *\n * @param serverName - The name of the server as defined in the client configuration\n * @param autoInitialize - Whether to automatically initialize the session (default: true)\n * @returns A promise that resolves to the created MCPSession instance\n * @throws If the server is not found in the configuration\n *\n * @example\n * ```typescript\n * // Create and initialize a session\n * const session = await client.createSession('my-server');\n * const tools = await session.listTools();\n *\n * // Create without auto-initialization\n * const session = await client.createSession('my-server', false);\n * await session.connect();\n * await session.initialize();\n * ```\n *\n * @see {@link MCPSession} for session management methods\n * @see {@link closeSession} for closing sessions\n * @see {@link getSession} for retrieving existing sessions\n */\n public async createSession(\n serverName: string,\n autoInitialize = true\n ): Promise<MCPSession> {\n const servers = this.config.mcpServers ?? {};\n\n if (Object.keys(servers).length === 0) {\n logger.warn(\"No MCP servers defined in config\");\n }\n\n if (!servers[serverName]) {\n throw new Error(`Server '${serverName}' not found in config`);\n }\n\n let serverConfig: ServerConfig = { ...servers[serverName] };\n let oauthProvider: OAuthClientProvider | undefined;\n\n if (shouldAutoProvisionOAuth(serverConfig)) {\n const oauthOptions =\n serverConfig.oauth === false ? undefined : (serverConfig.oauth ?? {});\n oauthProvider = await this.createDefaultOAuthProvider(\n serverConfig.url,\n oauthOptions\n );\n serverConfig = {\n ...serverConfig,\n authProvider: oauthProvider,\n };\n } else if (\n \"authProvider\" in serverConfig &&\n serverConfig.authProvider &&\n isOAuthClientProvider(serverConfig.authProvider)\n ) {\n oauthProvider = serverConfig.authProvider;\n }\n\n const openSession = async (): Promise<MCPSession> => {\n const connector = await Promise.resolve(\n this.createConnectorFromConfig(serverConfig)\n );\n const session = new MCPSession(connector);\n if (autoInitialize) {\n await session.initialize();\n }\n return session;\n };\n\n let session: MCPSession;\n try {\n session = await openSession();\n } catch (err) {\n const httpConfig = serverConfig as HttpServerConfig;\n if (\n !autoInitialize ||\n !oauthProvider ||\n !(\"url\" in httpConfig) ||\n !isUnauthorized(err)\n ) {\n throw err;\n }\n if (\n (\n oauthProvider as OAuthClientProvider & {\n preventAutoAuth?: boolean;\n }\n ).preventAutoAuth\n ) {\n throw err;\n }\n logger.info(\n `[MCPClient] Unauthorized connecting to '${serverName}'; completing OAuth…`\n );\n await completeOAuthFlow(oauthProvider, httpConfig.url);\n session = await openSession();\n }\n\n const previous = this.sessions[serverName];\n this.sessions[serverName] = session;\n if (!this.activeSessions.includes(serverName)) {\n this.activeSessions.push(serverName);\n }\n\n // The slot only holds one session per server, so a replaced session would\n // no longer be reachable from closeSession()/closeAllSessions(). Disconnect\n // it here, after the new session is installed, so consumers calling\n // getSession() during the await still see a live session.\n if (previous && previous !== session) {\n try {\n logger.debug(`Disconnecting replaced session for server ${serverName}`);\n await this.disconnectSession(previous);\n } catch (e) {\n logger.error(\n `Error disconnecting replaced session for server '${serverName}': ${e}`\n );\n }\n }\n\n return session;\n }\n\n /**\n * Connect to a configured MCP server and return a ready, protocol-neutral\n * connection.\n *\n * The returned connection represents either a legacy sessionful server or a\n * modern sessionless server uniformly. Inspect {@link MCPConnection.info} for\n * the negotiated protocol version and normalized server metadata.\n *\n * @param serverName - The configured server name.\n */\n public async connect(serverName: string): Promise<MCPConnection> {\n return this.createSession(serverName);\n }\n\n /**\n * Creates sessions for all configured MCP servers.\n *\n * This is a convenience method that iterates through all servers in the\n * configuration and creates a session for each one. Sessions are created\n * sequentially to avoid overwhelming the system.\n *\n * @param autoInitialize - Whether to automatically initialize each session (default: true)\n * @returns A promise that resolves to a map of server names to sessions\n *\n * @example\n * ```typescript\n * // Create sessions for all configured servers\n * const sessions = await client.createAllSessions();\n * console.log(`Created ${Object.keys(sessions).length} sessions`);\n *\n * // List tools from all servers\n * for (const [name, session] of Object.entries(sessions)) {\n * const tools = await session.listTools();\n * console.log(`${name}: ${tools.length} tools`);\n * }\n * ```\n *\n * @see {@link createSession} for creating individual sessions\n * @see {@link closeAllSessions} for closing all sessions\n */\n public async createAllSessions(\n autoInitialize = true\n ): Promise<Record<string, MCPSession>> {\n const servers = this.config.mcpServers ?? {};\n\n if (Object.keys(servers).length === 0) {\n logger.warn(\"No MCP servers defined in config\");\n }\n\n for (const name of Object.keys(servers)) {\n await this.createSession(name, autoInitialize);\n }\n\n return this.sessions;\n }\n\n /**\n * Connect to every configured server sequentially.\n *\n * Each result uses the same {@link MCPConnection} API regardless of whether\n * the negotiated protocol is legacy/sessionful or modern/sessionless.\n */\n public async connectAll(): Promise<Record<string, MCPConnection>> {\n return this.createAllSessions();\n }\n\n /**\n * Retrieves an existing session by server name.\n *\n * This method returns null if no session exists, making it safe for\n * checking session existence without throwing errors.\n *\n * @param serverName - Name of the server\n * @returns The session instance or null if not found\n *\n * @example\n * ```typescript\n * const session = client.getSession('my-server');\n * if (session) {\n * const tools = await session.listTools();\n * } else {\n * console.log('Session not found, creating...');\n * await client.createSession('my-server');\n * }\n * ```\n *\n * @see {@link requireSession} for getting a session that throws if not found\n * @see {@link createSession} for creating sessions\n */\n public getSession(serverName: string): MCPSession | null {\n const session = this.sessions[serverName];\n if (!session) {\n return null;\n }\n return session;\n }\n\n /**\n * Retrieves an existing session by server name, throwing if not found.\n *\n * This method is useful when you need to ensure a session exists before\n * proceeding. It throws a descriptive error if the session is not found.\n *\n * @param serverName - Name of the server\n * @returns The session instance\n * @throws If the session is not found\n *\n * @example\n * ```typescript\n * try {\n * const session = client.requireSession('my-server');\n * const tools = await session.listTools();\n * } catch (error) {\n * console.error('Session not found:', error.message);\n * }\n * ```\n *\n * @see {@link getSession} for a null-returning alternative\n * @see {@link createSession} for creating sessions\n */\n public requireSession(serverName: string): MCPSession {\n const session = this.sessions[serverName];\n if (!session) {\n throw new Error(\n `Session '${serverName}' not found. Available sessions: ${this.activeSessions.join(\", \") || \"none\"}`\n );\n }\n return session;\n }\n\n /**\n * Gets all active sessions as a map of server names to sessions.\n *\n * @returns Map of server names to their active sessions\n *\n * @example\n * ```typescript\n * const sessions = client.getAllActiveSessions();\n *\n * // Iterate over all active sessions\n * for (const [name, session] of Object.entries(sessions)) {\n * console.log(`Server: ${name}`);\n * const tools = await session.listTools();\n * console.log(` Tools: ${tools.length}`);\n * }\n * ```\n *\n * @see {@link activeSessions} for just the list of server names\n * @see {@link getSession} for retrieving individual sessions\n */\n public getAllActiveSessions(): Record<string, MCPSession> {\n return Object.fromEntries(\n this.activeSessions.map((n) => [n, this.sessions[n]])\n );\n }\n\n /**\n * Closes a session and cleans up its resources.\n *\n * This method gracefully disconnects from the server and removes the\n * session from the active sessions list. It's safe to call even if\n * the session doesn't exist.\n *\n * @param serverName - Name of the server whose session should be closed\n *\n * @example\n * ```typescript\n * // Close a specific session\n * await client.closeSession('my-server');\n *\n * // Verify it's closed\n * console.log(client.activeSessions.includes('my-server')); // false\n * ```\n *\n * @see {@link closeAllSessions} for closing all sessions at once\n * @see {@link createSession} for creating new sessions\n */\n public async closeSession(serverName: string): Promise<void> {\n const session = this.sessions[serverName];\n if (!session) {\n logger.warn(\n `No session exists for server ${serverName}, nothing to close`\n );\n return;\n }\n try {\n logger.debug(`Closing session for server ${serverName}`);\n await this.disconnectSession(session);\n } catch (e) {\n logger.error(`Error closing session for server '${serverName}': ${e}`);\n } finally {\n // Only remove the slot if it still references the session we captured.\n // A parallel createSession() (e.g. URL/env change in useMcp) may have\n // written a new session here while we were awaiting `session.disconnect()`;\n // wiping that would leave consumers with `getSession() === null` and\n // surface as \"No active session found\".\n if (this.sessions[serverName] === session) {\n delete this.sessions[serverName];\n this.activeSessions = this.activeSessions.filter(\n (n) => n !== serverName\n );\n }\n }\n }\n\n /**\n * Closes all active sessions and cleans up their resources.\n *\n * This method iterates through all sessions and attempts to close each one\n * gracefully. If any session fails to close, the error is logged but the\n * method continues to close remaining sessions.\n *\n * This is particularly useful for cleanup on application shutdown.\n *\n * @example\n * ```typescript\n * // Clean shutdown\n * try {\n * await client.closeAllSessions();\n * console.log('All sessions closed successfully');\n * } catch (error) {\n * console.error('Error during cleanup:', error);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Use in application shutdown handler\n * process.on('SIGINT', async () => {\n * console.log('Shutting down...');\n * await client.closeAllSessions();\n * process.exit(0);\n * });\n * ```\n *\n * @see {@link closeSession} for closing individual sessions\n * @see {@link createAllSessions} for creating sessions\n */\n public async closeAllSessions(): Promise<void> {\n const serverNames = Object.keys(this.sessions);\n const errors: string[] = [];\n for (const serverName of serverNames) {\n try {\n logger.debug(`Closing session for server ${serverName}`);\n await this.closeSession(serverName);\n } catch (e: any) {\n const errorMsg = `Failed to close session for server '${serverName}': ${e}`;\n logger.error(errorMsg);\n errors.push(errorMsg);\n }\n }\n if (errors.length) {\n logger.error(\n `Encountered ${errors.length} errors while closing sessions`\n );\n } else {\n logger.debug(\"All sessions closed successfully\");\n }\n }\n\n /** Close every active MCP connection. */\n public async close(): Promise<void> {\n await this.closeAllSessions();\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/client\";\nimport type { AutoOAuthOptions, CallbackConfig } from \"./config.js\";\nimport { normalizeClientInfo, resolveCallbacks } from \"./config.js\";\nimport type { BaseConnector } from \"../transport/base.js\";\nimport { HttpConnector } from \"../transport/http.js\";\nimport {\n createOAuthProvider,\n type BrowserOAuthOptions,\n} from \"../auth/browser.js\";\nimport { logger } from \"../utils/logging.js\";\nimport { Tel } from \"../telemetry/telemetry-browser.js\";\nimport { getPackageVersion } from \"../utils/version.js\";\nimport { BaseMCPClient } from \"./base.js\";\n\n/**\n * Manages MCP server connections in browsers and other Web API runtimes.\n *\n * The browser client supports HTTP servers and the connection-management\n * operations inherited from its runtime-neutral base client. It does not spawn local\n * processes or read configuration files.\n */\nfunction trackBrowserClientInit(config: Record<string, any>): void {\n const servers = Object.keys(config.mcpServers ?? {});\n Tel.getInstance()\n .trackMCPClientInit({\n codeMode: false,\n sandbox: false,\n allCallbacks: false,\n verify: false,\n servers,\n numServers: servers.length,\n isBrowser: true,\n })\n .catch((e: unknown) =>\n logger.debug(`Failed to track BrowserMCPClient init: ${e}`)\n );\n}\n\nexport class BrowserMCPClient extends BaseMCPClient {\n /**\n * Returns the installed `@mcp-use/client` package version.\n *\n * @returns The package version string.\n */\n public static getPackageVersion(): string {\n return getPackageVersion();\n }\n\n /**\n * Creates a browser MCP client.\n *\n * @param config - Client configuration containing an optional `mcpServers` map.\n */\n constructor(config?: Record<string, any>) {\n super(config);\n trackBrowserClientInit(this.config);\n }\n\n /**\n * Creates a browser client from an inline configuration object.\n *\n * @param cfg - Client configuration containing an optional `mcpServers` map.\n * @returns A browser client initialized with `cfg`.\n */\n public static fromDict(cfg: Record<string, any>): BrowserMCPClient {\n return new BrowserMCPClient(cfg);\n }\n\n protected async createDefaultOAuthProvider(\n serverUrl: string,\n options: AutoOAuthOptions = {}\n ): Promise<OAuthClientProvider> {\n return createOAuthProvider(serverUrl, options as BrowserOAuthOptions);\n }\n\n /**\n * Create a connector from server configuration (Browser version)\n * Supports HTTP connector only\n */\n protected createConnectorFromConfig(\n serverConfig: Record<string, any>\n ): BaseConnector {\n const {\n url,\n headers,\n fetch: configuredFetch,\n authToken,\n authProvider,\n detectMixedAuth,\n wrapTransport,\n clientOptions,\n protocolNegotiation,\n timeout,\n gatewayUrl,\n serverId,\n reconnectionOptions,\n } = serverConfig;\n\n if (!url) {\n throw new Error(\"Server URL is required\");\n }\n\n // Resolve callbacks: per-server overrides global (from config root)\n const globalDefaults = this.config as CallbackConfig;\n const resolved = resolveCallbacks(\n serverConfig as CallbackConfig,\n globalDefaults\n );\n\n // Root clientInfo as fallback when server config omits it\n const clientInfo = normalizeClientInfo(\n serverConfig.clientInfo ?? this.config.clientInfo\n );\n\n // Prepare connector options\n const connectorOptions = {\n headers,\n fetch: configuredFetch ?? globalThis.fetch.bind(globalThis),\n authToken,\n authProvider,\n detectMixedAuth,\n wrapTransport,\n clientOptions,\n onSampling: resolved.onSampling,\n onElicitation: resolved.onElicitation,\n onNotification: resolved.onNotification,\n protocolNegotiation,\n timeout,\n clientInfo,\n gatewayUrl,\n serverId,\n reconnectionOptions,\n };\n\n logger.debug(\n `[BrowserMCPClient] Connector options prepared (clientOptions: ${clientOptions ? \"provided\" : \"none\"})`\n );\n\n return new HttpConnector(url, connectorOptions);\n }\n}\n","const FAVICON_API = \"https://favicon.tools.mcp-use.com\";\n\nconst IPV4_RE = /^\\d{1,3}(\\.\\d{1,3}){3}$/;\n\nfunction parseHostname(serverUrl: string): string | null {\n try {\n const raw = serverUrl.includes(\"://\") ? serverUrl : `https://${serverUrl}`;\n return new URL(raw).hostname;\n } catch {\n return null;\n }\n}\n\nfunction isLocalHost(hostname: string): boolean {\n const h = hostname.toLowerCase();\n if (h === \"localhost\" || h.endsWith(\".localhost\")) return true;\n if (h === \"host.docker.internal\" || h === \"0.0.0.0\") return true;\n if (!IPV4_RE.test(h)) return false;\n\n if (h === \"127.0.0.1\" || h.startsWith(\"127.\")) return true;\n if (h.startsWith(\"10.\")) return true;\n if (h.startsWith(\"192.168.\")) return true;\n\n const m = /^172\\.(\\d+)\\./.exec(h);\n if (m) {\n const second = Number.parseInt(m[1]!, 10);\n if (second >= 16 && second <= 31) return true;\n }\n\n return false;\n}\n\nfunction subdomainLevels(hostname: string): string[] {\n const parts = hostname.split(\".\");\n return Array.from({ length: parts.length - 1 }, (_, i) =>\n parts.slice(i).join(\".\")\n );\n}\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => resolve(reader.result as string);\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\n/**\n * Detect and retrieve an MCP server's favicon as a base64 data URL.\n * Skips local/private hosts; walks subdomain levels until a non-default favicon is found.\n */\nexport async function detectFavicon(serverUrl: string): Promise<string | null> {\n try {\n const hostname = parseHostname(serverUrl);\n if (!hostname || isLocalHost(hostname)) return null;\n\n for (const domain of subdomainLevels(hostname)) {\n try {\n const res = await fetch(`${FAVICON_API}/${domain}?response=json`, {\n signal: AbortSignal.timeout(2000),\n });\n if (!res.ok) continue;\n\n const data = (await res.json()) as { url: string; source: string };\n if (data.source === \"default\") continue;\n\n const imageUrl = data.url.replace(/^http:\\/\\//, \"https://\");\n const img = await fetch(imageUrl, {\n signal: AbortSignal.timeout(2000),\n });\n if (!img.ok) continue;\n\n return await blobToDataUrl(await img.blob());\n } catch {\n continue;\n }\n }\n\n return null;\n } catch (error) {\n console.warn(\"[favicon] Error detecting favicon:\", error);\n return null;\n }\n}\n"],"mappings":";AAOA,IAAI;AAGG,SAAS,0BACd,aACM;AACN,YAAU;AACZ;AAGO,SAAS,qBAAqB,MAAc,QAA4B;AAC7E,OAAK,SAAS,UAAU,MAAM,MAAM;AACtC;AAGO,SAAS,wBAAwB,MAAoB;AAC1D,OAAK,SAAS,aAAa,IAAI;AACjC;;;ACpBA,IAAIA;AAGG,SAAS,6BACd,aACM;AACN,EAAAA,WAAU;AACZ;AAGO,SAAS,wBAAwB,MAAoC;AAC1E,OAAKA,WAAU,IAAI;AACrB;;;ACJA,IAAM,SAAS;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,QAAkC;AAAA,EACtC,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AACT;AAEA,SAAS,WAAqB;AAC5B,MAAI;AACJ,MAAI;AACF,UACE,OAAO,YAAY,cACd,QAAQ,KAAK,qBAAqB,QAAQ,KAAK,QAChD;AAAA,EACR,QAAQ;AAAA,EAER;AACA,QAAM,IAAI,KAAK,KAAK,EAAE,YAAY;AAClC,MAAI,MAAM,IAAK,QAAO;AACtB,MAAI,KAAM,OAA6B,SAAS,CAAC,EAAG,QAAO;AAC3D,SAAO;AACT;AAEA,IAAM,sBAAN,MAA0B;AAAA,EACxB,YACU,OAAO,WACR,QAAkB,QAClB,SAAoB,WAC3B;AAHQ;AACD;AACA;AAAA,EACN;AAAA,EAEK,MAAM,OAAiB,SAAiB,MAAuB;AACrE,QACE,KAAK,UAAU,YACf,OAAO,QAAQ,KAAK,IAAI,OAA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F,cAAM,MAAM,MAAM,MAAM,GAAG,WAAW,IAAI,MAAM,kBAAkB;AAAA,UAChE,QAAQ,YAAY,QAAQ,GAAI;AAAA,QAClC,CAAC;AACD,YAAI,CAAC,IAAI,GAAI;AAEb,cAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,YAAI,KAAK,WAAW,UAAW;AAE/B,cAAM,WAAW,KAAK,IAAI,QAAQ,cAAc,UAAU;AAC1D,cAAM,MAAM,MAAM,MAAM,UAAU;AAAA,UAChC,QAAQ,YAAY,QAAQ,GAAI;AAAA,QAClC,CAAC;AACD,YAAI,CAAC,IAAI,GAAI;AAEb,eAAO,MAAM,cAAc,MAAM,IAAI,KAAK,CAAC;AAAA,MAC7C,QAAQ;AACN;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,KAAK,sCAAsC,KAAK;AACxD,WAAO;AAAA,EACT;AACF;","names":["tracker","response","auth","UnauthorizedError","StreamableHTTPClientTransport","UnauthorizedError","UnauthorizedError","StreamableHTTPClientTransport","sessionId","isOAuthClientProvider","session"]}
|