@dudko.dev/agent-web-react 0.0.3 → 0.0.4

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/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { DependencyList, ReactNode, CSSProperties } from 'react';
3
- import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunResult, Agent, AgentEventHandler, BrowserAgentConfig, CredentialStore, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunResult, Agent, AgentEventHandler, BrowserAgentConfig, CredentialStore, AgentToolSet, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
4
4
  export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, BrowserAgentConfig, CredentialStore, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, LogLevel, MemoryCredentialStore, ModelInput, ProviderModelSpec, ProviderType, RunOptions, RunResult, VaultCredentialStore, createAgent, createWebLLMModel, defineTool, isWebGPUAvailable, preloadWebLLMModel, unloadWebLLMModel } from '@dudko.dev/agent-web';
5
5
 
6
6
  /**
@@ -165,6 +165,175 @@ interface UseCredentialsReturn {
165
165
  */
166
166
  declare const useCredentials: (store?: CredentialStore) => UseCredentialsReturn;
167
167
 
168
+ /**
169
+ * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
170
+ *
171
+ * The subpath is loaded with a dynamic import and typed here rather than
172
+ * imported, for two reasons: it drags in `@modelcontextprotocol/sdk` (an
173
+ * optional peer of the core, which apps without MCP must not have to install),
174
+ * and the OAuth half only exists in newer cores while this package supports
175
+ * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
176
+ * reports `oauthSupported: false` on an older core instead of crashing.
177
+ */
178
+ interface McpCatalogEntry {
179
+ name: string;
180
+ description: string;
181
+ server: string;
182
+ }
183
+ interface McpServerResult {
184
+ name: string;
185
+ connected: boolean;
186
+ error?: string;
187
+ needsAuthorization?: boolean;
188
+ }
189
+ interface ConnectedMcp {
190
+ tools: AgentToolSet;
191
+ catalog: McpCatalogEntry[];
192
+ results: McpServerResult[];
193
+ refreshServer?: (name: string) => Promise<void>;
194
+ close: () => Promise<void>;
195
+ }
196
+ interface McpHttpServerConfig {
197
+ url: string;
198
+ headers?: Record<string, string>;
199
+ authProvider?: unknown;
200
+ }
201
+ interface McpOAuthCallback {
202
+ code?: string;
203
+ state?: string;
204
+ error?: string;
205
+ errorDescription?: string;
206
+ }
207
+ interface BrowserOAuthProvider {
208
+ serverUrl: string;
209
+ authorizationUrl?: URL;
210
+ isAuthorized(): Promise<boolean>;
211
+ reset(): Promise<void>;
212
+ }
213
+ interface BrowserOAuthProviderOptions {
214
+ serverUrl: string;
215
+ redirectUrl: string;
216
+ clientName?: string;
217
+ scope?: string;
218
+ }
219
+ /** The shape of the subpath module, as far as this package uses it. */
220
+ interface McpModule {
221
+ connectMcpHttp: (servers: Record<string, McpHttpServerConfig>, opts?: {
222
+ clientName?: string;
223
+ onLog?: (level: string, message: string) => void;
224
+ }) => Promise<ConnectedMcp>;
225
+ BrowserOAuthProvider?: new (opts: BrowserOAuthProviderOptions) => BrowserOAuthProvider;
226
+ readOAuthCallback?: (input?: string | URL) => McpOAuthCallback | undefined;
227
+ finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
228
+ /**
229
+ * The SDK's error class, re-exported by the core so an authorization failure
230
+ * can be recognised by identity. Absent on cores older than 0.0.12.
231
+ */
232
+ UnauthorizedError?: new (message?: string) => Error;
233
+ }
234
+
235
+ type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error';
236
+ interface McpConnectOptions {
237
+ /** The server's StreamableHTTP endpoint. */
238
+ url: string;
239
+ /** Prefix for the discovered tool names ("<name>__<tool>"). Default 'mcp'. */
240
+ name?: string;
241
+ /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */
242
+ headers?: Record<string, string>;
243
+ /**
244
+ * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core
245
+ * that ships the OAuth provider; check `oauthSupported` before offering it.
246
+ */
247
+ oauth?: boolean | {
248
+ redirectUrl?: string;
249
+ scope?: string;
250
+ clientName?: string;
251
+ };
252
+ }
253
+ interface UseMcpOptions {
254
+ /** Client name reported to the MCP server during initialize. */
255
+ clientName?: string;
256
+ /** Called with connector log lines — handy while debugging a server. */
257
+ onLog?: (level: string, message: string) => void;
258
+ }
259
+ interface UseMcpReturn {
260
+ status: McpStatus;
261
+ /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */
262
+ tools?: AgentToolSet;
263
+ catalog: McpCatalogEntry[];
264
+ error?: string;
265
+ /** Where to send the user when `status === 'needs-authorization'`. */
266
+ authorizationUrl?: string;
267
+ /**
268
+ * Whether the installed core exposes the OAuth API. `undefined` until the
269
+ * optional subpath has been loaded once — call `checkOAuthSupport()` to
270
+ * resolve it before offering OAuth in your UI.
271
+ */
272
+ oauthSupported?: boolean;
273
+ /** True while an OAuth redirect is being finished on mount. */
274
+ completingAuthorization: boolean;
275
+ connect: (options: McpConnectOptions) => Promise<void>;
276
+ disconnect: () => Promise<void>;
277
+ /** Navigate to the authorization server. Call it from a user gesture. */
278
+ authorize: () => void;
279
+ /** Drop the stored tokens and dynamic registration for the current server. */
280
+ forgetAuthorization: () => Promise<void>;
281
+ /** Load the optional subpath and report whether it can do OAuth. */
282
+ checkOAuthSupport: () => Promise<boolean>;
283
+ }
284
+ /** Map a single server's connect outcome onto the hook's status. Pure. */
285
+ declare const describeMcpResult: (result: McpServerResult | undefined) => {
286
+ status: McpStatus;
287
+ error?: string;
288
+ };
289
+ /**
290
+ * Read the authorization-code parameters out of a URL **synchronously**.
291
+ *
292
+ * The core exports an equivalent, but it lives behind a dynamic import: by the
293
+ * time that import resolves, React has flushed the rest of the app's effects,
294
+ * and any one of them may have rewritten `location` (the demo's own view
295
+ * router did exactly that). The callback has to be captured before the first
296
+ * await, so this parser is duplicated here on purpose.
297
+ *
298
+ * Reads the query string and, for hash-routed apps, the fragment. Returns
299
+ * undefined when neither a `code` nor an `error` is present.
300
+ */
301
+ declare const readCallbackParams: (href?: string) => McpOAuthCallback | undefined;
302
+ /**
303
+ * Remove the OAuth response parameters from a URL, leaving the rest intact —
304
+ * query string and fragment alike. The code is single-use and lands in history,
305
+ * referrers and screenshots, so it goes as soon as it has been read.
306
+ */
307
+ declare const stripOAuthParams: (href: string) => string;
308
+ declare const claimOAuthCallback: (callback: McpOAuthCallback) => boolean;
309
+ /**
310
+ * Did this error come from the server refusing our authorization?
311
+ *
312
+ * Identity, not strings: the SDK's `UnauthorizedError` never assigns
313
+ * `this.name` (so it reads as "Error"), and its message would also match a
314
+ * tool whose own error text mentions "unauthorized" — the connector throws a
315
+ * failing tool's text verbatim. The class is re-exported by the core's `./mcp`
316
+ * subpath for exactly this; `constructor.name` is the fallback for a core too
317
+ * old to export it.
318
+ */
319
+ declare const isUnauthorizedError: (err: unknown, mod?: McpModule) => boolean;
320
+ /**
321
+ * Connect the browser agent to a remote MCP server the user names at runtime —
322
+ * static header, or full OAuth 2.1 with dynamic client registration.
323
+ *
324
+ * The OAuth round-trip leaves the page, so the hook persists what it needs to
325
+ * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL
326
+ * and reconnects, all before the app renders anything MCP-related.
327
+ *
328
+ * ```tsx
329
+ * const mcp = useMcp()
330
+ * // await mcp.connect({ url, oauth: true })
331
+ * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>
332
+ * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>
333
+ * ```
334
+ */
335
+ declare const useMcp: (options?: UseMcpOptions) => UseMcpReturn;
336
+
168
337
  /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
