@mcpjam/widget-react 0.1.17 → 0.2.0

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
@@ -734,6 +734,7 @@ interface AppInstance {
734
734
  bridge: AppBridge;
735
735
  tools: AppToolDescriptor[];
736
736
  registeredAtMs: number;
737
+ toolSource?: "mcp-apps" | "webmcp";
737
738
  /**
738
739
  * Accessor for the iframe DOM node that hosts this app instance. Lets
739
740
  * callers (e.g. `onToolCall`) scroll the iframe into view before
@@ -766,6 +767,7 @@ interface AppToolAttribution {
766
767
  appName: string;
767
768
  }
768
769
  interface AppToolsRegistryState {
770
+ enabled: boolean;
769
771
  instancesByBridgeId: Map<BridgeId, AppInstance>;
770
772
  aliases: Map<string, AppToolAlias>;
771
773
  /** Active app-tool provider per chat-scoped host tool call. */
@@ -835,6 +837,7 @@ declare const useAppToolsRegistry: (<T = AppToolsRegistryState>(selector?: (stat
835
837
  * context.
836
838
  */
837
839
  interface AppToolInvocationRecord {
840
+ initiatedBy?: "user";
838
841
  alias: string;
839
842
  rawName: string;
840
843
  appName: string;
@@ -868,6 +871,107 @@ declare const __internal: {
868
871
  ALIAS_REGEX: RegExp;
869
872
  };
870
873
 
874
+ /** Dispatch exactly once using the source selected at discovery. */
875
+ declare function dispatchAppToolCall(entry: NonNullable<ReturnType<AppToolsRegistryState["resolve"]>>, args: Record<string, unknown>, options?: {
876
+ signal?: AbortSignal;
877
+ }): Promise<{
878
+ [x: string]: unknown;
879
+ content: ({
880
+ type: "text";
881
+ text: string;
882
+ annotations?: {
883
+ audience?: ("user" | "assistant")[] | undefined;
884
+ priority?: number | undefined;
885
+ lastModified?: string | undefined;
886
+ } | undefined;
887
+ _meta?: {
888
+ [x: string]: unknown;
889
+ } | undefined;
890
+ } | {
891
+ type: "image";
892
+ data: string;
893
+ mimeType: string;
894
+ annotations?: {
895
+ audience?: ("user" | "assistant")[] | undefined;
896
+ priority?: number | undefined;
897
+ lastModified?: string | undefined;
898
+ } | undefined;
899
+ _meta?: {
900
+ [x: string]: unknown;
901
+ } | undefined;
902
+ } | {
903
+ type: "audio";
904
+ data: string;
905
+ mimeType: string;
906
+ annotations?: {
907
+ audience?: ("user" | "assistant")[] | undefined;
908
+ priority?: number | undefined;
909
+ lastModified?: string | undefined;
910
+ } | undefined;
911
+ _meta?: {
912
+ [x: string]: unknown;
913
+ } | undefined;
914
+ } | {
915
+ uri: string;
916
+ name: string;
917
+ type: "resource_link";
918
+ description?: string | undefined;
919
+ mimeType?: string | undefined;
920
+ size?: number | undefined;
921
+ annotations?: {
922
+ audience?: ("user" | "assistant")[] | undefined;
923
+ priority?: number | undefined;
924
+ lastModified?: string | undefined;
925
+ } | undefined;
926
+ _meta?: {
927
+ [x: string]: unknown;
928
+ } | undefined;
929
+ icons?: {
930
+ src: string;
931
+ mimeType?: string | undefined;
932
+ sizes?: string[] | undefined;
933
+ theme?: "light" | "dark" | undefined;
934
+ }[] | undefined;
935
+ title?: string | undefined;
936
+ } | {
937
+ type: "resource";
938
+ resource: {
939
+ uri: string;
940
+ text: string;
941
+ mimeType?: string | undefined;
942
+ _meta?: {
943
+ [x: string]: unknown;
944
+ } | undefined;
945
+ } | {
946
+ uri: string;
947
+ blob: string;
948
+ mimeType?: string | undefined;
949
+ _meta?: {
950
+ [x: string]: unknown;
951
+ } | undefined;
952
+ };
953
+ annotations?: {
954
+ audience?: ("user" | "assistant")[] | undefined;
955
+ priority?: number | undefined;
956
+ lastModified?: string | undefined;
957
+ } | undefined;
958
+ _meta?: {
959
+ [x: string]: unknown;
960
+ } | undefined;
961
+ })[];
962
+ _meta?: {
963
+ [x: string]: unknown;
964
+ progressToken?: string | number | undefined;
965
+ "io.modelcontextprotocol/related-task"?: {
966
+ taskId: string;
967
+ } | undefined;
968
+ } | undefined;
969
+ structuredContent?: {
970
+ [x: string]: unknown;
971
+ } | undefined;
972
+ isError?: boolean | undefined;
973
+ }>;
974
+
871
975
  /**
872
976
  * useToolInputStreaming – manages the streaming delivery of tool input to
873
977
  * an MCP App bridge.
@@ -1372,4 +1476,21 @@ interface WidgetFullscreenPlacement {
1372
1476
  }
1373
1477
  declare const WidgetFullscreenPlacementContext: react.Context<WidgetFullscreenPlacement | null>;
1374
1478
 
1375
- export { type AddTrafficLog, type AppInstance, type AppToolAlias, type AppToolAttribution, type AppToolDescriptor, type AppToolInvocationLog, type AppToolInvocationLogState, type AppToolInvocationRecord, type AppToolSnapshotEntry, type AppToolsRegistry, type AppToolsRegistryState, type BridgeId, type CspApplicationIntent, type CspClientContext, type CspMode, type CspMountId, type CspSubtypePolicy, type CspViolation, type DeviceCapabilities, type DeviceType, type DisplayMode, type EffectiveCompatRuntime, type FetchWidgetContentRequest, type FetchWidgetContentResponse, type ListResourcesResult, MCPAppsRenderer, type MCPAppsRendererProps, MCPAppsRendererSurface, type OpenAiAppsCapabilities, PARTIAL_INPUT_THROTTLE_MS, type ProjectHostContextDraft, type ResolvedHostCapabilities, type ResolvedHostInfo, type ResolvedHostStyle, type ResolvedMcpAppsCapabilities, type ResolvedOpenAiAppsCapabilities, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, type SafeAreaInsets, type SandboxProxyLocation, SandboxedIframe, type SandboxedIframeHandle, type ScenarioHostStyle, type ThemeMode, type ToolLike, type ToolState, UIType, type UiLogEvent, type UiProtocol, type UseToolInputStreamingParams, type UseToolInputStreamingReturn, type WidgetCheckoutProps, type WidgetDebugInfo, type WidgetDebugSink, type WidgetFullscreenPlacement, WidgetFullscreenPlacementContext, type WidgetGlobals, type WidgetHost, type WidgetHostComponents, type WidgetHostEnvironment, type WidgetHostEnvironmentInputs, WidgetHostProvider, type WidgetHostProviderProps, type WidgetHostResolvers, type WidgetHostServices, type WidgetLifecycleEvent, type WidgetModalProps, type WidgetMount, type WidgetSandboxApplied, type WidgetSandboxInfo, type WidgetSurfaceAdmissionError, WidgetSurfaceHost, WidgetSurfaceHostProvider, type WidgetSurfaceId, type WidgetSurfaceInfo, type WidgetSurfaceKind, type WidgetSurfaceRecord, type WidgetSurfaceStore, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
1479
+ declare const MAX_SNAPSHOT_ENTRIES = 64;
1480
+ type AppToolDropReason = "entry_cap" | "schema_too_large" | "schema_unserializable";
1481
+ interface AppToolCatalogEntry extends AppToolAlias {
1482
+ instance: AppInstance;
1483
+ description?: string;
1484
+ inputSchema?: Record<string, unknown>;
1485
+ }
1486
+ interface AppToolCatalog {
1487
+ offered: AppToolCatalogEntry[];
1488
+ dropped: (AppToolCatalogEntry & {
1489
+ reason: AppToolDropReason;
1490
+ })[];
1491
+ }
1492
+ type AppToolCatalogState = Pick<AppToolsRegistryState, "aliases" | "instancesByBridgeId" | "activeBridgeByParent" | "enabled">;
1493
+ /** Alias order is the wire order, including when an app re-registers. */
1494
+ declare function listAppToolCatalog(state: AppToolCatalogState, chatSessionId?: string | null): AppToolCatalog;
1495
+
1496
+ export { type AddTrafficLog, type AppInstance, type AppToolAlias, type AppToolAttribution, type AppToolCatalog, type AppToolCatalogEntry, type AppToolCatalogState, type AppToolDescriptor, type AppToolDropReason, type AppToolInvocationLog, type AppToolInvocationLogState, type AppToolInvocationRecord, type AppToolSnapshotEntry, type AppToolsRegistry, type AppToolsRegistryState, type BridgeId, type CspApplicationIntent, type CspClientContext, type CspMode, type CspMountId, type CspSubtypePolicy, type CspViolation, type DeviceCapabilities, type DeviceType, type DisplayMode, type EffectiveCompatRuntime, type FetchWidgetContentRequest, type FetchWidgetContentResponse, type ListResourcesResult, MAX_SNAPSHOT_ENTRIES, MCPAppsRenderer, type MCPAppsRendererProps, MCPAppsRendererSurface, type OpenAiAppsCapabilities, PARTIAL_INPUT_THROTTLE_MS, type ProjectHostContextDraft, type ResolvedHostCapabilities, type ResolvedHostInfo, type ResolvedHostStyle, type ResolvedMcpAppsCapabilities, type ResolvedOpenAiAppsCapabilities, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, type SafeAreaInsets, type SandboxProxyLocation, SandboxedIframe, type SandboxedIframeHandle, type ScenarioHostStyle, type ThemeMode, type ToolLike, type ToolState, UIType, type UiLogEvent, type UiProtocol, type UseToolInputStreamingParams, type UseToolInputStreamingReturn, type WidgetCheckoutProps, type WidgetDebugInfo, type WidgetDebugSink, type WidgetFullscreenPlacement, WidgetFullscreenPlacementContext, type WidgetGlobals, type WidgetHost, type WidgetHostComponents, type WidgetHostEnvironment, type WidgetHostEnvironmentInputs, WidgetHostProvider, type WidgetHostProviderProps, type WidgetHostResolvers, type WidgetHostServices, type WidgetLifecycleEvent, type WidgetModalProps, type WidgetMount, type WidgetSandboxApplied, type WidgetSandboxInfo, type WidgetSurfaceAdmissionError, WidgetSurfaceHost, WidgetSurfaceHostProvider, type WidgetSurfaceId, type WidgetSurfaceInfo, type WidgetSurfaceKind, type WidgetSurfaceRecord, type WidgetSurfaceStore, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, dispatchAppToolCall, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, listAppToolCatalog, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createContext, forwardRef, useRef, useState, useMemo, useImperativeHandle, useCallback, useEffect, useContext, useLayoutEffect, Fragment as Fragment$1 } from 'react';
2
2
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
3
  import { isUIResource } from '@mcp-ui/client';
4
- import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, applyToolResultPolicy, openAIDisplayModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod } from '@mcpjam/sdk/widget-runtime';
4
+ import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, callViewWebmcpTool, applyToolResultPolicy, openAIDisplayModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod, appToolSourceFor, discoverViewAppTools, listViewWebmcpTools } from '@mcpjam/sdk/widget-runtime';
5
5
  export { getToolVisibility, isVisibleToAppOnly, isVisibleToModelOnly } from '@mcpjam/sdk/widget-runtime';
6
6
  import { useStore, create } from 'zustand';
7
7
  import { useShallow } from 'zustand/react/shallow';
@@ -108,9 +108,67 @@ function readToolResultServerId(result) {
108
108
  return typeof meta?._serverId === "string" ? meta._serverId : void 0;
109
109
  }
110
110
  var WidgetWorkspaceContext = createContext(null);
111
+
112
+ // src/app-tools-catalog.ts
111
113
  var MAX_SNAPSHOT_ENTRIES = 64;
112
114
  var MAX_DESCRIPTION_CHARS = 512;
113
115
  var MAX_INPUT_SCHEMA_BYTES = 8 * 1024;
116
+ function listAppToolCatalog(state, chatSessionId) {
117
+ const offered = [];
118
+ const dropped = [];
119
+ if (!state.enabled || !chatSessionId) return { offered, dropped };
120
+ for (const [alias, reference] of state.aliases) {
121
+ if (!/^app_[a-z0-9]{8}$/i.test(alias)) continue;
122
+ const instance = state.instancesByBridgeId.get(reference.bridgeId);
123
+ if (!instance || instance.chatSessionId !== chatSessionId) continue;
124
+ if (state.activeBridgeByParent.get(
125
+ `${chatSessionId}\0${instance.parentToolCallId}`
126
+ ) !== instance.bridgeId)
127
+ continue;
128
+ const tool = instance.tools.find((tool2) => tool2.name === reference.rawName);
129
+ if (!tool) continue;
130
+ const entry = {
131
+ ...reference,
132
+ alias,
133
+ instance,
134
+ description: tool.description ? tool.description.slice(0, MAX_DESCRIPTION_CHARS) : void 0,
135
+ inputSchema: tool.inputSchema
136
+ };
137
+ let reason;
138
+ if (offered.length >= MAX_SNAPSHOT_ENTRIES) reason = "entry_cap";
139
+ else if (tool.inputSchema) {
140
+ try {
141
+ if (new TextEncoder().encode(JSON.stringify(tool.inputSchema)).length > MAX_INPUT_SCHEMA_BYTES)
142
+ reason = "schema_too_large";
143
+ } catch {
144
+ reason = "schema_unserializable";
145
+ }
146
+ }
147
+ if (reason) dropped.push({ ...entry, reason });
148
+ else offered.push(entry);
149
+ }
150
+ const counts = /* @__PURE__ */ new Map();
151
+ const indices = /* @__PURE__ */ new Map();
152
+ for (const entry of offered) {
153
+ const key = `${entry.instance.appName}\0${entry.rawName}`;
154
+ counts.set(key, (counts.get(key) ?? 0) + 1);
155
+ }
156
+ for (const entry of offered) {
157
+ const key = `${entry.instance.appName}\0${entry.rawName}`;
158
+ const total = counts.get(key) ?? 1;
159
+ if (total <= 1) continue;
160
+ const index = (indices.get(key) ?? 0) + 1;
161
+ indices.set(key, index);
162
+ const hint = ` (from tool call ${entry.instance.parentToolCallId}; instance ${index} of ${total})`;
163
+ entry.description = ((entry.description ?? "") + hint).slice(
164
+ 0,
165
+ MAX_DESCRIPTION_CHARS
166
+ );
167
+ }
168
+ return { offered, dropped };
169
+ }
170
+
171
+ // src/app-tools-registry.ts
114
172
  var ALIAS_REGEX = /^app_[a-z0-9]{8}$/i;
115
173
  async function generateAlias(chatSessionId, serverId, parentToolCallId, surface, rawName, salt = 0) {
116
174
  const preimage = `${chatSessionId ?? ""}\0${serverId}\0${parentToolCallId}\0${surface}\0${rawName}\0${salt}`;
@@ -229,6 +287,7 @@ function createAppToolsRegistry(options = {}) {
229
287
  });
230
288
  };
231
289
  return create((set, get) => ({
290
+ enabled: true,
232
291
  instancesByBridgeId: /* @__PURE__ */ new Map(),
233
292
  aliases: /* @__PURE__ */ new Map(),
234
293
  activeBridgeByParent: /* @__PURE__ */ new Map(),
@@ -374,74 +433,32 @@ function createAppToolsRegistry(options = {}) {
374
433
  });
375
434
  },
376
435
  snapshotForChatBody: (chatSessionId) => {
377
- if (disposed || !enabled) return [];
378
- const { instancesByBridgeId, aliases, activeBridgeByParent } = get();
379
- const out = [];
380
- let dropped = 0;
381
- for (const [alias, a] of aliases) {
382
- if (out.length >= MAX_SNAPSHOT_ENTRIES) {
383
- dropped += 1;
384
- continue;
385
- }
386
- if (!ALIAS_REGEX.test(alias)) continue;
387
- const inst = instancesByBridgeId.get(a.bridgeId);
388
- if (!inst) continue;
389
- if (chatSessionId && inst.chatSessionId !== chatSessionId) continue;
390
- if (activeBridgeByParent.get(
391
- getActiveParentKey(inst.parentToolCallId, inst.chatSessionId)
392
- ) !== inst.bridgeId) {
393
- continue;
394
- }
395
- const tool = inst.tools.find((t) => t.name === a.rawName);
396
- if (!tool) continue;
397
- let inputSchema = tool.inputSchema;
398
- if (inputSchema) {
399
- let size = 0;
400
- try {
401
- size = new TextEncoder().encode(JSON.stringify(inputSchema)).length;
402
- } catch {
403
- continue;
404
- }
405
- if (size > MAX_INPUT_SCHEMA_BYTES) continue;
406
- }
407
- const description = tool.description ? tool.description.slice(0, MAX_DESCRIPTION_CHARS) : void 0;
408
- out.push({
409
- alias,
410
- appName: inst.appName,
411
- appVersion: inst.appVersion,
412
- serverId: inst.serverId,
413
- parentToolCallId: inst.parentToolCallId,
414
- rawName: a.rawName,
415
- description,
416
- inputSchema,
417
- readOnly: a.readOnly
418
- });
419
- }
420
- if (dropped > 0) {
436
+ const catalog = listAppToolCatalog(get(), chatSessionId);
437
+ const capped = catalog.dropped.filter(
438
+ (entry) => entry.reason === "entry_cap"
439
+ );
440
+ if (capped.length > 0) {
421
441
  console.warn(
422
- `[app-tools] snapshot capped at ${MAX_SNAPSHOT_ENTRIES} entries; dropped ${dropped}.`
442
+ `[app-tools] snapshot capped at ${MAX_SNAPSHOT_ENTRIES} entries; dropped ${capped.length}.`
423
443
  );
424
444
  }
425
- const groupCounts = /* @__PURE__ */ new Map();
426
- for (const entry of out) {
427
- const key = `${entry.appName}\0${entry.rawName}`;
428
- groupCounts.set(key, (groupCounts.get(key) ?? 0) + 1);
429
- }
430
- const groupIndex = /* @__PURE__ */ new Map();
431
- for (const entry of out) {
432
- const key = `${entry.appName}\0${entry.rawName}`;
433
- const total = groupCounts.get(key) ?? 1;
434
- if (total <= 1) continue;
435
- const n = (groupIndex.get(key) ?? 0) + 1;
436
- groupIndex.set(key, n);
437
- const hint = ` (from tool call ${entry.parentToolCallId}; instance ${n} of ${total})`;
438
- const base = entry.description ?? "";
439
- entry.description = (base + hint).slice(0, MAX_DESCRIPTION_CHARS);
440
- }
441
- return out;
445
+ return catalog.offered.map(
446
+ ({ alias, instance, rawName, description, inputSchema, readOnly }) => ({
447
+ alias,
448
+ appName: instance.appName,
449
+ appVersion: instance.appVersion,
450
+ serverId: instance.serverId,
451
+ parentToolCallId: instance.parentToolCallId,
452
+ rawName,
453
+ description,
454
+ inputSchema,
455
+ readOnly
456
+ })
457
+ );
442
458
  },
443
459
  setEnabled: (value) => {
444
460
  enabled = value;
461
+ set({ enabled: value });
445
462
  if (!value)
446
463
  for (const pending of get().pendingControllers.values())
447
464
  for (const controller of pending) controller.abort();
@@ -449,6 +466,7 @@ function createAppToolsRegistry(options = {}) {
449
466
  dispose: () => {
450
467
  disposed = true;
451
468
  enabled = false;
469
+ set({ enabled: false });
452
470
  for (const bridgeId of get().instancesByBridgeId.keys())
453
471
  get().unregisterInstance(bridgeId);
454
472
  },
@@ -532,6 +550,7 @@ function recordAppToolInvocation(args, addTrafficLog, invocationLog = legacyInvo
532
550
  alias: args.alias,
533
551
  toolName: args.rawName,
534
552
  appName: args.appName,
553
+ ...args.initiatedBy ? { initiatedBy: args.initiatedBy } : {},
535
554
  arguments: args.input,
536
555
  result: {
537
556
  content: args.raw.content,
@@ -578,6 +597,20 @@ function useAppToolAttribution(label, chatSessionId) {
578
597
  return resolveAppToolAttribution(label);
579
598
  }
580
599
  var __internal = { generateAlias, isReadOnly, ALIAS_REGEX };
600
+ async function dispatchAppToolCall(entry, args, options) {
601
+ options?.signal?.throwIfAborted();
602
+ const call = entry.instance.toolSource === "webmcp" ? callViewWebmcpTool(entry.bridge, entry.rawName, args, options) : entry.bridge.callTool({ name: entry.rawName, arguments: args });
603
+ const signal = options?.signal;
604
+ if (!signal) return call;
605
+ return new Promise((resolve, reject) => {
606
+ const abort = () => reject(
607
+ signal.reason ?? new Error("The app closed before the tool finished. Open the app and try again.")
608
+ );
609
+ signal.addEventListener("abort", abort, { once: true });
610
+ if (signal.aborted) abort();
611
+ call.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
612
+ });
613
+ }
581
614
  var PARTIAL_INPUT_THROTTLE_MS = 120;
582
615
  var STREAMING_REVEAL_FALLBACK_MS = 700;
583
616
  var SIGNATURE_MAX_DEPTH = 4;
@@ -1129,6 +1162,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1129
1162
  clientContext: clientContext ?? null,
1130
1163
  browserStorage: browserStorage ?? null,
1131
1164
  html: html ?? null,
1165
+ webmcpTools: true,
1132
1166
  permissive: permissive ?? null,
1133
1167
  permissions: permissions ?? null,
1134
1168
  sandbox,
@@ -1171,6 +1205,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1171
1205
  method: "ui/notifications/sandbox-resource-ready",
1172
1206
  params: {
1173
1207
  html,
1208
+ webmcpTools: true,
1174
1209
  sandbox,
1175
1210
  csp,
1176
1211
  permissions,
@@ -1232,6 +1267,96 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1232
1267
  `${sandboxProxyOrigin}\0${outerSandboxAttribute}`
1233
1268
  );
1234
1269
  });
1270
+ function createAppToolDiscovery(config) {
1271
+ const states = /* @__PURE__ */ new WeakMap();
1272
+ return function refresh(bridge, bridgeId, options) {
1273
+ let state = states.get(bridge);
1274
+ if (!state) {
1275
+ state = {
1276
+ source: appToolSourceFor(bridge.getAppCapabilities()),
1277
+ attempted: false,
1278
+ listed: false,
1279
+ dirty: false
1280
+ };
1281
+ states.set(bridge, state);
1282
+ }
1283
+ if (state.pending) {
1284
+ if (options.force) state.dirty = true;
1285
+ return state.pending;
1286
+ }
1287
+ if (state.listed && !options.force) return Promise.resolve();
1288
+ const current = state;
1289
+ const legacy = async () => {
1290
+ const tools = [];
1291
+ let cursor;
1292
+ for (let page = 0; page < 8; page++) {
1293
+ const result = await bridge.listTools(
1294
+ cursor === void 0 ? {} : { cursor }
1295
+ );
1296
+ tools.push(
1297
+ ...(result.tools ?? []).filter(
1298
+ (tool) => Boolean(
1299
+ tool && typeof tool.name === "string" && tool.name.length > 0
1300
+ )
1301
+ )
1302
+ );
1303
+ cursor = typeof result.nextCursor === "string" ? result.nextCursor : void 0;
1304
+ if (cursor === void 0) break;
1305
+ if (page === 7)
1306
+ console.warn(
1307
+ `[MCP Apps] tools/list still had more pages after 8; registering a partial tool set for bridge ${bridgeId}.`
1308
+ );
1309
+ }
1310
+ return tools;
1311
+ };
1312
+ current.pending = (async () => {
1313
+ try {
1314
+ do {
1315
+ current.dirty = false;
1316
+ if (!options.isLive()) return;
1317
+ const initial = !current.attempted;
1318
+ current.attempted = true;
1319
+ const result = initial ? await discoverViewAppTools(bridge, current.source, true, legacy) : {
1320
+ source: current.source,
1321
+ tools: current.source === "webmcp" ? await listViewWebmcpTools(bridge) : await legacy()
1322
+ };
1323
+ current.source = result.source;
1324
+ current.listed = true;
1325
+ if (!options.isLive()) return;
1326
+ if (result.source === "webmcp" && result.tools.length === 0) {
1327
+ config.registry.getState().unregisterInstance(bridgeId);
1328
+ } else {
1329
+ const context = config.context();
1330
+ const version = bridge.getAppVersion();
1331
+ await config.registry.getState().registerInstance({
1332
+ ...context,
1333
+ bridgeId,
1334
+ bridge,
1335
+ tools: result.tools,
1336
+ toolSource: result.source,
1337
+ appName: version?.name ?? context.serverId,
1338
+ appVersion: version?.version,
1339
+ surface: options.surface ?? "inline",
1340
+ registeredAtMs: Date.now(),
1341
+ getIframeElement: options.getIframeElement
1342
+ });
1343
+ if (!options.isLive())
1344
+ config.registry.getState().unregisterInstance(bridgeId);
1345
+ }
1346
+ } while (current.dirty && options.isLive());
1347
+ } catch (error) {
1348
+ current.listed = false;
1349
+ if (current.source === "webmcp" && options.isLive()) {
1350
+ config.registry.getState().unregisterInstance(bridgeId);
1351
+ }
1352
+ if (options.isLive()) config.onError(error);
1353
+ } finally {
1354
+ current.pending = void 0;
1355
+ }
1356
+ })();
1357
+ return current.pending;
1358
+ };
1359
+ }
1235
1360
  function useInitialRenderOutcome(ready, failed, notify) {
1236
1361
  const delivered = useRef(false);
1237
1362
  const callback = useRef(notify);
@@ -1406,8 +1531,7 @@ function McpAppsModal({
1406
1531
  )
1407
1532
  );
1408
1533
  }
1409
- const appCaps = bridge.getAppCapabilities();
1410
- if (appCaps?.tools) {
1534
+ {
1411
1535
  const bridgeId = modalAppToolsBridgeIdRef.current ?? crypto.randomUUID();
1412
1536
  modalAppToolsBridgeIdRef.current = bridgeId;
1413
1537
  void refreshAppProvidedTools(bridge, bridgeId, {
@@ -1443,7 +1567,7 @@ function McpAppsModal({
1443
1567
  pendingRpcMethods.delete(response.id);
1444
1568
  }
1445
1569
  const method = correlatedMethod ?? extractMethod(message, "mcp-apps");
1446
- if (method === "notifications/tools/list_changed") {
1570
+ if (method === "notifications/tools/list_changed" || method === "ui/notifications/sandbox-tools-changed") {
1447
1571
  const bridgeId = modalAppToolsBridgeIdRef.current;
1448
1572
  if (bridgeId) {
1449
1573
  void refreshAppProvidedTools(bridge, bridgeId, {
@@ -2642,9 +2766,6 @@ function MCPAppsRendererSurface({
2642
2766
  );
2643
2767
  const hasAutoPromotedForAppToolsRef = useRef(false);
2644
2768
  const appToolsBridgeIdRef = useRef(null);
2645
- const appToolsListedBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2646
- const appToolsListInFlightBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2647
- const appToolsListRefreshPendingBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2648
2769
  const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState(null);
2649
2770
  const appToolsRegistry = useAppToolsRegistryApi();
2650
2771
  const pendingAppToolCalls = useAppToolsRegistry(
@@ -3002,82 +3123,18 @@ function MCPAppsRendererSurface({
3002
3123
  },
3003
3124
  []
3004
3125
  );
3005
- const refreshAppProvidedTools = useCallback(
3006
- async (bridge, bridgeId, options = {}) => {
3007
- const surface = options.surface ?? "inline";
3008
- const getIframeElement = options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null);
3009
- const isLive = options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId);
3010
- const alreadyListed = appToolsListedBridgeIdsRef.current.has(bridgeId);
3011
- const inFlight = appToolsListInFlightBridgeIdsRef.current.has(bridgeId);
3012
- if (inFlight) {
3013
- if (options.force) {
3014
- appToolsListRefreshPendingBridgeIdsRef.current.add(bridgeId);
3015
- }
3016
- return;
3017
- }
3018
- if (!options.force && alreadyListed) return;
3019
- appToolsListInFlightBridgeIdsRef.current.add(bridgeId);
3020
- try {
3021
- let needsRefresh = true;
3022
- while (needsRefresh) {
3023
- appToolsListRefreshPendingBridgeIdsRef.current.delete(bridgeId);
3024
- const tools = [];
3025
- let cursor;
3026
- const APP_TOOLS_PAGE_CAP = 8;
3027
- for (let page = 0; page < APP_TOOLS_PAGE_CAP; page += 1) {
3028
- const result = await bridge.listTools(
3029
- cursor === void 0 ? {} : { cursor }
3030
- );
3031
- tools.push(
3032
- ...(result.tools ?? []).filter(
3033
- (t) => Boolean(t && typeof t.name === "string" && t.name.length > 0)
3034
- )
3035
- );
3036
- cursor = typeof result.nextCursor === "string" ? result.nextCursor : void 0;
3037
- if (cursor === void 0) break;
3038
- if (page === APP_TOOLS_PAGE_CAP - 1) {
3039
- console.warn(
3040
- `[MCP Apps] tools/list still had more pages after ${APP_TOOLS_PAGE_CAP}; registering a partial tool set for bridge ${bridgeId}.`
3041
- );
3042
- }
3043
- }
3044
- appToolsListedBridgeIdsRef.current.add(bridgeId);
3045
- if (!isLive()) return;
3046
- const appVersion = bridge.getAppVersion();
3047
- await appToolsRegistry.getState().registerInstance({
3048
- bridgeId,
3049
- chatSessionId,
3050
- parentToolCallId: toolCallIdRef.current,
3051
- serverId: serverIdRef.current,
3052
- appName: appVersion?.name ?? serverIdRef.current,
3053
- appVersion: appVersion?.version,
3054
- surface,
3055
- bridge,
3056
- tools,
3057
- registeredAtMs: Date.now(),
3058
- // Stable closure: the inline default reads `sandboxRef.current`
3059
- // which is React-managed and tracks the live SandboxedIframe
3060
- // across re-renders. The modal passes its own accessor against
3061
- // `modalSandboxRef`.
3062
- getIframeElement
3063
- });
3064
- if (!isLive()) {
3065
- appToolsRegistry.getState().unregisterInstance(bridgeId);
3066
- return;
3067
- }
3068
- needsRefresh = appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);
3069
- }
3070
- } catch (err) {
3071
- appToolsListedBridgeIdsRef.current.delete(bridgeId);
3072
- logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
3073
- error: err instanceof Error ? err.message : String(err)
3074
- });
3075
- } finally {
3076
- appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);
3077
- }
3078
- },
3079
- [appToolsRegistry, chatSessionId, logWidgetDebug]
3080
- );
3126
+ const discoverAppTools = useMemo(() => createAppToolDiscovery({
3127
+ registry: appToolsRegistry,
3128
+ context: () => ({ chatSessionId, parentToolCallId: toolCallIdRef.current, serverId: serverIdRef.current }),
3129
+ onError: (error) => logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
3130
+ error: error instanceof Error ? error.message : String(error)
3131
+ })
3132
+ }), [appToolsRegistry, chatSessionId, logWidgetDebug]);
3133
+ const refreshAppProvidedTools = useCallback((bridge, bridgeId, options = {}) => discoverAppTools(bridge, bridgeId, {
3134
+ ...options,
3135
+ getIframeElement: options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null),
3136
+ isLive: options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId)
3137
+ }), [discoverAppTools]);
3081
3138
  const setWidgetDebugInfo = debug.setWidgetDebugInfo;
3082
3139
  const setWidgetGlobals = debug.setWidgetGlobals;
3083
3140
  const setWidgetStateStore = debug.setWidgetState;
@@ -3708,12 +3765,12 @@ function MCPAppsRendererSurface({
3708
3765
  if (wasReady) {
3709
3766
  setReinitCount((c) => c + 1);
3710
3767
  }
3711
- if (appCaps?.tools) {
3768
+ {
3712
3769
  const bridgeId = appToolsBridgeIdRef.current ?? crypto.randomUUID();
3713
3770
  appToolsBridgeIdRef.current = bridgeId;
3714
3771
  setAppToolsBridgeIdState(bridgeId);
3715
3772
  void refreshAppProvidedTools(b, bridgeId);
3716
- if (!hasAutoPromotedForAppToolsRef.current && !userPreferInlineRef.current && declaredAppModes?.includes("fullscreen")) {
3773
+ if (appCaps?.tools && !hasAutoPromotedForAppToolsRef.current && !userPreferInlineRef.current && declaredAppModes?.includes("fullscreen")) {
3717
3774
  hasAutoPromotedForAppToolsRef.current = true;
3718
3775
  setDisplayModeRef.current?.("fullscreen");
3719
3776
  }
@@ -4057,7 +4114,7 @@ function MCPAppsRendererSurface({
4057
4114
  if (method === "ui/notifications/size-changed") {
4058
4115
  signalStreamingRender();
4059
4116
  }
4060
- if (method === "notifications/tools/list_changed") {
4117
+ if (method === "notifications/tools/list_changed" || method === "ui/notifications/sandbox-tools-changed") {
4061
4118
  const bridgeId = appToolsBridgeIdRef.current;
4062
4119
  if (bridgeId) {
4063
4120
  void refreshAppProvidedTools(bridge, bridgeId, { force: true });
@@ -4104,13 +4161,6 @@ function MCPAppsRendererSurface({
4104
4161
  bridgeRef.current = null;
4105
4162
  if (appToolsBridgeIdRef.current) {
4106
4163
  appToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
4107
- appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);
4108
- appToolsListInFlightBridgeIdsRef.current.delete(
4109
- appToolsBridgeIdRef.current
4110
- );
4111
- appToolsListRefreshPendingBridgeIdsRef.current.delete(
4112
- appToolsBridgeIdRef.current
4113
- );
4114
4164
  appToolsBridgeIdRef.current = null;
4115
4165
  setAppToolsBridgeIdState(null);
4116
4166
  }
@@ -4933,6 +4983,6 @@ function WidgetWorkspaceSurfaceHost({
4933
4983
  ] });
4934
4984
  }
4935
4985
 
4936
- export { MCPAppsRenderer, MCPAppsRendererSurface, PARTIAL_INPUT_THROTTLE_MS, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, SandboxedIframe, UIType, WidgetFullscreenPlacementContext, WidgetHostProvider, WidgetSurfaceHost, WidgetSurfaceHostProvider, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
4986
+ export { MAX_SNAPSHOT_ENTRIES, MCPAppsRenderer, MCPAppsRendererSurface, PARTIAL_INPUT_THROTTLE_MS, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, SandboxedIframe, UIType, WidgetFullscreenPlacementContext, WidgetHostProvider, WidgetSurfaceHost, WidgetSurfaceHostProvider, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, dispatchAppToolCall, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, listAppToolCatalog, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
4937
4987
  //# sourceMappingURL=index.js.map
4938
4988
  //# sourceMappingURL=index.js.map