@dudko.dev/agent-web-react 0.0.18 → 0.0.20

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.
@@ -0,0 +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/sdk` — 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/sdk/…\" 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 readCallbackParams,\n stripOAuthParams,\n} from './hooks/use-mcp.js'\nexport type { McpConnectOptions, McpStatus, UseMcpOptions, UseMcpReturn } 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 ConnectedMcp,\n McpCatalogEntry,\n McpOAuthCallback,\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 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\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 | { redirectUrl?: string; scope?: string; clientName?: string }\n}\n\nexport interface UseMcpOptions {\n /** Client name reported to the MCP server during initialize. */\n clientName?: 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 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\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 /** 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/sdk` 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 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 * Did this error come from the server refusing our authorization?\n *\n * Identity, not strings: the SDK's `UnauthorizedError` never assigns\n * `this.name` (so it reads as \"Error\"), and its message would also match a\n * tool whose own error text mentions \"unauthorized\" — the connector throws a\n * failing tool's text verbatim. The class is re-exported by the core's `./mcp`\n * subpath for exactly this; `constructor.name` is the fallback for a core too\n * old to export it.\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 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 [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\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 oauth = typeof opts.oauth === 'object' ? opts.oauth : {}\n const record: OAuthRecord = {\n url: opts.url,\n name,\n redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),\n scope: oauth.scope,\n clientName: oauth.clientName ?? optionsRef.current.clientName,\n startedAt: Date.now(),\n }\n authProvider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\n })\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 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 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 provider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\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({\n serverUrl: pending.url,\n redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),\n clientName: pending.clientName,\n scope: pending.scope,\n })\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 await connect({ url: pending.url, name: pending.name, oauth: true })\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 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 OAUTH_UNSUPPORTED,\n PENDING_TTL_MS,\n readCallbackParams,\n readRecord,\n stripOAuthParams,\n watchAuthorization,\n writeRecord,\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'`. */\n oauth?: { redirectUrl?: string; scope?: string; clientName?: string }\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\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 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 const [servers, setServers] = useState<McpServerView[]>(() =>\n persist ? (readRecord<StoredServer[]>(storageKey) ?? []).map((s) => view(s)) : [],\n )\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 specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth })\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 return new mod.BrowserOAuthProvider({\n serverUrl: spec.url,\n redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),\n clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,\n scope: spec.oauth?.scope,\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 })\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, { status: 'connected', catalog: connection.catalog })\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 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) provider = providerFor(mod, spec)\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, { status: 'idle', authorizationUrl: undefined, catalog: [], error: undefined })\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 },\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;;;ACAA,mBAAyD;AA4DlD,IAAM,oBACX;AAEF,IAAM,cAAc;AACpB,IAAM,YAAY;AAeX,IAAM,iBAAiB,KAAK,KAAK;AAExC,IAAI;AAOG,IAAM,UAAU,MAA0B;AAC/C,oBAAkB,OAAO,0BAA0B,EAChD,KAAK,CAAC,MAAM,CAAyB,EACrC,MAAM,CAAC,QAAiB;AAGvB,oBAAgB;AAChB,UAAM;A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W,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO;AAAA,IAC9E,CAAC,OAAO;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"]}
package/dist/mcp.d.cts ADDED
@@ -0,0 +1,265 @@
1
+ import { AgentToolSet } from '@dudko.dev/agent-web';
2
+
3
+ /**
4
+ * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
5
+ *
6
+ * The subpath is loaded with a dynamic import and typed here rather than
7
+ * imported, for two reasons: it drags in `@modelcontextprotocol/sdk` (an
8
+ * optional peer of the core, which apps without MCP must not have to install),
9
+ * and the OAuth half only exists in newer cores while this package supports
10
+ * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
11
+ * reports `oauthSupported: false` on an older core instead of crashing.
12
+ */
13
+ interface McpCatalogEntry {
14
+ name: string;
15
+ description: string;
16
+ server: string;
17
+ /** The server marked the tool read-only (newer cores). */
18
+ readOnly?: boolean;
19
+ }
20
+ interface McpServerResult {
21
+ name: string;
22
+ connected: boolean;
23
+ error?: string;
24
+ needsAuthorization?: boolean;
25
+ }
26
+ interface ConnectedMcp {
27
+ tools: AgentToolSet;
28
+ catalog: McpCatalogEntry[];
29
+ results: McpServerResult[];
30
+ refreshServer?: (name: string) => Promise<void>;
31
+ close: () => Promise<void>;
32
+ }
33
+ interface McpHttpServerConfig {
34
+ url: string;
35
+ headers?: Record<string, string>;
36
+ authProvider?: unknown;
37
+ /** Per-server connect deadline (newer cores; ignored by older ones). */
38
+ connectTimeoutMs?: number;
39
+ }
40
+ interface McpOAuthCallback {
41
+ code?: string;
42
+ state?: string;
43
+ error?: string;
44
+ errorDescription?: string;
45
+ }
46
+ interface BrowserOAuthProvider {
47
+ serverUrl: string;
48
+ authorizationUrl?: URL;
49
+ isAuthorized(): Promise<boolean>;
50
+ reset(): Promise<void>;
51
+ }
52
+ interface BrowserOAuthProviderOptions {
53
+ serverUrl: string;
54
+ redirectUrl: string;
55
+ clientName?: string;
56
+ scope?: string;
57
+ }
58
+ /** The shape of the subpath module, as far as this package uses it. */
59
+ interface McpModule {
60
+ connectMcpHttp: (servers: Record<string, McpHttpServerConfig>, opts?: {
61
+ clientName?: string;
62
+ onLog?: (level: string, message: string) => void;
63
+ connectTimeoutMs?: number;
64
+ }) => Promise<ConnectedMcp>;
65
+ BrowserOAuthProvider?: new (opts: BrowserOAuthProviderOptions) => BrowserOAuthProvider;
66
+ readOAuthCallback?: (input?: string | URL) => McpOAuthCallback | undefined;
67
+ finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
68
+ /**
69
+ * The SDK's error class, re-exported by the core so an authorization failure
70
+ * can be recognised by identity. Absent on cores older than 0.0.12.
71
+ */
72
+ UnauthorizedError?: new (message?: string) => Error;
73
+ }
74
+
75
+ type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error';
76
+ interface McpConnectOptions {
77
+ /** The server's StreamableHTTP endpoint. */
78
+ url: string;
79
+ /** Prefix for the discovered tool names ("<name>__<tool>"). Default 'mcp'. */
80
+ name?: string;
81
+ /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */
82
+ headers?: Record<string, string>;
83
+ /**
84
+ * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core
85
+ * that ships the OAuth provider; check `oauthSupported` before offering it.
86
+ */
87
+ oauth?: boolean | {
88
+ redirectUrl?: string;
89
+ scope?: string;
90
+ clientName?: string;
91
+ };
92
+ }
93
+ interface UseMcpOptions {
94
+ /** Client name reported to the MCP server during initialize. */
95
+ clientName?: string;
96
+ /** Called with connector log lines — handy while debugging a server. */
97
+ onLog?: (level: string, message: string) => void;
98
+ }
99
+ interface UseMcpReturn {
100
+ status: McpStatus;
101
+ /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */
102
+ tools?: AgentToolSet;
103
+ catalog: McpCatalogEntry[];
104
+ error?: string;
105
+ /** Where to send the user when `status === 'needs-authorization'`. */
106
+ authorizationUrl?: string;
107
+ /**
108
+ * Whether the installed core exposes the OAuth API. `undefined` until the
109
+ * optional subpath has been loaded once — call `checkOAuthSupport()` to
110
+ * resolve it before offering OAuth in your UI.
111
+ */
112
+ oauthSupported?: boolean;
113
+ /** True while an OAuth redirect is being finished on mount. */
114
+ completingAuthorization: boolean;
115
+ connect: (options: McpConnectOptions) => Promise<void>;
116
+ disconnect: () => Promise<void>;
117
+ /** Navigate to the authorization server. Call it from a user gesture. */
118
+ authorize: () => void;
119
+ /** Drop the stored tokens and dynamic registration for the current server. */
120
+ forgetAuthorization: () => Promise<void>;
121
+ /** Load the optional subpath and report whether it can do OAuth. */
122
+ checkOAuthSupport: () => Promise<boolean>;
123
+ }
124
+ /** Map a single server's connect outcome onto the hook's status. Pure. */
125
+ declare const describeMcpResult: (result: McpServerResult | undefined) => {
126
+ status: McpStatus;
127
+ error?: string;
128
+ };
129
+ /**
130
+ * Read the authorization-code parameters out of a URL **synchronously**.
131
+ *
132
+ * The core exports an equivalent, but it lives behind a dynamic import: by the
133
+ * time that import resolves, React has flushed the rest of the app's effects,
134
+ * and any one of them may have rewritten `location` (the demo's own view
135
+ * router did exactly that). The callback has to be captured before the first
136
+ * await, so this parser is duplicated here on purpose.
137
+ *
138
+ * Reads the query string and, for hash-routed apps, the fragment. Returns
139
+ * undefined when neither a `code` nor an `error` is present.
140
+ */
141
+ declare const readCallbackParams: (href?: string) => McpOAuthCallback | undefined;
142
+ /**
143
+ * Remove the OAuth response parameters from a URL, leaving the rest intact —
144
+ * query string and fragment alike. The code is single-use and lands in history,
145
+ * referrers and screenshots, so it goes as soon as it has been read.
146
+ */
147
+ declare const stripOAuthParams: (href: string) => string;
148
+ declare const claimOAuthCallback: (callback: McpOAuthCallback) => boolean;
149
+ /**
150
+ * Did this error come from the server refusing our authorization?
151
+ *
152
+ * Identity, not strings: the SDK's `UnauthorizedError` never assigns
153
+ * `this.name` (so it reads as "Error"), and its message would also match a
154
+ * tool whose own error text mentions "unauthorized" — the connector throws a
155
+ * failing tool's text verbatim. The class is re-exported by the core's `./mcp`
156
+ * subpath for exactly this; `constructor.name` is the fallback for a core too
157
+ * old to export it.
158
+ */
159
+ declare const isUnauthorizedError: (err: unknown, mod?: McpModule) => boolean;
160
+ /**
161
+ * Connect the browser agent to a remote MCP server the user names at runtime —
162
+ * static header, or full OAuth 2.1 with dynamic client registration.
163
+ *
164
+ * The OAuth round-trip leaves the page, so the hook persists what it needs to
165
+ * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL
166
+ * and reconnects, all before the app renders anything MCP-related.
167
+ *
168
+ * ```tsx
169
+ * const mcp = useMcp()
170
+ * // await mcp.connect({ url, oauth: true })
171
+ * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>
172
+ * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>
173
+ * ```
174
+ */
175
+ declare const useMcp: (options?: UseMcpOptions) => UseMcpReturn;
176
+
177
+ type McpAuthMode = 'none' | 'bearer' | 'oauth';
178
+ /** One server the user wants connected. */
179
+ interface McpServerSpec {
180
+ /**
181
+ * Unique name; also the tool prefix ("<name>__<tool>"). Sanitised to
182
+ * `[a-zA-Z0-9_-]`; a taken name gets a numeric suffix.
183
+ */
184
+ name: string;
185
+ /** The server's StreamableHTTP endpoint. */
186
+ url: string;
187
+ auth?: McpAuthMode;
188
+ /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */
189
+ token?: string;
190
+ /** OAuth details for `auth: 'oauth'`. */
191
+ oauth?: {
192
+ redirectUrl?: string;
193
+ scope?: string;
194
+ clientName?: string;
195
+ };
196
+ }
197
+ /** A server's live state. */
198
+ interface McpServerView {
199
+ name: string;
200
+ url: string;
201
+ auth: McpAuthMode;
202
+ status: McpStatus;
203
+ error?: string;
204
+ /** Where to send the user when `status === 'needs-authorization'`. */
205
+ authorizationUrl?: string;
206
+ catalog: McpCatalogEntry[];
207
+ }
208
+ interface UseMcpServersOptions extends UseMcpOptions {
209
+ /**
210
+ * Remember the server list (never tokens) in localStorage so it survives a
211
+ * reload — and the OAuth redirect, which IS a reload (default true).
212
+ */
213
+ persist?: boolean;
214
+ /** localStorage key of the list (default 'agent-web-react:mcp-servers'). */
215
+ storageKey?: string;
216
+ /** Reconnect remembered servers on mount (default true). Bearer servers wait for their token. */
217
+ autoConnect?: boolean;
218
+ /** Per-server connect deadline in ms (default: the core's, 30 s). */
219
+ connectTimeoutMs?: number;
220
+ }
221
+ interface UseMcpServersReturn {
222
+ servers: McpServerView[];
223
+ /** Tools of every connected server, merged — pass to `BrowserAgentConfig.tools`. */
224
+ tools: AgentToolSet;
225
+ /** Catalogue of every connected server, merged. */
226
+ catalog: McpCatalogEntry[];
227
+ connectedCount: number;
228
+ /** True while an OAuth redirect is being finished on mount. */
229
+ completingAuthorization: boolean;
230
+ /** Whether the installed core can do OAuth (undefined until checked). */
231
+ oauthSupported?: boolean;
232
+ checkOAuthSupport: () => Promise<boolean>;
233
+ /** Add (or replace, by name) a server and connect it. Resolves with the final name. */
234
+ add: (spec: McpServerSpec) => Promise<string>;
235
+ /** Disconnect and forget a server. */
236
+ remove: (name: string) => Promise<void>;
237
+ /** Connect again — optionally with a fresh bearer token. */
238
+ reconnect: (name: string, token?: string) => Promise<void>;
239
+ /** Navigate to the server's authorization page. Call it from a user gesture. */
240
+ authorize: (name: string) => void;
241
+ /** Drop a server's stored OAuth tokens and registration. */
242
+ forgetAuthorization: (name: string) => Promise<void>;
243
+ }
244
+ /**
245
+ * Connect the browser agent to SEVERAL remote MCP servers at once, each with
246
+ * its own auth (none, a bearer token, or OAuth 2.1 + dynamic registration).
247
+ * Every server is its own connection — adding or removing one never touches
248
+ * the others — and their tools merge into one `tools` set, prefixed by server
249
+ * name. The list is remembered across reloads (tokens excepted), and an OAuth
250
+ * round-trip resumes on return.
251
+ *
252
+ * ```tsx
253
+ * const mcp = useMcpServers()
254
+ * // await mcp.add({ name: 'github', url, auth: 'oauth' })
255
+ * // await mcp.add({ name: 'docs', url, auth: 'bearer', token })
256
+ * const agent = useAgent({ model, tools: { ...local, ...mcp.tools } }, { deps: [mcp.tools] })
257
+ * ```
258
+ *
259
+ * With many servers the merged catalogue can reach hundreds of tools; the core
260
+ * switches to tool search above `toolSearchThreshold` automatically.
261
+ */
262
+ declare const useMcpServers: (options?: UseMcpServersOptions) => UseMcpServersReturn;
263
+
264
+ export { claimOAuthCallback, describeMcpResult, isUnauthorizedError, readCallbackParams, stripOAuthParams, useMcp, useMcpServers };
265
+ export type { ConnectedMcp, McpAuthMode, McpCatalogEntry, McpConnectOptions, McpModule, McpOAuthCallback, McpServerResult, McpServerSpec, McpServerView, McpStatus, UseMcpOptions, UseMcpReturn, UseMcpServersOptions, UseMcpServersReturn };