@mcp-use/client 2.2.4 → 2.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/.tsbuildinfo +1 -0
  2. package/dist/auth/browser.d.ts +218 -0
  3. package/dist/auth/browser.d.ts.map +1 -0
  4. package/dist/auth/callback.d.ts +9 -0
  5. package/dist/auth/callback.d.ts.map +1 -0
  6. package/dist/auth/flow.d.ts +32 -0
  7. package/dist/auth/flow.d.ts.map +1 -0
  8. package/dist/auth/node.d.ts +212 -0
  9. package/dist/auth/node.d.ts.map +1 -0
  10. package/dist/auth/popup.d.ts +67 -0
  11. package/dist/auth/popup.d.ts.map +1 -0
  12. package/dist/auth/session-store.d.ts +125 -0
  13. package/dist/auth/session-store.d.ts.map +1 -0
  14. package/dist/auth/storage-file.d.ts +18 -0
  15. package/dist/auth/storage-file.d.ts.map +1 -0
  16. package/dist/auth/storage.d.ts +34 -0
  17. package/dist/auth/storage.d.ts.map +1 -0
  18. package/dist/auth/url.d.ts +17 -0
  19. package/dist/auth/url.d.ts.map +1 -0
  20. package/dist/code-mode/connector.d.ts +27 -0
  21. package/dist/code-mode/connector.d.ts.map +1 -0
  22. package/dist/code-mode/executor-e2b.d.ts +46 -0
  23. package/dist/code-mode/executor-e2b.d.ts.map +1 -0
  24. package/dist/code-mode/executor-vm.d.ts +39 -0
  25. package/dist/code-mode/executor-vm.d.ts.map +1 -0
  26. package/dist/code-mode/executor.d.ts +81 -0
  27. package/dist/code-mode/executor.d.ts.map +1 -0
  28. package/dist/core/base.d.ts +423 -0
  29. package/dist/core/base.d.ts.map +1 -0
  30. package/dist/core/browser.d.ts +32 -0
  31. package/dist/core/browser.d.ts.map +1 -0
  32. package/dist/core/config.d.ts +225 -0
  33. package/dist/core/config.d.ts.map +1 -0
  34. package/dist/core/node.d.ts +437 -0
  35. package/dist/core/node.d.ts.map +1 -0
  36. package/dist/core/session.d.ts +792 -0
  37. package/dist/core/session.d.ts.map +1 -0
  38. package/dist/core/skills.d.ts +47 -0
  39. package/dist/core/skills.d.ts.map +1 -0
  40. package/dist/index-browser.d.ts +26 -0
  41. package/dist/index-browser.d.ts.map +1 -0
  42. package/dist/index-browser.js +4767 -0
  43. package/dist/index-browser.js.map +1 -0
  44. package/dist/index.d.ts +23 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +6113 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/react/McpClientProvider.d.ts +254 -0
  49. package/dist/react/McpClientProvider.d.ts.map +1 -0
  50. package/dist/react/index.d.ts +39 -0
  51. package/dist/react/index.d.ts.map +1 -0
  52. package/dist/react/index.js +9444 -0
  53. package/dist/react/index.js.map +1 -0
  54. package/dist/react/rpc-logger.d.ts +47 -0
  55. package/dist/react/rpc-logger.d.ts.map +1 -0
  56. package/dist/react/storage.d.ts +98 -0
  57. package/dist/react/storage.d.ts.map +1 -0
  58. package/dist/react/token-expiry.d.ts +9 -0
  59. package/dist/react/token-expiry.d.ts.map +1 -0
  60. package/dist/react/types.d.ts +727 -0
  61. package/dist/react/types.d.ts.map +1 -0
  62. package/dist/react/useMcp-helpers.d.ts +99 -0
  63. package/dist/react/useMcp-helpers.d.ts.map +1 -0
  64. package/dist/react/useMcp-operations.d.ts +180 -0
  65. package/dist/react/useMcp-operations.d.ts.map +1 -0
  66. package/dist/react/useMcp.d.ts +48 -0
  67. package/dist/react/useMcp.d.ts.map +1 -0
  68. package/dist/react/useMcpServerQueues.d.ts +403 -0
  69. package/dist/react/useMcpServerQueues.d.ts.map +1 -0
  70. package/dist/react/view/ViewRenderer.d.ts +20 -0
  71. package/dist/react/view/ViewRenderer.d.ts.map +1 -0
  72. package/dist/react/view/ext-apps-bridge.d.ts +3 -0
  73. package/dist/react/view/ext-apps-bridge.d.ts.map +1 -0
  74. package/dist/react/view/initialized-sync.d.ts +13 -0
  75. package/dist/react/view/initialized-sync.d.ts.map +1 -0
  76. package/dist/react/view/inject-openai-file-apis.d.ts +9 -0
  77. package/dist/react/view/inject-openai-file-apis.d.ts.map +1 -0
  78. package/dist/react/view/parse-custom-props.d.ts +10 -0
  79. package/dist/react/view/parse-custom-props.d.ts.map +1 -0
  80. package/dist/react/view/resolve-view-resource.d.ts +22 -0
  81. package/dist/react/view/resolve-view-resource.d.ts.map +1 -0
  82. package/dist/react/view/sandbox-blob-url.d.ts +27 -0
  83. package/dist/react/view/sandbox-blob-url.d.ts.map +1 -0
  84. package/dist/react/view/types.d.ts +220 -0
  85. package/dist/react/view/types.d.ts.map +1 -0
  86. package/dist/react/view/use-display-mode.d.ts +19 -0
  87. package/dist/react/view/use-display-mode.d.ts.map +1 -0
  88. package/dist/react/view/view-detection.d.ts +22 -0
  89. package/dist/react/view/view-detection.d.ts.map +1 -0
  90. package/dist/react/view/view-host-policy.d.ts +61 -0
  91. package/dist/react/view/view-host-policy.d.ts.map +1 -0
  92. package/dist/sandbox.d.ts +2 -0
  93. package/dist/sandbox.d.ts.map +1 -0
  94. package/dist/sandbox.js +288 -0
  95. package/dist/sandbox.js.map +1 -0
  96. package/dist/telemetry/client-telemetry.d.ts +13 -0
  97. package/dist/telemetry/client-telemetry.d.ts.map +1 -0
  98. package/dist/telemetry/configure-browser.d.ts +2 -0
  99. package/dist/telemetry/configure-browser.d.ts.map +1 -0
  100. package/dist/telemetry/configure-node.d.ts +2 -0
  101. package/dist/telemetry/configure-node.d.ts.map +1 -0
  102. package/dist/telemetry/connector-telemetry.d.ts +8 -0
  103. package/dist/telemetry/connector-telemetry.d.ts.map +1 -0
  104. package/dist/telemetry/events.d.ts +91 -0
  105. package/dist/telemetry/events.d.ts.map +1 -0
  106. package/dist/telemetry/index.d.ts +3 -0
  107. package/dist/telemetry/index.d.ts.map +1 -0
  108. package/dist/telemetry/tel-fetch.d.ts +19 -0
  109. package/dist/telemetry/tel-fetch.d.ts.map +1 -0
  110. package/dist/telemetry/telemetry-browser.d.ts +6 -0
  111. package/dist/telemetry/telemetry-browser.d.ts.map +1 -0
  112. package/dist/telemetry/telemetry-node.d.ts +8 -0
  113. package/dist/telemetry/telemetry-node.d.ts.map +1 -0
  114. package/dist/telemetry/telemetry.d.ts +75 -0
  115. package/dist/telemetry/telemetry.d.ts.map +1 -0
  116. package/dist/transport/base.d.ts +656 -0
  117. package/dist/transport/base.d.ts.map +1 -0
  118. package/dist/transport/connection-manager.d.ts +59 -0
  119. package/dist/transport/connection-manager.d.ts.map +1 -0
  120. package/dist/transport/http.d.ts +137 -0
  121. package/dist/transport/http.d.ts.map +1 -0
  122. package/dist/transport/stdio.d.ts +97 -0
  123. package/dist/transport/stdio.d.ts.map +1 -0
  124. package/dist/utils/elicitation.d.ts +54 -0
  125. package/dist/utils/elicitation.d.ts.map +1 -0
  126. package/dist/utils/favicon.d.ts +6 -0
  127. package/dist/utils/favicon.d.ts.map +1 -0
  128. package/dist/utils/json-schema-validator.d.ts +13 -0
  129. package/dist/utils/json-schema-validator.d.ts.map +1 -0
  130. package/dist/utils/logging.d.ts +33 -0
  131. package/dist/utils/logging.d.ts.map +1 -0
  132. package/dist/utils/version.d.ts +9 -0
  133. package/dist/utils/version.d.ts.map +1 -0
  134. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/telemetry/connector-telemetry.ts","../src/utils/logging.ts","../src/auth/popup.ts","../src/auth/flow.ts","../src/utils/json-schema-validator.ts","../src/transport/base.ts","../src/transport/connection-manager.ts","../src/transport/stdio.ts","../src/telemetry/client-telemetry.ts","../src/telemetry/configure-node.ts","../src/telemetry/telemetry.ts","../src/utils/version.ts","../src/telemetry/events.ts","../src/telemetry/tel-fetch.ts","../src/telemetry/telemetry-node.ts","../src/index.ts","../src/auth/node.ts","../src/auth/storage-file.ts","../src/auth/session-store.ts","../src/auth/url.ts","../src/transport/http.ts","../src/core/config.ts","../src/core/node.ts","../src/core/base.ts","../src/core/skills.ts","../src/core/session.ts","../src/code-mode/executor.ts","../src/code-mode/executor-e2b.ts","../src/code-mode/executor-vm.ts","../src/code-mode/connector.ts","../src/utils/elicitation.ts"],"sourcesContent":["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","// 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","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 { logger } from \"../utils/logging.js\";\n\nexport abstract class ConnectionManager<T = any> {\n private _readyPromise!: Promise<void>;\n private _readyResolver!: () => void;\n\n private _donePromise!: Promise<void>;\n private _doneResolver!: () => void;\n\n private _exception: Error | null = null;\n private _connection: T | null = null;\n private _task: Promise<void> | null = null;\n private _abortController: AbortController | null = null;\n private _startPromise: Promise<T> | null = null;\n private _stopPromise: Promise<void> | null = null;\n\n constructor() {\n this.reset();\n }\n\n /**\n * Establish the connection.\n *\n * This method should be implemented by subclasses to establish the specific\n * type of connection needed.\n *\n * @returns The established connection.\n * @throws If the connection cannot be established.\n */\n protected abstract establishConnection(): Promise<T>;\n\n /**\n * Close the connection.\n *\n * This method should be implemented by subclasses to close the specific type\n * of connection.\n *\n * @param connection - The connection to close.\n */\n protected abstract closeConnection(connection: T): Promise<void>;\n\n /**\n * Start the connection manager and establish a connection.\n *\n * @returns The established connection.\n * @throws If the connection cannot be established.\n */\n start(): Promise<T> {\n if (this._stopPromise) {\n return this._stopPromise.then(() => this.start());\n }\n if (this._startPromise) return this._startPromise;\n\n // Reset internal state before starting\n this.reset();\n\n logger.debug(`Starting ${this.constructor.name}`);\n\n // Kick off the background task that manages the connection\n this._task = this.connectionTask();\n this._startPromise = this.waitUntilReady().catch((error) => {\n this._startPromise = null;\n throw error;\n });\n return this._startPromise;\n }\n\n private async waitUntilReady(): Promise<T> {\n // Wait until the connection is ready or an error occurs\n await this._readyPromise;\n\n // If an exception occurred during startup, re‑throw it\n if (this._exception) {\n throw this._exception;\n }\n\n if (this._connection === null) {\n throw new Error(\"Connection was not established\");\n }\n\n return this._connection;\n }\n\n /**\n * Stop the connection manager and close the connection.\n */\n stop(): Promise<void> {\n if (this._stopPromise) return this._stopPromise;\n if (!this._task) return Promise.resolve();\n\n const trackedStop = this.stopTask().finally(() => {\n if (this._stopPromise === trackedStop) {\n this._stopPromise = null;\n }\n });\n this._stopPromise = trackedStop;\n return trackedStop;\n }\n\n private async stopTask(): Promise<void> {\n if (this._task && this._abortController) {\n logger.debug(`Cancelling ${this.constructor.name} task`);\n\n this._abortController.abort();\n\n try {\n await this._task;\n } catch (e) {\n if (e instanceof Error && e.name === \"AbortError\") {\n logger.debug(`${this.constructor.name} task aborted successfully`);\n } else {\n logger.warn(`Error stopping ${this.constructor.name} task: ${e}`);\n }\n }\n }\n\n // Wait until the connection cleanup has completed\n await this._donePromise;\n this._task = null;\n this._startPromise = null;\n logger.debug(`${this.constructor.name} task completed`);\n }\n\n /**\n * Reset all internal state.\n */\n private reset(): void {\n this._readyPromise = new Promise((res) => (this._readyResolver = res));\n this._donePromise = new Promise((res) => (this._doneResolver = res));\n this._exception = null;\n this._connection = null;\n this._task = null;\n this._abortController = new AbortController();\n }\n\n /**\n * The background task responsible for establishing and maintaining the\n * connection until it is cancelled.\n */\n private async connectionTask(): Promise<void> {\n logger.debug(`Running ${this.constructor.name} task`);\n\n try {\n // Establish the connection\n this._connection = await this.establishConnection();\n logger.debug(`${this.constructor.name} connected successfully`);\n\n // Signal that the connection is ready\n this._readyResolver();\n\n // Keep the task alive until it is cancelled\n await this.waitForAbort();\n } catch (err) {\n this._exception = err as Error;\n logger.error(`Error in ${this.constructor.name} task: ${err}`);\n\n // Ensure the ready promise resolves so that start() can handle the error\n this._readyResolver();\n } finally {\n // Clean up the connection if it was established\n if (this._connection !== null) {\n try {\n await this.closeConnection(this._connection);\n } catch (closeErr) {\n logger.warn(\n `Error closing connection in ${this.constructor.name}: ${closeErr}`\n );\n }\n this._connection = null;\n }\n\n // Signal that cleanup is finished\n this._doneResolver();\n }\n }\n\n /**\n * Helper that returns a promise which resolves when the abort signal fires.\n */\n private async waitForAbort(): Promise<void> {\n return new Promise((_resolve, _reject) => {\n if (!this._abortController) {\n return;\n }\n\n const signal = this._abortController.signal;\n\n if (signal.aborted) {\n _resolve();\n return;\n }\n\n const onAbort = (): void => {\n signal.removeEventListener(\"abort\", onAbort);\n _resolve();\n };\n\n signal.addEventListener(\"abort\", onAbort);\n });\n }\n}\n","import type {\n ClientOptions,\n VersionNegotiationMode,\n} from \"@modelcontextprotocol/client\";\nimport { Client } from \"@modelcontextprotocol/client\";\nimport type { StdioServerParameters } from \"@modelcontextprotocol/client/stdio\";\nimport type { Writable } from \"node:stream\";\n\nimport process from \"node:process\";\nimport type { ConnectorInitOptions } from \"./base.js\";\n\nimport { logger } from \"../utils/logging.js\";\nimport { DialectJsonSchemaValidator } from \"../utils/json-schema-validator.js\";\nimport { ConnectionManager } from \"./connection-manager.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/client/stdio\";\nimport { BaseConnector } from \"./base.js\";\nimport type { ClientInfo } from \"./http.js\";\n\n/**\n * How a spawned server's standard error is handled.\n *\n * - `\"pipe\"` forwards the child's stderr to the connector's `errlog`.\n * - `\"inherit\"` hands the parent's stderr file descriptor to the child, which\n * preserves TTY detection and colorization but bypasses `errlog`.\n * - `\"ignore\"` discards it.\n *\n * @defaultValue `\"pipe\"`\n */\nexport type StdioStderrMode = \"pipe\" | \"inherit\" | \"ignore\";\n\n/** Stdio-specific connector options. */\ninterface StdioConnectorOptions extends ConnectorInitOptions {\n /** Client identity advertised to the server. */\n clientInfo?: ClientInfo;\n /**\n * Protocol version negotiation mode. Defaults to `\"legacy\"` for stdio: the\n * SDK docs advise against `\"auto\"` for spawn-per-invocation CLI/debug tools\n * (a legacy server that never answers unknown pre-`initialize` requests\n * stalls the probe, and the probe round trip perturbs byte-stable\n * transcripts). Opt into `\"auto\"` or a pin explicitly.\n */\n protocolNegotiation?: VersionNegotiationMode;\n}\n\n/**\n * Launches and connects to a local MCP server over standard input and output.\n */\nexport class StdioConnector extends BaseConnector {\n private readonly command: string;\n private readonly args: string[];\n private readonly env?: Record<string, string>;\n private readonly cwd?: string;\n private readonly errlog: Writable;\n private readonly stderr: StdioStderrMode;\n private readonly clientInfo: ClientInfo;\n private readonly protocolNegotiation: VersionNegotiationMode;\n\n /**\n * Creates a stdio connector.\n *\n * @param options - Process launch, client identity, and shared connector options.\n */\n constructor({\n command = \"npx\",\n args = [],\n env,\n errlog = process.stderr,\n stderr = \"pipe\",\n ...rest\n }: {\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n errlog?: Writable;\n /**\n * How the child's standard error is handled. Defaults to `\"pipe\"` so\n * {@link StdioStderrMode} forwarding to `errlog` works without extra\n * configuration; pass `\"inherit\"` to keep the child on the parent's\n * stderr file descriptor.\n */\n stderr?: StdioStderrMode;\n cwd?: string;\n } & StdioConnectorOptions = {}) {\n super(rest);\n\n this.command = command;\n this.args = args;\n this.env = env;\n this.errlog = errlog;\n this.stderr = stderr;\n this.clientInfo = rest.clientInfo ?? {\n name: \"stdio-connector\",\n version: \"1.0.0\",\n };\n this.cwd = rest.cwd;\n this.protocolNegotiation = rest.protocolNegotiation ?? \"legacy\";\n }\n\n /**\n * Starts the child process and establishes an MCP connection.\n *\n * @returns A promise that resolves after protocol negotiation completes.\n */\n async connect(): Promise<void> {\n if (this.connected) {\n logger.debug(\"Already connected to MCP implementation\");\n return;\n }\n\n logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);\n try {\n // 1. Build server parameters for the transport\n\n const serverParams: StdioServerParameters = {\n command: this.command,\n args: this.args,\n // The SDK layers explicit values over getDefaultEnvironment(). Passing\n // the configured env through avoids exposing unrelated parent secrets.\n env: this.env,\n cwd: this.cwd,\n stderr: this.stderr,\n };\n\n // 2. Start the connection manager -> returns a live transport\n this.connectionManager = new StdioConnectionManager(\n serverParams,\n this.errlog\n );\n const transport = await this.connectionManager.start();\n\n // 3. Create & connect the MCP client\n // Always advertise roots capability - server may query roots/list even if client has no roots\n const clientOptions: ClientOptions = {\n ...(this.opts.clientOptions || {}),\n jsonSchemaValidator:\n this.opts.clientOptions?.jsonSchemaValidator ??\n new DialectJsonSchemaValidator(),\n versionNegotiation: {\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 }, // Always advertise roots capability\n // Add sampling capability if callback is provided\n ...(this.opts.onSampling ? { sampling: {} } : {}),\n // Add elicitation capability if callback is provided\n ...(this.opts.onElicitation\n ? { elicitation: { form: {}, url: {} } }\n : {}),\n },\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 logger.debug(\n \"Roots/sampling/elicitation handlers registered before connect (stdio)\"\n );\n\n await this.client.connect(transport);\n this.setupRoundProgressForwarding();\n\n this.connected = true;\n this.setupNotificationHandler();\n // Inbound request handlers (roots/sampling/elicitation) were registered before connect()\n logger.debug(\n `Successfully connected to MCP implementation: ${this.command}`\n );\n\n // Track connector initialization\n this.trackConnectorInit({\n serverCommand: this.command,\n serverArgs: this.args,\n publicIdentifier: `${this.command} ${this.args.join(\" \")}`,\n });\n } catch (err) {\n logger.error(`Failed to connect to MCP implementation: ${err}`);\n await this.cleanupResources();\n throw err;\n }\n }\n\n /**\n * Returns fields identifying the launched command and arguments.\n *\n * @returns Stdio connector identity metadata.\n */\n get publicIdentifier(): Record<string, string> {\n return {\n type: \"stdio\",\n \"command&args\": `${this.command} ${this.args.join(\" \")}`,\n };\n }\n}\n\n/**\n * Owns the lifecycle of a stdio client transport.\n */\nexport class StdioConnectionManager extends ConnectionManager<StdioClientTransport> {\n private readonly serverParams: StdioServerParameters;\n private readonly errlog: Writable;\n private _transport: StdioClientTransport | null = null;\n private _stderrSource: NodeJS.ReadableStream | null = null;\n private readonly _onErrlogError = (error: Error): void => {\n logger.warn(`Error writing child stderr to errlog: ${error}`);\n };\n\n /**\n * Creates a connection manager for a local server process.\n *\n * @param serverParams - Process parameters passed to the SDK transport.\n * @param errlog - Destination for the child process's standard error stream.\n */\n constructor(\n serverParams: StdioServerParameters,\n errlog: Writable = process.stderr\n ) {\n super();\n this.serverParams = serverParams;\n this.errlog = errlog;\n }\n\n protected async establishConnection(): Promise<StdioClientTransport> {\n // The SDK defaults stderr to \"inherit\", which leaves `transport.stderr`\n // null and makes the forwarding below dead code. Default to \"pipe\" so\n // `errlog` works without extra configuration. The coalesce is applied\n // after the spread on purpose: an explicit `stderr: undefined` in\n // serverParams would otherwise defeat the default.\n const stderr = this.serverParams.stderr ?? \"pipe\";\n this._transport = new StdioClientTransport({\n ...this.serverParams,\n stderr,\n });\n\n // Only \"pipe\" leaves a readable stream; \"inherit\" and \"ignore\" do not.\n const childStderr = this._transport.stderr;\n if (stderr === \"pipe\" && childStderr && \"pipe\" in childStderr) {\n this._stderrSource = childStderr as unknown as NodeJS.ReadableStream;\n // `errlog` is caller-owned and may be reused across reconnects, so the\n // child exiting must not end it. Without a handler, a destroyed errlog\n // would surface as an unhandled 'error' event.\n this._stderrSource.on(\"error\", (error) => {\n logger.warn(`Error forwarding child stderr: ${error}`);\n });\n this.errlog.on(\"error\", this._onErrlogError);\n this._stderrSource.pipe(this.errlog, { end: false });\n }\n\n logger.debug(`${this.constructor.name} connected successfully`);\n return this._transport;\n }\n\n protected async closeConnection(\n _connection: StdioClientTransport\n ): Promise<void> {\n if (this._stderrSource) {\n this._stderrSource.unpipe(this.errlog);\n this.errlog.off(\"error\", this._onErrlogError);\n this._stderrSource = null;\n }\n if (this._transport) {\n try {\n await this._transport.close();\n } catch (e) {\n logger.warn(`Error closing stdio transport: ${e}`);\n } finally {\n this._transport = null;\n }\n }\n }\n}\n","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 { setClientTelemetryTracker } from \"./client-telemetry.js\";\nimport { setConnectorTelemetryTracker } from \"./connector-telemetry.js\";\nimport { Telemetry } from \"./telemetry-node.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","/**\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","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 * Node entry for telemetry: installs filesystem persistence, then re-exports\n * the shared Telemetry singleton. `node:fs` stays here so it never enters\n * browser bundles.\n */\n/* eslint-disable @typescript-eslint/no-require-imports */\nimport {\n configureTelemetryStorage,\n Tel,\n Telemetry,\n setProductVersion,\n setTelemetrySource,\n type TelemetryStorage,\n} from \"./telemetry.js\";\n\nfunction getCacheHome(\n os: typeof import(\"node:os\"),\n path: typeof import(\"node:path\")\n): string {\n const envVar = process.env.XDG_CACHE_HOME;\n if (envVar && path.isAbsolute(envVar)) {\n return envVar;\n }\n\n const homeDir = os.homedir();\n if (process.platform === \"win32\") {\n const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;\n if (appdata) return appdata;\n return path.join(homeDir, \"AppData\", \"Local\");\n }\n if (process.platform === \"darwin\") {\n return path.join(homeDir, \"Library\", \"Caches\");\n }\n return path.join(homeDir, \".cache\");\n}\n\nfunction createFsStorage(): TelemetryStorage {\n let fs: typeof import(\"node:fs\");\n let os: typeof import(\"node:os\");\n let path: typeof import(\"node:path\");\n try {\n fs = require(\"node:fs\");\n os = require(\"node:os\");\n path = require(\"node:path\");\n } catch {\n return {\n getUserId: () => null,\n setUserId: () => undefined,\n };\n }\n\n const cacheHome = getCacheHome(os, path);\n const userIdPath = path.join(cacheHome, \"mcp_use_3\", \"telemetry_user_id\");\n\n return {\n getUserId() {\n try {\n if (!fs.existsSync(userIdPath)) return null;\n return fs.readFileSync(userIdPath, \"utf-8\").trim() || null;\n } catch {\n return null;\n }\n },\n setUserId(id: string) {\n try {\n fs.mkdirSync(path.dirname(userIdPath), { recursive: true });\n fs.writeFileSync(userIdPath, id);\n } catch {\n // ignore\n }\n },\n };\n}\n\nconfigureTelemetryStorage(createFsStorage());\n\nexport { Telemetry, Tel, setTelemetrySource, setProductVersion };\n","/**\n * `@mcp-use/client` — MCP client for connecting to Model Context Protocol servers.\n *\n * Connectors, protocol-neutral MCP connections, project configuration, OAuth,\n * and code-mode helpers. The SDK negotiates legacy sessionful and modern\n * sessionless MCP servers automatically.\n */\n\nimport \"./telemetry/configure-node.js\";\n\nexport { auth, UnauthorizedError } from \"@modelcontextprotocol/client\";\nexport {\n completeOAuthFlow,\n isOAuthInteractionRequired,\n isUnauthorized,\n} from \"./auth/flow.js\";\nexport {\n createOAuthProvider,\n NodeOAuthClientProvider,\n OAuthFlowError,\n type NodeOAuthAuthorizationResponse,\n type NodeOAuthOptions,\n type OAuthProviderOptions,\n} from \"./auth/node.js\";\nexport { FileKVStore } from \"./auth/storage-file.js\";\nexport * from \"./core/config.js\";\nexport * from \"./core/node.js\";\nexport * from \"./core/session.js\";\n\n// Connectors\nexport * from \"./transport/base.js\";\nexport * from \"./transport/http.js\";\nexport * from \"./transport/stdio.js\";\n\n// JSON Schema validation\nexport * from \"./utils/json-schema-validator.js\";\n\n// Code mode (executors re-exported from core/node)\nexport * from \"./code-mode/connector.js\";\n\n// Logging + internal telemetry\nexport {\n setTelemetrySource,\n setProductVersion,\n Tel,\n Telemetry,\n telFetch,\n capturePostHog,\n POSTHOG_HOST,\n POSTHOG_API_KEY,\n} from \"./telemetry/index.js\";\nexport { logger } from \"./utils/logging.js\";\n","import type {\n OAuthClientInformation,\n OAuthClientInformationContext,\n OAuthClientMetadata,\n OAuthClientProvider,\n OAuthDiscoveryState,\n OAuthTokens,\n} from \"@modelcontextprotocol/client\";\nimport { createServer as createNetServer } from \"node:net\";\nimport { createServer as createHttpServer, type Server } from \"node:http\";\nimport { FileKVStore } from \"./storage-file.js\";\nimport type { KVStore } from \"./storage.js\";\nimport {\n OAuthSessionStore,\n type OAuthSessionStoreOptions,\n} from \"./session-store.js\";\n\nconst DEFAULT_PORT = 33418;\nconst PORT_RANGE = 10;\nconst DEFAULT_AUTH_TIMEOUT_MS = 5 * 60_000;\n\n/** Configures OAuth authorization for Node.js and CLI clients. */\nexport interface NodeOAuthOptions extends OAuthSessionStoreOptions {\n /** Preferred loopback port. Default 33418. Walks up by `portRange` on EADDRINUSE. */\n preferredPort?: number;\n /** Number of consecutive loopback ports to try. Defaults to `10`. */\n portRange?: number;\n /** Override the on-disk store directory (mostly for tests). */\n baseDir?: string;\n /** Override KV store entirely (mostly for tests). */\n kvStore?: KVStore;\n /** Loopback wait timeout. Default 5 minutes. */\n authTimeoutMs?: number;\n /** Suppress the default `open(url)` browser launch (test hook). */\n openBrowser?: (url: string) => Promise<void> | void;\n}\n\n/**\n * Error reported by the local OAuth callback flow.\n *\n * The {@link OAuthFlowError.code} value is a stable OAuth or local-flow error\n * code such as `\"timeout\"` or `\"cancelled\"`.\n */\nexport class OAuthFlowError extends Error {\n /** OAuth or local-flow error code. */\n readonly code: string;\n /** Optional human-readable error description. */\n readonly description?: string;\n\n /**\n * Creates an OAuth flow error.\n *\n * @param code - OAuth or local-flow error code.\n * @param description - Optional human-readable description.\n */\n constructor(code: string, description?: string) {\n super(description ? `${code}: ${description}` : code);\n this.code = code;\n this.description = description;\n this.name = \"OAuthFlowError\";\n }\n}\n\n/** Authorization response captured by the Node loopback callback. */\nexport interface NodeOAuthAuthorizationResponse {\n /** Authorization code returned by the authorization server. */\n code: string;\n /** RFC 9207 authorization-server issuer, when present in the callback. */\n iss?: string;\n}\n\ninterface Deferred<T> {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (err: Error) => void;\n}\n\nfunction createDeferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (err: Error) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nasync function isPortFree(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const tester = createNetServer();\n tester.once(\"error\", () => resolve(false));\n tester.once(\"listening\", () => {\n tester.close(() => resolve(true));\n });\n tester.listen(port, \"127.0.0.1\");\n });\n}\n\nasync function reservePort(\n preferred: number,\n range: number\n): Promise<number | null> {\n for (let p = preferred; p < preferred + range; p++) {\n if (await isPortFree(p)) return p;\n }\n return null;\n}\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\"><title>Authentication complete</title>\n<style>body{font-family:system-ui,sans-serif;max-width:480px;margin:80px auto;padding:0 24px;color:#222}\nh1{font-size:20px;margin:0 0 12px}p{line-height:1.5}</style></head>\n<body><h1>Authentication complete</h1>\n<p>You can close this tab and return to your terminal.</p></body></html>`;\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nconst FAILURE_HTML = (err: string, desc?: string) => `<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\"><title>Authentication failed</title>\n<style>body{font-family:system-ui,sans-serif;max-width:480px;margin:80px auto;padding:0 24px;color:#222}\nh1{font-size:20px;margin:0 0 12px;color:#b00020}p{line-height:1.5}code{background:#f3f3f3;padding:2px 6px;border-radius:3px}</style></head>\n<body><h1>Authentication failed</h1>\n<p><code>${escapeHtml(err)}</code>${desc ? `: ${escapeHtml(desc)}` : \"\"}</p>\n<p>You can close this tab and return to your terminal.</p></body></html>`;\n\n/**\n * Node/CLI OAuth client provider for MCP. Owns a localhost loopback callback\n * server, opens the user's browser, and resolves the authorization code via\n * `getAuthorizationCode()` — designed for the orchestrator pattern in\n * `useMcp.ts:1121-1145`.\n *\n * Use the static `create()` factory; the constructor is internal because\n * port reservation is async.\n */\nexport class NodeOAuthClientProvider implements OAuthClientProvider {\n /** Protected MCP server URL associated with this provider. */\n readonly serverUrl: string;\n /** Reserved localhost callback port. */\n readonly port: number;\n\n private session: OAuthSessionStore;\n private kv: KVStore;\n private authTimeoutMs: number;\n private openBrowserOverride?: (url: string) => Promise<void> | void;\n /** Whether the selected callback port still needs to be written to storage. */\n private shouldPersistSelectedPort: boolean;\n\n private server: Server | null = null;\n /** Provider authorization URL, exposed only through the local redirect route. */\n private authorizationUrl: string | null = null;\n /** Currently in-flight deferred — used to prevent overlapping flows. */\n private pending: Deferred<NodeOAuthAuthorizationResponse> | null = null;\n /** Latest deferred (settled or in-flight) for the loopback response. */\n private lastFlow: Deferred<NodeOAuthAuthorizationResponse> | null = null;\n private pendingTimer: NodeJS.Timeout | null = null;\n\n private constructor(\n serverUrl: string,\n port: number,\n session: OAuthSessionStore,\n kv: KVStore,\n options: NodeOAuthOptions,\n shouldPersistSelectedPort: boolean\n ) {\n this.serverUrl = serverUrl;\n this.port = port;\n this.session = session;\n this.kv = kv;\n this.authTimeoutMs = options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;\n this.openBrowserOverride = options.openBrowser;\n this.shouldPersistSelectedPort = shouldPersistSelectedPort;\n }\n\n /**\n * Creates a Node OAuth provider and reserves a localhost callback port.\n *\n * @param serverUrl - Protected MCP server URL.\n * @param options - OAuth metadata, storage, loopback, and browser options.\n * @returns A provider ready to participate in the SDK OAuth flow.\n */\n static async create(\n serverUrl: string,\n options: NodeOAuthOptions = {}\n ): Promise<NodeOAuthClientProvider> {\n const serverUrlHash = OAuthSessionStore.hashString(serverUrl);\n const kv =\n options.kvStore ?? new FileKVStore(serverUrlHash, options.baseDir);\n\n const persistedPortRaw = await kv.get(\"port\");\n const persistedPort = persistedPortRaw\n ? Number.parseInt(persistedPortRaw, 10)\n : null;\n const preferred =\n persistedPort && Number.isFinite(persistedPort)\n ? persistedPort\n : (options.preferredPort ?? DEFAULT_PORT);\n const range = options.portRange ?? PORT_RANGE;\n\n let port = await reservePort(preferred, range);\n if (port === null) {\n // Fall back to ephemeral. Will trigger DCR re-register on next call\n // because the redirect_uri changes — that path already works.\n port = await new Promise<number>((resolve, reject) => {\n const probe = createNetServer();\n probe.once(\"error\", reject);\n probe.once(\"listening\", () => {\n const addr = probe.address();\n const p = typeof addr === \"object\" && addr ? addr.port : 0;\n probe.close(() => resolve(p));\n });\n probe.listen(0, \"127.0.0.1\");\n });\n }\n\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n const session = new OAuthSessionStore(\n serverUrl,\n { ...options, callbackUrl },\n kv\n );\n\n return new NodeOAuthClientProvider(\n serverUrl,\n port,\n session,\n kv,\n options,\n port !== persistedPort\n );\n }\n\n // --- Identity passthroughs (parallel to BrowserOAuthClientProvider) ---\n\n /** Prefix used for persisted OAuth session keys. */\n get storageKeyPrefix(): string {\n return this.session.storageKeyPrefix;\n }\n\n /** Stable hash of the protected server URL used to namespace storage. */\n get serverUrlHash(): string {\n return this.session.serverUrlHash;\n }\n\n // --- SDK Interface (delegated to OAuthSessionStore) ---\n\n /** Loopback redirect URL registered for this provider. */\n get redirectUrl(): string {\n return this.session.redirectUrl;\n }\n\n /** OAuth client metadata presented during registration. */\n get clientMetadata(): OAuthClientMetadata {\n return this.session.clientMetadata;\n }\n\n /** OAuth Client ID Metadata Document URL, when configured. */\n get clientMetadataUrl(): string | undefined {\n return this.session.clientMetadataUrl;\n }\n\n /**\n * Loads saved OAuth tokens.\n *\n * @param ctx - Optional client registration context.\n * @returns Saved tokens, or `undefined` when none exist.\n */\n tokens(\n ctx?: OAuthClientInformationContext\n ): Promise<OAuthTokens | undefined> {\n return this.session.tokens(ctx);\n }\n\n /**\n * Persists OAuth tokens.\n *\n * @param tokens - Tokens to save.\n * @param ctx - Optional client registration context.\n */\n saveTokens(\n tokens: OAuthTokens,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n return this.session.saveTokens(tokens, ctx);\n }\n\n /**\n * Loads saved OAuth client registration information.\n *\n * @param ctx - Optional registration context.\n * @returns Saved registration information, or `undefined`.\n */\n clientInformation(\n ctx?: OAuthClientInformationContext\n ): Promise<OAuthClientInformation | undefined> {\n return this.session.clientInformation(ctx);\n }\n\n /**\n * Persists OAuth client registration information.\n *\n * @param info - Client information to save.\n * @param ctx - Optional registration context.\n */\n saveClientInformation(\n info: OAuthClientInformation,\n ctx?: OAuthClientInformationContext\n ): Promise<void> {\n return this.session.saveClientInformation(info, ctx);\n }\n\n /**\n * Loads the saved PKCE code verifier.\n *\n * @returns The saved verifier.\n */\n codeVerifier(): Promise<string> {\n return this.session.codeVerifier();\n }\n\n /**\n * Persists a PKCE code verifier.\n *\n * @param codeVerifier - Verifier to save.\n */\n saveCodeVerifier(codeVerifier: string): Promise<void> {\n return this.session.saveCodeVerifier(codeVerifier);\n }\n\n /**\n * Invalidates selected persisted OAuth credentials.\n *\n * @param scope - Credential group to remove.\n */\n invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"\n ): Promise<void> {\n return this.session.invalidateCredentials(scope);\n }\n\n /**\n * Persists OAuth discovery state.\n *\n * @param state - Discovery state to save.\n */\n saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n return this.session.saveDiscoveryState(state);\n }\n\n /**\n * Returns previously saved OAuth discovery state.\n *\n * @returns Saved discovery state, or `undefined`.\n */\n discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n return this.session.discoveryState();\n }\n\n /**\n * Bind the loopback server, set up the pending-code deferred, and ask the\n * platform to open the user's browser. Does NOT await the code; the\n * orchestrator awaits via `getAuthorizationCode()`.\n *\n * @param authorizationUrl - Authorization URL generated by the SDK.\n * @returns A promise that resolves once the loopback listener is ready and\n * the browser-open attempt completes.\n */\n async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n if (this.pending) {\n throw new Error(\n \"NodeOAuthClientProvider: an authorization is already in progress\"\n );\n }\n\n if (this.shouldPersistSelectedPort) {\n await this.kv.set(\"port\", String(this.port));\n this.shouldPersistSelectedPort = false;\n }\n\n const sanitizedUrl = await this.session.storeAuthorizationState(\n authorizationUrl,\n { flowType: \"redirect\" }\n );\n this.authorizationUrl = sanitizedUrl;\n\n await this.startLoopback();\n\n this.pending = createDeferred<NodeOAuthAuthorizationResponse>();\n this.lastFlow = this.pending;\n // Swallow unhandled rejections — callers may not subscribe before the\n // callback fires, but `getAuthorizationCode()` still returns the same\n // settled promise so the rejection is observable when awaited.\n this.pending.promise.catch(() => {});\n this.pendingTimer = setTimeout(() => {\n this.rejectPending(\n new OAuthFlowError(\n \"timeout\",\n `No callback received within ${this.authTimeoutMs}ms`\n )\n );\n }, this.authTimeoutMs);\n\n const opener = this.openBrowserOverride ?? defaultOpener;\n const launcherUrl = `http://127.0.0.1:${this.port}/authorize`;\n try {\n await opener(launcherUrl);\n // The local launcher redirects without exposing OAuth state in terminal\n // output when a CLI callback prints the opener URL for manual use.\n } catch (err) {\n // Non-fatal: we still print/keep listening so the user can paste.\n console.error(\n `[mcp-use] Could not open browser automatically: ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n }\n\n /**\n * Resolves with the authorization code captured by the loopback callback.\n *\n * @remarks This compatibility method omits the RFC 9207 issuer. OAuth flow\n * orchestrators should use {@link getAuthorizationResponse} when available.\n * Must be called after `redirectToAuthorization()`. Returns the same\n * promise whether the callback has fired or not — callers may subscribe\n * before or after.\n *\n * @returns The authorization code received by the loopback callback.\n */\n getAuthorizationCode(): Promise<string> {\n return this.getAuthorizationResponse().then((response) => response.code);\n }\n\n /**\n * Resolves with the authorization code and RFC 9207 issuer captured by the\n * loopback callback.\n *\n * @returns The loopback authorization response.\n * @throws When called before {@link NodeOAuthClientProvider.redirectToAuthorization}.\n */\n getAuthorizationResponse(): Promise<NodeOAuthAuthorizationResponse> {\n if (!this.lastFlow) {\n return Promise.reject(\n new Error(\n \"NodeOAuthClientProvider.getAuthorizationResponse() called before redirectToAuthorization()\"\n )\n );\n }\n return this.lastFlow.promise;\n }\n\n /**\n * Cancel an in-progress flow (timeout, SIGINT, etc.) and close the loopback.\n *\n * Pending calls to {@link NodeOAuthClientProvider.getAuthorizationResponse}\n * reject with an {@link OAuthFlowError} whose code is `\"cancelled\"`.\n */\n dispose(): void {\n if (this.pending) {\n this.rejectPending(new OAuthFlowError(\"cancelled\", \"Flow cancelled\"));\n } else {\n this.stopLoopback();\n }\n }\n\n /** Local callback port, useful for status output and tests. */\n get callbackPort(): number {\n return this.port;\n }\n\n /**\n * True if `redirectToAuthorization()` has been called and we're awaiting\n * a callback (loopback bound, browser opened). Lets orchestrators detect\n * when the SDK transport has already kicked off the flow on a 401, so they\n * can skip straight to `getAuthorizationCode()` instead of calling `auth()`\n * again (which would throw \"already in progress\").\n */\n get hasPendingFlow(): boolean {\n return this.pending !== null;\n }\n\n // --- Loopback internals ---\n\n private async startLoopback(): Promise<void> {\n if (this.server) return;\n const server = createHttpServer((req, res) => {\n this.handleCallback(req.url ?? \"/\", res);\n });\n // Track the server during binding so dispose() can find it.\n this.server = server;\n try {\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(this.port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", reject);\n resolve();\n });\n });\n } catch (err) {\n if (this.server === server) {\n this.server = null;\n }\n server.close();\n throw err;\n }\n }\n\n private stopLoopback(): void {\n if (this.pendingTimer) {\n clearTimeout(this.pendingTimer);\n this.pendingTimer = null;\n }\n if (this.server) {\n this.server.close();\n this.server = null;\n }\n this.authorizationUrl = null;\n }\n\n private resolvePending(response: NodeOAuthAuthorizationResponse): void {\n const p = this.pending;\n this.pending = null;\n this.stopLoopback();\n p?.resolve(response);\n }\n\n private rejectPending(err: Error): void {\n const p = this.pending;\n this.pending = null;\n this.stopLoopback();\n p?.reject(err);\n }\n\n private handleCallback(\n rawUrl: string,\n res: import(\"node:http\").ServerResponse\n ): void {\n const url = new URL(rawUrl, `http://127.0.0.1:${this.port}`);\n\n if (url.pathname === \"/authorize\") {\n if (this.authorizationUrl === null || this.pending === null) {\n res.statusCode = 410;\n res.end(\"Authorization flow is not active\");\n return;\n }\n res.statusCode = 302;\n res.setHeader(\"location\", this.authorizationUrl);\n res.setHeader(\"cache-control\", \"no-store\");\n res.setHeader(\"referrer-policy\", \"no-referrer\");\n res.end();\n return;\n }\n\n if (url.pathname !== \"/callback\") {\n res.statusCode = 404;\n res.end(\"Not Found\");\n return;\n }\n\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n const iss = url.searchParams.get(\"iss\") ?? undefined;\n const err = url.searchParams.get(\"error\");\n const errDesc = url.searchParams.get(\"error_description\") ?? undefined;\n\n if (err) {\n res.statusCode = 400;\n res.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n res.end(FAILURE_HTML(err, errDesc));\n this.rejectPending(new OAuthFlowError(err, errDesc));\n return;\n }\n\n if (!code || !state) {\n res.statusCode = 400;\n res.end(\"Missing code or state\");\n // Don't reject — the user might retry; let timeout do the cleanup.\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n res.end(SUCCESS_HTML);\n this.resolvePending({ code, ...(iss !== undefined ? { iss } : {}) });\n }\n}\n\nasync function defaultOpener(url: string): Promise<void> {\n // Best-effort fallback. CLI passes a richer override (the `open` package).\n const { spawn } = await import(\"node:child_process\");\n const { platform } = await import(\"node:process\");\n const cmd =\n platform === \"darwin\" ? \"open\" : platform === \"win32\" ? \"cmd\" : \"xdg-open\";\n const args = platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n await new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { stdio: \"ignore\", detached: true });\n child.once(\"error\", reject);\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n\n/**\n * Creates a Node OAuth provider for an MCP server.\n *\n * @param serverUrl - Protected MCP server URL.\n * @param options - OAuth metadata, storage, loopback, and browser options.\n * @returns A provider compatible with the MCP SDK OAuth flow.\n */\nexport async function createOAuthProvider(\n serverUrl: string,\n options: NodeOAuthOptions = {}\n): Promise<OAuthClientProvider> {\n return NodeOAuthClientProvider.create(serverUrl, options);\n}\n\nexport type { NodeOAuthOptions as OAuthProviderOptions };\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { KVStore } from \"./storage.js\";\n\nconst isWindows = process.platform === \"win32\";\n\n/**\n * `KVStore` implementation backed by `~/.mcp-use/oauth/<serverUrlHash>/`.\n *\n * @internal\n */\nexport class FileKVStore implements KVStore {\n readonly dir: string;\n\n constructor(serverUrlHash: string, baseDir?: string) {\n const root = baseDir ?? join(homedir(), \".mcp-use\", \"oauth\");\n this.dir = join(root, serverUrlHash);\n // Keep construction and reads side-effect free. The directory is created\n // only by set(), when OAuth state actually needs to be persisted.\n }\n\n private ensureDir(): void {\n if (!existsSync(this.dir)) {\n mkdirSync(this.dir, { recursive: true, mode: 0o700 });\n }\n if (!isWindows) {\n try {\n chmodSync(this.dir, 0o700);\n } catch {\n // Best-effort: chmod can fail on shared volumes.\n }\n }\n }\n\n private sanitize(key: string): string {\n return key.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n }\n\n private pathFor(key: string): string {\n return join(this.dir, this.sanitize(key));\n }\n\n get(key: string): string | null {\n const file = this.pathFor(key);\n if (!existsSync(file)) return null;\n try {\n return readFileSync(file, \"utf-8\");\n } catch {\n return null;\n }\n }\n\n set(key: string, value: string): void {\n this.ensureDir();\n const file = this.pathFor(key);\n const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;\n writeFileSync(tmp, value, { encoding: \"utf-8\", mode: 0o600 });\n if (!isWindows) {\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // Best-effort.\n }\n }\n renameSync(tmp, file);\n }\n\n remove(key: string): void {\n const file = this.pathFor(key);\n if (existsSync(file)) {\n rmSync(file, { force: true });\n }\n }\n\n keys(): string[] {\n if (!existsSync(this.dir)) return [];\n return readdirSync(this.dir).filter((name) => !name.includes(\".tmp.\"));\n }\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 {\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 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","import type {\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n OAuthClientProvider,\n} from \"@modelcontextprotocol/client\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { BaseMCPClient } from \"./base.js\";\nimport type {\n ExecutionResult,\n ToolSearchResponse,\n} from \"../code-mode/executor.js\";\nimport {\n BaseCodeExecutor,\n FunctionCodeExecutor,\n} from \"../code-mode/executor.js\";\nimport { E2BCodeExecutor } from \"../code-mode/executor-e2b.js\";\nimport { VMCodeExecutor } from \"../code-mode/executor-vm.js\";\nimport { CodeModeConnector } from \"../code-mode/connector.js\";\nimport { createOAuthProvider, type NodeOAuthOptions } from \"../auth/node.js\";\nimport {\n createConnectorFromConfig,\n normalizeClientInfo,\n resolveCallbacks,\n resolveClientOptions,\n type AutoOAuthOptions,\n type CallbackConfig,\n type MCPClientConfigShape,\n type SamplingCreateMessageParams,\n type SamplingCreateMessageResult,\n type ServerConfig,\n} from \"./config.js\";\nimport type { BaseConnector } from \"../transport/base.js\";\nimport { logger } from \"../utils/logging.js\";\nimport { MCPSession } from \"./session.js\";\nimport { Tel } from \"../telemetry/telemetry-node.js\";\nimport { getPackageVersion } from \"../utils/version.js\";\n\n/** Read and parse a JSON MCP client config file. Node-only. */\nexport function loadConfigFile(filepath: string): Record<string, any> {\n return JSON.parse(fs.readFileSync(filepath, \"utf-8\"));\n}\n\nfunction trackNodeClientInit(\n config: Record<string, any>,\n codeMode: boolean,\n callbacks: CallbackConfig\n): void {\n const servers = Object.keys(config.mcpServers ?? {});\n const hasSamplingCallback = !!callbacks.onSampling;\n const hasElicitationCallback = !!callbacks.onElicitation;\n Tel.getInstance()\n .trackMCPClientInit({\n codeMode,\n sandbox: false,\n allCallbacks: hasSamplingCallback && hasElicitationCallback,\n verify: false,\n servers,\n numServers: servers.length,\n isBrowser: false,\n })\n .catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));\n}\n\n/**\n * Custom function type for code execution in code mode.\n * Allows providing a custom executor implementation.\n */\nexport type CodeExecutorFunction = (\n code: string,\n timeout?: number\n) => Promise<ExecutionResult>;\n\n/**\n * Built-in code executor types.\n * - `\"vm\"`: Node.js VM-based executor (default, local execution)\n * - `\"e2b\"`: E2B cloud sandbox executor (secure remote execution)\n */\nexport type CodeExecutorType = \"vm\" | \"e2b\";\n\n/**\n * Configuration options for the VM-based code executor.\n */\nexport interface VMExecutorOptions {\n /** Maximum execution time in milliseconds. Default: 30000 (30 seconds) */\n timeoutMs?: number;\n /** Memory limit in megabytes. Default: undefined (no limit) */\n memoryLimitMb?: number;\n}\n\n/**\n * Configuration options for the E2B cloud sandbox executor.\n */\nexport interface E2BExecutorOptions {\n /** E2B API key (required). Get one at https://e2b.dev */\n apiKey: string;\n /** Maximum execution time in milliseconds. Default: 300000 (5 minutes) */\n timeoutMs?: number;\n}\n\n/**\n * Union type for executor configuration options.\n */\nexport type ExecutorOptions = VMExecutorOptions | E2BExecutorOptions;\n\n/**\n * Advanced configuration for code execution mode.\n */\nexport interface CodeModeConfig {\n /** Whether to enable code execution mode */\n enabled: boolean;\n /** Executor type or custom implementation. Defaults to \"vm\" */\n executor?: CodeExecutorType | CodeExecutorFunction | BaseCodeExecutor;\n /** Type-safe configuration options for the executor */\n executorOptions?: ExecutorOptions;\n}\n\n/**\n * Options for configuring MCPClient behavior.\n */\nexport interface MCPClientOptions {\n /** Enable code execution mode (simple boolean or advanced configuration) */\n codeMode?: boolean | CodeModeConfig;\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 function for server notifications.\n * Applied as default when per-server config does not specify one.\n */\n onNotification?: (\n notification: import(\"@modelcontextprotocol/client\").Notification\n ) => void | Promise<void>;\n}\n\n// Export executor classes and utilities for external use\nexport { BaseCodeExecutor } from \"../code-mode/executor.js\";\nexport { E2BCodeExecutor } from \"../code-mode/executor-e2b.js\";\nexport { isVMAvailable, VMCodeExecutor } from \"../code-mode/executor-vm.js\";\n\n// Export elicitation helpers for client-side form/URL elicitation\nexport {\n accept,\n acceptWithDefaults,\n applyDefaults,\n cancel,\n decline,\n getDefaults,\n validate,\n} from \"../utils/elicitation.js\";\nexport type {\n ElicitContent,\n ElicitValidationResult,\n} from \"../utils/elicitation.js\";\n\n// Export MCPSession and related types for CLI and other consumers\nexport { MCPSession } from \"./session.js\";\nexport type {\n CallToolResult,\n MetaObject,\n Notification,\n Root,\n Tool,\n} from \"./session.js\";\n\n/**\n * Node.js-specific MCP client implementation with advanced features.\n *\n * The MCPClient class provides a complete MCP client implementation for Node.js\n * environments, extending the runtime-neutral `BaseMCPClient` with platform-specific capabilities:\n *\n * - **All Connector Types**: Supports Stdio, HTTP, and WebSocket connectors\n * - **Code Execution Mode**: Execute code dynamically using VM or E2B sandboxes\n * - **File System Operations**: Load and save configurations from/to files\n * - **Sampling & Elicitation**: Handle advanced MCP protocol features\n * - **Session Management**: Create and manage multiple server connections\n *\n * @example\n * ```typescript\n * // Basic usage with config file\n * const client = new MCPClient('./mcp-config.json');\n * const session = await client.createSession('my-server');\n * const tools = await session.listTools();\n * ```\n *\n * @example\n * ```typescript\n * // With inline configuration\n * const client = new MCPClient({\n * mcpServers: {\n * 'filesystem': {\n * command: 'npx',\n * args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp']\n * }\n * }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With code execution mode\n * const client = new MCPClient('./config.json', {\n * codeMode: {\n * enabled: true,\n * executor: 'e2b',\n * executorOptions: { apiKey: process.env.E2B_API_KEY }\n * }\n * });\n *\n * const result = await client.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @see {@link MCPSession} for session management\n */\nexport class MCPClient extends BaseMCPClient {\n /**\n * Gets the mcp-use package version.\n *\n * This static method returns the version string of the installed mcp-use package,\n * which is useful for debugging and compatibility checks.\n *\n * @returns The package version string (e.g., \"1.13.2\")\n *\n * @example\n * ```typescript\n * console.log(`mcp-use version: ${MCPClient.getPackageVersion()}`);\n * ```\n */\n public static getPackageVersion(): string {\n return getPackageVersion();\n }\n\n /**\n * Indicates whether code execution mode is enabled.\n *\n * When true, the client provides special tools for executing code dynamically\n * through the {@link executeCode} and {@link searchTools} methods.\n *\n * @example\n * ```typescript\n * if (client.codeMode) {\n * const result = await client.executeCode('return 2 + 2');\n * console.log(result.output); // \"4\"\n * }\n * ```\n */\n public codeMode: boolean = false;\n private _codeExecutor: BaseCodeExecutor | null = null;\n private _codeExecutorConfig:\n | CodeExecutorType\n | CodeExecutorFunction\n | BaseCodeExecutor = \"vm\";\n private _executorOptions?: ExecutorOptions;\n private _globalCallbacks: CallbackConfig;\n\n /**\n * Creates a new MCPClient instance.\n *\n * The client can be initialized with either a configuration object, a path to\n * a configuration file, or no configuration at all (servers can be added later\n * using {@link addServer}).\n *\n * @param config - Configuration object or path to JSON config file. If omitted,\n * starts with empty configuration\n * @param options - Optional client behavior configuration\n * Options can enable code mode or provide sampling and elicitation callbacks.\n *\n * @example\n * ```typescript\n * // From config file\n * const client = new MCPClient('./mcp-config.json');\n * ```\n *\n * @example\n * ```typescript\n * // From inline config\n * const client = new MCPClient({\n * mcpServers: {\n * 'my-server': {\n * command: 'node',\n * args: ['server.js']\n * }\n * }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With code mode enabled\n * const client = new MCPClient('./config.json', {\n * codeMode: true\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With sampling callback\n * const client = new MCPClient('./config.json', {\n * onSampling: async (params) => {\n * // Call your LLM here\n * return anthropic.messages.create(params);\n * }\n * });\n * ```\n *\n * @see {@link fromDict} for creating from config object (alternative syntax)\n * @see {@link fromConfigFile} for creating from file (alternative syntax)\n */\n constructor(\n config?: string | Record<string, any>,\n options?: MCPClientOptions\n ) {\n if (config) {\n if (typeof config === \"string\") {\n super(loadConfigFile(config));\n } else {\n super(config);\n }\n } else {\n super();\n }\n\n let codeModeEnabled = false;\n let executorConfig:\n | CodeExecutorType\n | CodeExecutorFunction\n | BaseCodeExecutor = \"vm\";\n let executorOptions: ExecutorOptions | undefined;\n\n if (options?.codeMode) {\n if (typeof options.codeMode === \"boolean\") {\n codeModeEnabled = options.codeMode;\n // defaults: executor=\"vm\", executorOptions=undefined\n } else {\n codeModeEnabled = options.codeMode.enabled;\n executorConfig = options.codeMode.executor ?? \"vm\";\n executorOptions = options.codeMode.executorOptions;\n }\n }\n\n this.codeMode = codeModeEnabled;\n this._codeExecutorConfig = executorConfig;\n this._executorOptions = executorOptions;\n // Build global callback defaults: config root merged with options (options win)\n const configRoot = this.config as MCPClientConfigShape;\n this._globalCallbacks = {\n onSampling: options?.onSampling ?? configRoot?.onSampling,\n onElicitation: options?.onElicitation ?? configRoot?.onElicitation,\n onNotification: options?.onNotification ?? configRoot?.onNotification,\n };\n\n if (this.codeMode) {\n this._setupCodeModeConnector();\n }\n\n trackNodeClientInit(this.config, this.codeMode, this._globalCallbacks);\n }\n\n /**\n * Creates a client instance from a configuration dictionary.\n *\n * This static factory method provides an alternative syntax for creating\n * a client from an inline configuration object.\n *\n * @param cfg - Configuration dictionary with server definitions\n * @param options - Optional client behavior configuration\n * @returns New MCPClient instance\n *\n * @example\n * ```typescript\n * const client = MCPClient.fromDict({\n * mcpServers: {\n * 'filesystem': {\n * command: 'npx',\n * args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp']\n * }\n * }\n * });\n * ```\n *\n * @see {@link MCPClient} for direct instantiation\n * @see {@link fromConfigFile} for loading from file\n */\n public static fromDict(\n cfg: Record<string, any>,\n options?: MCPClientOptions\n ): MCPClient {\n return new MCPClient(cfg, options);\n }\n\n /**\n * Creates a client instance from a configuration file.\n *\n * This static factory method loads MCP server configurations from a JSON\n * file and creates a new client instance.\n *\n * @param path - Path to the JSON configuration file\n * @param options - Optional client behavior configuration\n * @returns New MCPClient instance\n * @throws If the file cannot be read or parsed\n *\n * @example\n * ```typescript\n * const client = MCPClient.fromConfigFile('./mcp-config.json');\n * await client.createAllSessions();\n * ```\n *\n * @example\n * ```typescript\n * // With code mode\n * const client = MCPClient.fromConfigFile('./config.json', {\n * codeMode: true\n * });\n * ```\n *\n * @see {@link MCPClient} for direct instantiation\n * @see {@link fromDict} for inline configuration\n */\n public static fromConfigFile(\n path: string,\n options?: MCPClientOptions\n ): MCPClient {\n return new MCPClient(loadConfigFile(path), options);\n }\n\n /**\n * Saves the current configuration to a file.\n *\n * This Node.js-specific method writes the client's current configuration\n * (including all server definitions) to a JSON file. The directory will be\n * created if it doesn't exist.\n *\n * @param filepath - Path where the configuration file should be saved\n *\n * @example\n * ```typescript\n * const client = new MCPClient();\n * client.addServer('my-server', {\n * command: 'node',\n * args: ['server.js']\n * });\n *\n * // Save configuration for later use\n * client.saveConfig('./mcp-config.json');\n * ```\n *\n * @see {@link fromConfigFile} for loading configurations\n */\n public saveConfig(filepath: string): void {\n const dir = path.dirname(filepath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filepath, JSON.stringify(this.config, null, 2), \"utf-8\");\n }\n\n protected async createDefaultOAuthProvider(\n serverUrl: string,\n options: AutoOAuthOptions = {}\n ): Promise<OAuthClientProvider> {\n return createOAuthProvider(serverUrl, options as NodeOAuthOptions);\n }\n\n /**\n * Create a connector from server configuration (Node.js version)\n * Supports all connector types including StdioConnector (lazy-loaded to avoid pulling Node-only code into browser bundles).\n */\n protected async createConnectorFromConfig(\n serverConfig: Record<string, any>\n ): Promise<BaseConnector> {\n const resolved = resolveCallbacks(\n serverConfig as CallbackConfig,\n this._globalCallbacks\n );\n const merged = {\n ...serverConfig,\n clientInfo: serverConfig.clientInfo ?? this.config.clientInfo,\n };\n\n if (\"command\" in merged && \"args\" in merged) {\n const { StdioConnector } = await import(\"../transport/stdio.js\");\n const stdioConfig = merged as ServerConfig & {\n command: string;\n args: string[];\n env?: Record<string, string>;\n cwd?: string;\n stderr?: import(\"../transport/stdio.js\").StdioStderrMode;\n protocolNegotiation?: import(\"@modelcontextprotocol/client\").VersionNegotiationMode;\n };\n return new StdioConnector({\n command: stdioConfig.command,\n args: stdioConfig.args,\n env: stdioConfig.env,\n cwd: stdioConfig.cwd,\n ...(stdioConfig.stderr !== undefined && { stderr: stdioConfig.stderr }),\n protocolNegotiation: stdioConfig.protocolNegotiation,\n clientInfo: normalizeClientInfo(merged.clientInfo),\n roots: stdioConfig.roots,\n clientOptions: resolveClientOptions(stdioConfig.clientOptions),\n defaultRequestOptions: stdioConfig.defaultRequestOptions,\n onSampling: resolved.onSampling,\n onElicitation: resolved.onElicitation,\n onNotification: resolved.onNotification,\n });\n }\n\n return createConnectorFromConfig(merged as ServerConfig, {\n onSampling: resolved.onSampling,\n onElicitation: resolved.onElicitation,\n onNotification: resolved.onNotification,\n });\n }\n\n private _setupCodeModeConnector(): void {\n logger.debug(\"Code mode connector initialized as internal meta server\");\n const connector = new CodeModeConnector(this);\n const session = new MCPSession(connector);\n\n // Register as internal session\n this.sessions[\"code_mode\"] = session;\n this.activeSessions.push(\"code_mode\");\n }\n\n private _ensureCodeExecutor(): BaseCodeExecutor {\n if (!this._codeExecutor) {\n const config = this._codeExecutorConfig;\n\n if (config instanceof BaseCodeExecutor) {\n this._codeExecutor = config;\n } else if (typeof config === \"function\") {\n // Custom function: adapt it so searchTools() and cleanup() work too.\n this._codeExecutor = new FunctionCodeExecutor(this, config);\n } else if (config === \"e2b\") {\n const opts = this._executorOptions as E2BExecutorOptions | undefined;\n if (!opts?.apiKey) {\n logger.warn(\"E2B executor requires apiKey. Falling back to VM.\");\n try {\n this._codeExecutor = new VMCodeExecutor(\n this,\n this._executorOptions as VMExecutorOptions\n );\n } catch (error) {\n throw new Error(\n \"VM executor is not available in this environment and E2B API key is not provided. \" +\n \"Please provide an E2B API key or run in a Node.js environment.\"\n );\n }\n } else {\n this._codeExecutor = new E2BCodeExecutor(this, opts);\n }\n } else {\n // Default to VM, but fall back to E2B if VM is not available\n try {\n this._codeExecutor = new VMCodeExecutor(\n this,\n this._executorOptions as VMExecutorOptions\n );\n } catch (error) {\n // VM not available (e.g., in Deno), try E2B fallback\n const e2bOpts = this._executorOptions as\n | E2BExecutorOptions\n | undefined;\n const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;\n\n if (e2bApiKey) {\n logger.info(\n \"VM executor not available in this environment. Falling back to E2B.\"\n );\n this._codeExecutor = new E2BCodeExecutor(this, {\n ...e2bOpts,\n apiKey: e2bApiKey,\n });\n } else {\n throw new Error(\n \"VM executor is not available in this environment. \" +\n \"Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, \" +\n \"or run in a Node.js environment.\"\n );\n }\n }\n }\n }\n return this._codeExecutor;\n }\n\n /**\n * Executes JavaScript/TypeScript code in a sandboxed environment.\n *\n * This method is only available when code mode is enabled. It executes the\n * provided code in an isolated environment (VM or E2B sandbox) and returns\n * the results including stdout, stderr, and return value.\n *\n * @param code - JavaScript/TypeScript code to execute\n * @param timeout - Optional execution timeout in milliseconds\n * @returns Execution result with output, errors, and return value\n * @throws If code mode is not enabled\n *\n * @example\n * ```typescript\n * const client = new MCPClient('./config.json', { codeMode: true });\n *\n * const result = await client.executeCode(`\n * console.log('Hello, world!');\n * return 2 + 2;\n * `);\n *\n * console.log(result.stdout); // \"Hello, world!\\n\"\n * console.log(result.returnValue); // 4\n * ```\n *\n * @example\n * ```typescript\n * // With timeout\n * try {\n * const result = await client.executeCode('while(true) {}', 1000);\n * } catch (error) {\n * console.log('Execution timed out');\n * }\n * ```\n *\n * @see {@link searchTools} for discovering available tools in code mode\n */\n public async executeCode(\n code: string,\n timeout?: number\n ): Promise<ExecutionResult> {\n if (!this.codeMode) {\n throw new Error(\"Code execution mode is not enabled\");\n }\n\n // Resolves to the configured executor: a custom function or instance when\n // provided, otherwise the VM/E2B default.\n return this._ensureCodeExecutor().execute(code, timeout);\n }\n\n /**\n * Searches for available tools across all MCP servers.\n *\n * This method is only available when code mode is enabled. It searches\n * through tools from all active servers and returns matching tools based\n * on the query and detail level.\n *\n * @param query - Optional search query to filter tools (defaults to empty string for all tools)\n * @param detailLevel - Level of detail to return: \"names\", \"descriptions\", or \"full\"\n * @returns Tool search results with matching tools\n * @throws If code mode is not enabled\n *\n * @example\n * ```typescript\n * const client = new MCPClient('./config.json', { codeMode: true });\n * await client.createAllSessions();\n *\n * // Search for all tools\n * const allTools = await client.searchTools();\n * console.log(`Found ${allTools.tools.length} tools`);\n *\n * // Search for specific tools\n * const fileTools = await client.searchTools('file', 'descriptions');\n * ```\n *\n * @see {@link executeCode} for executing code in code mode\n */\n public async searchTools(\n query: string = \"\",\n detailLevel: \"names\" | \"descriptions\" | \"full\" = \"full\"\n ): Promise<ToolSearchResponse> {\n if (!this.codeMode) {\n throw new Error(\"Code execution mode is not enabled\");\n }\n return this._ensureCodeExecutor().createSearchToolsFunction()(\n query,\n detailLevel\n );\n }\n\n /**\n * Gets the names of all configured MCP servers (excluding internal servers).\n *\n * This method overrides the base implementation to filter out internal\n * meta-servers like the code mode server, which is an implementation detail\n * not intended for direct user interaction.\n *\n * @returns Array of user-configured server names\n *\n * @example\n * ```typescript\n * const names = client.getServerNames();\n * console.log(`User servers: ${names.join(', ')}`);\n * // Note: 'code_mode' is excluded even if code mode is enabled\n * ```\n *\n * @see {@link activeSessions} for servers with active sessions\n */\n public getServerNames(): string[] {\n const isCodeModeEnabled = this.codeMode;\n return super.getServerNames().filter((name) => {\n return !isCodeModeEnabled || name !== \"code_mode\";\n });\n }\n\n /**\n * Closes the client and cleans up all resources.\n *\n * This method performs a complete cleanup by:\n * 1. Shutting down code executors (VM or E2B sandboxes)\n * 2. Closing all active MCP sessions\n * 3. Releasing any other held resources\n *\n * Always call this method when you're done with the client to ensure\n * proper resource cleanup, especially when using E2B sandboxes which\n * have associated costs.\n *\n * @example\n * ```typescript\n * const client = new MCPClient('./config.json', { codeMode: true });\n * await client.createAllSessions();\n *\n * // Do work...\n *\n * // Clean up\n * await client.close();\n * ```\n *\n * @example\n * ```typescript\n * // Use in shutdown handler\n * process.on('SIGINT', async () => {\n * console.log('Shutting down...');\n * await client.close();\n * process.exit(0);\n * });\n * ```\n *\n * @see {@link closeAllSessions} for closing just the sessions\n */\n public async close(): Promise<void> {\n // Clean up code executor first (e.g., E2B sandboxes)\n if (this._codeExecutor) {\n await this._codeExecutor.cleanup();\n this._codeExecutor = null;\n }\n\n // Then close all MCP sessions\n await this.closeAllSessions();\n }\n}\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","/** 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 { Tool } from \"@modelcontextprotocol/client\";\nimport type { CodeExecutorFunction, MCPClient } from \"../core/node.js\";\nimport { logger } from \"../utils/logging.js\";\n\nexport interface ExecutionResult {\n result: unknown;\n logs: string[];\n error: string | null;\n execution_time: number;\n}\n\ninterface ToolSearchResult {\n name: string;\n server: string;\n description?: string;\n input_schema?: Tool[\"inputSchema\"];\n}\n\ninterface ToolSearchMeta {\n total_tools: number;\n namespaces: string[];\n result_count: number;\n}\n\nexport interface ToolSearchResponse {\n meta: ToolSearchMeta;\n results: ToolSearchResult[];\n}\n\ntype SearchToolsFunction = (\n query?: string,\n detailLevel?: \"names\" | \"descriptions\" | \"full\"\n) => Promise<ToolSearchResponse>;\n\ninterface ToolNamespaceInfo {\n serverName: string;\n tools: Tool[];\n session: any;\n}\n\n/**\n * Abstract base class for code executors.\n * Provides shared functionality for connecting to MCP servers and building tool contexts.\n */\nexport abstract class BaseCodeExecutor {\n protected client: MCPClient;\n protected _connecting: boolean = false;\n\n constructor(client: MCPClient) {\n this.client = client;\n }\n\n /**\n * Execute code with access to MCP tools.\n * @param code - The code to execute\n * @param timeout - Execution timeout in milliseconds\n */\n abstract execute(code: string, timeout?: number): Promise<ExecutionResult>;\n\n /**\n * Clean up resources used by the executor.\n * Should be called when the executor is no longer needed.\n */\n abstract cleanup(): Promise<void>;\n\n /**\n * Ensure all configured MCP servers are connected before execution.\n * Prevents race conditions with a connection lock.\n */\n protected async ensureServersConnected(): Promise<void> {\n const configuredServers = this.client.getServerNames();\n const activeSessions = Object.keys(this.client.getAllActiveSessions());\n\n // Check if we need to connect to any servers\n const missingServers = configuredServers.filter(\n (s) => !activeSessions.includes(s)\n );\n\n // Prevent race conditions with a lock\n if (missingServers.length > 0 && !this._connecting) {\n this._connecting = true;\n try {\n logger.debug(\n `Connecting to configured servers for code execution: ${missingServers.join(\", \")}`\n );\n await this.client.createAllSessions();\n } finally {\n this._connecting = false;\n }\n } else if (missingServers.length > 0 && this._connecting) {\n // Wait for connection to complete if already in progress\n logger.debug(\"Waiting for ongoing server connection...\");\n // Simple polling for now\n const startWait = Date.now();\n while (this._connecting && Date.now() - startWait < 5000) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n /**\n * Get tool namespace information from all active MCP sessions.\n * Filters out the internal code_mode server.\n */\n protected getToolNamespaces(): ToolNamespaceInfo[] {\n const namespaces: ToolNamespaceInfo[] = [];\n const activeSessions = this.client.getAllActiveSessions();\n\n for (const [serverName, session] of Object.entries(activeSessions)) {\n // Skip internal code_mode server to avoid recursion\n if (serverName === \"code_mode\") continue;\n\n try {\n const connector = session.connector;\n let tools;\n try {\n tools = connector.tools;\n } catch (e) {\n logger.warn(`Tools not available for server ${serverName}: ${e}`);\n continue;\n }\n\n if (!tools || tools.length === 0) continue;\n\n namespaces.push({ serverName, tools, session });\n } catch (e) {\n logger.warn(`Failed to load tools for server ${serverName}: ${e}`);\n }\n }\n\n return namespaces;\n }\n\n /**\n * Create a search function for discovering available MCP tools.\n * Used by code execution environments to find tools at runtime.\n */\n public createSearchToolsFunction(): SearchToolsFunction {\n return async (\n query = \"\",\n detailLevel: \"names\" | \"descriptions\" | \"full\" = \"full\"\n ) => {\n const allTools: ToolSearchResult[] = [];\n const allNamespaces = new Set<string>();\n const queryLower = query.toLowerCase();\n const activeSessions = this.client.getAllActiveSessions();\n\n // First pass: collect all tools and namespaces\n for (const [serverName, session] of Object.entries(activeSessions)) {\n if (serverName === \"code_mode\") continue;\n\n try {\n const tools = session.connector.tools;\n if (tools && tools.length > 0) {\n allNamespaces.add(serverName);\n }\n\n for (const tool of tools) {\n // Build tool info based on detail level (before filtering)\n if (detailLevel === \"names\") {\n allTools.push({ name: tool.name, server: serverName });\n } else if (detailLevel === \"descriptions\") {\n allTools.push({\n name: tool.name,\n server: serverName,\n description: tool.description,\n });\n } else {\n allTools.push({\n name: tool.name,\n server: serverName,\n description: tool.description,\n input_schema: tool.inputSchema,\n });\n }\n }\n } catch (e) {\n logger.warn(`Failed to search tools in server ${serverName}: ${e}`);\n }\n }\n\n // Filter by query if provided\n let filteredTools = allTools;\n if (query) {\n filteredTools = allTools.filter((tool) => {\n const nameMatch = tool.name.toLowerCase().includes(queryLower);\n const descMatch = tool.description\n ?.toLowerCase()\n .includes(queryLower);\n const serverMatch = tool.server.toLowerCase().includes(queryLower);\n return nameMatch || descMatch || serverMatch;\n });\n }\n\n // Return metadata along with results\n return {\n meta: {\n total_tools: allTools.length,\n namespaces: Array.from(allNamespaces).sort(),\n result_count: filteredTools.length,\n },\n results: filteredTools,\n };\n };\n }\n}\n\n/**\n * Adapts a plain `(code, timeout) => Promise<ExecutionResult>` function to the\n * {@link BaseCodeExecutor} interface so a custom executor participates in the\n * normal executor lifecycle (`searchTools`, `close()` cleanup).\n *\n * The function is invoked with the `MCPClient` as its `this`, matching how a\n * custom executor was called before this adapter existed. Cleanup is a no-op:\n * the caller owns whatever runtime the function wraps.\n */\nexport class FunctionCodeExecutor extends BaseCodeExecutor {\n private fn: CodeExecutorFunction;\n\n constructor(client: MCPClient, fn: CodeExecutorFunction) {\n super(client);\n this.fn = fn;\n }\n\n async execute(code: string, timeout?: number): Promise<ExecutionResult> {\n return this.fn.call(this.client, code, timeout);\n }\n\n async cleanup(): Promise<void> {\n // Nothing to release: the caller owns whatever runtime the function uses.\n }\n}\n","import type { Tool } from \"@modelcontextprotocol/client\";\nimport type { E2BExecutorOptions, MCPClient } from \"../core/node.js\";\nimport { logger } from \"../utils/logging.js\";\nimport { BaseCodeExecutor, type ExecutionResult } from \"./executor.js\";\n\n// Dynamic import type for E2B Sandbox\ntype Sandbox = any;\n\n/**\n * E2B-based code executor using remote sandboxes.\n * Executes code in an E2B sandbox with tool calls proxied back to the host.\n */\nexport class E2BCodeExecutor extends BaseCodeExecutor {\n private e2bApiKey: string;\n private codeExecSandbox: Sandbox | null = null;\n private SandboxClass: any = null;\n private timeoutMs: number;\n\n constructor(client: MCPClient, options: E2BExecutorOptions) {\n super(client);\n this.e2bApiKey = options.apiKey;\n this.timeoutMs = options.timeoutMs ?? 300000; // Default: 5 minutes\n }\n\n /**\n * Lazy load E2B Sandbox class.\n * This allows the library to work without E2B installed.\n */\n private async ensureSandboxClass(): Promise<void> {\n if (this.SandboxClass) return;\n\n try {\n // @ts-ignore - Optional dependency, may not be installed\n const e2b = await import(\"@e2b/code-interpreter\");\n this.SandboxClass = e2b.Sandbox;\n } catch (error) {\n throw new Error(\n \"@e2b/code-interpreter is not installed. \" +\n \"The E2B code executor requires this optional dependency. \" +\n \"Install it with: npm install @e2b/code-interpreter, pnpm add @e2b/code-interpreter, or bun add @e2b/code-interpreter\"\n );\n }\n }\n\n /**\n * Get or create a dedicated sandbox for code execution.\n */\n private async getOrCreateCodeExecSandbox(): Promise<Sandbox> {\n if (this.codeExecSandbox) return this.codeExecSandbox;\n\n await this.ensureSandboxClass();\n logger.debug(\"Starting E2B sandbox for code execution...\");\n\n this.codeExecSandbox = await this.SandboxClass.create(\"base\", {\n apiKey: this.e2bApiKey,\n timeoutMs: this.timeoutMs,\n });\n\n return this.codeExecSandbox;\n }\n\n /**\n * Generate the shim code that exposes tools to the sandbox environment.\n * Creates a bridge that intercepts tool calls and sends them back to host.\n */\n private generateShim(tools: Record<string, Tool[]>): string {\n let shim = `\n// MCP Bridge Shim\nglobal.__callMcpTool = async (server, tool, args) => {\n const id = Math.random().toString(36).substring(7);\n console.log(JSON.stringify({\n type: '__MCP_TOOL_CALL__',\n id,\n server,\n tool,\n args\n }));\n \n const resultPath = \\`/tmp/mcp_result_\\${id}.json\\`;\n const fs = require('fs');\n \n // Poll for result file\n let attempts = 0;\n while (attempts < 300) { // 30 seconds timeout\n if (fs.existsSync(resultPath)) {\n const content = fs.readFileSync(resultPath, 'utf8');\n const result = JSON.parse(content);\n fs.unlinkSync(resultPath); // Clean up\n \n if (result.error) {\n throw new Error(result.error);\n }\n return result.data;\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n attempts++;\n }\n throw new Error('Tool execution timed out');\n};\n\n// Global search_tools helper\nglobal.search_tools = async (query, detailLevel = 'full') => {\n const allTools = ${JSON.stringify(\n Object.entries(tools).flatMap(([server, serverTools]) =>\n serverTools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n server,\n input_schema: tool.inputSchema,\n }))\n )\n )};\n \n const filtered = allTools.filter(tool => {\n if (!query) return true;\n const q = query.toLowerCase();\n return tool.name.toLowerCase().includes(q) || \n (tool.description && tool.description.toLowerCase().includes(q));\n });\n \n if (detailLevel === 'names') {\n return filtered.map(t => ({ name: t.name, server: t.server }));\n } else if (detailLevel === 'descriptions') {\n return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));\n }\n return filtered;\n};\n`;\n\n // Generate namespaces for each server\n for (const [serverName, serverTools] of Object.entries(tools)) {\n // Skip empty tool lists\n if (!serverTools || serverTools.length === 0) continue;\n\n // Create safe server name for JS identifier (replace hyphens etc)\n const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, \"_\");\n\n // Serialize names so quotes and other special characters stay valid in the generated code\n const escapedServerName = JSON.stringify(serverName);\n const escapedSafeServerName = JSON.stringify(safeServerName);\n\n shim += `\nglobal[${escapedServerName}] = {`;\n\n for (const tool of serverTools) {\n const escapedToolName = JSON.stringify(tool.name);\n shim += `\n [${escapedToolName}]: async (args) => await global.__callMcpTool(${escapedServerName}, ${escapedToolName}, args),`;\n }\n\n shim += `\n};\n`;\n\n if (safeServerName !== serverName) {\n shim += `\n// Also expose as safe name if different\nglobal[${escapedSafeServerName}] = global[${escapedServerName}];\n`;\n }\n }\n\n return shim;\n }\n\n /**\n * Build the tool catalog for the shim.\n * Returns a map of server names to their available tools.\n */\n private buildToolCatalog(): Record<string, Tool[]> {\n const catalog: Record<string, Tool[]> = {};\n const namespaces = this.getToolNamespaces();\n\n for (const { serverName, tools } of namespaces) {\n catalog[serverName] = tools;\n }\n\n return catalog;\n }\n\n /**\n * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.\n * Tool calls are proxied back to the host via the bridge pattern.\n *\n * @param code - Code to execute\n * @param timeout - Execution timeout in milliseconds (default: 30000)\n */\n async execute(code: string, timeout = 30000): Promise<ExecutionResult> {\n const startTime = Date.now();\n let result: any = null;\n let error: string | null = null;\n let logs: string[] = [];\n\n try {\n // Ensure all servers are connected\n await this.ensureServersConnected();\n\n // Get or create sandbox\n const sandbox = await this.getOrCreateCodeExecSandbox();\n\n // Build tool catalog and generate shim\n const toolCatalog = this.buildToolCatalog();\n const shim = this.generateShim(toolCatalog);\n\n // Write code to a file, wrapping it to capture the return value\n // Inject shim before user code\n const wrappedCode = `\n${shim}\n\n(async () => {\n try {\n const func = async () => {\n ${code}\n };\n const result = await func();\n console.log('__MCP_RESULT_START__');\n console.log(JSON.stringify(result));\n console.log('__MCP_RESULT_END__');\n } catch (e) {\n console.error(e);\n process.exit(1);\n }\n})();\n`;\n\n const filename = `exec_${Date.now()}.js`;\n await sandbox.files.write(filename, wrappedCode);\n\n // Execute the file\n const execution = await sandbox.commands.run(`node ${filename}`, {\n timeoutMs: timeout,\n onStdout: async (data: string) => {\n // Check for tool calls\n try {\n const lines = data.split(\"\\n\");\n for (const line of lines) {\n if (line.trim().startsWith('{\"type\":\"__MCP_TOOL_CALL__\"')) {\n const call = JSON.parse(line);\n if (call.type === \"__MCP_TOOL_CALL__\") {\n // Execute tool on host\n try {\n logger.debug(\n `[E2B Bridge] Calling tool ${call.server}.${call.tool}`\n );\n\n // Get the session and call the tool\n const activeSessions = this.client.getAllActiveSessions();\n const session = activeSessions[call.server];\n\n if (!session) {\n throw new Error(`Server ${call.server} not found`);\n }\n\n const toolResult = await session.connector.callTool(\n call.tool,\n call.args\n );\n\n // Extract result from MCP response\n let extractedResult: any = toolResult;\n if (toolResult.content && toolResult.content.length > 0) {\n const item = toolResult.content[0];\n if (item.type === \"text\") {\n try {\n extractedResult = JSON.parse(item.text);\n } catch {\n extractedResult = item.text;\n }\n } else {\n extractedResult = item;\n }\n }\n\n // Write result back to sandbox\n const resultPath = `/tmp/mcp_result_${call.id}.json`;\n await sandbox.files.write(\n resultPath,\n JSON.stringify({ data: extractedResult })\n );\n } catch (err: any) {\n logger.error(\n `[E2B Bridge] Tool execution failed: ${err.message}`\n );\n // Write error back to sandbox\n const resultPath = `/tmp/mcp_result_${call.id}.json`;\n await sandbox.files.write(\n resultPath,\n JSON.stringify({\n error: err.message || String(err),\n })\n );\n }\n }\n }\n }\n } catch (e) {\n // Ignore parsing errors for non-JSON lines\n }\n },\n });\n\n logs = [execution.stdout, execution.stderr].filter(Boolean);\n\n if (execution.exitCode !== 0) {\n error = execution.stderr || \"Execution failed\";\n } else {\n const stdout = execution.stdout;\n const startMarker = \"__MCP_RESULT_START__\";\n const endMarker = \"__MCP_RESULT_END__\";\n\n const startIndex = stdout.indexOf(startMarker);\n const endIndex = stdout.indexOf(endMarker);\n\n if (startIndex !== -1 && endIndex !== -1) {\n const jsonStr = stdout\n .substring(startIndex + startMarker.length, endIndex)\n .trim();\n try {\n result = JSON.parse(jsonStr);\n } catch (e) {\n result = jsonStr;\n }\n\n // Clean logs - remove result block and tool calls\n logs = logs.map((log) => {\n let cleaned = log.replace(\n new RegExp(startMarker + \"[\\\\s\\\\S]*?\" + endMarker),\n \"[Result captured]\"\n );\n // Also hide the raw tool call JSON lines from user logs to keep it clean\n cleaned = cleaned\n .split(\"\\n\")\n .filter((l) => !l.includes(\"__MCP_TOOL_CALL__\"))\n .join(\"\\n\");\n return cleaned;\n });\n }\n }\n } catch (e: any) {\n error = e.message || String(e);\n\n // Check for timeout\n if (error && (error.includes(\"timeout\") || error.includes(\"timed out\"))) {\n error = \"Script execution timed out\";\n }\n }\n\n return {\n result,\n logs,\n error,\n execution_time: (Date.now() - startTime) / 1000,\n };\n }\n\n /**\n * Clean up the E2B sandbox.\n * Should be called when the executor is no longer needed.\n */\n async cleanup(): Promise<void> {\n if (this.codeExecSandbox) {\n try {\n await this.codeExecSandbox.kill();\n this.codeExecSandbox = null;\n logger.debug(\"E2B code execution sandbox stopped\");\n } catch (error) {\n logger.error(\"Failed to stop E2B code execution sandbox:\", error);\n }\n }\n }\n}\n","import type { MCPClient, VMExecutorOptions } from \"../core/node.js\";\nimport { logger } from \"../utils/logging.js\";\nimport { BaseCodeExecutor, type ExecutionResult } from \"./executor.js\";\n\n// Lazy-loaded VM module - may not be available in all environments (e.g., Deno)\nlet vm: any = null;\nlet vmCheckAttempted = false;\n\n/**\n * Get the node:vm module name dynamically to prevent bundlers from resolving it\n */\nfunction getVMModuleName(): string {\n // Use this indirection to prevent static analysis by bundlers like Deno\n return [\"node\", \"vm\"].join(\":\");\n}\n\n/**\n * Attempt to load the node:vm module synchronously\n * @returns true if successful, false otherwise\n */\nfunction tryLoadVM(): boolean {\n if (vmCheckAttempted) {\n return vm !== null;\n }\n\n vmCheckAttempted = true;\n\n try {\n // Try synchronous require first (CommonJS)\n const nodeRequire = typeof require !== \"undefined\" ? require : null;\n if (nodeRequire) {\n // Use dynamic module name to hide from bundler\n vm = nodeRequire(getVMModuleName());\n return true;\n }\n } catch (error) {\n // Not available or in ESM-only environment\n logger.debug(\"node:vm module not available via require\");\n }\n\n return false;\n}\n\n/**\n * Async version to load VM module via dynamic import\n */\nasync function tryLoadVMAsync(): Promise<boolean> {\n if (vm !== null) {\n return true;\n }\n\n // If sync require failed, try async import\n if (!vmCheckAttempted) {\n // Try sync first\n if (tryLoadVM()) {\n return true;\n }\n }\n\n try {\n // Try ESM dynamic import - use dynamic module name to hide from bundler\n // This prevents Deno's bundler from trying to resolve node:vm at build time\n vm = await import(/* @vite-ignore */ getVMModuleName());\n return true;\n } catch (error) {\n logger.debug(\n \"node:vm module not available in this environment (e.g., Deno)\"\n );\n return false;\n }\n}\n\n/**\n * Check if VM executor is available in the current environment\n * This is a synchronous check that returns true if vm was already loaded\n */\nexport function isVMAvailable(): boolean {\n tryLoadVM();\n return vm !== null;\n}\n\n/**\n * VM-based code executor using Node.js vm module.\n * Executes code in an isolated V8 context with access to MCP tools.\n */\nexport class VMCodeExecutor extends BaseCodeExecutor {\n private defaultTimeout: number;\n private memoryLimitMb?: number;\n\n constructor(client: MCPClient, options?: VMExecutorOptions) {\n super(client);\n this.defaultTimeout = options?.timeoutMs ?? 30000;\n this.memoryLimitMb = options?.memoryLimitMb;\n\n // Try to load VM synchronously - will throw in execute() if not available\n tryLoadVM();\n }\n\n /**\n * Ensure VM module is loaded before execution\n */\n private async ensureVMLoaded(): Promise<void> {\n if (vm !== null) {\n return;\n }\n\n const loaded = await tryLoadVMAsync();\n if (!loaded) {\n throw new Error(\n \"node:vm module is not available in this environment. \" +\n \"Please use E2B executor instead or run in a Node.js environment.\"\n );\n }\n }\n\n /**\n * Execute JavaScript/TypeScript code with access to MCP tools.\n *\n * @param code - Code to execute\n * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)\n */\n async execute(code: string, timeout?: number): Promise<ExecutionResult> {\n const effectiveTimeout = timeout ?? this.defaultTimeout;\n\n // Ensure VM module is loaded\n await this.ensureVMLoaded();\n\n // Ensure all servers are connected\n await this.ensureServersConnected();\n\n const logs: string[] = [];\n const startTime = Date.now();\n let result: any = null;\n let error: string | null = null;\n\n try {\n // Build execution context (sandbox)\n const context = await this._buildContext(logs);\n\n // Wrap code in an async function to allow await\n // We use a wrapper to capture the return value\n const wrappedCode = `\n (async () => {\n try {\n ${code}\n } catch (e) {\n throw e;\n }\n })()\n `;\n\n // Create a script\n const script = new vm.Script(wrappedCode, {\n filename: \"agent_code.js\",\n });\n\n // Execute with timeout\n const promise = script.runInNewContext(context, {\n timeout: effectiveTimeout,\n displayErrors: true,\n });\n\n result = await promise;\n } catch (e: any) {\n error = e.message || String(e);\n // Check for timeout error\n // Check for vm timeout specific error message\n if (\n e.code === \"ERR_SCRIPT_EXECUTION_TIMEOUT\" ||\n e.message === \"Script execution timed out.\" ||\n (typeof error === \"string\" &&\n (error.includes(\"timed out\") || error.includes(\"timeout\")))\n ) {\n error = \"Script execution timed out\";\n }\n // Capture stack trace if available for debugging (optional)\n if (e.stack) {\n logger.debug(`Code execution error stack: ${e.stack}`);\n }\n }\n\n const executionTime = (Date.now() - startTime) / 1000;\n\n return {\n result,\n logs,\n error,\n execution_time: executionTime,\n };\n }\n\n /**\n * Build the VM execution context with MCP tools and standard globals.\n *\n * @param logs - Array to capture console output\n */\n private async _buildContext(logs: string[]): Promise<any> {\n // Helper to capture logs\n const logHandler = (...args: unknown[]) => {\n logs.push(\n args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg, null, 2) : String(arg)\n )\n .join(\" \")\n );\n };\n\n // Basic safe globals\n const sandbox: Record<string, unknown> = {\n console: {\n log: logHandler,\n error: (...args: unknown[]) => {\n logHandler(\"[ERROR]\", ...args);\n },\n warn: (...args: unknown[]) => {\n logHandler(\"[WARN]\", ...args);\n },\n info: logHandler,\n debug: logHandler,\n },\n // Standard globals\n Object,\n Array,\n String,\n Number,\n Boolean,\n Date,\n Math,\n JSON,\n RegExp,\n Map,\n Set,\n Promise,\n parseInt,\n parseFloat,\n isNaN,\n isFinite,\n encodeURI,\n decodeURI,\n encodeURIComponent,\n decodeURIComponent,\n setTimeout,\n clearTimeout,\n // Helper for tools\n search_tools: this.createSearchToolsFunction(),\n __tool_namespaces: [],\n };\n\n // Add tool namespaces\n const toolNamespaces: Record<string, boolean> = {};\n const namespaceInfos = this.getToolNamespaces();\n\n for (const { serverName, tools, session } of namespaceInfos) {\n // Create namespace object with tool functions\n type ToolFunction = (args?: Record<string, unknown>) => Promise<unknown>;\n const serverNamespace: Record<string, ToolFunction> = {};\n\n for (const tool of tools) {\n const toolName = tool.name;\n // Create wrapper function that calls MCP tool and extracts result\n serverNamespace[toolName] = async (args?: Record<string, unknown>) => {\n const result = await session.connector.callTool(toolName, args || {});\n\n // Extract content from MCP result\n if (result.content && result.content.length > 0) {\n const item = result.content[0];\n if (item.type === \"text\") {\n try {\n return JSON.parse(item.text);\n } catch {\n return item.text;\n }\n }\n return item;\n }\n return result;\n };\n }\n\n sandbox[serverName] = serverNamespace;\n toolNamespaces[serverName] = true;\n }\n\n sandbox.__tool_namespaces = Object.keys(toolNamespaces);\n\n return vm.createContext(sandbox);\n }\n\n /**\n * Clean up resources.\n * VM executor doesn't need cleanup, but method kept for interface consistency.\n */\n async cleanup(): Promise<void> {\n // VM executor doesn't need cleanup, but method kept for interface consistency\n }\n}\n","import type { CallToolResult, Tool } from \"@modelcontextprotocol/client\";\nimport type { MCPClient } from \"../core/node.js\";\nimport { BaseConnector } from \"../transport/base.js\";\n\nexport const CODE_MODE_AGENT_PROMPT = `\n## MCP Code Mode Tool Usage Guide\n\nYou have access to an MCP Code Mode Client that allows you to execute JavaScript/TypeScript code with access to registered tools. Follow this workflow:\n\n### 1. Tool Discovery Phase\n**Always start by discovering available tools:**\n- Tools are organized by server namespace (e.g., \\`server_name.tool_name\\`)\n- Use the \\`search_tools(query, detail_level)\\` function to find available tools\n- You can access \\`__tool_namespaces\\` to see all available server namespaces\n\n\\`\\`\\`javascript\n// Find all GitHub-related tools\nconst tools = await search_tools(\"github\");\nfor (const tool of tools) {\n console.log(\\`\\${tool.server}.\\${tool.name}: \\${tool.description}\\`);\n}\n\n// Get only tool names for quick overview\nconst tools = await search_tools(\"\", \"names\");\n\\`\\`\\`\n\n### 2. Interface Introspection\n**Understand tool contracts before using them:**\n- Use \\`search_tools\\` to get tool descriptions and input schemas\n- Look for \"Access as: server.tool(args)\" patterns in descriptions\n\n### 3. Code Execution Guidelines\n**When writing code:**\n- Use \\`await server.tool({ param: value })\\` syntax for all tool calls\n- Tools are async functions that return promises\n- You have access to standard JavaScript globals: \\`console\\`, \\`JSON\\`, \\`Math\\`, \\`Date\\`, etc.\n- All console output (\\`console.log\\`, \\`console.error\\`, etc.) is automatically captured and returned\n- Build properly structured input objects based on interface definitions\n- Handle errors appropriately with try/catch blocks\n- Chain tool calls by using results from previous calls\n\n### 4. Best Practices\n- **Discover first, code second**: Always explore available tools before writing execution code\n- **Respect namespaces**: Use full \\`server.tool\\` names to avoid conflicts\n- **Minimize Context**: Process large data in code, return only essential results\n- **Error handling**: Wrap tool calls in try/catch for robustness\n- **Data flow**: Chain tools by passing outputs as inputs to subsequent tools\n\n### 5. Available Runtime Context\n- \\`search_tools(query, detail_level)\\`: Function to discover tools\n- \\`__tool_namespaces\\`: Array of available server namespaces\n- All registered tools as \\`server.tool\\` functions\n- Standard JavaScript built-ins for data processing\n\n### Example Workflow\n\n\\`\\`\\`javascript\n// 1. Discover available tools\nconst github_tools = await search_tools(\"github pull request\");\nconsole.log(\\`Available GitHub PR tools: \\${github_tools.map(t => t.name)}\\`);\n\n// 2. Call tools with proper parameters\nconst pr = await github.get_pull_request({\n owner: \"facebook\",\n repo: \"react\",\n number: 12345\n});\n\n// 3. Process results\nlet result;\nif (pr.state === 'open' && pr.labels.some(l => l.name === 'bug')) {\n // 4. Chain with other tools\n await slack.post_message({\n channel: \"#bugs\",\n text: \\`🐛 Bug PR needs review: \\${pr.title}\\`\n });\n result = \"Notification sent\";\n} else {\n result = \"No action needed\";\n}\n\n// 5. Return structured results\nreturn {\n pr_number: pr.number,\n pr_title: pr.title,\n action_taken: result\n};\n\\`\\`\\`\n\nRemember: Always discover and understand available tools before attempting to use them in code execution.\n`;\n\n/** Detail levels accepted by the `search_tools` meta tool. */\nconst DETAIL_LEVELS = new Set([\"names\", \"descriptions\", \"full\"]);\n\n/**\n * CodeModeConnector provides a special \"code mode\" interface for executing JavaScript/TypeScript\n * code with access to MCP tools. Unlike other connectors, it doesn't establish its own external\n * connection - instead, it wraps an already-connected BaseMCPClient and exposes special tools\n * (execute_code, search_tools) on top of it.\n *\n * Since there's no connection phase to perform, the connector is immediately ready to use\n * (connected=true) upon construction. The connect() and disconnect() methods exist for\n * lifecycle compatibility with the BaseConnector interface but don't manage actual connections.\n */\nexport class CodeModeConnector extends BaseConnector {\n private mcpClient: MCPClient;\n private _tools: Tool[];\n\n constructor(client: MCPClient) {\n super();\n this.mcpClient = client;\n this.connected = true; // No connection phase needed - immediately ready\n this._tools = this._createToolsList();\n }\n\n async connect(): Promise<void> {\n this.connected = true;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n }\n\n get publicIdentifier(): Record<string, string> {\n return { name: \"code_mode\", version: \"1.0.0\" };\n }\n\n private _createToolsList(): Tool[] {\n return [\n {\n name: \"execute_code\",\n description:\n \"Execute JavaScript/TypeScript code with access to MCP tools. \" +\n \"This is the PRIMARY way to interact with MCP servers in code mode. \" +\n \"Write code that discovers tools using search_tools(), \" +\n \"calls tools as async functions (e.g., await github.get_pull_request(...)), \" +\n \"processes data efficiently, and returns results. \" +\n \"Use 'await' for async operations and 'return' to return values. \" +\n \"Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"JavaScript/TypeScript code to execute. \" +\n \"Use 'await' for async operations. Use 'return' to return a value. \" +\n \"Available: search_tools(), server.tool_name(), __tool_namespaces\",\n },\n timeout: {\n type: \"number\",\n description: \"Execution timeout in milliseconds\",\n default: 30000,\n },\n },\n required: [\"code\"],\n },\n },\n {\n name: \"search_tools\",\n description:\n \"Search and discover available MCP tools across all servers. \" +\n \"Use this to find out what tools are available before writing code. \" +\n \"Returns tool information including names, descriptions, and schemas. \" +\n \"Can filter by query and control detail level.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description:\n \"Search query to filter tools by name or description\",\n default: \"\",\n },\n detail_level: {\n type: \"string\",\n description: \"Detail level: 'names', 'descriptions', or 'full'\",\n enum: [\"names\", \"descriptions\", \"full\"],\n default: \"full\",\n },\n },\n },\n },\n ];\n }\n\n // Override tools getter to return static list immediately\n get tools(): Tool[] {\n return this._tools;\n }\n\n async initialize(): Promise<any> {\n this.toolsCache = this._tools;\n return { capabilities: {}, version: \"1.0.0\" };\n }\n\n async callTool(\n name: string,\n args: Record<string, any>\n ): Promise<CallToolResult> {\n if (name === \"execute_code\") {\n const code = args.code as string;\n const timeout = (args.timeout as number) || 30000;\n\n // We need to access executeCode on the client\n // Since BaseConnector doesn't know about executeCode, we cast client\n const result = await this.mcpClient.executeCode(code, timeout);\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(result),\n },\n ],\n };\n } else if (name === \"search_tools\") {\n const query = (args.query as string) || \"\";\n const detailLevel = args.detail_level as\n | \"names\"\n | \"descriptions\"\n | \"full\";\n\n const result = await this.mcpClient.searchTools(\n query,\n DETAIL_LEVELS.has(detailLevel) ? detailLevel : \"full\"\n );\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(result),\n },\n ],\n };\n }\n\n throw new Error(`Unknown tool: ${name}`);\n }\n}\n","/**\n * Client-side helpers for MCP elicitation (form/URL mode).\n *\n * The server sends `requestedSchema` as JSON Schema. These helpers provide\n * defaults extraction, validation (via Zod's `z.fromJSONSchema`), and typed\n * ElicitResult builders.\n */\n\nimport type {\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n} from \"@modelcontextprotocol/client\";\nimport { z } from \"zod\";\n\n/** Content shape for ElicitResult when action is \"accept\". */\nexport type ElicitContent = Record<\n string,\n string | number | boolean | string[]\n>;\n\n/** Result of validate(params, content). */\nexport type ElicitValidationResult = {\n /** Whether the submitted content satisfies the requested schema. */\n valid: boolean;\n /** Validation error messages when `valid` is `false`. */\n errors?: string[];\n};\n\ntype ElicitParams = ElicitRequestFormParams | ElicitRequestURLParams;\n\nfunction hasRequestedSchema(\n params: ElicitParams\n): params is ElicitRequestFormParams & { requestedSchema: object } {\n return \"requestedSchema\" in params && params.requestedSchema != null;\n}\n\n/**\n * Get default values from the elicitation request's requestedSchema (form mode).\n * For URL mode or when no schema is present, returns an empty object.\n */\nexport function getDefaults(params: ElicitParams): ElicitContent {\n const content: ElicitContent = {};\n if (!hasRequestedSchema(params)) return content;\n const schema = params.requestedSchema as Record<string, unknown>;\n const properties = (schema.properties ?? {}) as Record<string, unknown>;\n for (const [fieldName, fieldSchema] of Object.entries(properties)) {\n const field = fieldSchema as Record<string, unknown>;\n if (\"default\" in field) {\n const v = field.default;\n if (\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n (Array.isArray(v) && v.every((x) => typeof x === \"string\"))\n ) {\n content[fieldName] = v as string | number | boolean | string[];\n }\n }\n }\n return content;\n}\n\n/**\n * Merge partial content with schema defaults. Keys present in partial are kept;\n * missing keys are filled from requestedSchema.properties[*].default.\n */\nexport function applyDefaults(\n params: ElicitParams,\n partial?: ElicitContent\n): ElicitContent {\n const defaults = getDefaults(params);\n if (partial == null) return defaults;\n return { ...defaults, ...partial };\n}\n\n/**\n * Return an ElicitResult that accepts with content built from schema defaults.\n */\nexport function acceptWithDefaults(params: ElicitParams): ElicitResult {\n return { action: \"accept\", content: getDefaults(params) };\n}\n\n/**\n * Return an ElicitResult that accepts with the given content.\n */\nexport function accept(content: ElicitContent): ElicitResult {\n return { action: \"accept\", content };\n}\n\n/**\n * Return an ElicitResult that declines the elicitation (user chose not to provide).\n * Optional reason is for logging; the SDK result is `{ action: \"decline\" }`.\n */\nexport function decline(_reason?: string): ElicitResult {\n return { action: \"decline\" };\n}\n\n/**\n * Return an ElicitResult that cancels the elicitation (user cancelled the operation).\n */\nexport function cancel(): ElicitResult {\n return { action: \"cancel\" };\n}\n\n/**\n * Validate content against the request's requestedSchema using Zod.\n * Converts requestedSchema (JSON Schema) via `z.fromJSONSchema`, then\n * safeParse(content). If conversion fails, returns\n * `{ valid: false, errors: [\"Unsupported or invalid schema\"] }`.\n */\nexport function validate(\n params: ElicitParams,\n content: ElicitContent\n): ElicitValidationResult {\n if (!hasRequestedSchema(params)) {\n return { valid: true };\n }\n try {\n const zodSchema = z.fromJSONSchema(params.requestedSchema);\n const result = zodSchema.safeParse(content);\n if (result.success) {\n return { valid: true };\n }\n const messages = result.error.issues.map((i) =>\n i.path.length > 0 ? `${i.path.join(\".\")}: ${i.message}` : i.message\n );\n return { valid: false, errors: messages };\n } catch {\n return { valid: false, errors: [\"Unsupported or invalid schema\"] };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOO,SAAS,6BACd,aACM;AACN,EAAAA,WAAU;AACZ;AAGO,SAAS,wBAAwB,MAAoC;AAC1E,OAAKA,WAAU,IAAI;AACrB;AAhBA,IAIIA;AAJJ;AAAA;AAAA;AAAA;AAAA;;;ACkCA,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;AAhDA,IAYM,QAWA,OA2BA,qBAuDO,QA6CA;AAtJb;AAAA;AAAA;AAYA,IAAM,SAAS;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,IAAM,QAAkC;AAAA,MACtC,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,MACT,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AAkBA,IAAM,sBAAN,MAA0B;AAAA,MACxB,YACU,OAAO,WACR,QAAkB,QAClB,SAAoB,WAC3B;AAHQ;AACD;AACA;AAAA,MACN;AAAA,MAEK,MAAM,OAAiB,SAAiB,MAAuB;AACrE,YACE,KAAK,UAAU,YACf,OAAO,QAAQ,KAAK,IAAI,OAAO,QAAQ,KAAK,KAAK,GACjD;AACA;AAAA,QACF;AACA,cAAM,QAAQ,KACX,IAAI,CAAC,MAAM;AACV,cAAI,OAAO,MAAM,SAAU,QAAO;AAClC,c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C7C,aAAO,CAAC,qBAAqB,SAAS;AAAA,IACxC,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCA,MAAa,QAAuB;AAElC,QAAI,KAAK,eAAe;AACtB,YAAM,KAAK,cAAc,QAAQ;AACjC,WAAK,gBAAgB;AAAA,IACvB;AAGA,UAAM,KAAK,iBAAiB;AAAA,EAC9B;AACF;;;APhuBA;AAEA;AAGA;AAgBA;","names":["tracker","Client","process","path","fs","auth","UnauthorizedError","DEFAULT_AUTH_TIMEOUT_MS","UnauthorizedError","sessionId","isOAuthClientProvider","session","path","StdioConnector"]}