@mcpjam/widget-react 0.1.16 → 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.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);
@@ -1245,6 +1370,27 @@ function useInitialRenderOutcome(ready, failed, notify) {
1245
1370
  }
1246
1371
  }, [ready, failed, notify]);
1247
1372
  }
1373
+ function useSandboxProxyGeneration({
1374
+ bridgeTransportReady,
1375
+ hasWidgetHtml,
1376
+ logReady
1377
+ }) {
1378
+ const [generation, setGeneration] = useState(0);
1379
+ const bridgeTransportReadyRef = useRef(bridgeTransportReady);
1380
+ bridgeTransportReadyRef.current = bridgeTransportReady;
1381
+ const hasWidgetHtmlRef = useRef(hasWidgetHtml);
1382
+ hasWidgetHtmlRef.current = hasWidgetHtml;
1383
+ const logReadyRef = useRef(logReady);
1384
+ logReadyRef.current = logReady;
1385
+ const onReady = useCallback(() => {
1386
+ setGeneration((current) => current + 1);
1387
+ logReadyRef.current({
1388
+ bridgeTransportReady: bridgeTransportReadyRef.current,
1389
+ hasWidgetHtml: hasWidgetHtmlRef.current
1390
+ });
1391
+ }, []);
1392
+ return { generation, onReady };
1393
+ }
1248
1394
  var WidgetFullscreenPlacementContext = createContext(null);