169
338
  type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
170
339
  /**
@@ -378,4 +547,4 @@ interface ApiKeyFormProps {
378
547
  */
379
548
  declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
380
549
 
381
- export { type AgentAction, AgentChat, type AgentChatProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, type ChatMessage, Composer, type ComposerProps, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, PlanView, type PlanViewProps, type ReplanState, StepList, type StepListProps, type StepView, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseCredentialsReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, createInitialAgentState, useAgent, useAgentContext, useCredentials, useOptionalAgentContext, useWebLLMModel };
550
+ export { type AgentAction, AgentChat, type AgentChatProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, type ChatMessage, Composer, type ComposerProps, type ConnectedMcp, type McpCatalogEntry, type McpConnectOptions, type McpModule, type McpOAuthCallback, type McpServerResult, type McpStatus, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, PlanView, type PlanViewProps, type ReplanState, StepList, type StepListProps, type StepView, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseCredentialsReturn, type UseMcpOptions, type UseMcpReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, claimOAuthCallback, createInitialAgentState, describeMcpResult, isUnauthorizedError, readCallbackParams, stripOAuthParams, useAgent, useAgentContext, useCredentials, useMcp, useOptionalAgentContext, useWebLLMModel };
package/dist/index.js CHANGED
@@ -309,22 +309,356 @@ var useCredentials = (store) => {
309
309
  return { store: resolved, setKey, removeKey, hasKey, version };
310
310
  };
