@dudko.dev/agent-web-react 0.0.29 → 0.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +345 -19
- package/dist/{chunk-UUB7CE6N.js → chunk-EMF7DTGS.js} +69 -1
- package/dist/chunk-EMF7DTGS.js.map +1 -0
- package/dist/chunk-FXHQXIOU.js +94 -0
- package/dist/chunk-FXHQXIOU.js.map +1 -0
- package/dist/chunk-VMCWL6VH.js +294 -0
- package/dist/chunk-VMCWL6VH.js.map +1 -0
- package/dist/elicitation-CcZe5-EK.d.cts +1535 -0
- package/dist/elicitation-CcZe5-EK.d.ts +1535 -0
- package/dist/index.cjs +4360 -618
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +705 -433
- package/dist/index.d.ts +705 -433
- package/dist/index.js +4029 -628
- package/dist/index.js.map +1 -1
- package/dist/mcp-app-policy-DIUmGPJP.d.cts +55 -0
- package/dist/mcp-app-policy-DIUmGPJP.d.ts +55 -0
- package/dist/mcp-app-sandbox.cjs +313 -0
- package/dist/mcp-app-sandbox.cjs.map +1 -0
- package/dist/mcp-app-sandbox.d.cts +65 -0
- package/dist/mcp-app-sandbox.d.ts +65 -0
- package/dist/mcp-app-sandbox.js +201 -0
- package/dist/mcp-app-sandbox.js.map +1 -0
- package/dist/mcp.cjs +315 -42
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +182 -96
- package/dist/mcp.d.ts +182 -96
- package/dist/mcp.js +233 -46
- package/dist/mcp.js.map +1 -1
- package/dist/pipeline.cjs.map +1 -1
- package/dist/pipeline.js +1 -1
- package/dist/styles.css +1139 -0
- package/package.json +13 -3
- package/dist/chunk-UUB7CE6N.js.map +0 -1
package/dist/mcp.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp.ts","../src/hooks/use-mcp.ts","../src/hooks/use-mcp-servers.ts"],"sourcesContent":["// The MCP half of the bindings, behind its own subpath: `@dudko.dev/agent-web-react/mcp`.\n//\n// WHY THIS IS NOT IN THE MAIN ENTRY. `useMcp` loads the core's `./mcp` subpath with a dynamic\n// `import()`, and that was meant to keep `@modelcontextprotocol/client` — an optional peer — out of\n// the way of hosts that never use MCP. It does at RUNTIME. A bundler does not run anything: for a\n// dynamic import it must resolve the target at build time to emit a chunk, and the core's `mcp.js`\n// imports the SDK statically (and re-exports `UnauthorizedError` by identity, so that cannot be\n// made lazy). So a host that merely imported `useAgent` from the main entry got\n// \"Module not found: @modelcontextprotocol/client\" from webpack, with MCP nowhere in its code.\n//\n// A subpath moves the decision to the host, where it belongs: import from here and the SDK is\n// needed (and bundled); never import from here and no part of the build ever mentions it. This is\n// the same rule the core follows for its own `./mcp`.\nexport {\n useMcp,\n claimOAuthCallback,\n describeMcpResult,\n isUnauthorizedError,\n mcpInstructionsOf,\n mcpOAuthProviderOptions,\n readCallbackParams,\n stripOAuthParams,\n} from './hooks/use-mcp.js'\nexport type {\n McpConnectOptions,\n McpOAuthOptions,\n McpStatus,\n UseMcpOptions,\n UseMcpReturn,\n} from './hooks/use-mcp.js'\nexport { useMcpServers } from './hooks/use-mcp-servers.js'\nexport type {\n McpAuthMode,\n McpServerSpec,\n McpServerView,\n UseMcpServersOptions,\n UseMcpServersReturn,\n} from './hooks/use-mcp-servers.js'\nexport type {\n BrowserOAuthProviderOptions,\n ConnectedMcp,\n McpCatalogEntry,\n McpOAuthCallback,\n McpServerInstructions,\n McpServerResult,\n McpModule,\n} from './mcp-types.js'\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { AgentToolSet } from '@dudko.dev/agent-web'\nimport type {\n BrowserOAuthProvider,\n BrowserOAuthProviderOptions,\n ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n McpOAuthCallback,\n McpServerResult,\n} from '../mcp-types.js'\n\nexport type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error'\n\n/** The OAuth details of one server. Everything is optional. */\nexport interface McpOAuthOptions {\n /** Where the authorization server sends the user back (default: this page, without query or hash). */\n redirectUrl?: string\n /** Fallback scope when the server's metadata advertises none. */\n scope?: string\n /** `client_name` for dynamic registration (default: the hook's `clientName`). */\n clientName?: string\n /**\n * URL of a client ID metadata document (CIMD) your app hosts (default: the\n * hook's `clientMetadataUrl`). An authorization server that advertises\n * `client_id_metadata_document_supported` takes it as the `client_id` and no\n * dynamic registration is made; any other server is registered with as\n * before. Must be https with a non-root path, and the document must list the\n * `redirectUrl` in its `redirect_uris` - the core refuses anything else and\n * the server ends in `status: 'error'`. A core that does not know the option\n * ignores it and registers dynamically.\n */\n clientMetadataUrl?: string\n}\n\nexport interface McpConnectOptions {\n /** The server's StreamableHTTP endpoint. */\n url: string\n /** Prefix for the discovered tool names (\"<name>__<tool>\"). Default 'mcp'. */\n name?: string\n /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */\n headers?: Record<string, string>\n /**\n * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core\n * that ships the OAuth provider; check `oauthSupported` before offering it.\n */\n oauth?: boolean | McpOAuthOptions\n}\n\nexport interface UseMcpOptions {\n /** Client name reported to the MCP server during initialize. */\n clientName?: string\n /**\n * URL of the client ID metadata document (CIMD) this app hosts, used for\n * every OAuth server unless its own `oauth.clientMetadataUrl` says otherwise.\n * See `McpOAuthOptions.clientMetadataUrl`.\n */\n clientMetadataUrl?: string\n /** Called with connector log lines — handy while debugging a server. */\n onLog?: (level: string, message: string) => void\n}\n\nexport interface UseMcpReturn {\n status: McpStatus\n /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */\n tools?: AgentToolSet\n catalog: McpCatalogEntry[]\n /**\n * What the connected server told the agent in its handshake (its MCP `instructions`), when it\n * sent any. Third-party text that the core puts in the agent's system prompt: show it to the\n * user as the server's words, never as your own.\n */\n instructions?: string\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * Whether the installed core exposes the OAuth API. `undefined` until the\n * optional subpath has been loaded once — call `checkOAuthSupport()` to\n * resolve it before offering OAuth in your UI.\n */\n oauthSupported?: boolean\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n connect: (options: McpConnectOptions) => Promise<void>\n disconnect: () => Promise<void>\n /** Navigate to the authorization server. Call it from a user gesture. */\n authorize: () => void\n /** Drop the stored tokens and dynamic registration for the current server. */\n forgetAuthorization: () => Promise<void>\n /** Load the optional subpath and report whether it can do OAuth. */\n checkOAuthSupport: () => Promise<boolean>\n}\n\n/**\n * The instructions the server `name` sent, or undefined when it sent none (or the core is too\n * old to report them). The text is the server's, not the host's: show it as such.\n */\nexport const mcpInstructionsOf = (\n connection: Pick<ConnectedMcp, 'instructions'>,\n name: string,\n): string | undefined => {\n const list = Array.isArray(connection.instructions) ? connection.instructions : []\n const text = list.find((i) => i?.server === name)?.instructions\n return typeof text === 'string' && text.trim() ? text : undefined\n}\n\nexport const OAUTH_UNSUPPORTED =\n 'The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.'\n\nconst PENDING_KEY = 'agent-web-react:mcp:pending'\nconst OAUTH_KEY = 'agent-web-react:mcp:oauth'\n\ninterface OAuthRecord {\n url: string\n name?: string\n redirectUrl: string\n scope?: string\n clientName?: string\n clientMetadataUrl?: string\n /** When the redirect was started, so a stale record can't claim a callback. */\n startedAt?: number\n}\n\n// A round-trip to an authorization server and back takes seconds. Anything\n// older than this is not the flow that produced the ?code= we are looking at —\n// most likely another sign-in on the same page — so we leave it alone.\nexport const PENDING_TTL_MS = 10 * 60 * 1000\n\nlet modulePromise: Promise<McpModule> | undefined\n\n/**\n * Load the core's optional `./mcp` subpath. Kept dynamic so apps that never\n * touch MCP don't pull `@modelcontextprotocol/client` into their bundle, and so a\n * core without the OAuth half degrades to a clear message instead of a crash.\n */\nexport const loadMcp = (): Promise<McpModule> => {\n modulePromise ??= import('@dudko.dev/agent-web/mcp')\n .then((m) => m as unknown as McpModule)\n .catch((err: unknown) => {\n // A rejected promise is neither null nor undefined, so ??= would cache\n // the failure forever — one flaky chunk fetch would kill MCP for the tab.\n modulePromise = undefined\n throw err\n })\n return modulePromise\n}\n\n/** Map a single server's connect outcome onto the hook's status. Pure. */\nexport const describeMcpResult = (\n result: McpServerResult | undefined,\n): { status: McpStatus; error?: string } => {\n if (!result) return { status: 'error', error: 'The connector returned no result for the server' }\n if (result.connected) return { status: 'connected' }\n if (result.needsAuthorization) return { status: 'needs-authorization' }\n return { status: 'error', error: result.error ?? 'Could not connect to the MCP server' }\n}\n\nconst OAUTH_PARAMS = ['code', 'state', 'error', 'error_description', 'iss']\n\n/**\n * Read the authorization-code parameters out of a URL **synchronously**.\n *\n * The core exports an equivalent, but it lives behind a dynamic import: by the\n * time that import resolves, React has flushed the rest of the app's effects,\n * and any one of them may have rewritten `location` (the demo's own view\n * router did exactly that). The callback has to be captured before the first\n * await, so this parser is duplicated here on purpose.\n *\n * Reads the query string and, for hash-routed apps, the fragment. Returns\n * undefined when neither a `code` nor an `error` is present.\n */\nexport const readCallbackParams = (href?: string): McpOAuthCallback | undefined => {\n const target =\n href ?? (typeof globalThis.location !== 'undefined' ? globalThis.location.href : undefined)\n if (!target) return undefined\n let url: URL\n try {\n url = new URL(target)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n // RFC 9207: the core's `finishMcpOAuth` checks it against the authorization\n // server the flow was started with, before the code is exchanged.\n iss: params.get('iss') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Remove the OAuth response parameters from a URL, leaving the rest intact —\n * query string and fragment alike. The code is single-use and lands in history,\n * referrers and screenshots, so it goes as soon as it has been read.\n */\nexport const stripOAuthParams = (href: string): string => {\n const url = new URL(href)\n for (const key of OAUTH_PARAMS) url.searchParams.delete(key)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n const params = new URLSearchParams(hash.slice(q + 1))\n for (const key of OAUTH_PARAMS) params.delete(key)\n const rest = params.toString()\n url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q)\n }\n return url.toString()\n}\n\n// An authorization code is single-use, and React StrictMode mounts every effect\n// twice in development. Claiming happens synchronously, before any await, so\n// the second pass cannot race the first into the token endpoint (where it would\n// lose the state check and report a CSRF failure on a perfectly good flow).\nconst claimedCallbacks = new Set<string>()\n\nexport const claimOAuthCallback = (callback: McpOAuthCallback): boolean => {\n const key = `${callback.code ?? ''}|${callback.state ?? ''}|${callback.error ?? ''}`\n if (claimedCallbacks.has(key)) return false\n claimedCallbacks.add(key)\n return true\n}\n\nexport const readRecord = <T>(key: string): T | undefined => {\n try {\n const raw = globalThis.localStorage?.getItem(key)\n return raw ? (JSON.parse(raw) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nexport const writeRecord = (key: string, value: unknown): void => {\n try {\n if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))\n else globalThis.localStorage?.removeItem(key)\n } catch {\n // Private mode / storage disabled: the OAuth round-trip simply won't\n // resume automatically, which the UI already handles.\n }\n}\n\n// A redirect_uri must not carry a fragment (RFC 6749 §3.1.2), and it has to\n// match the registered value byte-for-byte, so query and hash are dropped.\nexport const defaultRedirectUrl = (): string =>\n typeof globalThis.location === 'undefined'\n ? ''\n : `${globalThis.location.origin}${globalThis.location.pathname}`\n\n/**\n * The options of the core's OAuth provider for one server: the server's own\n * `oauth` details first, then the hook-level defaults (`clientName`,\n * `clientMetadataUrl`), then this page as the redirect. Pure - both hooks build\n * every provider through it, on connect, on the way back from the redirect and\n * when forgetting, so the three always describe the same client.\n */\nexport const mcpOAuthProviderOptions = (\n serverUrl: string,\n oauth: McpOAuthOptions = {},\n defaults: Pick<McpOAuthOptions, 'clientName' | 'clientMetadataUrl'> = {},\n): BrowserOAuthProviderOptions => {\n const clientMetadataUrl = oauth.clientMetadataUrl ?? defaults.clientMetadataUrl\n return {\n serverUrl,\n redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),\n clientName: oauth.clientName ?? defaults.clientName,\n scope: oauth.scope,\n // Left out when unset: a provider built without it keeps registering dynamically.\n ...(clientMetadataUrl !== undefined ? { clientMetadataUrl } : {}),\n }\n}\n\n/**\n * Did this error come from the server refusing our authorization?\n *\n * Never by the message: it would also match a tool whose own error text\n * mentions \"unauthorized\" — the connector throws a failing tool's text\n * verbatim. Three handles, in order:\n *\n * 1. the class the core's `./mcp` subpath re-exports. On the 2.x MCP SDK\n * (`@modelcontextprotocol/client`) `instanceof` goes by a brand the error\n * carries, not by prototype, so it also holds when the error was made by\n * another copy of the SDK than the one the core module resolved to (two\n * bundles, an ESM and a CJS build on one page);\n * 2. the error's own `name`, which the 2.x class sets to `'UnauthorizedError'`\n * (a string, so it survives a minifier; the 1.x class left it `'Error'`);\n * 3. `constructor.name`, for a core on the 1.x SDK that is too old to export\n * the class (and only where the bundle keeps class names).\n */\nexport const isUnauthorizedError = (err: unknown, mod?: McpModule): boolean => {\n if (!(err instanceof Error)) return false\n if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true\n if (err.name === 'UnauthorizedError') return true\n return err.constructor?.name === 'UnauthorizedError'\n}\n\n/**\n * Wrap each tool so a mid-session authorization failure is visible. Without\n * this the panel keeps reporting \"connected\" while every call fails: the core\n * refreshes silently on a 401, but once the refresh token is gone (revoked,\n * expired) it can only ask for a new authorization.\n */\nexport const watchAuthorization = (\n tools: AgentToolSet,\n mod: McpModule,\n onUnauthorized: () => void,\n): AgentToolSet => {\n const entries = Object.entries(tools as Record<string, unknown>).map(([name, value]) => {\n const tool = value as { execute?: (args: unknown, options: unknown) => unknown }\n if (typeof tool.execute !== 'function') return [name, value]\n const execute = tool.execute.bind(tool)\n const watched = (args: unknown, options: unknown): unknown => {\n // Deliberately not an async function: the AI SDK inspects what `execute`\n // returns SYNCHRONOUSLY to decide whether a tool streams (isAsyncIterable),\n // so wrapping everything in a promise would collapse a streaming tool into\n // a single opaque result.\n try {\n const out = execute(args, options)\n if (out && typeof (out as Promise<unknown>).then === 'function') {\n return (out as Promise<unknown>).then(undefined, (err: unknown) => {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n })\n }\n return out\n } catch (err) {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n }\n }\n return [name, { ...(value as object), execute: watched }]\n })\n return Object.fromEntries(entries) as AgentToolSet\n}\n\n/**\n * Connect the browser agent to a remote MCP server the user names at runtime —\n * static header, or full OAuth 2.1 with dynamic client registration.\n *\n * The OAuth round-trip leaves the page, so the hook persists what it needs to\n * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL\n * and reconnects, all before the app renders anything MCP-related.\n *\n * ```tsx\n * const mcp = useMcp()\n * // await mcp.connect({ url, oauth: true })\n * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>\n * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>\n * ```\n */\nexport const useMcp = (options: UseMcpOptions = {}): UseMcpReturn => {\n const [status, setStatus] = useState<McpStatus>('idle')\n const [tools, setTools] = useState<AgentToolSet | undefined>(undefined)\n const [catalog, setCatalog] = useState<McpCatalogEntry[]>([])\n const [instructions, setInstructions] = useState<string | undefined>(undefined)\n const [error, setError] = useState<string | undefined>(undefined)\n const [authorizationUrl, setAuthorizationUrl] = useState<string | undefined>(undefined)\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompletingAuthorization] = useState(\n () => readCallbackParams() !== undefined,\n )\n\n const connectionRef = useRef<ConnectedMcp | undefined>(undefined)\n const providerRef = useRef<BrowserOAuthProvider | undefined>(undefined)\n // Bumped by every connect / disconnect / unmount. A handshake that finishes\n // after its epoch has passed closes itself instead of writing state or\n // leaking an open MCP session onto a dead component.\n const epochRef = useRef(0)\n // Options land in a ref so `connect` keeps a stable identity: it is a natural\n // dependency of effects in host components.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const closeConnection = useCallback(async () => {\n const open = connectionRef.current\n connectionRef.current = undefined\n if (open) await open.close().catch(() => {})\n }, [])\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n const connect = useCallback(\n async (opts: McpConnectOptions) => {\n const epoch = ++epochRef.current\n const current = () => epochRef.current === epoch\n await closeConnection()\n if (!current()) return\n setStatus('connecting')\n setError(undefined)\n setAuthorizationUrl(undefined)\n setTools(undefined)\n setCatalog([])\n setInstructions(undefined)\n\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n const name = opts.name ?? 'mcp'\n let authProvider: BrowserOAuthProvider | undefined\n\n if (opts.oauth) {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const providerOptions = mcpOAuthProviderOptions(\n opts.url,\n typeof opts.oauth === 'object' ? opts.oauth : {},\n optionsRef.current,\n )\n const record: OAuthRecord = {\n url: opts.url,\n name,\n redirectUrl: providerOptions.redirectUrl,\n scope: providerOptions.scope,\n clientName: providerOptions.clientName,\n clientMetadataUrl: providerOptions.clientMetadataUrl,\n startedAt: Date.now(),\n }\n // Throws on a clientMetadataUrl the core refuses (not https, or a bare\n // origin): reported below as this server's error, before any request.\n authProvider = new mod.BrowserOAuthProvider(providerOptions)\n providerRef.current = authProvider\n // `pending` resumes the redirect; `oauth` outlives it so tokens stay\n // addressable for forgetAuthorization() after a reload.\n writeRecord(PENDING_KEY, record)\n writeRecord(OAUTH_KEY, record)\n } else {\n providerRef.current = undefined\n }\n\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: opts.url,\n headers: opts.oauth ? undefined : opts.headers,\n authProvider,\n },\n },\n { clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog },\n )\n\n if (!current()) {\n // Unmounted, or another connect started while we were shaking hands.\n await connection.close().catch(() => {})\n return\n }\n\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = authProvider?.authorizationUrl\n setAuthorizationUrl(url ? String(url) : undefined)\n setStatus('needs-authorization')\n return\n }\n throw new Error(outcome.error)\n }\n\n connectionRef.current = connection\n // The round-trip is over: a stale record would later make an unrelated\n // ?code= on this page look like ours.\n writeRecord(PENDING_KEY, undefined)\n setTools(\n watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = providerRef.current?.authorizationUrl\n if (url) setAuthorizationUrl(String(url))\n setStatus('needs-authorization')\n }),\n )\n setCatalog(connection.catalog)\n setInstructions(mcpInstructionsOf(connection, name))\n setStatus('connected')\n } catch (err) {\n if (!current()) return\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n }\n },\n [closeConnection],\n )\n\n const disconnect = useCallback(async () => {\n epochRef.current++\n await closeConnection()\n setTools(undefined)\n setCatalog([])\n setInstructions(undefined)\n setAuthorizationUrl(undefined)\n setError(undefined)\n setStatus('idle')\n }, [closeConnection])\n\n const authorize = useCallback(() => {\n if (authorizationUrl && typeof globalThis.location !== 'undefined') {\n globalThis.location.href = authorizationUrl\n }\n }, [authorizationUrl])\n\n const forgetAuthorization = useCallback(async () => {\n const record = readRecord<OAuthRecord>(OAUTH_KEY)\n writeRecord(PENDING_KEY, undefined)\n writeRecord(OAUTH_KEY, undefined)\n // After a reload there is no live provider, but the tokens are still in the\n // vault — rebuild one for the same server so \"forget\" actually forgets\n // rather than only resetting the UI.\n let provider = providerRef.current\n if (!provider && record) {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n try {\n provider = new mod.BrowserOAuthProvider(mcpOAuthProviderOptions(record.url, record))\n } catch {\n // Options the core refuses never built a provider, so nothing was stored for them.\n }\n }\n }\n await provider?.reset().catch(() => {})\n providerRef.current = undefined\n await disconnect()\n }, [disconnect])\n\n // Resume an OAuth round-trip: the authorization server has just sent the user\n // back with ?code=… and this component is mounting for the first time.\n useEffect(() => {\n // Everything up to the first await runs synchronously, on purpose: React\n // flushes the remaining passive effects (which may rewrite location) before\n // an awaited continuation resumes, and StrictMode runs this effect twice.\n const callback = readCallbackParams()\n if (!callback) {\n setCompletingAuthorization(false)\n return\n }\n const pending = readRecord<OAuthRecord>(PENDING_KEY)\n // A record only proves that WE started a flow, not that THIS callback is\n // its answer — so an expired one is treated as somebody else's. Either way\n // the URL is left exactly as we found it: another sign-in flow on this page\n // may still need those parameters.\n const fresh =\n pending !== undefined &&\n (pending.startedAt === undefined || Date.now() - pending.startedAt < PENDING_TTL_MS)\n if (!pending || !fresh) {\n if (pending) writeRecord(PENDING_KEY, undefined)\n setCompletingAuthorization(false)\n return\n }\n if (!claimOAuthCallback(callback)) {\n setCompletingAuthorization(false)\n return\n }\n // Ours, and claimed: the code is in hand, so clear it from the address bar\n // now rather than after the reconnect.\n if (typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n\n void (async () => {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const provider = new mod.BrowserOAuthProvider(mcpOAuthProviderOptions(pending.url, pending))\n providerRef.current = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(PENDING_KEY, undefined)\n // NOT gated on `cancelled`. StrictMode's simulated cleanup sets it in\n // development, and the second setup cannot take over — the code has\n // already been claimed and stripped from the URL — so bailing here\n // would finish the authorization and then never connect. `connect` is\n // epoch-guarded and a setState after a real unmount is a no-op, so\n // letting it run is safe either way.\n //\n // Hand back to `connect`, which owns the status from here — a slow or\n // hung handshake must not leave the UI stuck on \"finishing\".\n setCompletingAuthorization(false)\n // With the details the flow was started with: the same redirect, scope,\n // client name and client ID metadata document, not the hook's defaults.\n await connect({\n url: pending.url,\n name: pending.name,\n oauth: {\n redirectUrl: pending.redirectUrl,\n scope: pending.scope,\n clientName: pending.clientName,\n clientMetadataUrl: pending.clientMetadataUrl,\n },\n })\n } catch (err) {\n writeRecord(PENDING_KEY, undefined)\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n } finally {\n setCompletingAuthorization(false)\n }\n })()\n // Runs once: `connect` is stable and the callback exists only on first load.\n }, [connect])\n\n useEffect(\n () => () => {\n epochRef.current++\n void closeConnection()\n },\n [closeConnection],\n )\n\n return {\n status,\n tools,\n catalog,\n instructions,\n error,\n authorizationUrl,\n oauthSupported,\n completingAuthorization,\n connect,\n disconnect,\n authorize,\n forgetAuthorization,\n checkOAuthSupport,\n }\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { AgentToolSet } from '@dudko.dev/agent-web'\nimport type {\n BrowserOAuthProvider,\n ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n} from '../mcp-types.js'\nimport {\n claimOAuthCallback,\n defaultRedirectUrl,\n describeMcpResult,\n loadMcp,\n mcpInstructionsOf,\n mcpOAuthProviderOptions,\n OAUTH_UNSUPPORTED,\n PENDING_TTL_MS,\n readCallbackParams,\n readRecord,\n stripOAuthParams,\n watchAuthorization,\n writeRecord,\n type McpOAuthOptions,\n type McpStatus,\n type UseMcpOptions,\n} from './use-mcp.js'\n\nexport type McpAuthMode = 'none' | 'bearer' | 'oauth'\n\n/** One server the user wants connected. */\nexport interface McpServerSpec {\n /**\n * Unique name; also the tool prefix (\"<name>__<tool>\"). Sanitised to\n * `[a-zA-Z0-9_-]`; a taken name gets a numeric suffix.\n */\n name: string\n /** The server's StreamableHTTP endpoint. */\n url: string\n auth?: McpAuthMode\n /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */\n token?: string\n /** OAuth details for `auth: 'oauth'` (`clientMetadataUrl` for CIMD among them). */\n oauth?: McpOAuthOptions\n}\n\n/** A server's live state. */\nexport interface McpServerView {\n name: string\n url: string\n auth: McpAuthMode\n status: McpStatus\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n catalog: McpCatalogEntry[]\n /**\n * What the server told the agent in its handshake (its MCP `instructions`), while it is\n * connected and if it sent any. Third-party text that the core puts in the agent's system\n * prompt: show it to the user as the server's words.\n */\n instructions?: string\n}\n\nexport interface UseMcpServersOptions extends UseMcpOptions {\n /**\n * Remember the server list (never tokens) in localStorage so it survives a\n * reload — and the OAuth redirect, which IS a reload (default true).\n */\n persist?: boolean\n /** localStorage key of the list (default 'agent-web-react:mcp-servers'). */\n storageKey?: string\n /** Reconnect remembered servers on mount (default true). Bearer servers wait for their token. */\n autoConnect?: boolean\n /** Per-server connect deadline in ms (default: the core's, 30 s). */\n connectTimeoutMs?: number\n}\n\nexport interface UseMcpServersReturn {\n servers: McpServerView[]\n /** Tools of every connected server, merged — pass to `BrowserAgentConfig.tools`. */\n tools: AgentToolSet\n /** Catalogue of every connected server, merged. */\n catalog: McpCatalogEntry[]\n connectedCount: number\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n /** Whether the installed core can do OAuth (undefined until checked). */\n oauthSupported?: boolean\n checkOAuthSupport: () => Promise<boolean>\n /** Add (or replace, by name) a server and connect it. Resolves with the final name. */\n add: (spec: McpServerSpec) => Promise<string>\n /** Disconnect and forget a server. */\n remove: (name: string) => Promise<void>\n /** Connect again — optionally with a fresh bearer token. */\n reconnect: (name: string, token?: string) => Promise<void>\n /** Navigate to the server's authorization page. Call it from a user gesture. */\n authorize: (name: string) => void\n /** Drop a server's stored OAuth tokens and registration. */\n forgetAuthorization: (name: string) => Promise<void>\n}\n\ninterface StoredServer {\n name: string\n url: string\n auth: McpAuthMode\n oauth?: McpServerSpec['oauth']\n}\n\ninterface PendingRecord {\n name: string\n url: string\n redirectUrl: string\n scope?: string\n clientName?: string\n clientMetadataUrl?: string\n startedAt: number\n}\n\ninterface Live {\n epoch: number\n connection?: ConnectedMcp\n provider?: BrowserOAuthProvider\n tools?: AgentToolSet\n token?: string\n}\n\nconst DEFAULT_KEY = 'agent-web-react:mcp-servers'\n\nconst sanitize = (s: string): string => s.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 32) || 'mcp'\n\nconst view = (s: StoredServer, patch: Partial<McpServerView> = {}): McpServerView => ({\n name: s.name,\n url: s.url,\n auth: s.auth,\n status: 'idle',\n catalog: [],\n ...patch,\n})\n\n/**\n * Connect the browser agent to SEVERAL remote MCP servers at once, each with\n * its own auth (none, a bearer token, or OAuth 2.1 + dynamic registration).\n * Every server is its own connection — adding or removing one never touches\n * the others — and their tools merge into one `tools` set, prefixed by server\n * name. The list is remembered across reloads (tokens excepted), and an OAuth\n * round-trip resumes on return.\n *\n * ```tsx\n * const mcp = useMcpServers()\n * // await mcp.add({ name: 'github', url, auth: 'oauth' })\n * // await mcp.add({ name: 'docs', url, auth: 'bearer', token })\n * const agent = useAgent({ model, tools: { ...local, ...mcp.tools } }, { deps: [mcp.tools] })\n * ```\n *\n * With many servers the merged catalogue can reach hundreds of tools; the core\n * switches to tool search above `toolSearchThreshold` automatically.\n */\nexport const useMcpServers = (options: UseMcpServersOptions = {}): UseMcpServersReturn => {\n const storageKey = options.storageKey ?? DEFAULT_KEY\n const pendingKey = `${storageKey}:pending`\n const persist = options.persist !== false\n\n // The remembered list as it was stored, read once: the views below drop `oauth`.\n const [stored] = useState<StoredServer[]>(() =>\n persist ? (readRecord<StoredServer[]>(storageKey) ?? []) : [],\n )\n const [servers, setServers] = useState<McpServerView[]>(() => stored.map((s) => view(s)))\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompleting] = useState(\n () => readCallbackParams() !== undefined && readRecord(pendingKey) !== undefined,\n )\n // Bumped whenever a server's tools change, to recompute the merged set.\n const [toolsVersion, setToolsVersion] = useState(0)\n\n const liveRef = useRef(new Map<string, Live>())\n const specsRef = useRef(new Map<string, StoredServer>())\n if (specsRef.current.size === 0 && servers.length > 0) {\n for (const s of servers) {\n // With the OAuth details the server was added with (redirect, scope, client name, client\n // ID metadata document): after a reload it must be the same client, and the next save of\n // the list must not drop them.\n const oauth = stored.find((x) => x.name === s.name && x.url === s.url)?.oauth\n specsRef.current.set(s.name, {\n name: s.name,\n url: s.url,\n auth: s.auth,\n ...(oauth && typeof oauth === 'object' ? { oauth } : {}),\n })\n }\n }\n const optionsRef = useRef(options)\n optionsRef.current = options\n const unmountedRef = useRef(false)\n\n const saveList = useCallback(() => {\n if (!persist) return\n writeRecord(storageKey, [...specsRef.current.values()])\n }, [persist, storageKey])\n\n const patch = useCallback((name: string, p: Partial<McpServerView>) => {\n if (unmountedRef.current) return\n setServers((list) => list.map((s) => (s.name === name ? { ...s, ...p } : s)))\n }, [])\n\n const live = (name: string): Live => {\n let l = liveRef.current.get(name)\n if (!l) {\n l = { epoch: 0 }\n liveRef.current.set(name, l)\n }\n return l\n }\n\n const closeServer = useCallback(async (name: string) => {\n const l = liveRef.current.get(name)\n if (!l) return\n l.epoch += 1\n const open = l.connection\n l.connection = undefined\n if (l.tools) {\n l.tools = undefined\n setToolsVersion((v) => v + 1)\n }\n if (open) await open.close().catch(() => {})\n }, [])\n\n const providerFor = (mod: McpModule, spec: StoredServer): BrowserOAuthProvider => {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n // Throws on a clientMetadataUrl the core refuses (not https, or a bare origin).\n return new mod.BrowserOAuthProvider(\n mcpOAuthProviderOptions(spec.url, spec.oauth, optionsRef.current),\n )\n }\n\n const connectServer = useCallback(\n async (name: string): Promise<void> => {\n const spec = specsRef.current.get(name)\n if (!spec) return\n await closeServer(name)\n const l = live(name)\n const epoch = ++l.epoch\n const current = () => !unmountedRef.current && l.epoch === epoch\n if (spec.auth === 'bearer' && !l.token) {\n patch(name, { status: 'idle', error: 'Enter the bearer token to connect.' })\n return\n }\n patch(name, {\n status: 'connecting',\n error: undefined,\n authorizationUrl: undefined,\n catalog: [],\n instructions: undefined,\n })\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n let provider: BrowserOAuthProvider | undefined\n if (spec.auth === 'oauth') {\n provider = providerFor(mod, spec)\n l.provider = provider\n }\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: spec.url,\n headers:\n spec.auth === 'bearer' && l.token\n ? { Authorization: `Bearer ${l.token}` }\n : undefined,\n authProvider: provider,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n },\n {\n clientName: optionsRef.current.clientName,\n onLog: optionsRef.current.onLog,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n )\n if (!current()) {\n await connection.close().catch(() => {})\n return\n }\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n return\n }\n throw new Error(outcome.error)\n }\n l.connection = connection\n l.tools = watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = l.provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n })\n setToolsVersion((v) => v + 1)\n patch(name, {\n status: 'connected',\n catalog: connection.catalog,\n instructions: mcpInstructionsOf(connection, name),\n })\n } catch (err) {\n if (!current()) return\n patch(name, { status: 'error', error: err instanceof Error ? err.message : String(err) })\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const add = useCallback(\n async (input: McpServerSpec): Promise<string> => {\n let name = sanitize(input.name)\n // A different server under a taken name gets a suffix; the same URL replaces.\n const taken = specsRef.current.get(name)\n if (taken && taken.url !== input.url) {\n let n = 2\n while (specsRef.current.has(`${name}_${n}`)) n += 1\n name = `${name}_${n}`\n }\n const spec: StoredServer = {\n name,\n url: input.url,\n auth: input.auth ?? 'none',\n ...(input.oauth ? { oauth: input.oauth } : {}),\n }\n specsRef.current.set(name, spec)\n live(name).token = input.auth === 'bearer' ? input.token : undefined\n setServers((list) =>\n list.some((s) => s.name === name)\n ? list.map((s) => (s.name === name ? view(spec) : s))\n : [...list, view(spec)],\n )\n saveList()\n await connectServer(name)\n return name\n },\n [connectServer, saveList],\n )\n\n const remove = useCallback(\n async (name: string) => {\n await closeServer(name)\n liveRef.current.delete(name)\n specsRef.current.delete(name)\n saveList()\n setServers((list) => list.filter((s) => s.name !== name))\n },\n [closeServer, saveList],\n )\n\n const reconnect = useCallback(\n async (name: string, token?: string) => {\n if (token !== undefined) live(name).token = token\n await connectServer(name)\n },\n [connectServer],\n )\n\n const authorize = useCallback(\n (name: string) => {\n const url = servers.find((s) => s.name === name)?.authorizationUrl\n const spec = specsRef.current.get(name)\n if (!url || !spec || typeof globalThis.location === 'undefined') return\n // The redirect reloads the page: remember which server it is for. Written\n // here, at the user's click, so with several servers awaiting consent the\n // record always names the one actually being authorized.\n const pending: PendingRecord = {\n name,\n url: spec.url,\n redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),\n scope: spec.oauth?.scope,\n clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,\n clientMetadataUrl: spec.oauth?.clientMetadataUrl ?? optionsRef.current.clientMetadataUrl,\n startedAt: Date.now(),\n }\n writeRecord(pendingKey, pending)\n globalThis.location.href = url\n },\n [servers, pendingKey],\n )\n\n const forgetAuthorization = useCallback(\n async (name: string) => {\n const spec = specsRef.current.get(name)\n const l = liveRef.current.get(name)\n let provider = l?.provider\n if (!provider && spec?.auth === 'oauth') {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n try {\n provider = providerFor(mod, spec)\n } catch {\n // Options the core refuses never built a provider, so nothing was stored for them.\n }\n }\n }\n await provider?.reset().catch(() => {})\n if (l) l.provider = undefined\n const pending = readRecord<PendingRecord>(pendingKey)\n if (pending?.name === name) writeRecord(pendingKey, undefined)\n await closeServer(name)\n patch(name, {\n status: 'idle',\n authorizationUrl: undefined,\n catalog: [],\n instructions: undefined,\n error: undefined,\n })\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n // On mount: finish an OAuth round-trip that came back to this page, then\n // reconnect the remembered servers.\n useEffect(() => {\n unmountedRef.current = false\n // Synchronous up to the first await, like useMcp: another effect may\n // rewrite `location`, and StrictMode runs this twice.\n const callback = readCallbackParams()\n const pending = readRecord<PendingRecord>(pendingKey)\n const fresh = pending !== undefined && Date.now() - pending.startedAt < PENDING_TTL_MS\n const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback))\n if (callback && pending && !fresh) writeRecord(pendingKey, undefined)\n if (ours && typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n const autoConnect = optionsRef.current.autoConnect !== false\n void (async () => {\n if (ours && pending && callback) {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const spec = specsRef.current.get(pending.name) ?? {\n name: pending.name,\n url: pending.url,\n auth: 'oauth' as const,\n }\n if (!specsRef.current.has(spec.name)) {\n specsRef.current.set(spec.name, spec)\n setServers((list) => [...list, view(spec)])\n saveList()\n }\n const provider = providerFor(mod, {\n ...spec,\n oauth: {\n redirectUrl: pending.redirectUrl,\n scope: pending.scope,\n clientName: pending.clientName,\n clientMetadataUrl: pending.clientMetadataUrl,\n },\n })\n live(spec.name).provider = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(pendingKey, undefined)\n } catch (err) {\n writeRecord(pendingKey, undefined)\n patch(pending.name, {\n status: 'error',\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n setCompleting(false)\n if (autoConnect || ours) {\n await Promise.all(\n [...specsRef.current.keys()]\n .filter((name) => autoConnect || name === pending?.name)\n .map((name) => connectServer(name)),\n )\n }\n })()\n return () => {\n unmountedRef.current = true\n for (const name of liveRef.current.keys()) void closeServer(name)\n }\n // Runs once: the callbacks are stable and the redirect exists only on first load.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const tools = useMemo<AgentToolSet>(() => {\n const merged: AgentToolSet = {}\n for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools)\n return merged\n // toolsVersion is the change signal for the mutable map.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toolsVersion])\n\n const catalog = useMemo(\n () => servers.filter((s) => s.status === 'connected').flatMap((s) => s.catalog),\n [servers],\n )\n\n return {\n servers,\n tools,\n catalog,\n connectedCount: servers.filter((s) => s.status === 'connected').length,\n completingAuthorization,\n oauthSupported,\n checkOAuthSupport,\n add,\n remove,\n reconnect,\n authorize,\n forgetAuthorization,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAyD;AAkGlD,IAAM,oBAAoB,CAC/B,YACA,SACuB;AACvB,QAAM,OAAO,MAAM,QAAQ,WAAW,YAAY,IAAI,WAAW,eAAe,CAAC;AACjF,QAAM,OAAO,KAAK,KAAK,CAAC,MAAM,GAAG,WAAW,IAAI,GAAG;AACnD,SAAO,OAAO,SAAS,YAAY,KAAK,KA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AAO;AAAA,EACV;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,EAAE;AAAA,IAChE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/hooks/use-mcp.ts","../src/elicitation.ts","../src/hooks/use-mcp-servers.ts"],"sourcesContent":["// The MCP half of the bindings, behind its own subpath: `@dudko.dev/agent-web-react/mcp`.\n//\n// WHY THIS IS NOT IN THE MAIN ENTRY. `useMcp` loads the core's `./mcp` subpath with a dynamic\n// `import()`, and that was meant to keep `@modelcontextprotocol/client` — an optional peer — out of\n// the way of hosts that never use MCP. It does at RUNTIME. A bundler does not run anything: for a\n// dynamic import it must resolve the target at build time to emit a chunk, and the core's `mcp.js`\n// imports the SDK statically (and re-exports `UnauthorizedError` by identity, so that cannot be\n// made lazy). So a host that merely imported `useAgent` from the main entry got\n// \"Module not found: @modelcontextprotocol/client\" from webpack, with MCP nowhere in its code.\n//\n// A subpath moves the decision to the host, where it belongs: import from here and the SDK is\n// needed (and bundled); never import from here and no part of the build ever mentions it. This is\n// the same rule the core follows for its own `./mcp`.\nexport {\n useMcp,\n claimOAuthCallback,\n describeMcpResult,\n isUnauthorizedError,\n mcpAppsRouter,\n mcpInstructionsOf,\n mcpOAuthOptionsOfRecord,\n mcpOAuthProviderOptions,\n mcpOAuthRecordOf,\n mcpOAuthRegistrationOf,\n mcpProtocolOf,\n mcpSkillsSettingOf,\n newMcpOAuthProvider,\n readCallbackParams,\n stripOAuthParams,\n} from './hooks/use-mcp.js'\nexport type {\n McpConnectOptions,\n McpElicitationControls,\n McpOAuthOptions,\n McpOAuthRecord,\n McpSkillsSetting,\n McpStatus,\n UseMcpOptions,\n UseMcpReturn,\n} from './hooks/use-mcp.js'\nexport { useMcpServers } from './hooks/use-mcp-servers.js'\nexport type {\n McpAuthMode,\n McpServerSpec,\n McpServerView,\n UseMcpServersOptions,\n UseMcpServersReturn,\n} from './hooks/use-mcp-servers.js'\n// The queue behind `pendingElicitations` / `answerElicitation`, for a host that calls the core's\n// `connectMcpHttp` itself. (`<ElicitationPrompt>` and the form helpers are in the main entry.)\nexport {\n createElicitationQueue,\n elicitationConnectOptions,\n elicitationSettings,\n elicitationTimeoutOf,\n} from './elicitation.js'\nexport type {\n ElicitationQueue,\n ElicitationQueueOptions,\n PendingElicitation,\n} from './elicitation.js'\nexport type {\n BrowserOAuthProvider,\n BrowserOAuthProviderOptions,\n ConnectedMcp,\n McpCatalogEntry,\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n McpOAuthCallback,\n McpOAuthRegistration,\n McpOAuthRegistrationKind,\n McpProtocolMode,\n McpServerInstructions,\n McpServerProtocol,\n McpServerResult,\n McpModule,\n} from './mcp-types.js'\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { AgentToolSet, McpSkillConsent } from '@dudko.dev/agent-web'\nimport type { McpAppsConnectionLike } from './use-mcp-app-host.js'\nimport {\n createElicitationQueue,\n elicitationConnectOptions,\n elicitationSettings,\n elicitationTimeoutOf,\n type ElicitationQueue,\n type PendingElicitation,\n} from '../elicitation.js'\nimport type {\n BrowserOAuthProvider,\n BrowserOAuthProviderOptions,\n ConnectedMcp,\n McpCatalogEntry,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationResult,\n McpModule,\n McpOAuthCallback,\n McpOAuthRegistration,\n McpOAuthRegistrationKind,\n McpProtocolMode,\n McpServerProtocol,\n McpServerResult,\n} from '../mcp-types.js'\n\nexport type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error'\n\n/** The OAuth details of one server. Everything is optional. */\nexport interface McpOAuthOptions {\n /** Where the authorization server sends the user back (default: this page, without query or hash). */\n redirectUrl?: string\n /** Fallback scope when the server's metadata advertises none. */\n scope?: string\n /** `client_name` for dynamic registration (default: the hook's `clientName`). */\n clientName?: string\n /**\n * URL of a client ID metadata document (CIMD) your app hosts (default: the\n * hook's `clientMetadataUrl`). An authorization server that advertises\n * `client_id_metadata_document_supported` takes it as the `client_id` and no\n * dynamic registration is made; any other server is registered with as\n * before. Must be https with a non-root path, and the document must list the\n * `redirectUrl` in its `redirect_uris` - the core refuses anything else and\n * the server ends in `status: 'error'`. A core that does not know the option\n * ignores it and registers dynamically.\n */\n clientMetadataUrl?: string\n /**\n * How the client is registered with the server's authorization server:\n * `'auto'` (the default - the document where the server supports it, dynamic\n * registration otherwise), `'cimd'` (the document only: needs a\n * `clientMetadataUrl`, and a server without support ends in `status: 'error'`\n * before anything is sent to its registration endpoint) or `'dcr'` (dynamic\n * registration only, even with a `clientMetadataUrl`). Kept across the\n * redirect, and with the server list of `useMcpServers`. Left out, nothing is\n * passed. A core that does not know the option is refused for `'cimd'` /\n * `'dcr'` (it would register as it always did). Which way was taken is in\n * `oauthRegistration`.\n */\n registration?: McpOAuthRegistration\n}\n\nexport interface McpConnectOptions {\n /** The server's StreamableHTTP endpoint. */\n url: string\n /** Prefix for the discovered tool names (\"<name>__<tool>\"). Default 'mcp'. */\n name?: string\n /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */\n headers?: Record<string, string>\n /**\n * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core\n * that ships the OAuth provider; check `oauthSupported` before offering it.\n */\n oauth?: boolean | McpOAuthOptions\n /**\n * The MCP protocol revisions this connection may use: `'legacy'` the 2025 revisions,\n * `'auto'` 2026-07-28 when the server offers it and the 2025 ones otherwise (one probe\n * request; from a page the server's CORS must allow `Mcp-Method` and `Mcp-Name`, or the\n * probe is blocked and the connection falls back with a warning), `'modern'` 2026-07-28 only.\n * Left out, nothing is passed and the core decides (`'legacy'`). What was negotiated is in\n * the hook's `protocol`.\n */\n protocol?: McpProtocolMode\n /**\n * EXPERIMENTAL (the MCP Skills extension is Beta): load the skills the server serves into the\n * agent's skills catalog, as `<server>/<skill>` - they come with `tools`, so nothing else is\n * wired. Needs `protocol: 'auto'` or `'modern'`. Third-party text: the core loads it as\n * knowledge only, never policy, and - unless `{ consent: 'never' }` - only after a person\n * allowed it (`useAgent().pendingApprovals`, a request with `skill`). `true` or `{ consent }`\n * (see `McpSkillsSetting`). Left out, nothing is passed (off).\n */\n skills?: McpSkillsSetting\n}\n\n/**\n * `skills` on a server, as the hooks pass it on and remember it: `true`, or `{ consent }` -\n * `'once-per-skill'` (the core's default), `'ask'` or `'never'` (see the core's\n * `McpHttpServerConfig.skills`).\n */\nexport type McpSkillsSetting = true | { consent?: McpSkillConsent }\n\n/**\n * A `skills` value as the hooks take it - also from storage, so anything else is dropped: `true`,\n * an object with a known `consent` (or none: `true`), else `undefined` (off).\n */\nexport const mcpSkillsSettingOf = (value: unknown): McpSkillsSetting | undefined => {\n if (value === true) return true\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const consent = (value as { consent?: unknown }).consent\n return consent === 'ask' || consent === 'once-per-skill' || consent === 'never'\n ? { consent }\n : consent === undefined\n ? true\n : undefined\n}\n\nexport interface UseMcpOptions {\n /** Client name reported to the MCP server during initialize. */\n clientName?: string\n /**\n * URL of the client ID metadata document (CIMD) this app hosts, used for\n * every OAuth server unless its own `oauth.clientMetadataUrl` says otherwise.\n * See `McpOAuthOptions.clientMetadataUrl`.\n */\n clientMetadataUrl?: string\n /** Called with connector log lines — handy while debugging a server. */\n onLog?: (level: string, message: string) => void\n /**\n * MCP Apps: declare the extension and read the tools' apps (default false). The hook then\n * returns `apps` - pass it to `<AgentChat mcpApps>` - and a tool's results come with an app.\n * A tool for its app only is then not in `tools`. Needs a core with MCP Apps.\n */\n apps?: boolean\n /**\n * MCP elicitation: let a server ask the USER for input in the middle of a tool call - a\n * form, or (with `url: true`) a link to open. Off by default, and then nothing is passed to\n * the core: no capability is declared and the wire is what it was. `true` turns it on with\n * the core's defaults; an object is the core's `elicitation` settings (`url`, `timeoutMs`,\n * `maxPerToolCall`, `maxPerRun`, `subagents`). Questions land in `pendingElicitations`; show\n * them (`<ElicitationPrompt>`, or `<AgentChat elicitations>`) and answer with\n * `answerElicitation`. Read when a server connects: changing it takes a reconnect.\n */\n elicitation?: boolean | McpElicitationOptions\n}\n\n/**\n * A stable `McpAppsConnectionLike` for the hooks: each call reaches the connection the server is\n * on NOW (or says it is not connected), so it can be handed to `<AgentChat>` once.\n */\nexport const mcpAppsRouter = (\n connectionOf: (server: string) => ConnectedMcp | undefined,\n): McpAppsConnectionLike => {\n const appsOf = (server: string) => connectionOf(server)?.apps\n const notConnected = (server: string) => new Error(`the server “${server}” is not connected`)\n return {\n readUiResource: (server, uri, options) => {\n const apps = appsOf(server)\n return apps ? apps.readUiResource(server, uri, options) : Promise.reject(notConnected(server))\n },\n appTool: (server, name) => appsOf(server)?.appTool(server, name),\n readResource: (server, uri, options) => {\n const apps = appsOf(server)\n if (!apps) return Promise.reject(notConnected(server))\n // An older core has no such read: a linked file is refused, never fetched instead.\n if (!apps.readResource) {\n return Promise.reject(new Error('this version of the core cannot read a linked file'))\n }\n return apps.readResource(server, uri, options)\n },\n callAppTool: (server, name, args, options) => {\n const apps = appsOf(server)\n return apps\n ? apps.callAppTool(server, name, args, options)\n : Promise.reject(notConnected(server))\n },\n }\n}\n\n/** What both MCP hooks return for elicitation. */\nexport interface McpElicitationControls {\n /**\n * Questions servers are waiting on, oldest first (empty unless `elicitation` is on). Every\n * string in a request is the SERVER's text. A question leaves the list when it is answered,\n * when the core stops waiting (its time ran out, the run stopped), when its server is\n * disconnected and when the component unmounts - the last three answer `cancel`.\n */\n pendingElicitations: PendingElicitation[]\n /**\n * Answer a pending question: `{ action: 'accept', content }` (a form's values; no content\n * for a link), `{ action: 'decline' }` or `{ action: 'cancel' }`. The answer is handed to\n * the core and kept nowhere. False when no such question is waiting any more.\n */\n answerElicitation: (id: string, result: McpElicitationResult) => boolean\n}\n\nexport interface UseMcpReturn extends McpElicitationControls {\n status: McpStatus\n /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */\n tools?: AgentToolSet\n catalog: McpCatalogEntry[]\n /**\n * What the connected server told the agent in its handshake (its MCP `instructions`), when it\n * sent any. Third-party text that the core puts in the agent's system prompt: show it to the\n * user as the server's words, never as your own.\n */\n instructions?: string\n /**\n * The protocol revision negotiated with the connected server (`version`, `era`); absent\n * until it is connected, and on a core that does not report it.\n */\n protocol?: McpServerProtocol\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * How the OAuth client of the connected server was registered - `'cimd'`\n * (its client ID metadata document) or `'dcr'` (dynamic registration) - once\n * it is connected with OAuth, on a core that reports it.\n */\n oauthRegistration?: McpOAuthRegistrationKind\n /**\n * Whether the installed core exposes the OAuth API. `undefined` until the\n * optional subpath has been loaded once — call `checkOAuthSupport()` to\n * resolve it before offering OAuth in your UI.\n */\n oauthSupported?: boolean\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n connect: (options: McpConnectOptions) => Promise<void>\n disconnect: () => Promise<void>\n /** Navigate to the authorization server. Call it from a user gesture. */\n authorize: () => void\n /** Drop the stored tokens and dynamic registration for the current server. */\n forgetAuthorization: () => Promise<void>\n /** Load the optional subpath and report whether it can do OAuth. */\n checkOAuthSupport: () => Promise<boolean>\n /** MCP Apps of the connected server (with `apps: true`): pass it to `<AgentChat mcpApps>`. */\n apps?: McpAppsConnectionLike\n}\n\n/**\n * The instructions the server `name` sent, or undefined when it sent none (or the core is too\n * old to report them). The text is the server's, not the host's: show it as such.\n */\nexport const mcpInstructionsOf = (\n connection: Pick<ConnectedMcp, 'instructions'>,\n name: string,\n): string | undefined => {\n const list = Array.isArray(connection.instructions) ? connection.instructions : []\n const text = list.find((i) => i?.server === name)?.instructions\n return typeof text === 'string' && text.trim() ? text : undefined\n}\n\n/** What was negotiated with the server `name`, or undefined (not connected, or an older core). */\nexport const mcpProtocolOf = (\n connection: Pick<ConnectedMcp, 'protocols'>,\n name: string,\n): McpServerProtocol | undefined => {\n const list = Array.isArray(connection.protocols) ? connection.protocols : []\n const found = list.find((p) => p?.server === name)\n return found && typeof found.version === 'string'\n ? { server: name, version: found.version, era: found.era }\n : undefined\n}\n\n/**\n * The queue of questions behind both MCP hooks (`pendingElicitations`, `answerElicitation`),\n * and the handler they give the core when `elicitation` is on. Whatever is still waiting is\n * cancelled on unmount; a question that arrives after it is cancelled at once.\n */\nexport const useElicitationQueue = (optionsRef: {\n current: Pick<UseMcpOptions, 'elicitation'>\n}): McpElicitationControls & {\n handler: McpElicitationHandler\n /** Cancel the waiting questions: all, or one server's. */\n cancel: (server?: string) => void\n} => {\n const [pendingElicitations, setPending] = useState<PendingElicitation[]>([])\n const mountedRef = useRef(true)\n const queueRef = useRef<ElicitationQueue | undefined>(undefined)\n queueRef.current ??= createElicitationQueue({\n timeoutMs: () => {\n const settings = elicitationSettings(optionsRef.current.elicitation)\n return settings ? elicitationTimeoutOf(settings) : undefined\n },\n onChange: (pending) => {\n if (mountedRef.current) setPending(pending)\n },\n })\n const queue = queueRef.current\n const handler = useCallback<McpElicitationHandler>(\n (request, ctx) =>\n mountedRef.current ? queue.handler(request, ctx) : { action: 'cancel' as const },\n [queue],\n )\n const answerElicitation = useCallback(\n (id: string, result: McpElicitationResult) => queue.answer(id, result),\n [queue],\n )\n const cancel = useCallback(\n (server?: string) =>\n queue.cancel(server === undefined ? undefined : (request) => request.server === server),\n [queue],\n )\n useEffect(() => {\n // Set again on every mount: StrictMode unmounts and remounts once in development.\n mountedRef.current = true\n return () => {\n mountedRef.current = false\n queue.cancel()\n }\n }, [queue])\n return { pendingElicitations, answerElicitation, handler, cancel }\n}\n\nexport const OAUTH_UNSUPPORTED =\n 'The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.'\n\nconst PENDING_KEY = 'agent-web-react:mcp:pending'\nconst OAUTH_KEY = 'agent-web-react:mcp:oauth'\n\n/**\n * The OAuth details a redirect record keeps for one server - both hooks write one before the\n * user leaves for the authorization server, and build the provider and the reconnect from it\n * on the way back, so the client is the same both times.\n */\nexport interface McpOAuthRecord {\n redirectUrl: string\n scope?: string\n clientName?: string\n clientMetadataUrl?: string\n registration?: McpOAuthRegistration\n}\n\ninterface OAuthRecord extends McpOAuthRecord {\n url: string\n name?: string\n /** The protocol revisions the connection was asked for, kept across the redirect. */\n protocol?: McpProtocolMode\n /** `skills` was asked for (`true` or `{ consent }`), kept across the redirect. */\n skills?: McpSkillsSetting\n /** When the redirect was started, so a stale record can't claim a callback. */\n startedAt?: number\n}\n\n// A round-trip to an authorization server and back takes seconds. Anything\n// older than this is not the flow that produced the ?code= we are looking at —\n// most likely another sign-in on the same page — so we leave it alone.\nexport const PENDING_TTL_MS = 10 * 60 * 1000\n\nlet modulePromise: Promise<McpModule> | undefined\n\n/**\n * Load the core's optional `./mcp` subpath. Kept dynamic so apps that never\n * touch MCP don't pull `@modelcontextprotocol/client` into their bundle, and so a\n * core without the OAuth half degrades to a clear message instead of a crash.\n */\nexport const loadMcp = (): Promise<McpModule> => {\n modulePromise ??= import('@dudko.dev/agent-web/mcp')\n .then((m) => m as unknown as McpModule)\n .catch((err: unknown) => {\n // A rejected promise is neither null nor undefined, so ??= would cache\n // the failure forever — one flaky chunk fetch would kill MCP for the tab.\n modulePromise = undefined\n throw err\n })\n return modulePromise\n}\n\n/** Map a single server's connect outcome onto the hook's status. Pure. */\nexport const describeMcpResult = (\n result: McpServerResult | undefined,\n): { status: McpStatus; error?: string } => {\n if (!result) return { status: 'error', error: 'The connector returned no result for the server' }\n if (result.connected) return { status: 'connected' }\n if (result.needsAuthorization) return { status: 'needs-authorization' }\n return { status: 'error', error: result.error ?? 'Could not connect to the MCP server' }\n}\n\nconst OAUTH_PARAMS = ['code', 'state', 'error', 'error_description', 'iss']\n\n/**\n * Read the authorization-code parameters out of a URL **synchronously**.\n *\n * The core exports an equivalent, but it lives behind a dynamic import: by the\n * time that import resolves, React has flushed the rest of the app's effects,\n * and any one of them may have rewritten `location` (the demo's own view\n * router did exactly that). The callback has to be captured before the first\n * await, so this parser is duplicated here on purpose.\n *\n * Reads the query string and, for hash-routed apps, the fragment. Returns\n * undefined when neither a `code` nor an `error` is present.\n */\nexport const readCallbackParams = (href?: string): McpOAuthCallback | undefined => {\n const target =\n href ?? (typeof globalThis.location !== 'undefined' ? globalThis.location.href : undefined)\n if (!target) return undefined\n let url: URL\n try {\n url = new URL(target)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n // RFC 9207: the core's `finishMcpOAuth` checks it against the authorization\n // server the flow was started with, before the code is exchanged.\n iss: params.get('iss') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Remove the OAuth response parameters from a URL, leaving the rest intact —\n * query string and fragment alike. The code is single-use and lands in history,\n * referrers and screenshots, so it goes as soon as it has been read.\n */\nexport const stripOAuthParams = (href: string): string => {\n const url = new URL(href)\n for (const key of OAUTH_PARAMS) url.searchParams.delete(key)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n const params = new URLSearchParams(hash.slice(q + 1))\n for (const key of OAUTH_PARAMS) params.delete(key)\n const rest = params.toString()\n url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q)\n }\n return url.toString()\n}\n\n// An authorization code is single-use, and React StrictMode mounts every effect\n// twice in development. Claiming happens synchronously, before any await, so\n// the second pass cannot race the first into the token endpoint (where it would\n// lose the state check and report a CSRF failure on a perfectly good flow).\nconst claimedCallbacks = new Set<string>()\n\nexport const claimOAuthCallback = (callback: McpOAuthCallback): boolean => {\n const key = `${callback.code ?? ''}|${callback.state ?? ''}|${callback.error ?? ''}`\n if (claimedCallbacks.has(key)) return false\n claimedCallbacks.add(key)\n return true\n}\n\nexport const readRecord = <T>(key: string): T | undefined => {\n try {\n const raw = globalThis.localStorage?.getItem(key)\n return raw ? (JSON.parse(raw) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nexport const writeRecord = (key: string, value: unknown): void => {\n try {\n if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))\n else globalThis.localStorage?.removeItem(key)\n } catch {\n // Private mode / storage disabled: the OAuth round-trip simply won't\n // resume automatically, which the UI already handles.\n }\n}\n\n// A redirect_uri must not carry a fragment (RFC 6749 §3.1.2), and it has to\n// match the registered value byte-for-byte, so query and hash are dropped.\nexport const defaultRedirectUrl = (): string =>\n typeof globalThis.location === 'undefined'\n ? ''\n : `${globalThis.location.origin}${globalThis.location.pathname}`\n\n/**\n * The options of the core's OAuth provider for one server: the server's own\n * `oauth` details first, then the hook-level defaults (`clientName`,\n * `clientMetadataUrl`), then this page as the redirect. Pure - both hooks build\n * every provider through it, on connect, on the way back from the redirect and\n * when forgetting, so the three always describe the same client.\n */\nexport const mcpOAuthProviderOptions = (\n serverUrl: string,\n oauth: McpOAuthOptions = {},\n defaults: Pick<McpOAuthOptions, 'clientName' | 'clientMetadataUrl'> = {},\n): BrowserOAuthProviderOptions => {\n const clientMetadataUrl = oauth.clientMetadataUrl ?? defaults.clientMetadataUrl\n return {\n serverUrl,\n redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),\n clientName: oauth.clientName ?? defaults.clientName,\n scope: oauth.scope,\n // Left out when unset: a provider built without it keeps registering dynamically.\n ...(clientMetadataUrl !== undefined ? { clientMetadataUrl } : {}),\n // Left out when unset, too: the core's default is 'auto'.\n ...(oauth.registration !== undefined ? { registration: oauth.registration } : {}),\n }\n}\n\n/**\n * What a redirect record keeps of the options `mcpOAuthProviderOptions` resolved (the server's\n * URL is kept beside it). Pure; written as JSON, so an unset field is simply absent.\n */\nexport const mcpOAuthRecordOf = (resolved: BrowserOAuthProviderOptions): McpOAuthRecord => ({\n redirectUrl: resolved.redirectUrl,\n scope: resolved.scope,\n clientName: resolved.clientName,\n clientMetadataUrl: resolved.clientMetadataUrl,\n ...(resolved.registration !== undefined ? { registration: resolved.registration } : {}),\n})\n\n/**\n * The OAuth details read back from a redirect record on the way in: what the provider and the\n * reconnect are built with. Pure. `registration` is passed on as it was stored - a value the\n * core does not know is refused by the core, never read as \"auto\".\n */\nexport const mcpOAuthOptionsOfRecord = (record: McpOAuthRecord): McpOAuthOptions => ({\n redirectUrl: record.redirectUrl,\n scope: record.scope,\n clientName: record.clientName,\n clientMetadataUrl: record.clientMetadataUrl,\n ...(record.registration !== undefined ? { registration: record.registration } : {}),\n})\n\nexport const registrationUnsupported = (registration: McpOAuthRegistration): string =>\n `The installed @dudko.dev/agent-web does not support oauth.registration ('${registration}'): it would register as it always did. Upgrade the core, or leave registration out.`\n\n/**\n * The core's OAuth provider for one server. A `registration` other than `'auto'` needs a core\n * that knows it - an older one would ignore it and register the old way (a document under\n * `'dcr'`, a dynamic registration under `'cimd'`) - so that is refused here, before any request.\n */\nexport const newMcpOAuthProvider = (\n mod: McpModule,\n options: BrowserOAuthProviderOptions,\n): BrowserOAuthProvider => {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const provider = new mod.BrowserOAuthProvider(options)\n const asked = options.registration\n if (asked !== undefined && asked !== 'auto' && provider.registration !== asked) {\n throw new Error(registrationUnsupported(asked))\n }\n return provider\n}\n\n/**\n * How the provider's stored client was registered (`'cimd'` / `'dcr'`), read after a sign-in;\n * undefined without a provider, on a core that does not report it, or when the read fails.\n * Never throws: it is what the UI shows, not a check.\n */\nexport const mcpOAuthRegistrationOf = async (\n provider: BrowserOAuthProvider | undefined,\n): Promise<McpOAuthRegistrationKind | undefined> => {\n if (typeof provider?.registrationKind !== 'function') return undefined\n try {\n const kind = await provider.registrationKind()\n return kind === 'cimd' || kind === 'dcr' ? kind : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Did this error come from the server refusing our authorization?\n *\n * Never by the message: it would also match a tool whose own error text\n * mentions \"unauthorized\" — the connector throws a failing tool's text\n * verbatim. Three handles, in order:\n *\n * 1. the class the core's `./mcp` subpath re-exports. On the 2.x MCP SDK\n * (`@modelcontextprotocol/client`) `instanceof` goes by a brand the error\n * carries, not by prototype, so it also holds when the error was made by\n * another copy of the SDK than the one the core module resolved to (two\n * bundles, an ESM and a CJS build on one page);\n * 2. the error's own `name`, which the 2.x class sets to `'UnauthorizedError'`\n * (a string, so it survives a minifier; the 1.x class left it `'Error'`);\n * 3. `constructor.name`, for a core on the 1.x SDK that is too old to export\n * the class (and only where the bundle keeps class names).\n */\nexport const isUnauthorizedError = (err: unknown, mod?: McpModule): boolean => {\n if (!(err instanceof Error)) return false\n if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true\n if (err.name === 'UnauthorizedError') return true\n return err.constructor?.name === 'UnauthorizedError'\n}\n\n/**\n * Wrap each tool so a mid-session authorization failure is visible. Without\n * this the panel keeps reporting \"connected\" while every call fails: the core\n * refreshes silently on a 401, but once the refresh token is gone (revoked,\n * expired) it can only ask for a new authorization.\n */\nexport const watchAuthorization = (\n tools: AgentToolSet,\n mod: McpModule,\n onUnauthorized: () => void,\n): AgentToolSet => {\n const entries = Object.entries(tools as Record<string, unknown>).map(([name, value]) => {\n const tool = value as { execute?: (args: unknown, options: unknown) => unknown }\n if (typeof tool.execute !== 'function') return [name, value]\n const execute = tool.execute.bind(tool)\n const watched = (args: unknown, options: unknown): unknown => {\n // Deliberately not an async function: the AI SDK inspects what `execute`\n // returns SYNCHRONOUSLY to decide whether a tool streams (isAsyncIterable),\n // so wrapping everything in a promise would collapse a streaming tool into\n // a single opaque result.\n try {\n const out = execute(args, options)\n if (out && typeof (out as Promise<unknown>).then === 'function') {\n return (out as Promise<unknown>).then(undefined, (err: unknown) => {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n })\n }\n return out\n } catch (err) {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n }\n }\n return [name, { ...(value as object), execute: watched }]\n })\n return Object.fromEntries(entries) as AgentToolSet\n}\n\n/**\n * Connect the browser agent to a remote MCP server the user names at runtime —\n * static header, or full OAuth 2.1 with dynamic client registration.\n *\n * The OAuth round-trip leaves the page, so the hook persists what it needs to\n * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL\n * and reconnects, all before the app renders anything MCP-related.\n *\n * ```tsx\n * const mcp = useMcp()\n * // await mcp.connect({ url, oauth: true })\n * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>\n * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>\n * ```\n */\nexport const useMcp = (options: UseMcpOptions = {}): UseMcpReturn => {\n const [status, setStatus] = useState<McpStatus>('idle')\n const [tools, setTools] = useState<AgentToolSet | undefined>(undefined)\n const [catalog, setCatalog] = useState<McpCatalogEntry[]>([])\n const [instructions, setInstructions] = useState<string | undefined>(undefined)\n const [protocol, setProtocol] = useState<McpServerProtocol | undefined>(undefined)\n const [error, setError] = useState<string | undefined>(undefined)\n const [authorizationUrl, setAuthorizationUrl] = useState<string | undefined>(undefined)\n const [oauthRegistration, setOauthRegistration] = useState<McpOAuthRegistrationKind | undefined>(\n undefined,\n )\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompletingAuthorization] = useState(\n () => readCallbackParams() !== undefined,\n )\n\n const connectionRef = useRef<ConnectedMcp | undefined>(undefined)\n const providerRef = useRef<BrowserOAuthProvider | undefined>(undefined)\n // Bumped by every connect / disconnect / unmount. A handshake that finishes\n // after its epoch has passed closes itself instead of writing state or\n // leaking an open MCP session onto a dead component.\n const epochRef = useRef(0)\n // Options land in a ref so `connect` keeps a stable identity: it is a natural\n // dependency of effects in host components.\n const optionsRef = useRef(options)\n optionsRef.current = options\n const elicitation = useElicitationQueue(optionsRef)\n const cancelElicitations = elicitation.cancel\n\n const closeConnection = useCallback(async () => {\n const open = connectionRef.current\n connectionRef.current = undefined\n // Nobody is left to take the answers of a connection that is being closed.\n cancelElicitations()\n if (open) await open.close().catch(() => {})\n }, [cancelElicitations])\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n const connect = useCallback(\n async (opts: McpConnectOptions) => {\n const epoch = ++epochRef.current\n const current = () => epochRef.current === epoch\n await closeConnection()\n if (!current()) return\n setStatus('connecting')\n setError(undefined)\n setAuthorizationUrl(undefined)\n setOauthRegistration(undefined)\n setTools(undefined)\n setCatalog([])\n setInstructions(undefined)\n setProtocol(undefined)\n\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n const name = opts.name ?? 'mcp'\n let authProvider: BrowserOAuthProvider | undefined\n\n if (opts.oauth) {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const providerOptions = mcpOAuthProviderOptions(\n opts.url,\n typeof opts.oauth === 'object' ? opts.oauth : {},\n optionsRef.current,\n )\n const record: OAuthRecord = {\n url: opts.url,\n name,\n ...mcpOAuthRecordOf(providerOptions),\n ...(opts.protocol ? { protocol: opts.protocol } : {}),\n ...(mcpSkillsSettingOf(opts.skills) ? { skills: mcpSkillsSettingOf(opts.skills) } : {}),\n startedAt: Date.now(),\n }\n // Throws on a clientMetadataUrl or registration the core refuses (not\n // https, a bare origin, 'cimd' without a document, a core that does not\n // know the option): reported below as this server's error, before any request.\n authProvider = newMcpOAuthProvider(mod, providerOptions)\n providerRef.current = authProvider\n // `pending` resumes the redirect; `oauth` outlives it so tokens stay\n // addressable for forgetAuthorization() after a reload.\n writeRecord(PENDING_KEY, record)\n writeRecord(OAUTH_KEY, record)\n } else {\n providerRef.current = undefined\n }\n\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: opts.url,\n headers: opts.oauth ? undefined : opts.headers,\n authProvider,\n // Only when asked for: without it the connection is built as it always was.\n ...(opts.protocol ? { protocol: opts.protocol } : {}),\n ...(mcpSkillsSettingOf(opts.skills)\n ? { skills: mcpSkillsSettingOf(opts.skills) }\n : {}),\n },\n },\n {\n clientName: optionsRef.current.clientName,\n onLog: optionsRef.current.onLog,\n ...(optionsRef.current.apps ? { apps: true } : {}),\n // Off: neither key is passed, so the core declares no capability.\n ...elicitationConnectOptions(optionsRef.current.elicitation, elicitation.handler),\n },\n )\n\n if (!current()) {\n // Unmounted, or another connect started while we were shaking hands.\n await connection.close().catch(() => {})\n return\n }\n\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = authProvider?.authorizationUrl\n setAuthorizationUrl(url ? String(url) : undefined)\n setStatus('needs-authorization')\n return\n }\n throw new Error(outcome.error)\n }\n\n connectionRef.current = connection\n // The round-trip is over: a stale record would later make an unrelated\n // ?code= on this page look like ours.\n writeRecord(PENDING_KEY, undefined)\n setTools(\n watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = providerRef.current?.authorizationUrl\n if (url) setAuthorizationUrl(String(url))\n setStatus('needs-authorization')\n }),\n )\n setCatalog(connection.catalog)\n setInstructions(mcpInstructionsOf(connection, name))\n setProtocol(mcpProtocolOf(connection, name))\n const registered = await mcpOAuthRegistrationOf(authProvider)\n if (!current()) return\n setOauthRegistration(registered)\n setStatus('connected')\n } catch (err) {\n if (!current()) return\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n }\n },\n [closeConnection, elicitation.handler],\n )\n\n const disconnect = useCallback(async () => {\n epochRef.current++\n await closeConnection()\n setTools(undefined)\n setCatalog([])\n setInstructions(undefined)\n setProtocol(undefined)\n setAuthorizationUrl(undefined)\n setOauthRegistration(undefined)\n setError(undefined)\n setStatus('idle')\n }, [closeConnection])\n\n const authorize = useCallback(() => {\n if (authorizationUrl && typeof globalThis.location !== 'undefined') {\n globalThis.location.href = authorizationUrl\n }\n }, [authorizationUrl])\n\n const forgetAuthorization = useCallback(async () => {\n const record = readRecord<OAuthRecord>(OAUTH_KEY)\n writeRecord(PENDING_KEY, undefined)\n writeRecord(OAUTH_KEY, undefined)\n // After a reload there is no live provider, but the tokens are still in the\n // vault — rebuild one for the same server so \"forget\" actually forgets\n // rather than only resetting the UI.\n let provider = providerRef.current\n if (!provider && record) {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n try {\n provider = new mod.BrowserOAuthProvider(mcpOAuthProviderOptions(record.url, record))\n } catch {\n // Options the core refuses never built a provider, so nothing was stored for them.\n }\n }\n }\n await provider?.reset().catch(() => {})\n providerRef.current = undefined\n await disconnect()\n }, [disconnect])\n\n // Resume an OAuth round-trip: the authorization server has just sent the user\n // back with ?code=… and this component is mounting for the first time.\n useEffect(() => {\n // Everything up to the first await runs synchronously, on purpose: React\n // flushes the remaining passive effects (which may rewrite location) before\n // an awaited continuation resumes, and StrictMode runs this effect twice.\n const callback = readCallbackParams()\n if (!callback) {\n setCompletingAuthorization(false)\n return\n }\n const pending = readRecord<OAuthRecord>(PENDING_KEY)\n // A record only proves that WE started a flow, not that THIS callback is\n // its answer — so an expired one is treated as somebody else's. Either way\n // the URL is left exactly as we found it: another sign-in flow on this page\n // may still need those parameters.\n const fresh =\n pending !== undefined &&\n (pending.startedAt === undefined || Date.now() - pending.startedAt < PENDING_TTL_MS)\n if (!pending || !fresh) {\n if (pending) writeRecord(PENDING_KEY, undefined)\n setCompletingAuthorization(false)\n return\n }\n if (!claimOAuthCallback(callback)) {\n setCompletingAuthorization(false)\n return\n }\n // Ours, and claimed: the code is in hand, so clear it from the address bar\n // now rather than after the reconnect.\n if (typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n\n void (async () => {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const oauth = mcpOAuthOptionsOfRecord(pending)\n const provider = newMcpOAuthProvider(mod, mcpOAuthProviderOptions(pending.url, oauth))\n providerRef.current = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(PENDING_KEY, undefined)\n // NOT gated on `cancelled`. StrictMode's simulated cleanup sets it in\n // development, and the second setup cannot take over — the code has\n // already been claimed and stripped from the URL — so bailing here\n // would finish the authorization and then never connect. `connect` is\n // epoch-guarded and a setState after a real unmount is a no-op, so\n // letting it run is safe either way.\n //\n // Hand back to `connect`, which owns the status from here — a slow or\n // hung handshake must not leave the UI stuck on \"finishing\".\n setCompletingAuthorization(false)\n // With the details the flow was started with: the same redirect, scope,\n // client name, client ID metadata document and registration, not the\n // hook's defaults.\n await connect({\n url: pending.url,\n name: pending.name,\n oauth,\n ...(pending.protocol ? { protocol: pending.protocol } : {}),\n ...(mcpSkillsSettingOf(pending.skills)\n ? { skills: mcpSkillsSettingOf(pending.skills) }\n : {}),\n })\n } catch (err) {\n writeRecord(PENDING_KEY, undefined)\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n } finally {\n setCompletingAuthorization(false)\n }\n })()\n // Runs once: `connect` is stable and the callback exists only on first load.\n }, [connect])\n\n useEffect(\n () => () => {\n epochRef.current++\n void closeConnection()\n },\n [closeConnection],\n )\n\n const appsOn = options.apps === true\n const apps = useMemo(\n () => (appsOn ? mcpAppsRouter(() => connectionRef.current) : undefined),\n [appsOn],\n )\n\n return {\n apps,\n status,\n tools,\n catalog,\n instructions,\n protocol,\n error,\n authorizationUrl,\n oauthRegistration,\n oauthSupported,\n completingAuthorization,\n pendingElicitations: elicitation.pendingElicitations,\n answerElicitation: elicitation.answerElicitation,\n connect,\n disconnect,\n authorize,\n forgetAuthorization,\n checkOAuthSupport,\n }\n}\n","import type {\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './mcp-types.js'\n\n/**\n * MCP elicitation, the part of it that is not React: what a field of a server's form is drawn\n * as, what the user typed turned into the answer, the checks an answer must pass before it is\n * sent (the core's own rules, so the form says what is wrong instead of the tool call failing),\n * what a link may be opened as, and the queue of questions waiting for the user.\n *\n * Pure, and free of the MCP SDK and of the core's `./mcp` subpath: the prompt is in the main\n * entry of this package, the hooks that fill the queue are in `./mcp`.\n *\n * Nothing here keeps, logs or returns a value the user entered except to the one caller that\n * hands it to the server: an issue names the field and the rule, never the value.\n */\n\n// ── a question waiting for the user ──────────────────────────────────────\n\n/**\n * A question waiting for the user: the core's request (every string in it is the SERVER's\n * text), and when the core will stop waiting for the answer.\n */\nexport interface PendingElicitation extends McpElicitationRequest {\n /** Epoch ms after which the core cancels the question by itself; absent when it has no limit. */\n expiresAt?: number\n}\n\n/** The core's default for `elicitation.timeoutMs` (`MCP_ELICITATION_TIMEOUT_MS`). */\nexport const ELICITATION_TIMEOUT_MS = 300_000\n\n/**\n * The hooks' `elicitation` option as the core's settings, or `undefined` when it is off - and\n * then NOTHING is passed to the core: no capability is declared and the wire is what it was.\n */\nexport const elicitationSettings = (\n option: boolean | McpElicitationOptions | undefined | null,\n): McpElicitationOptions | undefined => {\n if (option === true) return {}\n if (typeof option === 'object' && option !== null) return { ...option }\n return undefined\n}\n\n/**\n * What the hooks add to the options of the core's `connectMcpHttp`: the handler and the\n * settings when elicitation is on, and NOTHING - not even the keys - when it is off.\n */\nexport const elicitationConnectOptions = (\n option: boolean | McpElicitationOptions | undefined | null,\n handler: McpElicitationHandler,\n): { onElicitation?: McpElicitationHandler; elicitation?: McpElicitationOptions } => {\n const settings = elicitationSettings(option)\n return settings ? { onElicitation: handler, elicitation: settings } : {}\n}\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n/**\n * How long the core waits for an answer with these settings; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const elicitationTimeoutOf = (settings: McpElicitationOptions): number | undefined => {\n const raw = settings.timeoutMs\n if (raw === undefined || raw === null) return ELICITATION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\nexport interface ElicitationQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read\n * when a question arrives (the settings of the connection that is open then).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of pending questions changed. */\n onChange?: (pending: PendingElicitation[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface ElicitationQueue {\n /** The core's `onElicitation`: resolves when the user answers, or as `cancel`. */\n handler: McpElicitationHandler\n /** The questions waiting, oldest first. */\n pending: () => PendingElicitation[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, result: McpElicitationResult) => boolean\n /** Cancel the waiting questions - all of them, or those `match` picks (one server's). */\n cancel: (match?: (request: PendingElicitation) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is cancelled at once. */\n dispose: () => void\n}\n\n/**\n * The questions MCP servers are waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the user, cancelled because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (a disconnect, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createElicitationQueue = (options: ElicitationQueueOptions = {}): ElicitationQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { request: PendingElicitation; settle: (result: McpElicitationResult) => void }\n >()\n let disposed = false\n\n const list = (): PendingElicitation[] => [...waiting.values()].map((w) => w.request)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: McpElicitationHandler = (request, ctx) =>\n new Promise<McpElicitationResult>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, or nobody wants the answer any more.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve({ action: 'cancel' })\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle({ action: 'cancel' })\n changed()\n }\n const settle = (result: McpElicitationResult): void => {\n // Exactly once: a second answer to the same question finds nothing to resolve.\n if (waiting.get(request.id)?.settle !== settle) return\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n request: {\n ...request,\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, result) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(result)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.request)) continue\n entry.settle({ action: 'cancel' })\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle({ action: 'cancel' })\n },\n }\n}\n\n// ── a form: fields, values, the answer ───────────────────────────────────\n\n/** What a field is drawn as. */\nexport type ElicitationControl =\n 'text' | 'email' | 'url' | 'date' | 'datetime' | 'number' | 'checkbox' | 'select' | 'multiselect'\n\nexport interface ElicitationOption {\n /** What goes back to the server, verbatim. */\n value: string\n /** What the user reads (the option's title, or the value). */\n label: string\n}\n\n/** One field of a form, ready to draw. `label`, `description` and option labels are the server's text. */\nexport interface ElicitationField {\n name: string\n label: string\n description?: string\n required: boolean\n control: ElicitationControl\n /** `select` / `multiselect`. */\n options?: ElicitationOption[]\n schema: McpElicitationFieldSchema\n}\n\n/** What the form holds while it is being filled in: text as typed, a tick, the ticked options. */\nexport type ElicitationDraftValue = string | boolean | string[]\nexport type ElicitationDraft = Record<string, ElicitationDraftValue>\n\nconst titled = (options: { const: string; title: string }[]): ElicitationOption[] =>\n options.map((o) => ({ value: o.const, label: o.title || o.const }))\n\n/** The options of a select, in the three forms the core lets through. */\nconst optionsOf = (schema: McpElicitationFieldSchema): ElicitationOption[] | undefined => {\n if (schema.type === 'array') {\n const items = schema.items\n if (items?.anyOf) return titled(items.anyOf)\n return (items?.enum ?? []).map((value) => ({ value, label: value }))\n }\n if (schema.type !== 'string') return undefined\n if (schema.oneOf) return titled(schema.oneOf)\n if (schema.enum) {\n const names = schema.enumNames\n return schema.enum.map((value, i) => ({ value, label: names?.[i] || value }))\n }\n return undefined\n}\n\nconst controlOf = (schema: McpElicitationFieldSchema): ElicitationControl => {\n switch (schema.type) {\n case 'boolean':\n return 'checkbox'\n case 'number':\n case 'integer':\n return 'number'\n case 'array':\n return 'multiselect'\n default:\n if (schema.enum || schema.oneOf) return 'select'\n switch (schema.format) {\n case 'email':\n return 'email'\n case 'uri':\n return 'url'\n case 'date':\n return 'date'\n case 'date-time':\n return 'datetime'\n default:\n return 'text'\n }\n }\n}\n\n/**\n * The fields of a form in the order the server listed them - exactly the set the core's schema\n * guard lets through: a text (plain, email, uri, date, date-time), a number / integer, a\n * boolean, a single select (`enum`, `enum` + `enumNames`, `oneOf`) and a multi-select (an array\n * of `enum` or `anyOf` options).\n */\nexport const elicitationFields = (schema: McpElicitationSchema | undefined): ElicitationField[] => {\n const required = new Set(schema?.required ?? [])\n return Object.entries(schema?.properties ?? {}).map(([name, field]) => {\n const options = optionsOf(field)\n return {\n name,\n label: field.title || name,\n ...(field.description ? { description: field.description } : {}),\n required: required.has(name),\n control: controlOf(field),\n ...(options ? { options } : {}),\n schema: field,\n }\n })\n}\n\nconst pad = (n: number): string => String(n).padStart(2, '0')\n\n// A date-time default as `<input type=\"datetime-local\">` wants it (local time, to the minute).\nconst toLocalInput = (value: string): string => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return ''\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/** What the form starts with: the schema's defaults (the core dropped the ones that do not fit). */\nexport const elicitationInitialDraft = (\n schema: McpElicitationSchema | undefined,\n): ElicitationDraft => {\n const draft: ElicitationDraft = {}\n for (const field of elicitationFields(schema)) {\n const preset = field.schema.default\n switch (field.control) {\n case 'checkbox':\n draft[field.name] = preset === true\n break\n case 'multiselect':\n draft[field.name] = Array.isArray(preset) ? [...preset] : []\n break\n case 'number':\n draft[field.name] = typeof preset === 'number' ? String(preset) : ''\n break\n case 'datetime':\n draft[field.name] = typeof preset === 'string' ? toLocalInput(preset) : ''\n break\n default:\n draft[field.name] = typeof preset === 'string' ? preset : ''\n }\n }\n return draft\n}\n\n/** The rules an answer can break. An issue never carries the value. */\nexport type ElicitationIssueKind =\n | 'required'\n | 'tooShort'\n | 'tooLong'\n | 'email'\n | 'uri'\n | 'date'\n | 'dateTime'\n | 'notNumber'\n | 'notInteger'\n | 'belowMinimum'\n | 'aboveMaximum'\n | 'notAnOption'\n | 'tooFew'\n | 'tooMany'\n\nexport interface ElicitationIssue {\n kind: ElicitationIssueKind\n /** The limit the rule states (a length, a bound, a count), when it has one. */\n limit?: number\n}\n\n/** The longest text a field without its own `maxLength` takes (the core's cap). */\nexport const ELICITATION_VALUE_MAX_CHARS = 10_000\n/** The most options one multi-select may be answered with (the core's cap). */\nexport const ELICITATION_MAX_OPTIONS = 100\n\n// A number as a person types it: digits, a sign, a decimal point, an exponent. `Number('')` is\n// 0 and `Number(' 1 ')` is 1, so the text is checked first.\nconst NUMBER = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?$/i\n\nconst numberOf = (text: string): number | undefined => {\n const trimmed = text.trim()\n if (!NUMBER.test(trimmed)) return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n}\n\n// The core's `validFormat`, rule for rule.\nconst formatIssue = (\n format: McpElicitationFieldSchema['format'],\n value: string,\n): ElicitationIssueKind | undefined => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value) ? undefined : 'email'\n case 'uri':\n try {\n return new URL(value) ? undefined : 'uri'\n } catch {\n return 'uri'\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'date'\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n ? undefined\n : 'dateTime'\n default:\n return undefined\n }\n}\n\n// A date-time goes back as RFC 3339 with its offset (UTC): the input's value is local time\n// without one, which a server could read as any zone.\nconst dateTimeOf = (value: string): string => {\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? value : date.toISOString()\n}\n\ntype FieldAnswer =\n { issue: ElicitationIssue } | { value: string | number | boolean | string[] } | { empty: true }\n\n// One field: its value as the server gets it, why it does not fit, or \"left empty\".\nconst answerOf = (field: ElicitationField, raw: ElicitationDraftValue | undefined): FieldAnswer => {\n const { schema } = field\n switch (field.control) {\n case 'checkbox':\n // A tick box always has a value: unticked is `false`, which is an answer.\n return { value: raw === true }\n case 'multiselect': {\n const picked = Array.isArray(raw) ? raw : []\n // Nothing ticked in an optional list is \"not answered\", as an empty text is.\n if (picked.length === 0 && !field.required) return { empty: true }\n const allowed = new Set((field.options ?? []).map((o) => o.value))\n if (!picked.every((item) => allowed.has(item))) return { issue: { kind: 'notAnOption' } }\n if (schema.minItems !== undefined && picked.length < schema.minItems) {\n return { issue: { kind: 'tooFew', limit: schema.minItems } }\n }\n const max = Math.min(schema.maxItems ?? ELICITATION_MAX_OPTIONS, ELICITATION_MAX_OPTIONS)\n if (picked.length > max) return { issue: { kind: 'tooMany', limit: max } }\n return { value: [...picked] }\n }\n case 'number': {\n const text = typeof raw === 'string' ? raw.trim() : ''\n if (!text) return { empty: true }\n const n = numberOf(text)\n if (n === undefined) return { issue: { kind: 'notNumber' } }\n if (schema.type === 'integer' && !Number.isInteger(n)) {\n return { issue: { kind: 'notInteger' } }\n }\n if (schema.minimum !== undefined && n < schema.minimum) {\n return { issue: { kind: 'belowMinimum', limit: schema.minimum } }\n }\n if (schema.maximum !== undefined && n > schema.maximum) {\n return { issue: { kind: 'aboveMaximum', limit: schema.maximum } }\n }\n return { value: n }\n }\n case 'select': {\n const text = typeof raw === 'string' ? raw : ''\n if (!text) return { empty: true }\n return (field.options ?? []).some((o) => o.value === text)\n ? { value: text }\n : { issue: { kind: 'notAnOption' } }\n }\n default: {\n const typed = typeof raw === 'string' ? raw : ''\n if (!typed) return { empty: true }\n const text = field.control === 'datetime' ? dateTimeOf(typed) : typed\n const max = schema.maxLength ?? ELICITATION_VALUE_MAX_CHARS\n if (text.length > max) return { issue: { kind: 'tooLong', limit: max } }\n if (schema.minLength !== undefined && text.length < schema.minLength) {\n return { issue: { kind: 'tooShort', limit: schema.minLength } }\n }\n const format = formatIssue(schema.format, text)\n return format ? { issue: { kind: format } } : { value: text }\n }\n }\n}\n\nexport type ElicitationFormOutcome =\n | { ok: true; content: Record<string, string | number | boolean | string[]> }\n | { ok: false; issues: Record<string, ElicitationIssue> }\n\n/**\n * A filled-in form as the answer the core will accept, or what is wrong with it, per field. The\n * rules are the core's (`validateMcpElicitationContent`): a required field is there, every\n * value is of its field's type and within its limits, and nothing the form did not ask for is\n * sent. A field left empty is left out, not sent as an empty text.\n */\nexport const elicitationFormAnswer = (\n schema: McpElicitationSchema | undefined,\n draft: ElicitationDraft,\n): ElicitationFormOutcome => {\n const content: Record<string, string | number | boolean | string[]> = {}\n const issues: Record<string, ElicitationIssue> = {}\n for (const field of elicitationFields(schema)) {\n const answer = answerOf(field, Object.hasOwn(draft, field.name) ? draft[field.name] : undefined)\n if ('issue' in answer) {\n issues[field.name] = answer.issue\n } else if ('empty' in answer) {\n if (field.required) issues[field.name] = { kind: 'required' }\n } else {\n content[field.name] = answer.value\n }\n }\n return Object.keys(issues).length > 0 ? { ok: false, issues } : { ok: true, content }\n}\n\n// ── a link ───────────────────────────────────────────────────────────────\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\nexport interface ElicitationLink {\n /** The host the link leads to (with its port), as the browser will resolve it; '' if unparseable. */\n host: string\n /** The whole link as text: the parsed form when it parses, what the server sent otherwise. */\n href: string\n /** Whether an \"Open\" action may exist for it: https, or http on a loopback host, no credentials. */\n openable: boolean\n}\n\n/**\n * A link a server wants the user to open, as the prompt may show it. The core already refuses\n * anything but https (http on loopback); this is the same rule applied again where the link is\n * about to be opened, because a host may hand the prompt a request the core never checked.\n */\nexport const elicitationLink = (raw: unknown): ElicitationLink => {\n const text = typeof raw === 'string' ? raw : ''\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return { host: '', href: text, openable: false }\n }\n const secure =\n url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n return {\n host: url.host,\n href: url.href,\n openable: secure && !url.username && !url.password && !/\\s/.test(text),\n }\n}\n\n// ── an answer nobody gave ────────────────────────────────────────────────\n\n/**\n * Why a question was answered without anybody deciding: the core's reasons\n * (`mcp.elicitation-answered` with `automatic: true`), and `stopped`, which the reducer sets on\n * whatever was still waiting when the run stopped.\n */\nexport type ElicitationOutcomeReason =\n | 'timeout'\n | 'step-timeout'\n | 'aborted'\n | 'stopped'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'handler-error'\n | 'invalid-answer'\n | 'after-failure'\n | 'no-tool-call'\n\n/** \"4:05\" - what is left of a question's time. */\nexport const formatCountdown = (ms: number): string => {\n const total = Math.max(0, Math.ceil(ms / 1000))\n return `${Math.floor(total / 60)}:${pad(total % 60)}`\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { AgentToolSet } from '@dudko.dev/agent-web'\nimport { elicitationConnectOptions } from '../elicitation.js'\nimport type {\n BrowserOAuthProvider,\n ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n McpOAuthRegistrationKind,\n McpProtocolMode,\n McpServerProtocol,\n} from '../mcp-types.js'\nimport type { McpAppsConnectionLike } from './use-mcp-app-host.js'\nimport {\n claimOAuthCallback,\n describeMcpResult,\n loadMcp,\n mcpAppsRouter,\n mcpInstructionsOf,\n mcpOAuthOptionsOfRecord,\n mcpOAuthProviderOptions,\n mcpOAuthRecordOf,\n mcpOAuthRegistrationOf,\n mcpProtocolOf,\n mcpSkillsSettingOf,\n newMcpOAuthProvider,\n OAUTH_UNSUPPORTED,\n PENDING_TTL_MS,\n readCallbackParams,\n readRecord,\n stripOAuthParams,\n useElicitationQueue,\n watchAuthorization,\n writeRecord,\n type McpElicitationControls,\n type McpOAuthOptions,\n type McpOAuthRecord,\n type McpSkillsSetting,\n type McpStatus,\n type UseMcpOptions,\n} from './use-mcp.js'\n\nexport type McpAuthMode = 'none' | 'bearer' | 'oauth'\n\n/** One server the user wants connected. */\nexport interface McpServerSpec {\n /**\n * Unique name; also the tool prefix (\"<name>__<tool>\"). Sanitised to\n * `[a-zA-Z0-9_-]`; a taken name gets a numeric suffix.\n */\n name: string\n /** The server's StreamableHTTP endpoint. */\n url: string\n auth?: McpAuthMode\n /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */\n token?: string\n /**\n * OAuth details for `auth: 'oauth'` (`clientMetadataUrl` for CIMD and `registration` among\n * them). Remembered with the server.\n */\n oauth?: McpOAuthOptions\n /**\n * The MCP protocol revisions this connection may use (`'legacy'` / `'auto'` / `'modern'`,\n * see `McpConnectOptions.protocol`). Remembered with the server. Left out, nothing is passed\n * and the core decides (`'legacy'`).\n */\n protocol?: McpProtocolMode\n /**\n * EXPERIMENTAL: load the server's skills into the agent's catalog, as `<server>/<skill>` (see\n * `McpConnectOptions.skills`; needs `protocol: 'auto'` or `'modern'`): `true`, or\n * `{ consent }`. Remembered with the server. Left out, nothing is passed (off).\n */\n skills?: McpSkillsSetting\n /**\n * MCP Apps for this server: `false` keeps its apps off while other servers' are shown (nothing\n * is declared to it, no app of it is read, its app-only tools are hidden from everyone and its\n * other tools are the model's, as plain tools); `true` shows them even when the hook's `apps`\n * is off. Remembered with the server. Left out, the hook's `apps` decides.\n */\n apps?: boolean\n}\n\n/** A server's live state. */\nexport interface McpServerView {\n name: string\n url: string\n auth: McpAuthMode\n /** The protocol revisions the server was added with, when it was given any. */\n protocolMode?: McpProtocolMode\n /** It was added with `skills` (as given): its skills (if it serves any) are in the catalog. */\n skills?: McpSkillsSetting\n /** It was added with `apps` set (`false`: its apps are off; absent: the hook's `apps`). */\n apps?: boolean\n /** What was negotiated (`version`, `era`), while it is connected and the core reports it. */\n protocol?: Omit<McpServerProtocol, 'server'>\n status: McpStatus\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * How its OAuth client was registered - `'cimd'` (the client ID metadata document) or `'dcr'`\n * (dynamic registration) - while it is connected with OAuth, on a core that reports it.\n */\n oauthRegistration?: McpOAuthRegistrationKind\n catalog: McpCatalogEntry[]\n /**\n * What the server told the agent in its handshake (its MCP `instructions`), while it is\n * connected and if it sent any. Third-party text that the core puts in the agent's system\n * prompt: show it to the user as the server's words.\n */\n instructions?: string\n}\n\nexport interface UseMcpServersOptions extends UseMcpOptions {\n /**\n * Remember the server list (never tokens) in localStorage so it survives a\n * reload — and the OAuth redirect, which IS a reload (default true).\n */\n persist?: boolean\n /** localStorage key of the list (default 'agent-web-react:mcp-servers'). */\n storageKey?: string\n /** Reconnect remembered servers on mount (default true). Bearer servers wait for their token. */\n autoConnect?: boolean\n /** Per-server connect deadline in ms (default: the core's, 30 s). */\n connectTimeoutMs?: number\n}\n\nexport interface UseMcpServersReturn extends McpElicitationControls {\n servers: McpServerView[]\n /** Tools of every connected server, merged — pass to `BrowserAgentConfig.tools`. */\n tools: AgentToolSet\n /** Catalogue of every connected server, merged. */\n catalog: McpCatalogEntry[]\n /** The protocol revision negotiated with each connected server (cores that report it). */\n protocols: McpServerProtocol[]\n connectedCount: number\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n /** Whether the installed core can do OAuth (undefined until checked). */\n oauthSupported?: boolean\n checkOAuthSupport: () => Promise<boolean>\n /** Add (or replace, by name) a server and connect it. Resolves with the final name. */\n add: (spec: McpServerSpec) => Promise<string>\n /** Disconnect and forget a server. */\n remove: (name: string) => Promise<void>\n /** Connect again — optionally with a fresh bearer token. */\n reconnect: (name: string, token?: string) => Promise<void>\n /** Navigate to the server's authorization page. Call it from a user gesture. */\n authorize: (name: string) => void\n /** Drop a server's stored OAuth tokens and registration. */\n forgetAuthorization: (name: string) => Promise<void>\n /**\n * MCP Apps of every connected server (with `apps: true`): pass it to `<AgentChat mcpApps>`.\n * Each call goes to the server it names, on the connection it has now.\n */\n apps?: McpAppsConnectionLike\n}\n\ninterface StoredServer {\n name: string\n url: string\n auth: McpAuthMode\n oauth?: McpServerSpec['oauth']\n protocol?: McpProtocolMode\n skills?: McpSkillsSetting\n apps?: boolean\n}\n\ninterface PendingRecord extends McpOAuthRecord {\n name: string\n url: string\n startedAt: number\n}\n\ninterface Live {\n epoch: number\n connection?: ConnectedMcp\n provider?: BrowserOAuthProvider\n tools?: AgentToolSet\n token?: string\n}\n\nconst DEFAULT_KEY = 'agent-web-react:mcp-servers'\n\nconst sanitize = (s: string): string => s.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 32) || 'mcp'\n\n// The remembered list is read from localStorage: anything but the three names is dropped.\nconst isProtocolMode = (value: unknown): value is McpProtocolMode =>\n value === 'legacy' || value === 'auto' || value === 'modern'\n\nconst view = (s: StoredServer, patch: Partial<McpServerView> = {}): McpServerView => ({\n name: s.name,\n url: s.url,\n auth: s.auth,\n ...(isProtocolMode(s.protocol) ? { protocolMode: s.protocol } : {}),\n ...(mcpSkillsSettingOf(s.skills) ? { skills: mcpSkillsSettingOf(s.skills) } : {}),\n ...(typeof s.apps === 'boolean' ? { apps: s.apps } : {}),\n status: 'idle',\n catalog: [],\n ...patch,\n})\n\n/**\n * Connect the browser agent to SEVERAL remote MCP servers at once, each with\n * its own auth (none, a bearer token, or OAuth 2.1 + dynamic registration).\n * Every server is its own connection — adding or removing one never touches\n * the others — and their tools merge into one `tools` set, prefixed by server\n * name. The list is remembered across reloads (tokens excepted), and an OAuth\n * round-trip resumes on return.\n *\n * ```tsx\n * const mcp = useMcpServers()\n * // await mcp.add({ name: 'github', url, auth: 'oauth' })\n * // await mcp.add({ name: 'docs', url, auth: 'bearer', token })\n * const agent = useAgent({ model, tools: { ...local, ...mcp.tools } }, { deps: [mcp.tools] })\n * ```\n *\n * With many servers the merged catalogue can reach hundreds of tools; the core\n * switches to tool search above `toolSearchThreshold` automatically.\n */\nexport const useMcpServers = (options: UseMcpServersOptions = {}): UseMcpServersReturn => {\n const storageKey = options.storageKey ?? DEFAULT_KEY\n const pendingKey = `${storageKey}:pending`\n const persist = options.persist !== false\n\n // The remembered list as it was stored, read once: the views below drop `oauth`.\n const [stored] = useState<StoredServer[]>(() =>\n persist ? (readRecord<StoredServer[]>(storageKey) ?? []) : [],\n )\n const [servers, setServers] = useState<McpServerView[]>(() => stored.map((s) => view(s)))\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompleting] = useState(\n () => readCallbackParams() !== undefined && readRecord(pendingKey) !== undefined,\n )\n // Bumped whenever a server's tools change, to recompute the merged set.\n const [toolsVersion, setToolsVersion] = useState(0)\n\n const liveRef = useRef(new Map<string, Live>())\n const specsRef = useRef(new Map<string, StoredServer>())\n if (specsRef.current.size === 0 && servers.length > 0) {\n for (const s of servers) {\n // With the OAuth details the server was added with (redirect, scope, client name, client\n // ID metadata document): after a reload it must be the same client, and the next save of\n // the list must not drop them.\n const oauth = stored.find((x) => x.name === s.name && x.url === s.url)?.oauth\n specsRef.current.set(s.name, {\n name: s.name,\n url: s.url,\n auth: s.auth,\n ...(oauth && typeof oauth === 'object' ? { oauth } : {}),\n ...(s.protocolMode ? { protocol: s.protocolMode } : {}),\n ...(mcpSkillsSettingOf(s.skills) ? { skills: mcpSkillsSettingOf(s.skills) } : {}),\n ...(typeof s.apps === 'boolean' ? { apps: s.apps } : {}),\n })\n }\n }\n const optionsRef = useRef(options)\n optionsRef.current = options\n const unmountedRef = useRef(false)\n const elicitation = useElicitationQueue(optionsRef)\n const cancelElicitations = elicitation.cancel\n\n const saveList = useCallback(() => {\n if (!persist) return\n writeRecord(storageKey, [...specsRef.current.values()])\n }, [persist, storageKey])\n\n const patch = useCallback((name: string, p: Partial<McpServerView>) => {\n if (unmountedRef.current) return\n setServers((list) => list.map((s) => (s.name === name ? { ...s, ...p } : s)))\n }, [])\n\n const live = (name: string): Live => {\n let l = liveRef.current.get(name)\n if (!l) {\n l = { epoch: 0 }\n liveRef.current.set(name, l)\n }\n return l\n }\n\n const closeServer = useCallback(async (name: string) => {\n const l = liveRef.current.get(name)\n if (!l) return\n l.epoch += 1\n const open = l.connection\n l.connection = undefined\n if (l.tools) {\n l.tools = undefined\n setToolsVersion((v) => v + 1)\n }\n // Nobody is left to take the answers of a connection that is being closed.\n cancelElicitations(name)\n if (open) await open.close().catch(() => {})\n // `cancelElicitations` is stable (the queue lives as long as the hook).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Throws on a clientMetadataUrl or registration the core refuses (not https, a bare origin,\n // 'cimd' without a document, a core that does not know the option).\n const providerFor = (mod: McpModule, spec: StoredServer): BrowserOAuthProvider =>\n newMcpOAuthProvider(mod, mcpOAuthProviderOptions(spec.url, spec.oauth, optionsRef.current))\n\n const connectServer = useCallback(\n async (name: string): Promise<void> => {\n const spec = specsRef.current.get(name)\n if (!spec) return\n await closeServer(name)\n const l = live(name)\n const epoch = ++l.epoch\n const current = () => !unmountedRef.current && l.epoch === epoch\n if (spec.auth === 'bearer' && !l.token) {\n patch(name, { status: 'idle', error: 'Enter the bearer token to connect.' })\n return\n }\n patch(name, {\n status: 'connecting',\n error: undefined,\n authorizationUrl: undefined,\n oauthRegistration: undefined,\n catalog: [],\n instructions: undefined,\n protocol: undefined,\n })\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n let provider: BrowserOAuthProvider | undefined\n if (spec.auth === 'oauth') {\n provider = providerFor(mod, spec)\n l.provider = provider\n }\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: spec.url,\n headers:\n spec.auth === 'bearer' && l.token\n ? { Authorization: `Bearer ${l.token}` }\n : undefined,\n authProvider: provider,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n // Only when asked for: without it the connection is built as it always was.\n ...(spec.protocol ? { protocol: spec.protocol } : {}),\n ...(mcpSkillsSettingOf(spec.skills)\n ? { skills: mcpSkillsSettingOf(spec.skills) }\n : {}),\n // Only when given: without it the hook's `apps` decides, as before.\n ...(typeof spec.apps === 'boolean' ? { apps: spec.apps } : {}),\n },\n },\n {\n clientName: optionsRef.current.clientName,\n onLog: optionsRef.current.onLog,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n ...(optionsRef.current.apps ? { apps: true } : {}),\n // Off: neither key is passed, so the core declares no capability.\n ...elicitationConnectOptions(optionsRef.current.elicitation, elicitation.handler),\n },\n )\n if (!current()) {\n await connection.close().catch(() => {})\n return\n }\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n return\n }\n throw new Error(outcome.error)\n }\n l.connection = connection\n l.tools = watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = l.provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n })\n setToolsVersion((v) => v + 1)\n const negotiated = mcpProtocolOf(connection, name)\n const oauthRegistration = await mcpOAuthRegistrationOf(provider)\n if (!current()) return\n patch(name, {\n status: 'connected',\n oauthRegistration,\n catalog: connection.catalog,\n instructions: mcpInstructionsOf(connection, name),\n protocol: negotiated ? { version: negotiated.version, era: negotiated.era } : undefined,\n })\n } catch (err) {\n if (!current()) return\n patch(name, { status: 'error', error: err instanceof Error ? err.message : String(err) })\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const add = useCallback(\n async (input: McpServerSpec): Promise<string> => {\n let name = sanitize(input.name)\n // A different server under a taken name gets a suffix; the same URL replaces.\n const taken = specsRef.current.get(name)\n if (taken && taken.url !== input.url) {\n let n = 2\n while (specsRef.current.has(`${name}_${n}`)) n += 1\n name = `${name}_${n}`\n }\n const spec: StoredServer = {\n name,\n url: input.url,\n auth: input.auth ?? 'none',\n ...(input.oauth ? { oauth: input.oauth } : {}),\n ...(isProtocolMode(input.protocol) ? { protocol: input.protocol } : {}),\n ...(mcpSkillsSettingOf(input.skills) ? { skills: mcpSkillsSettingOf(input.skills) } : {}),\n ...(typeof input.apps === 'boolean' ? { apps: input.apps } : {}),\n }\n specsRef.current.set(name, spec)\n live(name).token = input.auth === 'bearer' ? input.token : undefined\n setServers((list) =>\n list.some((s) => s.name === name)\n ? list.map((s) => (s.name === name ? view(spec) : s))\n : [...list, view(spec)],\n )\n saveList()\n await connectServer(name)\n return name\n },\n [connectServer, saveList],\n )\n\n const remove = useCallback(\n async (name: string) => {\n await closeServer(name)\n liveRef.current.delete(name)\n specsRef.current.delete(name)\n saveList()\n setServers((list) => list.filter((s) => s.name !== name))\n },\n [closeServer, saveList],\n )\n\n const reconnect = useCallback(\n async (name: string, token?: string) => {\n if (token !== undefined) live(name).token = token\n await connectServer(name)\n },\n [connectServer],\n )\n\n const authorize = useCallback(\n (name: string) => {\n const url = servers.find((s) => s.name === name)?.authorizationUrl\n const spec = specsRef.current.get(name)\n if (!url || !spec || typeof globalThis.location === 'undefined') return\n // The redirect reloads the page: remember which server it is for. Written\n // here, at the user's click, so with several servers awaiting consent the\n // record always names the one actually being authorized.\n const pending: PendingRecord = {\n name,\n url: spec.url,\n ...mcpOAuthRecordOf(mcpOAuthProviderOptions(spec.url, spec.oauth, optionsRef.current)),\n startedAt: Date.now(),\n }\n writeRecord(pendingKey, pending)\n globalThis.location.href = url\n },\n [servers, pendingKey],\n )\n\n const forgetAuthorization = useCallback(\n async (name: string) => {\n const spec = specsRef.current.get(name)\n const l = liveRef.current.get(name)\n let provider = l?.provider\n if (!provider && spec?.auth === 'oauth') {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n try {\n provider = providerFor(mod, spec)\n } catch {\n // Options the core refuses never built a provider, so nothing was stored for them.\n }\n }\n }\n await provider?.reset().catch(() => {})\n if (l) l.provider = undefined\n const pending = readRecord<PendingRecord>(pendingKey)\n if (pending?.name === name) writeRecord(pendingKey, undefined)\n await closeServer(name)\n patch(name, {\n status: 'idle',\n authorizationUrl: undefined,\n oauthRegistration: undefined,\n catalog: [],\n instructions: undefined,\n protocol: undefined,\n error: undefined,\n })\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n // On mount: finish an OAuth round-trip that came back to this page, then\n // reconnect the remembered servers.\n useEffect(() => {\n unmountedRef.current = false\n // Synchronous up to the first await, like useMcp: another effect may\n // rewrite `location`, and StrictMode runs this twice.\n const callback = readCallbackParams()\n const pending = readRecord<PendingRecord>(pendingKey)\n const fresh = pending !== undefined && Date.now() - pending.startedAt < PENDING_TTL_MS\n const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback))\n if (callback && pending && !fresh) writeRecord(pendingKey, undefined)\n if (ours && typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n const autoConnect = optionsRef.current.autoConnect !== false\n void (async () => {\n if (ours && pending && callback) {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const spec = specsRef.current.get(pending.name) ?? {\n name: pending.name,\n url: pending.url,\n auth: 'oauth' as const,\n }\n if (!specsRef.current.has(spec.name)) {\n specsRef.current.set(spec.name, spec)\n setServers((list) => [...list, view(spec)])\n saveList()\n }\n const provider = providerFor(mod, { ...spec, oauth: mcpOAuthOptionsOfRecord(pending) })\n live(spec.name).provider = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(pendingKey, undefined)\n } catch (err) {\n writeRecord(pendingKey, undefined)\n patch(pending.name, {\n status: 'error',\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n setCompleting(false)\n if (autoConnect || ours) {\n await Promise.all(\n [...specsRef.current.keys()]\n .filter((name) => autoConnect || name === pending?.name)\n .map((name) => connectServer(name)),\n )\n }\n })()\n return () => {\n unmountedRef.current = true\n for (const name of liveRef.current.keys()) void closeServer(name)\n }\n // Runs once: the callbacks are stable and the redirect exists only on first load.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const tools = useMemo<AgentToolSet>(() => {\n const merged: AgentToolSet = {}\n for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools)\n return merged\n // toolsVersion is the change signal for the mutable map.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toolsVersion])\n\n const catalog = useMemo(\n () => servers.filter((s) => s.status === 'connected').flatMap((s) => s.catalog),\n [servers],\n )\n\n // Apps of every server whose own setting, or the hook's, turns them on. A server with\n // `apps: false` is never routed to - not even by a core too old to know the setting.\n const appsOn = options.apps === true || servers.some((s) => s.apps === true)\n const hookApps = options.apps === true\n const apps = useMemo(\n () =>\n appsOn\n ? mcpAppsRouter((server) => {\n const spec = specsRef.current.get(server)\n if (!spec || (spec.apps ?? hookApps) !== true) return undefined\n return liveRef.current.get(server)?.connection\n })\n : undefined,\n [appsOn, hookApps],\n )\n\n const protocols = useMemo<McpServerProtocol[]>(\n () =>\n servers.flatMap((s) =>\n s.status === 'connected' && s.protocol ? [{ server: s.name, ...s.protocol }] : [],\n ),\n [servers],\n )\n\n return {\n apps,\n servers,\n tools,\n catalog,\n protocols,\n pendingElicitations: elicitation.pendingElicitations,\n answerElicitation: elicitation.answerElicitation,\n connectedCount: servers.filter((s) => s.status === 'connected').length,\n completingAuthorization,\n oauthSupported,\n checkOAuthSupport,\n add,\n remove,\n reconnect,\n authorize,\n forgetAuthorization,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAkE;;;ACkC3D,IAAM,yBAAyB;AAM/B,IAAM,sBAAsB,CACjC,WACsC;AACtC,MAAI,WAAW,KAAM,QAAO,CAAC;AAC7B,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO,EAAE,GAAG,OAAO;AACtE,SAAO;AACT;AAMO,IAAM,4BAA4B,CACvC,QACA,YACmF;AACnF,QAAM,WAAW,oBAAoB,MAAM;AAC3C,SAAO,WAAW,EAAE,eAAe,SAAS,aAAa,SAAS,IAAI,CAAC;AACzE;AAGA,IAAM,eAAe;AAMd,IAAM,uBAAuB,CAAC,aAAwD;AAC3F,QAAM,MAAM,SAAS;AACrB,MAAI,QAAQ,UAAa,QAAQ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