1249
1395
  function McpAppsModal({
1250
1396
  open,
@@ -1385,8 +1531,7 @@ function McpAppsModal({
1385
1531
  )
1386
1532
  );
1387
1533
  }
1388
- const appCaps = bridge.getAppCapabilities();
1389
- if (appCaps?.tools) {
1534
+ {
1390
1535
  const bridgeId = modalAppToolsBridgeIdRef.current ?? crypto.randomUUID();
1391
1536
  modalAppToolsBridgeIdRef.current = bridgeId;
1392
1537
  void refreshAppProvidedTools(bridge, bridgeId, {
@@ -1422,7 +1567,7 @@ function McpAppsModal({
1422
1567
  pendingRpcMethods.delete(response.id);
1423
1568
  }
1424
1569
  const method = correlatedMethod ?? extractMethod(message, "mcp-apps");
1425
- if (method === "notifications/tools/list_changed") {
1570
+ if (method === "notifications/tools/list_changed" || method === "ui/notifications/sandbox-tools-changed") {
1426
1571
  const bridgeId = modalAppToolsBridgeIdRef.current;
1427
1572
  if (bridgeId) {
1428
1573
  void refreshAppProvidedTools(bridge, bridgeId, {
@@ -2509,7 +2654,6 @@ function MCPAppsRendererSurface({
2509
2654
  const [firstCspBlock, setFirstCspBlock] = useState(null);
2510
2655
  const [widgetHtml, setWidgetHtml] = useState(null);
2511
2656
  const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
2512
- const [sandboxProxyReady, setSandboxProxyReady] = useState(false);
2513
2657
  const [viewMount, setViewMount] = useState(null);
2514
2658
  const [bridgeTransportReady, setBridgeTransportReady] = useState(false);
2515
2659
  const [bridgeGeneration, setBridgeGeneration] = useState(0);
@@ -2622,9 +2766,6 @@ function MCPAppsRendererSurface({
2622
2766
  );
2623
2767
  const hasAutoPromotedForAppToolsRef = useRef(false);
2624
2768
  const appToolsBridgeIdRef = useRef(null);
2625
- const appToolsListedBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2626
- const appToolsListInFlightBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2627
- const appToolsListRefreshPendingBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2628
2769
  const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState(null);
2629
2770
  const appToolsRegistry = useAppToolsRegistryApi();
2630
2771
  const pendingAppToolCalls = useAppToolsRegistry(
@@ -2982,82 +3123,18 @@ function MCPAppsRendererSurface({
2982
3123
  },
2983
3124
  []
2984
3125
  );
2985
- const refreshAppProvidedTools = useCallback(
2986
- async (bridge, bridgeId, options = {}) => {
2987
- const surface = options.surface ?? "inline";
2988
- const getIframeElement = options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null);
2989
- const isLive = options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId);
2990
- const alreadyListed = appToolsListedBridgeIdsRef.current.has(bridgeId);
2991
- const inFlight = appToolsListInFlightBridgeIdsRef.current.has(bridgeId);
2992
- if (inFlight) {
2993
- if (options.force) {
2994
- appToolsListRefreshPendingBridgeIdsRef.current.add(bridgeId);
2995
- }
2996
- return;
2997
- }
2998
- if (!options.force && alreadyListed) return;
2999
- appToolsListInFlightBridgeIdsRef.current.add(bridgeId);
3000
- try {
3001
- let needsRefresh = true;
3002
- while (needsRefresh) {
3003
- appToolsListRefreshPendingBridgeIdsRef.current.delete(bridgeId);
3004
- const tools = [];
3005
- let cursor;
3006
- const APP_TOOLS_PAGE_CAP = 8;
3007
- for (let page = 0; page < APP_TOOLS_PAGE_CAP; page += 1) {
3008
- const result = await bridge.listTools(
3009
- cursor === void 0 ? {} : { cursor }
3010
- );
3011
- tools.push(
3012
- ...(result.tools ?? []).filter(
3013
- (t) => Boolean(t && typeof t.name === "string" && t.name.length > 0)
3014
- )
3015
- );
3016
- cursor = typeof result.nextCursor === "string" ? result.nextCursor : void 0;
3017
- if (cursor === void 0) break;
3018
- if (page === APP_TOOLS_PAGE_CAP - 1) {
3019
- console.warn(
3020
- `[MCP Apps] tools/list still had more pages after ${APP_TOOLS_PAGE_CAP}; registering a partial tool set for bridge ${bridgeId}.`
3021
- );
3022
- }
3023
- }
3024
- appToolsListedBridgeIdsRef.current.add(bridgeId);
3025
- if (!isLive()) return;
3026
- const appVersion = bridge.getAppVersion();
3027
- await appToolsRegistry.getState().registerInstance({
3028
- bridgeId,
3029
- chatSessionId,
3030
- parentToolCallId: toolCallIdRef.current,
3031
- serverId: serverIdRef.current,
3032
- appName: appVersion?.name ?? serverIdRef.current,
3033
- appVersion: appVersion?.version,
3034
- surface,
3035
- bridge,
3036
- tools,
3037
- registeredAtMs: Date.now(),
3038
- // Stable closure: the inline default reads `sandboxRef.current`
3039
- // which is React-managed and tracks the live SandboxedIframe
3040
- // across re-renders. The modal passes its own accessor against
3041
- // `modalSandboxRef`.
3042
- getIframeElement
3043
- });
3044
- if (!isLive()) {
3045
- appToolsRegistry.getState().unregisterInstance(bridgeId);
3046
- return;
3047
- }
3048
- needsRefresh = appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);
3049
- }
3050
- } catch (err) {
3051
- appToolsListedBridgeIdsRef.current.delete(bridgeId);
3052
- logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
3053
- error: err instanceof Error ? err.message : String(err)
3054
- });
3055
- } finally {
3056
- appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);
3057
- }
3058
- },
3059
- [appToolsRegistry, chatSessionId, logWidgetDebug]
3060
- );
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]);
3061
3138
  const setWidgetDebugInfo = debug.setWidgetDebugInfo;
3062
3139
  const setWidgetGlobals = debug.setWidgetGlobals;
3063
3140
  const setWidgetStateStore = debug.setWidgetState;
@@ -3688,12 +3765,12 @@ function MCPAppsRendererSurface({
3688
3765
  if (wasReady) {
3689
3766
  setReinitCount((c) => c + 1);
3690
3767
  }
3691
- if (appCaps?.tools) {
3768
+ {
3692
3769
  const bridgeId = appToolsBridgeIdRef.current ?? crypto.randomUUID();
3693
3770
  appToolsBridgeIdRef.current = bridgeId;
3694
3771
  setAppToolsBridgeIdState(bridgeId);
3695
3772
  void refreshAppProvidedTools(b, bridgeId);
3696
- if (!hasAutoPromotedForAppToolsRef.current && !userPreferInlineRef.current && declaredAppModes?.includes("fullscreen")) {
3773
+ if (appCaps?.tools && !hasAutoPromotedForAppToolsRef.current && !userPreferInlineRef.current && declaredAppModes?.includes("fullscreen")) {
3697
3774
  hasAutoPromotedForAppToolsRef.current = true;
3698
3775
  setDisplayModeRef.current?.("fullscreen");
3699
3776
  }
@@ -3955,9 +4032,17 @@ function MCPAppsRendererSurface({
3955
4032
  hasOwnedMessage
3956
4033
  ]
3957
4034
  );
4035
+ const {
4036
+ generation: sandboxProxyGeneration,
4037
+ onReady: handleSandboxProxyReady
4038
+ } = useSandboxProxyGeneration({
4039
+ bridgeTransportReady,
4040
+ hasWidgetHtml,
4041
+ logReady: (details) => logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", details)
4042
+ });
3958
4043
  useEffect(() => {
3959
4044
  if (!widgetHtml) return;
3960
- if (!sandboxProxyReady) {
4045
+ if (sandboxProxyGeneration === 0) {
3961
4046
  logWidgetDebug("host-to-ui", "debug/bridge-connect-skipped", {
3962
4047
  reason: "sandbox-proxy-not-ready"
3963
4048
  });
@@ -4029,7 +4114,7 @@ function MCPAppsRendererSurface({
4029
4114
  if (method === "ui/notifications/size-changed") {
4030
4115
  signalStreamingRender();
4031
4116
  }
4032
- if (method === "notifications/tools/list_changed") {
4117
+ if (method === "notifications/tools/list_changed" || method === "ui/notifications/sandbox-tools-changed") {
4033
4118
  const bridgeId = appToolsBridgeIdRef.current;
4034
4119
  if (bridgeId) {
4035
4120
  void refreshAppProvidedTools(bridge, bridgeId, { force: true });
@@ -4076,13 +4161,6 @@ function MCPAppsRendererSurface({
4076
4161
  bridgeRef.current = null;
4077
4162
  if (appToolsBridgeIdRef.current) {
4078
4163
  appToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
4079
- appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);
4080
- appToolsListInFlightBridgeIdsRef.current.delete(
4081
- appToolsBridgeIdRef.current
4082
- );
4083
- appToolsListRefreshPendingBridgeIdsRef.current.delete(
4084
- appToolsBridgeIdRef.current
4085
- );
4086
4164
  appToolsBridgeIdRef.current = null;
4087
4165
  setAppToolsBridgeIdState(null);
4088
4166
  }
@@ -4096,7 +4174,8 @@ function MCPAppsRendererSurface({
4096
4174
  };
4097
4175
  }, [
4098
4176
  widgetHtml,
4099
- sandboxProxyReady,
4177
+ // A reloaded proxy is a new window with no view: reconnect to it.
4178
+ sandboxProxyGeneration,
4100
4179
  registerBridgeHandlers,
4101
4180
  refreshAppProvidedTools,
4102
4181
  // Bridge must rebuild when the resolved sandbox policy changes — a host
@@ -4521,13 +4600,7 @@ function MCPAppsRendererSurface({
4521
4600
  browserStorage: effectiveSandbox.browserStorage,
4522
4601
  colorScheme: resolvedTheme,
4523
4602
  recordMode,
4524
- onProxyReady: () => {
4525
- setSandboxProxyReady(true);
4526
- logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", {
4527
- bridgeTransportReady,
4528
- hasWidgetHtml
4529
- });
4530
- },
4603
+ onProxyReady: handleSandboxProxyReady,
4531
4604
  onMessage: handleSandboxMessage,
4532
4605
  title: `MCP App: ${toolName}`,
4533
4606
  hostedMode: host.surface.hostedMode,
@@ -4910,6 +4983,6 @@ function WidgetWorkspaceSurfaceHost({
4910
4983
  ] });
4911
4984
  }
4912
4985
 
4913
- 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 };
4914
4987
  //# sourceMappingURL=index.js.map
4915
4988
  //# sourceMappingURL=index.js.map