311
311
 
312
+ // src/hooks/use-mcp.ts
313
+ import { useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2, useState as useState3 } from "react";
314
+ var OAUTH_UNSUPPORTED = "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.";
315
+ var PENDING_KEY = "agent-web-react:mcp:pending";
316
+ var OAUTH_KEY = "agent-web-react:mcp:oauth";
317
+ var PENDING_TTL_MS = 10 * 60 * 1e3;
318
+ var modulePromise;
319
+ var loadMcp = () => {
320
+ modulePromise ??= import("@dudko.dev/agent-web/mcp").then((m) => m).catch((err) => {
321
+ modulePromise = void 0;
322
+ throw err;
323
+ });
324
+ return modulePromise;
325
+ };
326
+ var describeMcpResult = (result) => {
327
+ if (!result) return { status: "error", error: "The connector returned no result for the server" };
328
+ if (result.connected) return { status: "connected" };
329
+ if (result.needsAuthorization) return { status: "needs-authorization" };
330
+ return { status: "error", error: result.error ?? "Could not connect to the MCP server" };
331
+ };
332
+ var OAUTH_PARAMS = ["code", "state", "error", "error_description", "iss"];
333
+ var readCallbackParams = (href) => {
334
+ const target = href ?? (typeof globalThis.location !== "undefined" ? globalThis.location.href : void 0);
335
+ if (!target) return void 0;
336
+ let url;
337
+ try {
338
+ url = new URL(target);
339
+ } catch {
340
+ return void 0;
341
+ }
342
+ const params = new URLSearchParams(url.search);
343
+ const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
344
+ const q = hash.indexOf("?");
345
+ if (q >= 0) {
346
+ for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {
347
+ if (!params.has(k)) params.set(k, v);
348
+ }
349
+ }
350
+ const code = params.get("code") ?? void 0;
351
+ const error = params.get("error") ?? void 0;
352
+ if (!code && !error) return void 0;
353
+ return {
354
+ code,
355
+ state: params.get("state") ?? void 0,
356
+ error,
357
+ errorDescription: params.get("error_description") ?? void 0
358
+ };
359
+ };
360
+ var stripOAuthParams = (href) => {
361
+ const url = new URL(href);
362
+ for (const key of OAUTH_PARAMS) url.searchParams.delete(key);
363
+ const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
364
+ const q = hash.indexOf("?");
365
+ if (q >= 0) {
366
+ const params = new URLSearchParams(hash.slice(q + 1));
367
+ for (const key of OAUTH_PARAMS) params.delete(key);
368
+ const rest = params.toString();
369
+ url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q);
370
+ }
371
+ return url.toString();
372
+ };
373
+ var claimedCallbacks = /* @__PURE__ */ new Set();
374
+ var claimOAuthCallback = (callback) => {
375
+ const key = `${callback.code ?? ""}|${callback.state ?? ""}|${callback.error ?? ""}`;
376
+ if (claimedCallbacks.has(key)) return false;
377
+ claimedCallbacks.add(key);
378
+ return true;
379
+ };
380
+ var readRecord = (key) => {
381
+ try {
382
+ const raw = globalThis.localStorage?.getItem(key);
383
+ return raw ? JSON.parse(raw) : void 0;
384
+ } catch {
385
+ return void 0;
386
+ }
387
+ };
388
+ var writeRecord = (key, value) => {
389
+ try {
390
+ if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value));
391
+ else globalThis.localStorage?.removeItem(key);
392
+ } catch {
393
+ }
394
+ };
395
+ var defaultRedirectUrl = () => typeof globalThis.location === "undefined" ? "" : `${globalThis.location.origin}${globalThis.location.pathname}`;
396
+ var isUnauthorizedError = (err, mod) => {
397
+ if (!(err instanceof Error)) return false;
398
+ if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
399
+ return err.constructor?.name === "UnauthorizedError";
400
+ };
401
+ var watchAuthorization = (tools, mod, onUnauthorized) => {
402
+ const entries = Object.entries(tools).map(([name, value]) => {
403
+ const tool = value;
404
+ if (typeof tool.execute !== "function") return [name, value];
405
+ const execute = tool.execute.bind(tool);
406
+ const watched = (args, options) => {
407
+ try {
408
+ const out = execute(args, options);
409
+ if (out && typeof out.then === "function") {
410
+ return out.then(void 0, (err) => {
411
+ if (isUnauthorizedError(err, mod)) onUnauthorized();
412
+ throw err;
413
+ });
414
+ }
415
+ return out;
416
+ } catch (err) {
417
+ if (isUnauthorizedError(err, mod)) onUnauthorized();
418
+ throw err;
419
+ }
420
+ };
421
+ return [name, { ...value, execute: watched }];
422
+ });
423
+ return Object.fromEntries(entries);
424
+ };
425
+ var useMcp = (options = {}) => {
426
+ const [status, setStatus] = useState3("idle");
427
+ const [tools, setTools] = useState3(void 0);
428
+ const [catalog, setCatalog] = useState3([]);
429
+ const [error, setError] = useState3(void 0);
430
+ const [authorizationUrl, setAuthorizationUrl] = useState3(void 0);
431
+ const [oauthSupported, setOauthSupported] = useState3(void 0);
432
+ const [completingAuthorization, setCompletingAuthorization] = useState3(
433
+ () => readCallbackParams() !== void 0
434
+ );
435
+ const connectionRef = useRef2(void 0);
436
+ const providerRef = useRef2(void 0);
437
+ const epochRef = useRef2(0);
438
+ const optionsRef = useRef2(options);
439
+ optionsRef.current = options;
440
+ const closeConnection = useCallback3(async () => {
441
+ const open = connectionRef.current;
442
+ connectionRef.current = void 0;
443
+ if (open) await open.close().catch(() => {
444
+ });
445
+ }, []);
446
+ const checkOAuthSupport = useCallback3(async () => {
447
+ try {
448
+ const mod = await loadMcp();
449
+ const supported = typeof mod.BrowserOAuthProvider === "function";
450
+ setOauthSupported(supported);
451
+ return supported;
452
+ } catch {
453
+ setOauthSupported(false);
454
+ return false;
455
+ }
456
+ }, []);
457
+ const connect = useCallback3(
458
+ async (opts) => {
459
+ const epoch = ++epochRef.current;
460
+ const current = () => epochRef.current === epoch;
461
+ await closeConnection();
462
+ if (!current()) return;
463
+ setStatus("connecting");
464
+ setError(void 0);
465
+ setAuthorizationUrl(void 0);
466
+ setTools(void 0);
467
+ setCatalog([]);
468
+ try {
469
+ const mod = await loadMcp();
470
+ setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
471
+ const name = opts.name ?? "mcp";
472
+ let authProvider;
473
+ if (opts.oauth) {
474
+ if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
475
+ const oauth = typeof opts.oauth === "object" ? opts.oauth : {};
476
+ const record = {
477
+ url: opts.url,
478
+ name,
479
+ redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),
480
+ scope: oauth.scope,
481
+ clientName: oauth.clientName ?? optionsRef.current.clientName,
482
+ startedAt: Date.now()
483
+ };
484
+ authProvider = new mod.BrowserOAuthProvider({
485
+ serverUrl: record.url,
486
+ redirectUrl: record.redirectUrl,
487
+ clientName: record.clientName,
488
+ scope: record.scope
489
+ });
490
+ providerRef.current = authProvider;
491
+ writeRecord(PENDING_KEY, record);
492
+ writeRecord(OAUTH_KEY, record);
493
+ } else {
494
+ providerRef.current = void 0;
495
+ }
496
+ const connection = await mod.connectMcpHttp(
497
+ {
498
+ [name]: {
499
+ url: opts.url,
500
+ headers: opts.oauth ? void 0 : opts.headers,
501
+ authProvider
502
+ }
503
+ },
504
+ { clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog }
505
+ );
506
+ if (!current()) {
507
+ await connection.close().catch(() => {
508
+ });
509
+ return;
510
+ }
511
+ const outcome = describeMcpResult(connection.results[0]);
512
+ if (outcome.status !== "connected") {
513
+ await connection.close().catch(() => {
514
+ });
515
+ if (outcome.status === "needs-authorization") {
516
+ const url = authProvider?.authorizationUrl;
517
+ setAuthorizationUrl(url ? String(url) : void 0);
518
+ setStatus("needs-authorization");
519
+ return;
520
+ }
521
+ throw new Error(outcome.error);
522
+ }
523
+ connectionRef.current = connection;
524
+ writeRecord(PENDING_KEY, void 0);
525
+ setTools(
526
+ watchAuthorization(connection.tools, mod, () => {
527
+ if (!current()) return;
528
+ const url = providerRef.current?.authorizationUrl;
529
+ if (url) setAuthorizationUrl(String(url));
530
+ setStatus("needs-authorization");
531
+ })
532
+ );
533
+ setCatalog(connection.catalog);
534
+ setStatus("connected");
535
+ } catch (err) {
536
+ if (!current()) return;
537
+ setError(err instanceof Error ? err.message : String(err));
538
+ setStatus("error");
539
+ }
540
+ },
541
+ [closeConnection]
542
+ );
543
+ const disconnect = useCallback3(async () => {
544
+ epochRef.current++;
545
+ await closeConnection();
546
+ setTools(void 0);
547
+ setCatalog([]);
548
+ setAuthorizationUrl(void 0);
549
+ setError(void 0);
550
+ setStatus("idle");
551
+ }, [closeConnection]);
552
+ const authorize = useCallback3(() => {
553
+ if (authorizationUrl && typeof globalThis.location !== "undefined") {
554
+ globalThis.location.href = authorizationUrl;
555
+ }
556
+ }, [authorizationUrl]);
557
+ const forgetAuthorization = useCallback3(async () => {
558
+ const record = readRecord(OAUTH_KEY);
559
+ writeRecord(PENDING_KEY, void 0);
560
+ writeRecord(OAUTH_KEY, void 0);
561
+ let provider = providerRef.current;
562
+ if (!provider && record) {
563
+ const mod = await loadMcp().catch(() => void 0);
564
+ if (mod?.BrowserOAuthProvider) {
565
+ provider = new mod.BrowserOAuthProvider({
566
+ serverUrl: record.url,
567
+ redirectUrl: record.redirectUrl,
568
+ clientName: record.clientName,
569
+ scope: record.scope
570
+ });
571
+ }
572
+ }
573
+ await provider?.reset().catch(() => {
574
+ });
575
+ providerRef.current = void 0;
576
+ await disconnect();
577
+ }, [disconnect]);
578
+ useEffect2(() => {
579
+ const callback = readCallbackParams();
580
+ if (!callback) {
581
+ setCompletingAuthorization(false);
582
+ return;
583
+ }
584
+ const pending = readRecord(PENDING_KEY);
585
+ const fresh = pending !== void 0 && (pending.startedAt === void 0 || Date.now() - pending.startedAt < PENDING_TTL_MS);
586
+ if (!pending || !fresh) {
587
+ if (pending) writeRecord(PENDING_KEY, void 0);
588
+ setCompletingAuthorization(false);
589
+ return;
590
+ }
591
+ if (!claimOAuthCallback(callback)) {
592
+ setCompletingAuthorization(false);
593
+ return;
594
+ }
595
+ if (typeof globalThis.history !== "undefined") {
596
+ globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
597
+ }
598
+ void (async () => {
599
+ try {
600
+ const mod = await loadMcp();
601
+ setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
602
+ if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
603
+ const provider = new mod.BrowserOAuthProvider({
604
+ serverUrl: pending.url,
605
+ redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),
606
+ clientName: pending.clientName,
607
+ scope: pending.scope
608
+ });
609
+ providerRef.current = provider;
610
+ await mod.finishMcpOAuth(provider, callback);
611
+ writeRecord(PENDING_KEY, void 0);
612
+ setCompletingAuthorization(false);
613
+ await connect({ url: pending.url, name: pending.name, oauth: true });
614
+ } catch (err) {
615
+ writeRecord(PENDING_KEY, void 0);
616
+ setError(err instanceof Error ? err.message : String(err));
617
+ setStatus("error");
618
+ } finally {
619
+ setCompletingAuthorization(false);
620
+ }
621
+ })();
622
+ }, [connect]);
623
+ useEffect2(
624
+ () => () => {
625
+ epochRef.current++;
626
+ void closeConnection();
627
+ },
628
+ [closeConnection]
629
+ );
630
+ return {
631
+ status,
632
+ tools,
633
+ catalog,
634
+ error,
635
+ authorizationUrl,
636
+ oauthSupported,
637
+ completingAuthorization,
638
+ connect,
639
+ disconnect,
640
+ authorize,
641
+ forgetAuthorization,
642
+ checkOAuthSupport
643
+ };
644
+ };
645
+
312
646
  // src/hooks/use-webllm-model.ts
