@dudko.dev/agent-web-react 0.0.28 → 0.0.29

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 CHANGED
@@ -350,18 +350,35 @@ import { useMcp, useMcpServers } from '@dudko.dev/agent-web-react/mcp'
350
350
  ```
351
351
 
352
352
  The MCP hooks are **not** exported from `@dudko.dev/agent-web-react`. They load the
353
- core's `@dudko.dev/agent-web/mcp`, which imports `@modelcontextprotocol/sdk` — an
353
+ core's `@dudko.dev/agent-web/mcp`, which imports the MCP SDK
354
+ (`@modelcontextprotocol/client`) — an
354
355
  *optional* peer, so npm does not install it for you. A bundler cannot honour
355
356
  "optional": it resolves even a dynamic `import()` at build time, so a host that
356
357
  merely imported `useAgent` from the main entry used to fail webpack/CRA with
357
- `Module not found: @modelcontextprotocol/sdk/…` while never touching MCP. Behind a
358
+ `Module not found` for the SDK while never touching MCP. Behind a
358
359
  subpath the decision is yours:
359
360
 
360
361
  - **Don't use MCP** → import only from the main entry. Nothing in your build
361
362
  mentions the SDK; install nothing extra.
362
- - **Use MCP** → import from `…/mcp` and `npm install @modelcontextprotocol/sdk`
363
+ - **Use MCP** → import from `…/mcp` and `npm install @modelcontextprotocol/client`
363
364
  next to the core (it is bundled into an async chunk, loaded when you connect).
364
365
 
366
+ > **The MCP SDK is the core's peer, and it was renamed.** A core on the 2.x MCP
367
+ > SDK (`@dudko.dev/agent-web@0.0.40` and later) imports
368
+ > `@modelcontextprotocol/client` (`^2.4.0`); cores up to 0.0.39 import
369
+ > `@modelcontextprotocol/sdk` 1.x. Install the one your core asks for — when you
370
+ > upgrade the core: `npm uninstall @modelcontextprotocol/sdk && npm install
371
+ > @modelcontextprotocol/client`. This package imports neither, and its hooks
372
+ > work with both. Nothing changes in the hooks' API: `ConnectedMcp`,
373
+ > `BrowserOAuthProviderOptions`, `McpServerResult` and the other types exported
374
+ > from `…/mcp` are structural types of this package, not the SDK's. The one
375
+ > difference you can observe: `isUnauthorizedError(err)` now also recognises the
376
+ > error by its `name` (the 2.x class sets it) and across two copies of the SDK.
377
+ > A tool call refused with `403 insufficient_scope` fails with the SDK's
378
+ > `InsufficientScopeError`, which is **not** an authorization failure for
379
+ > `isUnauthorizedError` — the status stays `connected`. See the core's
380
+ > [upgrade notes](https://github.com/dudko-dev/agents/blob/main/packages/agent-web/README.md#upgrading-to-the-2x-mcp-sdk).
381
+
365
382
  > **Migrating from ≤ 0.0.18.** `useMcp`, `useMcpServers` and their helpers
366
383
  > (`readCallbackParams`, `claimOAuthCallback`, `stripOAuthParams`,
367
384
  > `describeMcpResult`, `isUnauthorizedError`) and types (`McpStatus`,
@@ -475,8 +492,9 @@ Two notes:
475
492
 
476
493
  - The connector lives in the core's optional `@dudko.dev/agent-web/mcp` subpath
477
494
  and is loaded with a **dynamic import**, so the SDK stays out of your initial
478
- bundle until `connect` runs. Install `@modelcontextprotocol/sdk` alongside the
479
- core — importing these hooks is what puts it in your build.
495
+ bundle until `connect` runs. Install `@modelcontextprotocol/client` alongside the
496
+ core (`@modelcontextprotocol/sdk` for a core up to 0.0.39) — importing these
497
+ hooks is what puts it in your build.
480
498
  - `oauthSupported` is `false` on cores older than `@dudko.dev/agent-web@0.0.9`,
481
499
  which introduced `BrowserOAuthProvider`; header auth still works there. The
482
500
  peer floor is `>=0.0.39` — the first core with model tiers, dynamic subagents,
package/dist/mcp.cjs CHANGED
@@ -148,6 +148,7 @@ var mcpOAuthProviderOptions = (serverUrl, oauth = {}, defaults = {}) => {
148
148
  var isUnauthorizedError = (err, mod) => {
149
149
  if (!(err instanceof Error)) return false;
150
150
  if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
151
+ if (err.name === "UnauthorizedError") return true;
151
152
  return err.constructor?.name === "UnauthorizedError";
152
153
  };
153
154
  var watchAuthorization = (tools, mod, onUnauthorized) => {
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/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 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/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 // 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 * 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 [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,KAAK,IAAI,OAAO;AAC1D;AAEO,IAAM,oBACX;AAEF,IAAM,cAAc;AACpB,IAAM,YAAY;AAgBX,IAAM,iBAAiB,KAAK,KAAK;AAExC,IAAI;AAOG,IAAM,UAAU,MAA0B;AAC/C,oBAAk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ACA;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react"]}
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,QA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Y,CAAC;AAEjB,QAAM,cAAU;AAAA,IACd,MAAM,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,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 CHANGED
@@ -4,7 +4,7 @@ import { AgentToolSet } from '@dudko.dev/agent-web';
4
4
  * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
5
5
  *
6
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
7
+ * imported, for two reasons: it drags in `@modelcontextprotocol/client` (an
8
8
  * optional peer of the core, which apps without MCP must not have to install),
9
9
  * and the OAuth half only exists in newer cores while this package supports
10
10
  * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
@@ -83,7 +83,9 @@ interface McpModule {
83
83
  finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
84
84
  /**
85
85
  * The SDK's error class, re-exported by the core so an authorization failure
86
- * can be recognised by identity. Absent on cores older than 0.0.12.
86
+ * can be recognised by identity (`@modelcontextprotocol/client` on a core on
87
+ * the 2.x MCP SDK, `@modelcontextprotocol/sdk` before). Absent on cores older
88
+ * than 0.0.12.
87
89
  */
88
90
  UnauthorizedError?: new (message?: string) => Error;
89
91
  }
@@ -206,12 +208,19 @@ declare const mcpOAuthProviderOptions: (serverUrl: string, oauth?: McpOAuthOptio
206
208
  /**
207
209
  * Did this error come from the server refusing our authorization?
208
210
  *
209
- * Identity, not strings: the SDK's `UnauthorizedError` never assigns
210
- * `this.name` (so it reads as "Error"), and its message would also match a
211
- * tool whose own error text mentions "unauthorized" — the connector throws a
212
- * failing tool's text verbatim. The class is re-exported by the core's `./mcp`
213
- * subpath for exactly this; `constructor.name` is the fallback for a core too
214
- * old to export it.
211
+ * Never by the message: it would also match a tool whose own error text
212
+ * mentions "unauthorized" — the connector throws a failing tool's text
213
+ * verbatim. Three handles, in order:
214
+ *
215
+ * 1. the class the core's `./mcp` subpath re-exports. On the 2.x MCP SDK
216
+ * (`@modelcontextprotocol/client`) `instanceof` goes by a brand the error
217
+ * carries, not by prototype, so it also holds when the error was made by
218
+ * another copy of the SDK than the one the core module resolved to (two
219
+ * bundles, an ESM and a CJS build on one page);
220
+ * 2. the error's own `name`, which the 2.x class sets to `'UnauthorizedError'`
221
+ * (a string, so it survives a minifier; the 1.x class left it `'Error'`);
222
+ * 3. `constructor.name`, for a core on the 1.x SDK that is too old to export
223
+ * the class (and only where the bundle keeps class names).
215
224
  */
216
225
  declare const isUnauthorizedError: (err: unknown, mod?: McpModule) => boolean;
217
226
  /**
package/dist/mcp.d.ts CHANGED
@@ -4,7 +4,7 @@ import { AgentToolSet } from '@dudko.dev/agent-web';
4
4
  * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
5
5
  *
6
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
7
+ * imported, for two reasons: it drags in `@modelcontextprotocol/client` (an
8
8
  * optional peer of the core, which apps without MCP must not have to install),
9
9
  * and the OAuth half only exists in newer cores while this package supports
10
10
  * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
@@ -83,7 +83,9 @@ interface McpModule {
83
83
  finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
84
84
  /**
85
85
  * The SDK's error class, re-exported by the core so an authorization failure
86
- * can be recognised by identity. Absent on cores older than 0.0.12.
86
+ * can be recognised by identity (`@modelcontextprotocol/client` on a core on
87
+ * the 2.x MCP SDK, `@modelcontextprotocol/sdk` before). Absent on cores older
88
+ * than 0.0.12.
87
89
  */
88
90
  UnauthorizedError?: new (message?: string) => Error;
89
91
  }
@@ -206,12 +208,19 @@ declare const mcpOAuthProviderOptions: (serverUrl: string, oauth?: McpOAuthOptio
206
208
  /**
207
209
  * Did this error come from the server refusing our authorization?
208
210
  *
209
- * Identity, not strings: the SDK's `UnauthorizedError` never assigns
210
- * `this.name` (so it reads as "Error"), and its message would also match a
211
- * tool whose own error text mentions "unauthorized" — the connector throws a
212
- * failing tool's text verbatim. The class is re-exported by the core's `./mcp`
213
- * subpath for exactly this; `constructor.name` is the fallback for a core too
214
- * old to export it.
211
+ * Never by the message: it would also match a tool whose own error text
212
+ * mentions "unauthorized" — the connector throws a failing tool's text
213
+ * verbatim. Three handles, in order:
214
+ *
215
+ * 1. the class the core's `./mcp` subpath re-exports. On the 2.x MCP SDK
216
+ * (`@modelcontextprotocol/client`) `instanceof` goes by a brand the error
217
+ * carries, not by prototype, so it also holds when the error was made by
218
+ * another copy of the SDK than the one the core module resolved to (two
219
+ * bundles, an ESM and a CJS build on one page);
220
+ * 2. the error's own `name`, which the 2.x class sets to `'UnauthorizedError'`
221
+ * (a string, so it survives a minifier; the 1.x class left it `'Error'`);
222
+ * 3. `constructor.name`, for a core on the 1.x SDK that is too old to export
223
+ * the class (and only where the bundle keeps class names).
215
224
  */
216
225
  declare const isUnauthorizedError: (err: unknown, mod?: McpModule) => boolean;
217
226
  /**
package/dist/mcp.js CHANGED
@@ -104,6 +104,7 @@ var mcpOAuthProviderOptions = (serverUrl, oauth = {}, defaults = {}) => {
104
104
  var isUnauthorizedError = (err, mod) => {
105
105
  if (!(err instanceof Error)) return false;
106
106
  if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
107
+ if (err.name === "UnauthorizedError") return true;
107
108
  return err.constructor?.name === "UnauthorizedError";
108
109
  };
109
110
  var watchAuthorization = (tools, mod, onUnauthorized) => {
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-mcp.ts","../src/hooks/use-mcp-servers.ts"],"sourcesContent":["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/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 // 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 * 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 [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,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAkGlD,IAAM,oBAAoB,CAC/B,YACA,SACuB;AACvB,QAAM,OAAO,MAAM,QAAQ,WAAW,YAAY,IAAI,WAAW,eAAe,CAAC;AACj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OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,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":["useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect"]}
1
+ {"version":3,"sources":["../src/hooks/use-mcp.ts","../src/hooks/use-mcp-servers.ts"],"sourcesContent":["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,SAAS,aAAa,WAAW,QAAQ,gBAAgB;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,KAAK,IAAI,OAAO;AAC1D;AAEO,IAAM,oBACX;AAEF,IAAM,cAAc;AACpB,IAAM,YAAY;AAgBX,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;AAAA,EACR,CAAC;AACH,SAAO;AACT;AAGO,IAAM,oBAAoB,CAC/B,WAC0C;AAC1C,MAAI,CAAC,OAAQ,QAAO,EAAE,QAAQ,SAAS,OAAO,kDAAkD;AAChG,MAAI,OAAO,UAAW,QAAO,EAAE,QAAQ,YAAY;AACnD,MAAI,OAAO,mBAAoB,QAAO,EAAE,QAAQ,sBAAsB;AACtE,SAAO,EAAE,QAAQ,SAAS,OAAO,OAAO,SAAS,sCAAsC;AACzF;AAEA,IAAM,eAAe,CAAC,QA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vB,cAAM,QAAQ;AAAA,UACZ,CAAC,GAAG,SAAS,QAAQ,KAAK,CAAC,EACxB,OAAO,CAAC,SAAS,eAAe,SAAS,SAAS,IAAI,EACtD,IAAI,CAAC,SAAS,cAAc,IAAI,CAAC;AAAA,QACtC;AAAA,MACF;AAAA,IACF,GAAG;AACH,WAAO,MAAM;AACX,mBAAa,UAAU;AACvB,iBAAW,QAAQ,QAAQ,QAAQ,KAAK,EAAG,MAAK,YAAY,IAAI;AAAA,IAClE;AAAA,EAGF,GAAG,CAAC,CAAC;AAEL,QAAM,QAAQ,QAAsB,MAAM;AACxC,UAAM,SAAuB,CAAC;AAC9B,eAAW,KAAK,QAAQ,QAAQ,OAAO,EAAG,KAAI,EAAE,MAAO,QAAO,OAAO,QAAQ,EAAE,KAAK;AACpF,WAAO;AAAA,EAGT,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,UAAU;AAAA,IACd,MAAM,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,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":["useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect"]}
package/dist/styles.css CHANGED
@@ -1742,8 +1742,11 @@
1742
1742
  border-radius: 8px;
1743
1743
  border: 1px solid var(--awr-border);
1744
1744
  }
1745
+ /* A width of its own, capped by the column: the list of files shrinks to its content, so a
1746
+ width in per cent of it resolved to nothing and the player had no size. */
1745
1747
  .awr-media--audio {
1746
- width: min(100%, 320px);
1748
+ width: 320px;
1749
+ max-width: 100%;
1747
1750
  }
1748
1751
  .awr-media__audio {
1749
1752
  width: 100%;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent-web-react",
3
- "version": "0.0.28",
3
+ "version": "0.0.29",
4
4
  "description": "React bindings for @dudko.dev/agent-web: a headless useAgent hook, an AgentProvider context, and optional pre-styled components (chat panel, plan/step view, BYOK key form, WebLLM load bar) that connect the in-browser LLM agent to any React site. UI you can drop in — or a headless reducer you can build your own around.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -134,7 +134,7 @@
134
134
  "tsup": "^9.0.0",
135
135
  "typescript": "^6.0.3",
136
136
  "zod": "^4.6.7",
137
- "@dudko.dev/agent-web": "0.0.39",
137
+ "@dudko.dev/agent-web": "0.0.40",
138
138
  "@dudko.dev/test-servers": "0.0.0"
139
139
  },
140
140
  "scripts": {