@dudko.dev/agent-web-react 0.0.26 → 0.0.27

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/dist/mcp.d.ts CHANGED
@@ -40,6 +40,8 @@ interface McpHttpServerConfig {
40
40
  interface McpOAuthCallback {
41
41
  code?: string;
42
42
  state?: string;
43
+ /** The `iss` parameter of the response (RFC 9207); the core checks it. */
44
+ iss?: string;
43
45
  error?: string;
44
46
  errorDescription?: string;
45
47
  }
@@ -54,6 +56,8 @@ interface BrowserOAuthProviderOptions {
54
56
  redirectUrl: string;
55
57
  clientName?: string;
56
58
  scope?: string;
59
+ /** Client ID metadata document URL (CIMD). Cores without it ignore the field. */
60
+ clientMetadataUrl?: string;
57
61
  }
58
62
  /** The shape of the subpath module, as far as this package uses it. */
59
63
  interface McpModule {
@@ -73,6 +77,26 @@ interface McpModule {
73
77
  }
74
78
 
75
79
  type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error';
80
+ /** The OAuth details of one server. Everything is optional. */
81
+ interface McpOAuthOptions {
82
+ /** Where the authorization server sends the user back (default: this page, without query or hash). */
83
+ redirectUrl?: string;
84
+ /** Fallback scope when the server's metadata advertises none. */
85
+ scope?: string;
86
+ /** `client_name` for dynamic registration (default: the hook's `clientName`). */
87
+ clientName?: string;
88
+ /**
89
+ * URL of a client ID metadata document (CIMD) your app hosts (default: the
90
+ * hook's `clientMetadataUrl`). An authorization server that advertises
91
+ * `client_id_metadata_document_supported` takes it as the `client_id` and no
92
+ * dynamic registration is made; any other server is registered with as
93
+ * before. Must be https with a non-root path, and the document must list the
94
+ * `redirectUrl` in its `redirect_uris` - the core refuses anything else and
95
+ * the server ends in `status: 'error'`. A core that does not know the option
96
+ * ignores it and registers dynamically.
97
+ */
98
+ clientMetadataUrl?: string;
99
+ }
76
100
  interface McpConnectOptions {
77
101
  /** The server's StreamableHTTP endpoint. */
78
102
  url: string;
@@ -84,15 +108,17 @@ interface McpConnectOptions {
84
108
  * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core
85
109
  * that ships the OAuth provider; check `oauthSupported` before offering it.
86
110
  */
87
- oauth?: boolean | {
88
- redirectUrl?: string;
89
- scope?: string;
90
- clientName?: string;
91
- };
111
+ oauth?: boolean | McpOAuthOptions;
92
112
  }
93
113
  interface UseMcpOptions {
94
114
  /** Client name reported to the MCP server during initialize. */
95
115
  clientName?: string;
116
+ /**
117
+ * URL of the client ID metadata document (CIMD) this app hosts, used for
118
+ * every OAuth server unless its own `oauth.clientMetadataUrl` says otherwise.
119
+ * See `McpOAuthOptions.clientMetadataUrl`.
120
+ */
121
+ clientMetadataUrl?: string;
96
122
  /** Called with connector log lines — handy while debugging a server. */
97
123
  onLog?: (level: string, message: string) => void;
98
124
  }
@@ -146,6 +172,14 @@ declare const readCallbackParams: (href?: string) => McpOAuthCallback | undefine
146
172
  */
147
173
  declare const stripOAuthParams: (href: string) => string;
148
174
  declare const claimOAuthCallback: (callback: McpOAuthCallback) => boolean;
175
+ /**
176
+ * The options of the core's OAuth provider for one server: the server's own
177
+ * `oauth` details first, then the hook-level defaults (`clientName`,
178
+ * `clientMetadataUrl`), then this page as the redirect. Pure - both hooks build
179
+ * every provider through it, on connect, on the way back from the redirect and
180
+ * when forgetting, so the three always describe the same client.
181
+ */
182
+ declare const mcpOAuthProviderOptions: (serverUrl: string, oauth?: McpOAuthOptions, defaults?: Pick<McpOAuthOptions, "clientName" | "clientMetadataUrl">) => BrowserOAuthProviderOptions;
149
183
  /**
150
184
  * Did this error come from the server refusing our authorization?
151
185
  *
@@ -187,12 +221,8 @@ interface McpServerSpec {
187
221
  auth?: McpAuthMode;
188
222
  /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */
189
223
  token?: string;
190
- /** OAuth details for `auth: 'oauth'`. */
191
- oauth?: {
192
- redirectUrl?: string;
193
- scope?: string;
194
- clientName?: string;
195
- };
224
+ /** OAuth details for `auth: 'oauth'` (`clientMetadataUrl` for CIMD among them). */
225
+ oauth?: McpOAuthOptions;
196
226
  }
197
227
  /** A server's live state. */
198
228
  interface McpServerView {
@@ -261,5 +291,5 @@ interface UseMcpServersReturn {
261
291
  */
262
292
  declare const useMcpServers: (options?: UseMcpServersOptions) => UseMcpServersReturn;
263
293
 
264
- export { claimOAuthCallback, describeMcpResult, isUnauthorizedError, readCallbackParams, stripOAuthParams, useMcp, useMcpServers };
265
- export type { ConnectedMcp, McpAuthMode, McpCatalogEntry, McpConnectOptions, McpModule, McpOAuthCallback, McpServerResult, McpServerSpec, McpServerView, McpStatus, UseMcpOptions, UseMcpReturn, UseMcpServersOptions, UseMcpServersReturn };
294
+ export { claimOAuthCallback, describeMcpResult, isUnauthorizedError, mcpOAuthProviderOptions, readCallbackParams, stripOAuthParams, useMcp, useMcpServers };
295
+ export type { BrowserOAuthProviderOptions, ConnectedMcp, McpAuthMode, McpCatalogEntry, McpConnectOptions, McpModule, McpOAuthCallback, McpOAuthOptions, McpServerResult, McpServerSpec, McpServerView, McpStatus, UseMcpOptions, UseMcpReturn, UseMcpServersOptions, UseMcpServersReturn };
package/dist/mcp.js CHANGED
@@ -42,6 +42,9 @@ var readCallbackParams = (href) => {
42
42
  return {
43
43
  code,
44
44
  state: params.get("state") ?? void 0,
45
+ // RFC 9207: the core's `finishMcpOAuth` checks it against the authorization
46
+ // server the flow was started with, before the code is exchanged.
47
+ iss: params.get("iss") ?? void 0,
45
48
  error,
46
49
  errorDescription: params.get("error_description") ?? void 0
47
50
  };
@@ -82,6 +85,17 @@ var writeRecord = (key, value) => {
82
85
  }
83
86
  };
84
87
  var defaultRedirectUrl = () => typeof globalThis.location === "undefined" ? "" : `${globalThis.location.origin}${globalThis.location.pathname}`;
88
+ var mcpOAuthProviderOptions = (serverUrl, oauth = {}, defaults = {}) => {
89
+ const clientMetadataUrl = oauth.clientMetadataUrl ?? defaults.clientMetadataUrl;
90
+ return {
91
+ serverUrl,
92
+ redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),
93
+ clientName: oauth.clientName ?? defaults.clientName,
94
+ scope: oauth.scope,
95
+ // Left out when unset: a provider built without it keeps registering dynamically.
96
+ ...clientMetadataUrl !== void 0 ? { clientMetadataUrl } : {}
97
+ };
98
+ };
85
99
  var isUnauthorizedError = (err, mod) => {
86
100
  if (!(err instanceof Error)) return false;
87
101
  if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
@@ -161,21 +175,21 @@ var useMcp = (options = {}) => {
161
175
  let authProvider;
162
176
  if (opts.oauth) {
163
177
  if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
164
- const oauth = typeof opts.oauth === "object" ? opts.oauth : {};
178
+ const providerOptions = mcpOAuthProviderOptions(
179
+ opts.url,
180
+ typeof opts.oauth === "object" ? opts.oauth : {},
181
+ optionsRef.current
182
+ );
165
183
  const record = {
166
184
  url: opts.url,
167
185
  name,
168
- redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),
169
- scope: oauth.scope,
170
- clientName: oauth.clientName ?? optionsRef.current.clientName,
186
+ redirectUrl: providerOptions.redirectUrl,
187
+ scope: providerOptions.scope,
188
+ clientName: providerOptions.clientName,
189
+ clientMetadataUrl: providerOptions.clientMetadataUrl,
171
190
  startedAt: Date.now()
172
191
  };
173
- authProvider = new mod.BrowserOAuthProvider({
174
- serverUrl: record.url,
175
- redirectUrl: record.redirectUrl,
176
- clientName: record.clientName,
177
- scope: record.scope
178
- });
192
+ authProvider = new mod.BrowserOAuthProvider(providerOptions);
179
193
  providerRef.current = authProvider;
180
194
  writeRecord(PENDING_KEY, record);
181
195
  writeRecord(OAUTH_KEY, record);
@@ -251,12 +265,10 @@ var useMcp = (options = {}) => {
251
265
  if (!provider && record) {
252
266
  const mod = await loadMcp().catch(() => void 0);
253
267
  if (mod?.BrowserOAuthProvider) {
254
- provider = new mod.BrowserOAuthProvider({
255
- serverUrl: record.url,
256
- redirectUrl: record.redirectUrl,
257
- clientName: record.clientName,
258
- scope: record.scope
259
- });
268
+ try {
269
+ provider = new mod.BrowserOAuthProvider(mcpOAuthProviderOptions(record.url, record));
270
+ } catch {
271
+ }
260
272
  }
261
273
  }
262
274
  await provider?.reset().catch(() => {
@@ -289,17 +301,21 @@ var useMcp = (options = {}) => {
289
301
  const mod = await loadMcp();
290
302
  setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
291
303
  if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
292
- const provider = new mod.BrowserOAuthProvider({
293
- serverUrl: pending.url,
294
- redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),
295
- clientName: pending.clientName,
296
- scope: pending.scope
297
- });
304
+ const provider = new mod.BrowserOAuthProvider(mcpOAuthProviderOptions(pending.url, pending));
298
305
  providerRef.current = provider;
299
306
  await mod.finishMcpOAuth(provider, callback);
300
307
  writeRecord(PENDING_KEY, void 0);
301
308
  setCompletingAuthorization(false);
302
- await connect({ url: pending.url, name: pending.name, oauth: true });
309
+ await connect({
310
+ url: pending.url,
311
+ name: pending.name,
312
+ oauth: {
313
+ redirectUrl: pending.redirectUrl,
314
+ scope: pending.scope,
315
+ clientName: pending.clientName,
316
+ clientMetadataUrl: pending.clientMetadataUrl
317
+ }
318
+ });
303
319
  } catch (err) {
304
320
  writeRecord(PENDING_KEY, void 0);
305
321
  setError(err instanceof Error ? err.message : String(err));
@@ -348,9 +364,10 @@ var useMcpServers = (options = {}) => {
348
364
  const storageKey = options.storageKey ?? DEFAULT_KEY;
349
365
  const pendingKey = `${storageKey}:pending`;
350
366
  const persist = options.persist !== false;
351
- const [servers, setServers] = useState2(
352
- () => persist ? (readRecord(storageKey) ?? []).map((s) => view(s)) : []
367
+ const [stored] = useState2(
368
+ () => persist ? readRecord(storageKey) ?? [] : []
353
369
  );
370
+ const [servers, setServers] = useState2(() => stored.map((s) => view(s)));
354
371
  const [oauthSupported, setOauthSupported] = useState2(void 0);
355
372
  const [completingAuthorization, setCompleting] = useState2(
356
373
  () => readCallbackParams() !== void 0 && readRecord(pendingKey) !== void 0
@@ -359,8 +376,15 @@ var useMcpServers = (options = {}) => {
359
376
  const liveRef = useRef2(/* @__PURE__ */ new Map());
360
377
  const specsRef = useRef2(/* @__PURE__ */ new Map());
361
378
  if (specsRef.current.size === 0 && servers.length > 0) {
362
- for (const s of servers)
363
- specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth });
379
+ for (const s of servers) {
380
+ const oauth = stored.find((x) => x.name === s.name && x.url === s.url)?.oauth;
381
+ specsRef.current.set(s.name, {
382
+ name: s.name,
383
+ url: s.url,
384
+ auth: s.auth,
385
+ ...oauth && typeof oauth === "object" ? { oauth } : {}
386
+ });
387
+ }
364
388
  }
365
389
  const optionsRef = useRef2(options);
366
390
  optionsRef.current = options;
@@ -396,12 +420,9 @@ var useMcpServers = (options = {}) => {
396
420
  }, []);
397
421
  const providerFor = (mod, spec) => {
398
422
  if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
399
- return new mod.BrowserOAuthProvider({
400
- serverUrl: spec.url,
401
- redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
402
- clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
403
- scope: spec.oauth?.scope
404
- });
423
+ return new mod.BrowserOAuthProvider(
424
+ mcpOAuthProviderOptions(spec.url, spec.oauth, optionsRef.current)
425
+ );
405
426
  };
406
427
  const connectServer = useCallback2(
407
428
  async (name) => {
@@ -536,6 +557,7 @@ var useMcpServers = (options = {}) => {
536
557
  redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
537
558
  scope: spec.oauth?.scope,
538
559
  clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
560
+ clientMetadataUrl: spec.oauth?.clientMetadataUrl ?? optionsRef.current.clientMetadataUrl,
539
561
  startedAt: Date.now()
540
562
  };
541
563
  writeRecord(pendingKey, pending);
@@ -550,7 +572,12 @@ var useMcpServers = (options = {}) => {
550
572
  let provider = l?.provider;
551
573
  if (!provider && spec?.auth === "oauth") {
552
574
  const mod = await loadMcp().catch(() => void 0);
553
- if (mod?.BrowserOAuthProvider) provider = providerFor(mod, spec);
575
+ if (mod?.BrowserOAuthProvider) {
576
+ try {
577
+ provider = providerFor(mod, spec);
578
+ } catch {
579
+ }
580
+ }
554
581
  }
555
582
  await provider?.reset().catch(() => {
556
583
  });
@@ -606,7 +633,8 @@ var useMcpServers = (options = {}) => {
606
633
  oauth: {
607
634
  redirectUrl: pending.redirectUrl,
608
635
  scope: pending.scope,
609
- clientName: pending.clientName
636
+ clientName: pending.clientName,
637
+ clientMetadataUrl: pending.clientMetadataUrl
610
638
  }
611
639
  });
612
640
  live(spec.name).provider = provider;
@@ -660,6 +688,7 @@ export {
660
688
  claimOAuthCallback,
661
689
  describeMcpResult,
662
690
  isUnauthorizedError,
691
+ mcpOAuthProviderOptions,
663
692
  readCallbackParams,
664
693
  stripOAuthParams,
665
694
  useMcp,
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 ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n McpOAuthCallback,\n McpServerResult,\n} from '../mcp-types.js'\n\nexport type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error'\n\nexport interface McpConnectOptions {\n /** The server's StreamableHTTP endpoint. */\n url: string\n /** Prefix for the discovered tool names (\"<name>__<tool>\"). Default 'mcp'. */\n name?: string\n /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */\n headers?: Record<string, string>\n /**\n * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core\n * that ships the OAuth provider; check `oauthSupported` before offering it.\n */\n oauth?: boolean | { redirectUrl?: string; scope?: string; clientName?: string }\n}\n\nexport interface UseMcpOptions {\n /** Client name reported to the MCP server during initialize. */\n clientName?: string\n /** Called with connector log lines — handy while debugging a server. */\n onLog?: (level: string, message: string) => void\n}\n\nexport interface UseMcpReturn {\n status: McpStatus\n /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */\n tools?: AgentToolSet\n catalog: McpCatalogEntry[]\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * Whether the installed core exposes the OAuth API. `undefined` until the\n * optional subpath has been loaded once — call `checkOAuthSupport()` to\n * resolve it before offering OAuth in your UI.\n */\n oauthSupported?: boolean\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n connect: (options: McpConnectOptions) => Promise<void>\n disconnect: () => Promise<void>\n /** Navigate to the authorization server. Call it from a user gesture. */\n authorize: () => void\n /** Drop the stored tokens and dynamic registration for the current server. */\n forgetAuthorization: () => Promise<void>\n /** Load the optional subpath and report whether it can do OAuth. */\n checkOAuthSupport: () => Promise<boolean>\n}\n\nexport const OAUTH_UNSUPPORTED =\n 'The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.'\n\nconst PENDING_KEY = 'agent-web-react:mcp:pending'\nconst OAUTH_KEY = 'agent-web-react:mcp:oauth'\n\ninterface OAuthRecord {\n url: string\n name?: string\n redirectUrl: string\n scope?: string\n clientName?: string\n /** When the redirect was started, so a stale record can't claim a callback. */\n startedAt?: number\n}\n\n// A round-trip to an authorization server and back takes seconds. Anything\n// older than this is not the flow that produced the ?code= we are looking at —\n// most likely another sign-in on the same page — so we leave it alone.\nexport const PENDING_TTL_MS = 10 * 60 * 1000\n\nlet modulePromise: Promise<McpModule> | undefined\n\n/**\n * Load the core's optional `./mcp` subpath. Kept dynamic so apps that never\n * touch MCP don't pull `@modelcontextprotocol/sdk` into their bundle, and so a\n * core without the OAuth half degrades to a clear message instead of a crash.\n */\nexport const loadMcp = (): Promise<McpModule> => {\n modulePromise ??= import('@dudko.dev/agent-web/mcp')\n .then((m) => m as unknown as McpModule)\n .catch((err: unknown) => {\n // A rejected promise is neither null nor undefined, so ??= would cache\n // the failure forever — one flaky chunk fetch would kill MCP for the tab.\n modulePromise = undefined\n throw err\n })\n return modulePromise\n}\n\n/** Map a single server's connect outcome onto the hook's status. Pure. */\nexport const describeMcpResult = (\n result: McpServerResult | undefined,\n): { status: McpStatus; error?: string } => {\n if (!result) return { status: 'error', error: 'The connector returned no result for the server' }\n if (result.connected) return { status: 'connected' }\n if (result.needsAuthorization) return { status: 'needs-authorization' }\n return { status: 'error', error: result.error ?? 'Could not connect to the MCP server' }\n}\n\nconst OAUTH_PARAMS = ['code', 'state', 'error', 'error_description', 'iss']\n\n/**\n * Read the authorization-code parameters out of a URL **synchronously**.\n *\n * The core exports an equivalent, but it lives behind a dynamic import: by the\n * time that import resolves, React has flushed the rest of the app's effects,\n * and any one of them may have rewritten `location` (the demo's own view\n * router did exactly that). The callback has to be captured before the first\n * await, so this parser is duplicated here on purpose.\n *\n * Reads the query string and, for hash-routed apps, the fragment. Returns\n * undefined when neither a `code` nor an `error` is present.\n */\nexport const readCallbackParams = (href?: string): McpOAuthCallback | undefined => {\n const target =\n href ?? (typeof globalThis.location !== 'undefined' ? globalThis.location.href : undefined)\n if (!target) return undefined\n let url: URL\n try {\n url = new URL(target)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Remove the OAuth response parameters from a URL, leaving the rest intact —\n * query string and fragment alike. The code is single-use and lands in history,\n * referrers and screenshots, so it goes as soon as it has been read.\n */\nexport const stripOAuthParams = (href: string): string => {\n const url = new URL(href)\n for (const key of OAUTH_PARAMS) url.searchParams.delete(key)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n const q = hash.indexOf('?')\n if (q >= 0) {\n const params = new URLSearchParams(hash.slice(q + 1))\n for (const key of OAUTH_PARAMS) params.delete(key)\n const rest = params.toString()\n url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q)\n }\n return url.toString()\n}\n\n// An authorization code is single-use, and React StrictMode mounts every effect\n// twice in development. Claiming happens synchronously, before any await, so\n// the second pass cannot race the first into the token endpoint (where it would\n// lose the state check and report a CSRF failure on a perfectly good flow).\nconst claimedCallbacks = new Set<string>()\n\nexport const claimOAuthCallback = (callback: McpOAuthCallback): boolean => {\n const key = `${callback.code ?? ''}|${callback.state ?? ''}|${callback.error ?? ''}`\n if (claimedCallbacks.has(key)) return false\n claimedCallbacks.add(key)\n return true\n}\n\nexport const readRecord = <T>(key: string): T | undefined => {\n try {\n const raw = globalThis.localStorage?.getItem(key)\n return raw ? (JSON.parse(raw) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nexport const writeRecord = (key: string, value: unknown): void => {\n try {\n if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))\n else globalThis.localStorage?.removeItem(key)\n } catch {\n // Private mode / storage disabled: the OAuth round-trip simply won't\n // resume automatically, which the UI already handles.\n }\n}\n\n// A redirect_uri must not carry a fragment (RFC 6749 §3.1.2), and it has to\n// match the registered value byte-for-byte, so query and hash are dropped.\nexport const defaultRedirectUrl = (): string =>\n typeof globalThis.location === 'undefined'\n ? ''\n : `${globalThis.location.origin}${globalThis.location.pathname}`\n\n/**\n * Did this error come from the server refusing our authorization?\n *\n * Identity, not strings: the SDK's `UnauthorizedError` never assigns\n * `this.name` (so it reads as \"Error\"), and its message would also match a\n * tool whose own error text mentions \"unauthorized\" — the connector throws a\n * failing tool's text verbatim. The class is re-exported by the core's `./mcp`\n * subpath for exactly this; `constructor.name` is the fallback for a core too\n * old to export it.\n */\nexport const isUnauthorizedError = (err: unknown, mod?: McpModule): boolean => {\n if (!(err instanceof Error)) return false\n if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true\n return err.constructor?.name === 'UnauthorizedError'\n}\n\n/**\n * Wrap each tool so a mid-session authorization failure is visible. Without\n * this the panel keeps reporting \"connected\" while every call fails: the core\n * refreshes silently on a 401, but once the refresh token is gone (revoked,\n * expired) it can only ask for a new authorization.\n */\nexport const watchAuthorization = (\n tools: AgentToolSet,\n mod: McpModule,\n onUnauthorized: () => void,\n): AgentToolSet => {\n const entries = Object.entries(tools as Record<string, unknown>).map(([name, value]) => {\n const tool = value as { execute?: (args: unknown, options: unknown) => unknown }\n if (typeof tool.execute !== 'function') return [name, value]\n const execute = tool.execute.bind(tool)\n const watched = (args: unknown, options: unknown): unknown => {\n // Deliberately not an async function: the AI SDK inspects what `execute`\n // returns SYNCHRONOUSLY to decide whether a tool streams (isAsyncIterable),\n // so wrapping everything in a promise would collapse a streaming tool into\n // a single opaque result.\n try {\n const out = execute(args, options)\n if (out && typeof (out as Promise<unknown>).then === 'function') {\n return (out as Promise<unknown>).then(undefined, (err: unknown) => {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n })\n }\n return out\n } catch (err) {\n if (isUnauthorizedError(err, mod)) onUnauthorized()\n throw err\n }\n }\n return [name, { ...(value as object), execute: watched }]\n })\n return Object.fromEntries(entries) as AgentToolSet\n}\n\n/**\n * Connect the browser agent to a remote MCP server the user names at runtime —\n * static header, or full OAuth 2.1 with dynamic client registration.\n *\n * The OAuth round-trip leaves the page, so the hook persists what it needs to\n * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL\n * and reconnects, all before the app renders anything MCP-related.\n *\n * ```tsx\n * const mcp = useMcp()\n * // await mcp.connect({ url, oauth: true })\n * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>\n * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>\n * ```\n */\nexport const useMcp = (options: UseMcpOptions = {}): UseMcpReturn => {\n const [status, setStatus] = useState<McpStatus>('idle')\n const [tools, setTools] = useState<AgentToolSet | undefined>(undefined)\n const [catalog, setCatalog] = useState<McpCatalogEntry[]>([])\n const [error, setError] = useState<string | undefined>(undefined)\n const [authorizationUrl, setAuthorizationUrl] = useState<string | undefined>(undefined)\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompletingAuthorization] = useState(\n () => readCallbackParams() !== undefined,\n )\n\n const connectionRef = useRef<ConnectedMcp | undefined>(undefined)\n const providerRef = useRef<BrowserOAuthProvider | undefined>(undefined)\n // Bumped by every connect / disconnect / unmount. A handshake that finishes\n // after its epoch has passed closes itself instead of writing state or\n // leaking an open MCP session onto a dead component.\n const epochRef = useRef(0)\n // Options land in a ref so `connect` keeps a stable identity: it is a natural\n // dependency of effects in host components.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const closeConnection = useCallback(async () => {\n const open = connectionRef.current\n connectionRef.current = undefined\n if (open) await open.close().catch(() => {})\n }, [])\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n const connect = useCallback(\n async (opts: McpConnectOptions) => {\n const epoch = ++epochRef.current\n const current = () => epochRef.current === epoch\n await closeConnection()\n if (!current()) return\n setStatus('connecting')\n setError(undefined)\n setAuthorizationUrl(undefined)\n setTools(undefined)\n setCatalog([])\n\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n const name = opts.name ?? 'mcp'\n let authProvider: BrowserOAuthProvider | undefined\n\n if (opts.oauth) {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const oauth = typeof opts.oauth === 'object' ? opts.oauth : {}\n const record: OAuthRecord = {\n url: opts.url,\n name,\n redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),\n scope: oauth.scope,\n clientName: oauth.clientName ?? optionsRef.current.clientName,\n startedAt: Date.now(),\n }\n authProvider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\n })\n providerRef.current = authProvider\n // `pending` resumes the redirect; `oauth` outlives it so tokens stay\n // addressable for forgetAuthorization() after a reload.\n writeRecord(PENDING_KEY, record)\n writeRecord(OAUTH_KEY, record)\n } else {\n providerRef.current = undefined\n }\n\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: opts.url,\n headers: opts.oauth ? undefined : opts.headers,\n authProvider,\n },\n },\n { clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog },\n )\n\n if (!current()) {\n // Unmounted, or another connect started while we were shaking hands.\n await connection.close().catch(() => {})\n return\n }\n\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = authProvider?.authorizationUrl\n setAuthorizationUrl(url ? String(url) : undefined)\n setStatus('needs-authorization')\n return\n }\n throw new Error(outcome.error)\n }\n\n connectionRef.current = connection\n // The round-trip is over: a stale record would later make an unrelated\n // ?code= on this page look like ours.\n writeRecord(PENDING_KEY, undefined)\n setTools(\n watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = providerRef.current?.authorizationUrl\n if (url) setAuthorizationUrl(String(url))\n setStatus('needs-authorization')\n }),\n )\n setCatalog(connection.catalog)\n setStatus('connected')\n } catch (err) {\n if (!current()) return\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n }\n },\n [closeConnection],\n )\n\n const disconnect = useCallback(async () => {\n epochRef.current++\n await closeConnection()\n setTools(undefined)\n setCatalog([])\n setAuthorizationUrl(undefined)\n setError(undefined)\n setStatus('idle')\n }, [closeConnection])\n\n const authorize = useCallback(() => {\n if (authorizationUrl && typeof globalThis.location !== 'undefined') {\n globalThis.location.href = authorizationUrl\n }\n }, [authorizationUrl])\n\n const forgetAuthorization = useCallback(async () => {\n const record = readRecord<OAuthRecord>(OAUTH_KEY)\n writeRecord(PENDING_KEY, undefined)\n writeRecord(OAUTH_KEY, undefined)\n // After a reload there is no live provider, but the tokens are still in the\n // vault — rebuild one for the same server so \"forget\" actually forgets\n // rather than only resetting the UI.\n let provider = providerRef.current\n if (!provider && record) {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n provider = new mod.BrowserOAuthProvider({\n serverUrl: record.url,\n redirectUrl: record.redirectUrl,\n clientName: record.clientName,\n scope: record.scope,\n })\n }\n }\n await provider?.reset().catch(() => {})\n providerRef.current = undefined\n await disconnect()\n }, [disconnect])\n\n // Resume an OAuth round-trip: the authorization server has just sent the user\n // back with ?code=… and this component is mounting for the first time.\n useEffect(() => {\n // Everything up to the first await runs synchronously, on purpose: React\n // flushes the remaining passive effects (which may rewrite location) before\n // an awaited continuation resumes, and StrictMode runs this effect twice.\n const callback = readCallbackParams()\n if (!callback) {\n setCompletingAuthorization(false)\n return\n }\n const pending = readRecord<OAuthRecord>(PENDING_KEY)\n // A record only proves that WE started a flow, not that THIS callback is\n // its answer — so an expired one is treated as somebody else's. Either way\n // the URL is left exactly as we found it: another sign-in flow on this page\n // may still need those parameters.\n const fresh =\n pending !== undefined &&\n (pending.startedAt === undefined || Date.now() - pending.startedAt < PENDING_TTL_MS)\n if (!pending || !fresh) {\n if (pending) writeRecord(PENDING_KEY, undefined)\n setCompletingAuthorization(false)\n return\n }\n if (!claimOAuthCallback(callback)) {\n setCompletingAuthorization(false)\n return\n }\n // Ours, and claimed: the code is in hand, so clear it from the address bar\n // now rather than after the reconnect.\n if (typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n\n void (async () => {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const provider = new mod.BrowserOAuthProvider({\n serverUrl: pending.url,\n redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),\n clientName: pending.clientName,\n scope: pending.scope,\n })\n providerRef.current = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(PENDING_KEY, undefined)\n // NOT gated on `cancelled`. StrictMode's simulated cleanup sets it in\n // development, and the second setup cannot take over — the code has\n // already been claimed and stripped from the URL — so bailing here\n // would finish the authorization and then never connect. `connect` is\n // epoch-guarded and a setState after a real unmount is a no-op, so\n // letting it run is safe either way.\n //\n // Hand back to `connect`, which owns the status from here — a slow or\n // hung handshake must not leave the UI stuck on \"finishing\".\n setCompletingAuthorization(false)\n await connect({ url: pending.url, name: pending.name, oauth: true })\n } catch (err) {\n writeRecord(PENDING_KEY, undefined)\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n } finally {\n setCompletingAuthorization(false)\n }\n })()\n // Runs once: `connect` is stable and the callback exists only on first load.\n }, [connect])\n\n useEffect(\n () => () => {\n epochRef.current++\n void closeConnection()\n },\n [closeConnection],\n )\n\n return {\n status,\n tools,\n catalog,\n error,\n authorizationUrl,\n oauthSupported,\n completingAuthorization,\n connect,\n disconnect,\n authorize,\n forgetAuthorization,\n checkOAuthSupport,\n }\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { AgentToolSet } from '@dudko.dev/agent-web'\nimport type {\n BrowserOAuthProvider,\n ConnectedMcp,\n McpCatalogEntry,\n McpModule,\n} from '../mcp-types.js'\nimport {\n claimOAuthCallback,\n defaultRedirectUrl,\n describeMcpResult,\n loadMcp,\n OAUTH_UNSUPPORTED,\n PENDING_TTL_MS,\n readCallbackParams,\n readRecord,\n stripOAuthParams,\n watchAuthorization,\n writeRecord,\n type McpStatus,\n type UseMcpOptions,\n} from './use-mcp.js'\n\nexport type McpAuthMode = 'none' | 'bearer' | 'oauth'\n\n/** One server the user wants connected. */\nexport interface McpServerSpec {\n /**\n * Unique name; also the tool prefix (\"<name>__<tool>\"). Sanitised to\n * `[a-zA-Z0-9_-]`; a taken name gets a numeric suffix.\n */\n name: string\n /** The server's StreamableHTTP endpoint. */\n url: string\n auth?: McpAuthMode\n /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */\n token?: string\n /** OAuth details for `auth: 'oauth'`. */\n oauth?: { redirectUrl?: string; scope?: string; clientName?: string }\n}\n\n/** A server's live state. */\nexport interface McpServerView {\n name: string\n url: string\n auth: McpAuthMode\n status: McpStatus\n error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n catalog: McpCatalogEntry[]\n}\n\nexport interface UseMcpServersOptions extends UseMcpOptions {\n /**\n * Remember the server list (never tokens) in localStorage so it survives a\n * reload — and the OAuth redirect, which IS a reload (default true).\n */\n persist?: boolean\n /** localStorage key of the list (default 'agent-web-react:mcp-servers'). */\n storageKey?: string\n /** Reconnect remembered servers on mount (default true). Bearer servers wait for their token. */\n autoConnect?: boolean\n /** Per-server connect deadline in ms (default: the core's, 30 s). */\n connectTimeoutMs?: number\n}\n\nexport interface UseMcpServersReturn {\n servers: McpServerView[]\n /** Tools of every connected server, merged — pass to `BrowserAgentConfig.tools`. */\n tools: AgentToolSet\n /** Catalogue of every connected server, merged. */\n catalog: McpCatalogEntry[]\n connectedCount: number\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n /** Whether the installed core can do OAuth (undefined until checked). */\n oauthSupported?: boolean\n checkOAuthSupport: () => Promise<boolean>\n /** Add (or replace, by name) a server and connect it. Resolves with the final name. */\n add: (spec: McpServerSpec) => Promise<string>\n /** Disconnect and forget a server. */\n remove: (name: string) => Promise<void>\n /** Connect again — optionally with a fresh bearer token. */\n reconnect: (name: string, token?: string) => Promise<void>\n /** Navigate to the server's authorization page. Call it from a user gesture. */\n authorize: (name: string) => void\n /** Drop a server's stored OAuth tokens and registration. */\n forgetAuthorization: (name: string) => Promise<void>\n}\n\ninterface StoredServer {\n name: string\n url: string\n auth: McpAuthMode\n oauth?: McpServerSpec['oauth']\n}\n\ninterface PendingRecord {\n name: string\n url: string\n redirectUrl: string\n scope?: string\n clientName?: string\n startedAt: number\n}\n\ninterface Live {\n epoch: number\n connection?: ConnectedMcp\n provider?: BrowserOAuthProvider\n tools?: AgentToolSet\n token?: string\n}\n\nconst DEFAULT_KEY = 'agent-web-react:mcp-servers'\n\nconst sanitize = (s: string): string => s.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 32) || 'mcp'\n\nconst view = (s: StoredServer, patch: Partial<McpServerView> = {}): McpServerView => ({\n name: s.name,\n url: s.url,\n auth: s.auth,\n status: 'idle',\n catalog: [],\n ...patch,\n})\n\n/**\n * Connect the browser agent to SEVERAL remote MCP servers at once, each with\n * its own auth (none, a bearer token, or OAuth 2.1 + dynamic registration).\n * Every server is its own connection — adding or removing one never touches\n * the others — and their tools merge into one `tools` set, prefixed by server\n * name. The list is remembered across reloads (tokens excepted), and an OAuth\n * round-trip resumes on return.\n *\n * ```tsx\n * const mcp = useMcpServers()\n * // await mcp.add({ name: 'github', url, auth: 'oauth' })\n * // await mcp.add({ name: 'docs', url, auth: 'bearer', token })\n * const agent = useAgent({ model, tools: { ...local, ...mcp.tools } }, { deps: [mcp.tools] })\n * ```\n *\n * With many servers the merged catalogue can reach hundreds of tools; the core\n * switches to tool search above `toolSearchThreshold` automatically.\n */\nexport const useMcpServers = (options: UseMcpServersOptions = {}): UseMcpServersReturn => {\n const storageKey = options.storageKey ?? DEFAULT_KEY\n const pendingKey = `${storageKey}:pending`\n const persist = options.persist !== false\n\n const [servers, setServers] = useState<McpServerView[]>(() =>\n persist ? (readRecord<StoredServer[]>(storageKey) ?? []).map((s) => view(s)) : [],\n )\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompleting] = useState(\n () => readCallbackParams() !== undefined && readRecord(pendingKey) !== undefined,\n )\n // Bumped whenever a server's tools change, to recompute the merged set.\n const [toolsVersion, setToolsVersion] = useState(0)\n\n const liveRef = useRef(new Map<string, Live>())\n const specsRef = useRef(new Map<string, StoredServer>())\n if (specsRef.current.size === 0 && servers.length > 0) {\n for (const s of servers)\n specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth })\n }\n const optionsRef = useRef(options)\n optionsRef.current = options\n const unmountedRef = useRef(false)\n\n const saveList = useCallback(() => {\n if (!persist) return\n writeRecord(storageKey, [...specsRef.current.values()])\n }, [persist, storageKey])\n\n const patch = useCallback((name: string, p: Partial<McpServerView>) => {\n if (unmountedRef.current) return\n setServers((list) => list.map((s) => (s.name === name ? { ...s, ...p } : s)))\n }, [])\n\n const live = (name: string): Live => {\n let l = liveRef.current.get(name)\n if (!l) {\n l = { epoch: 0 }\n liveRef.current.set(name, l)\n }\n return l\n }\n\n const closeServer = useCallback(async (name: string) => {\n const l = liveRef.current.get(name)\n if (!l) return\n l.epoch += 1\n const open = l.connection\n l.connection = undefined\n if (l.tools) {\n l.tools = undefined\n setToolsVersion((v) => v + 1)\n }\n if (open) await open.close().catch(() => {})\n }, [])\n\n const providerFor = (mod: McpModule, spec: StoredServer): BrowserOAuthProvider => {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n return new mod.BrowserOAuthProvider({\n serverUrl: spec.url,\n redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),\n clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,\n scope: spec.oauth?.scope,\n })\n }\n\n const connectServer = useCallback(\n async (name: string): Promise<void> => {\n const spec = specsRef.current.get(name)\n if (!spec) return\n await closeServer(name)\n const l = live(name)\n const epoch = ++l.epoch\n const current = () => !unmountedRef.current && l.epoch === epoch\n if (spec.auth === 'bearer' && !l.token) {\n patch(name, { status: 'idle', error: 'Enter the bearer token to connect.' })\n return\n }\n patch(name, {\n status: 'connecting',\n error: undefined,\n authorizationUrl: undefined,\n catalog: [],\n })\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n let provider: BrowserOAuthProvider | undefined\n if (spec.auth === 'oauth') {\n provider = providerFor(mod, spec)\n l.provider = provider\n }\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: spec.url,\n headers:\n spec.auth === 'bearer' && l.token\n ? { Authorization: `Bearer ${l.token}` }\n : undefined,\n authProvider: provider,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n },\n {\n clientName: optionsRef.current.clientName,\n onLog: optionsRef.current.onLog,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n )\n if (!current()) {\n await connection.close().catch(() => {})\n return\n }\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n return\n }\n throw new Error(outcome.error)\n }\n l.connection = connection\n l.tools = watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = l.provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n })\n setToolsVersion((v) => v + 1)\n patch(name, { status: 'connected', catalog: connection.catalog })\n } catch (err) {\n if (!current()) return\n patch(name, { status: 'error', error: err instanceof Error ? err.message : String(err) })\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const add = useCallback(\n async (input: McpServerSpec): Promise<string> => {\n let name = sanitize(input.name)\n // A different server under a taken name gets a suffix; the same URL replaces.\n const taken = specsRef.current.get(name)\n if (taken && taken.url !== input.url) {\n let n = 2\n while (specsRef.current.has(`${name}_${n}`)) n += 1\n name = `${name}_${n}`\n }\n const spec: StoredServer = {\n name,\n url: input.url,\n auth: input.auth ?? 'none',\n ...(input.oauth ? { oauth: input.oauth } : {}),\n }\n specsRef.current.set(name, spec)\n live(name).token = input.auth === 'bearer' ? input.token : undefined\n setServers((list) =>\n list.some((s) => s.name === name)\n ? list.map((s) => (s.name === name ? view(spec) : s))\n : [...list, view(spec)],\n )\n saveList()\n await connectServer(name)\n return name\n },\n [connectServer, saveList],\n )\n\n const remove = useCallback(\n async (name: string) => {\n await closeServer(name)\n liveRef.current.delete(name)\n specsRef.current.delete(name)\n saveList()\n setServers((list) => list.filter((s) => s.name !== name))\n },\n [closeServer, saveList],\n )\n\n const reconnect = useCallback(\n async (name: string, token?: string) => {\n if (token !== undefined) live(name).token = token\n await connectServer(name)\n },\n [connectServer],\n )\n\n const authorize = useCallback(\n (name: string) => {\n const url = servers.find((s) => s.name === name)?.authorizationUrl\n const spec = specsRef.current.get(name)\n if (!url || !spec || typeof globalThis.location === 'undefined') return\n // The redirect reloads the page: remember which server it is for. Written\n // here, at the user's click, so with several servers awaiting consent the\n // record always names the one actually being authorized.\n const pending: PendingRecord = {\n name,\n url: spec.url,\n redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),\n scope: spec.oauth?.scope,\n clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,\n startedAt: Date.now(),\n }\n writeRecord(pendingKey, pending)\n globalThis.location.href = url\n },\n [servers, pendingKey],\n )\n\n const forgetAuthorization = useCallback(\n async (name: string) => {\n const spec = specsRef.current.get(name)\n const l = liveRef.current.get(name)\n let provider = l?.provider\n if (!provider && spec?.auth === 'oauth') {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) provider = providerFor(mod, spec)\n }\n await provider?.reset().catch(() => {})\n if (l) l.provider = undefined\n const pending = readRecord<PendingRecord>(pendingKey)\n if (pending?.name === name) writeRecord(pendingKey, undefined)\n await closeServer(name)\n patch(name, { status: 'idle', authorizationUrl: undefined, catalog: [], error: undefined })\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n // On mount: finish an OAuth round-trip that came back to this page, then\n // reconnect the remembered servers.\n useEffect(() => {\n unmountedRef.current = false\n // Synchronous up to the first await, like useMcp: another effect may\n // rewrite `location`, and StrictMode runs this twice.\n const callback = readCallbackParams()\n const pending = readRecord<PendingRecord>(pendingKey)\n const fresh = pending !== undefined && Date.now() - pending.startedAt < PENDING_TTL_MS\n const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback))\n if (callback && pending && !fresh) writeRecord(pendingKey, undefined)\n if (ours && typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n const autoConnect = optionsRef.current.autoConnect !== false\n void (async () => {\n if (ours && pending && callback) {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const spec = specsRef.current.get(pending.name) ?? {\n name: pending.name,\n url: pending.url,\n auth: 'oauth' as const,\n }\n if (!specsRef.current.has(spec.name)) {\n specsRef.current.set(spec.name, spec)\n setServers((list) => [...list, view(spec)])\n saveList()\n }\n const provider = providerFor(mod, {\n ...spec,\n oauth: {\n redirectUrl: pending.redirectUrl,\n scope: pending.scope,\n clientName: pending.clientName,\n },\n })\n live(spec.name).provider = provider\n await mod.finishMcpOAuth(provider, callback)\n writeRecord(pendingKey, undefined)\n } catch (err) {\n writeRecord(pendingKey, undefined)\n patch(pending.name, {\n status: 'error',\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n setCompleting(false)\n if (autoConnect || ours) {\n await Promise.all(\n [...specsRef.current.keys()]\n .filter((name) => autoConnect || name === pending?.name)\n .map((name) => connectServer(name)),\n )\n }\n })()\n return () => {\n unmountedRef.current = true\n for (const name of liveRef.current.keys()) void closeServer(name)\n }\n // Runs once: the callbacks are stable and the redirect exists only on first load.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const tools = useMemo<AgentToolSet>(() => {\n const merged: AgentToolSet = {}\n for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools)\n return merged\n // toolsVersion is the change signal for the mutable map.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toolsVersion])\n\n const catalog = useMemo(\n () => servers.filter((s) => s.status === 'connected').flatMap((s) => s.catalog),\n [servers],\n )\n\n return {\n servers,\n tools,\n catalog,\n connectedCount: servers.filter((s) => s.status === 'connected').length,\n completingAuthorization,\n oauthSupported,\n checkOAuthSupport,\n add,\n remove,\n reconnect,\n authorize,\n forgetAuthorization,\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AA4DlD,IAAM,oBACX;AAEF,IAAM,cAAc;AACpB,IAAM,YAAY;AAeX,IAAM,iBAAiB,KAAK,KAAK;AAExC,IAAI;AAOG,IAAM,UAAU,MAA0B;AAC/C,oBAAkB,OAAO,0BAA0B,EAChD,KAAK,CAAC,MAAM,CAAyB,EACrC,MAAM,CAAC,QAAiB;AAGvB,oBAAgB;AAChB,UAAM;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,QAAQ,SAAS,SAAS,qBAAqB,KAAK;AAcnE,IAAM,qBAAqB,CAAC,SAAgD;AACjF,QAAM,SACJ,SAAS,OAAO,WAAW,aAAa,cAAc,WAAW,SAAS,OAAO;AACnF,MAAI,C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,gBAAM,QAAQ,MAAM;AAAA,YAClB,QAAQ;AAAA,YACR,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,UACxD,CAAC;AAAA,QACH;AAAA,MACF;AACA,oBAAc,KAAK;AACnB,UAAI,eAAe,MAAM;AACvB,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"]}
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 error?: string\n /** Where to send the user when `status === 'needs-authorization'`. */\n authorizationUrl?: string\n /**\n * Whether the installed core exposes the OAuth API. `undefined` until the\n * optional subpath has been loaded once — call `checkOAuthSupport()` to\n * resolve it before offering OAuth in your UI.\n */\n oauthSupported?: boolean\n /** True while an OAuth redirect is being finished on mount. */\n completingAuthorization: boolean\n connect: (options: McpConnectOptions) => Promise<void>\n disconnect: () => Promise<void>\n /** Navigate to the authorization server. Call it from a user gesture. */\n authorize: () => void\n /** Drop the stored tokens and dynamic registration for the current server. */\n forgetAuthorization: () => Promise<void>\n /** Load the optional subpath and report whether it can do OAuth. */\n checkOAuthSupport: () => Promise<boolean>\n}\n\nexport const OAUTH_UNSUPPORTED =\n 'The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.'\n\nconst PENDING_KEY = 'agent-web-react:mcp:pending'\nconst OAUTH_KEY = 'agent-web-react:mcp:oauth'\n\ninterface OAuthRecord {\n url: string\n name?: string\n redirectUrl: string\n scope?: string\n clientName?: string\n 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 [error, setError] = useState<string | undefined>(undefined)\n const [authorizationUrl, setAuthorizationUrl] = useState<string | undefined>(undefined)\n const [oauthSupported, setOauthSupported] = useState<boolean | undefined>(undefined)\n const [completingAuthorization, setCompletingAuthorization] = useState(\n () => readCallbackParams() !== undefined,\n )\n\n const connectionRef = useRef<ConnectedMcp | undefined>(undefined)\n const providerRef = useRef<BrowserOAuthProvider | undefined>(undefined)\n // Bumped by every connect / disconnect / unmount. A handshake that finishes\n // after its epoch has passed closes itself instead of writing state or\n // leaking an open MCP session onto a dead component.\n const epochRef = useRef(0)\n // Options land in a ref so `connect` keeps a stable identity: it is a natural\n // dependency of effects in host components.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const closeConnection = useCallback(async () => {\n const open = connectionRef.current\n connectionRef.current = undefined\n if (open) await open.close().catch(() => {})\n }, [])\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n const connect = useCallback(\n async (opts: McpConnectOptions) => {\n const epoch = ++epochRef.current\n const current = () => epochRef.current === epoch\n await closeConnection()\n if (!current()) return\n setStatus('connecting')\n setError(undefined)\n setAuthorizationUrl(undefined)\n setTools(undefined)\n setCatalog([])\n\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n const name = opts.name ?? 'mcp'\n let authProvider: BrowserOAuthProvider | undefined\n\n if (opts.oauth) {\n if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED)\n const 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 setStatus('connected')\n } catch (err) {\n if (!current()) return\n setError(err instanceof Error ? err.message : String(err))\n setStatus('error')\n }\n },\n [closeConnection],\n )\n\n const disconnect = useCallback(async () => {\n epochRef.current++\n await closeConnection()\n setTools(undefined)\n setCatalog([])\n setAuthorizationUrl(undefined)\n setError(undefined)\n setStatus('idle')\n }, [closeConnection])\n\n const authorize = useCallback(() => {\n if (authorizationUrl && typeof globalThis.location !== 'undefined') {\n globalThis.location.href = authorizationUrl\n }\n }, [authorizationUrl])\n\n const forgetAuthorization = useCallback(async () => {\n const record = readRecord<OAuthRecord>(OAUTH_KEY)\n writeRecord(PENDING_KEY, undefined)\n writeRecord(OAUTH_KEY, undefined)\n // After a reload there is no live provider, but the tokens are still in the\n // vault — rebuild one for the same server so \"forget\" actually forgets\n // rather than only resetting the UI.\n let provider = providerRef.current\n if (!provider && record) {\n const mod = await loadMcp().catch(() => undefined)\n if (mod?.BrowserOAuthProvider) {\n 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 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 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\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 })\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n let provider: BrowserOAuthProvider | undefined\n if (spec.auth === 'oauth') {\n provider = providerFor(mod, spec)\n l.provider = provider\n }\n const connection = await mod.connectMcpHttp(\n {\n [name]: {\n url: spec.url,\n headers:\n spec.auth === 'bearer' && l.token\n ? { Authorization: `Bearer ${l.token}` }\n : undefined,\n authProvider: provider,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n },\n {\n clientName: optionsRef.current.clientName,\n onLog: optionsRef.current.onLog,\n connectTimeoutMs: optionsRef.current.connectTimeoutMs,\n },\n )\n if (!current()) {\n await connection.close().catch(() => {})\n return\n }\n const outcome = describeMcpResult(connection.results[0])\n if (outcome.status !== 'connected') {\n await connection.close().catch(() => {})\n if (outcome.status === 'needs-authorization') {\n const url = provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n return\n }\n throw new Error(outcome.error)\n }\n l.connection = connection\n l.tools = watchAuthorization(connection.tools, mod, () => {\n if (!current()) return\n const url = l.provider?.authorizationUrl\n patch(name, {\n status: 'needs-authorization',\n authorizationUrl: url ? String(url) : undefined,\n })\n })\n setToolsVersion((v) => v + 1)\n patch(name, { status: 'connected', catalog: connection.catalog })\n } catch (err) {\n if (!current()) return\n patch(name, { status: 'error', error: err instanceof Error ? err.message : String(err) })\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const add = useCallback(\n async (input: McpServerSpec): Promise<string> => {\n let name = sanitize(input.name)\n // A different server under a taken name gets a suffix; the same URL replaces.\n const taken = specsRef.current.get(name)\n if (taken && taken.url !== input.url) {\n let n = 2\n while (specsRef.current.has(`${name}_${n}`)) n += 1\n name = `${name}_${n}`\n }\n const spec: StoredServer = {\n name,\n url: input.url,\n auth: input.auth ?? 'none',\n ...(input.oauth ? { oauth: input.oauth } : {}),\n }\n specsRef.current.set(name, spec)\n live(name).token = input.auth === 'bearer' ? input.token : undefined\n setServers((list) =>\n list.some((s) => s.name === name)\n ? list.map((s) => (s.name === name ? view(spec) : s))\n : [...list, view(spec)],\n )\n saveList()\n await connectServer(name)\n return name\n },\n [connectServer, saveList],\n )\n\n const remove = useCallback(\n async (name: string) => {\n await closeServer(name)\n liveRef.current.delete(name)\n specsRef.current.delete(name)\n saveList()\n setServers((list) => list.filter((s) => s.name !== name))\n },\n [closeServer, saveList],\n )\n\n const reconnect = useCallback(\n async (name: string, token?: string) => {\n if (token !== undefined) live(name).token = token\n await connectServer(name)\n },\n [connectServer],\n )\n\n const authorize = useCallback(\n (name: string) => {\n const url = servers.find((s) => s.name === name)?.authorizationUrl\n const spec = specsRef.current.get(name)\n if (!url || !spec || typeof globalThis.location === 'undefined') return\n // The redirect reloads the page: remember which server it is for. Written\n // here, at the user's click, so with several servers awaiting consent the\n // record always names the one actually being authorized.\n const pending: PendingRecord = {\n name,\n url: spec.url,\n redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),\n scope: spec.oauth?.scope,\n clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,\n 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, { status: 'idle', authorizationUrl: undefined, catalog: [], error: undefined })\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [closeServer, patch, pendingKey],\n )\n\n const checkOAuthSupport = useCallback(async () => {\n try {\n const mod = await loadMcp()\n const supported = typeof mod.BrowserOAuthProvider === 'function'\n setOauthSupported(supported)\n return supported\n } catch {\n setOauthSupported(false)\n return false\n }\n }, [])\n\n // On mount: finish an OAuth round-trip that came back to this page, then\n // reconnect the remembered servers.\n useEffect(() => {\n unmountedRef.current = false\n // Synchronous up to the first await, like useMcp: another effect may\n // rewrite `location`, and StrictMode runs this twice.\n const callback = readCallbackParams()\n const pending = readRecord<PendingRecord>(pendingKey)\n const fresh = pending !== undefined && Date.now() - pending.startedAt < PENDING_TTL_MS\n const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback))\n if (callback && pending && !fresh) writeRecord(pendingKey, undefined)\n if (ours && typeof globalThis.history !== 'undefined') {\n globalThis.history.replaceState(null, '', stripOAuthParams(globalThis.location.href))\n }\n const autoConnect = optionsRef.current.autoConnect !== false\n void (async () => {\n if (ours && pending && callback) {\n try {\n const mod = await loadMcp()\n setOauthSupported(typeof mod.BrowserOAuthProvider === 'function')\n if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED)\n const spec = specsRef.current.get(pending.name) ?? {\n name: pending.name,\n url: pending.url,\n auth: 'oauth' as const,\n }\n if (!specsRef.current.has(spec.name)) {\n specsRef.current.set(spec.name, spec)\n setServers((list) => [...list, view(spec)])\n saveList()\n }\n const provider = providerFor(mod, {\n ...spec,\n oauth: {\n redirectUrl: pending.redirectUrl,\n scope: pending.scope,\n clientName: pending.clientName,\n 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;AAwFlD,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,QAAQ,SAAS,SAAS,qBAAqB,KAAK;AAcnE,IAAM,qBAAqB,CAAC,SAAgD;AACjF,QAAM,SACJ,SAAS,OAAO,WAAW,aAAa,cAAc,WAAW,SAAS,OAAO;AACnF,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,MAAM;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,IAAI,gBAAgB,IAAI,MAAM;AAC7C,QAAM,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI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