313
- import { useCallback as useCallback3, useRef as useRef2, useState as useState3 } from "react";
647
+ import { useCallback as useCallback4, useRef as useRef3, useState as useState4 } from "react";
314
648
  import {
315
649
  createWebLLMModel,
316
650
  isWebGPUAvailable,
317
651
  preloadWebLLMModel
318
652
  } from "@dudko.dev/agent-web";
319
653
  var useWebLLMModel = (modelId, options) => {
320
- const [model, setModel] = useState3(void 0);
321
- const [loading, setLoading] = useState3(false);
322
- const [progress, setProgress] = useState3(0);
323
- const [text, setText] = useState3("");
324
- const [error, setError] = useState3(void 0);
325
- const optionsRef = useRef2(options);
654
+ const [model, setModel] = useState4(void 0);
655
+ const [loading, setLoading] = useState4(false);
656
+ const [progress, setProgress] = useState4(0);
657
+ const [text, setText] = useState4("");
658
+ const [error, setError] = useState4(void 0);
659
+ const optionsRef = useRef3(options);
326
660
  optionsRef.current = options;
327
- const load = useCallback3(async () => {
661
+ const load = useCallback4(async () => {
328
662
  if (!isWebGPUAvailable()) {
329
663
  setError("WebGPU is not available in this browser.");
330
664
  return void 0;
@@ -385,7 +719,7 @@ var useAgentContext = () => {
385
719
  var useOptionalAgentContext = () => useContext(AgentContext);
386
720
 
387
721
  // src/components/AgentChat.tsx
388
- import { useEffect as useEffect2, useRef as useRef3 } from "react";
722
+ import { useEffect as useEffect3, useRef as useRef4 } from "react";
389
723
 
390
724
  // src/components/icons.tsx
391
725
  import { jsx as jsx2, jsxs } from "react/jsx-runtime";
@@ -415,7 +749,7 @@ var AlertIcon = ({ size, className }) => /* @__PURE__ */ jsxs("svg", { ...base(s
415
749
  var ToolIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z" }) });
416
750
 
417
751
  // src/components/Composer.tsx
418
- import { useState as useState4 } from "react";
752
+ import { useState as useState5 } from "react";
419
753
  import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
420
754
  var Composer = ({
421
755
  onSubmit,
@@ -425,7 +759,7 @@ var Composer = ({
425
759
  placeholder = "Ask the agent to do something\u2026",
426
760
  className
427
761
  }) => {
428
- const [text, setText] = useState4("");
762
+ const [text, setText] = useState5("");
429
763
  const submit = () => {
430
764
  const value = text.trim();
431
765
  if (!value || busy || disabled) return;
@@ -609,8 +943,8 @@ var AgentChat = ({
609
943
  "<AgentChat> needs a `controller` prop from useAgent(), or an enclosing <AgentProvider>."
610
944
  );
611
945
  }
612
- const bodyRef = useRef3(null);
613
- useEffect2(() => {
946
+ const bodyRef = useRef4(null);
947
+ useEffect3(() => {
614
948
  const el = bodyRef.current;
615
949
  if (el) el.scrollTop = el.scrollHeight;
616
950
  }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad]);
@@ -673,7 +1007,7 @@ var PlanView = ({ plan, showThought = true, className }) => {
673
1007
  };
674
1008
 
675
1009
  // src/components/ApiKeyForm.tsx
676
- import { useEffect as useEffect3, useState as useState5 } from "react";
1010
+ import { useEffect as useEffect4, useState as useState6 } from "react";
677
1011
  import { jsx as jsx9, jsxs as jsxs9 } from "react/jsx-runtime";
678
1012
  var ApiKeyForm = ({
679
1013
  credentials,
@@ -683,10 +1017,10 @@ var ApiKeyForm = ({
683
1017
  onChange,
684
1018
  className
685
1019
  }) => {
686
- const [value, setValue] = useState5("");
687
- const [present, setPresent] = useState5(false);
688
- const [busy, setBusy] = useState5(false);
689
- useEffect3(() => {
1020
+ const [value, setValue] = useState6("");
1021
+ const [present, setPresent] = useState6(false);
1022
+ const [busy, setBusy] = useState6(false);
1023
+ useEffect4(() => {
690
1024
  let active = true;
691
1025
  credentials.hasKey(credentialRef).then((has) => {
692
1026
  if (active) setPresent(has);
@@ -793,16 +1127,22 @@ export {
793
1127
  UsageBadge,
794
1128
  VaultCredentialStore2 as VaultCredentialStore,
795
1129
  agentStateReducer,
1130
+ claimOAuthCallback,
796
1131
  createAgent2 as createAgent,
797
1132
  createInitialAgentState,
798
1133
  createWebLLMModel2 as createWebLLMModel,
799
1134
  defineTool,
1135
+ describeMcpResult,
1136
+ isUnauthorizedError,
800
1137
  isWebGPUAvailable2 as isWebGPUAvailable,
801
1138
  preloadWebLLMModel2 as preloadWebLLMModel,
1139
+ readCallbackParams,
1140
+ stripOAuthParams,
802
1141
  unloadWebLLMModel,
803
1142
  useAgent,
804
1143
  useAgentContext,
805
1144
  useCredentials,
1145
+ useMcp,
806
1146
  useOptionalAgentContext,
807
1147
  useWebLLMModel
808
1148
  };