@mcpjam/widget-react 0.2.2 → 0.4.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
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentType, ReactNode, ContextType } from 'react';
3
3
  import * as _mcpjam_sdk_widget_runtime from '@mcpjam/sdk/widget-runtime';
4
- import { ToolResultPolicy, PrepareSandboxViewRequest, PreparedSandboxView, ReleaseSandboxViewRequest, BrowserStoragePolicy, AppToolRequestContext, AppToolInvocationUpdate } from '@mcpjam/sdk/widget-runtime';
4
+ import { ToolResultPolicy, PrepareSandboxViewRequest, PreparedSandboxView, ReleaseSandboxViewRequest, BrowserStoragePolicy, DisplayBehavior, AppToolRequestContext, AppToolInvocationUpdate } from '@mcpjam/sdk/widget-runtime';
5
5
  export { getToolVisibility, isVisibleToAppOnly, isVisibleToModelOnly } from '@mcpjam/sdk/widget-runtime';
6
6
  import { McpUiResourceCsp, McpUiResourcePermissions, McpUiHostCapabilities, McpUiStyles, AppBridge, McpUiHostContext } from '@modelcontextprotocol/ext-apps/app-bridge';
7
7
  import { MCPPrompt, MCPResourceTemplate, SandboxCspPolicy, SandboxPermissionsPolicy } from '@mcpjam/sdk/browser';
@@ -177,14 +177,16 @@ interface WidgetSurfaceInfo {
177
177
  */
178
178
  fixedDisplayMode?: DisplayMode;
179
179
  /**
180
- * Apply OpenAI's display-mode rules (ChatGPT and Codex with the Display
181
- * modes extension on): omitted resource modes mean every host mode, a
182
- * preference picks the starting mode without narrowing, a resource that
183
- * declares both inline and fullscreen starts fullscreen, and a fixed mode
184
- * the initialized App says it cannot show refuses the App. Absent: modes are
185
- * negotiated as before.
180
+ * How the client picks display modes while its Display modes extension is
181
+ * on. `hints` names the resource metadata the hints come from. `start:
182
+ * "hint-first"` is OpenAI's rules: omitted resource modes mean every host
183
+ * mode, a preference picks the starting mode without narrowing, a resource
184
+ * that declares both inline and fullscreen starts fullscreen, and a fixed
185
+ * mode the initialized App says it cannot show refuses the App.
186
+ * `"inline-then-move"` is Claude's: the App starts inline and moves once to
187
+ * the side panel. Absent: modes are negotiated as before.
186
188
  */
187
- openAIDisplayModes?: boolean;
189
+ displayBehavior?: DisplayBehavior;
188
190
  }
189
191
  interface WidgetMount {
190
192
  index: number;
@@ -573,6 +575,10 @@ interface FetchWidgetContentRequest {
573
575
  interface FetchWidgetContentResponse {
574
576
  sourceReceipt?: string;
575
577
  resourceDisplayHints?: _mcpjam_sdk_widget_runtime.ResourceDisplayHints;
578
+ /** `_meta.ui` display hints, read under `displayBehavior.hints: "ui"`. */
579
+ uiDisplayHints?: _mcpjam_sdk_widget_runtime.ResourceDisplayHints;
580
+ /** A `_meta.ui.preferredDisplayMode` that isn't a mode, as JSON; ignored. */
581
+ ignoredPreferredDisplayMode?: string;
576
582
  html: string;
577
583
  csp?: McpUiResourceCsp;
578
584
  permissions?: McpUiResourcePermissions;
@@ -1266,6 +1272,12 @@ interface MCPAppsRendererProps {
1266
1272
  }) => void;
1267
1273
  /** Modes allowed by the host, resource and initialized App for presentation controls. */
1268
1274
  onAppSupportedDisplayModesChange?: (modes: DisplayMode[] | undefined) => void;
1275
+ /**
1276
+ * The host fixed a display mode that the App's `availableDisplayModes`
1277
+ * leaves out. With this set, the renderer closes the App and hands its
1278
+ * declared modes back instead of showing a load error.
1279
+ */
1280
+ onFixedDisplayModeUnsupported?: (declared: DisplayMode[]) => void;
1269
1281
  /**
1270
1282
  * Called when the widget sends `ui/notifications/request-teardown`
1271
1283
  * and the host has agreed to honor it (matrix `requestTeardown !==
@@ -1353,7 +1365,7 @@ interface MCPAppsRendererProps {
1353
1365
  persistentSurfaceInitialToolCallId?: string;
1354
1366
  }
1355
1367
  declare function MCPAppsRenderer(props: MCPAppsRendererProps): react.JSX.Element;
1356
- declare function MCPAppsRendererSurface({ appToolSourceLabel, hostInputPending, chatSessionId, getModelChatSessionId, serverId, serverName, toolCallId, toolName, toolState, toolInput, toolOutput, toolResponseMetadata, toolErrorText, resourceUri, toolMetadata, toolsMetadata, onSendFollowUp, onCallTool, onAppToolInvocationChange, onWidgetStateChange, onInitialRenderOutcome, recordMode, onRecorderStep, onRecorderReady, onReplayControllerReady, pipWidgetId, fullscreenWidgetId, onRequestPip, onExitPip, displayMode: displayModeProp, onDisplayModeChange, onRequestFullscreen, onExitFullscreen, onModelContextUpdate, onAppSupportedDisplayModesChange, onRequestTeardown, onConfirmDownload, isOffline, cachedWidgetHtmlUrl, liveFetchPreferred, widgetCsp: initialWidgetCsp, widgetPermissions: initialWidgetPermissions, widgetPermissive: initialWidgetPermissive, prefersBorder: initialPrefersBorder, injectedOpenAiCompat: initialInjectedOpenAiCompat, injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities, initialWidgetState, minimalMode, hostManagedPresentation, persistentSurfaceId, persistentSurfaceInitialToolCallId, }: MCPAppsRendererProps): react.JSX.Element | null;
1368
+ declare function MCPAppsRendererSurface({ appToolSourceLabel, hostInputPending, chatSessionId, getModelChatSessionId, serverId, serverName, toolCallId, toolName, toolState, toolInput, toolOutput, toolResponseMetadata, toolErrorText, resourceUri, toolMetadata, toolsMetadata, onSendFollowUp, onCallTool, onAppToolInvocationChange, onWidgetStateChange, onInitialRenderOutcome, recordMode, onRecorderStep, onRecorderReady, onReplayControllerReady, pipWidgetId, fullscreenWidgetId, onRequestPip, onExitPip, displayMode: displayModeProp, onDisplayModeChange, onRequestFullscreen, onExitFullscreen, onModelContextUpdate, onAppSupportedDisplayModesChange, onFixedDisplayModeUnsupported, onRequestTeardown, onConfirmDownload, isOffline, cachedWidgetHtmlUrl, liveFetchPreferred, widgetCsp: initialWidgetCsp, widgetPermissions: initialWidgetPermissions, widgetPermissive: initialWidgetPermissive, prefersBorder: initialPrefersBorder, injectedOpenAiCompat: initialInjectedOpenAiCompat, injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities, initialWidgetState, minimalMode, hostManagedPresentation, persistentSurfaceId, persistentSurfaceInitialToolCallId, }: MCPAppsRendererProps): react.JSX.Element | null;
1357
1369
 
1358
1370
  declare function WidgetSurfaceHostProvider({ children, }: {
1359
1371
  children: ReactNode;
@@ -1503,6 +1515,12 @@ interface WidgetFullscreenPlacement {
1503
1515
  * opposed to the host ending it (another tab chosen, the panel hidden).
1504
1516
  */
1505
1517
  onExit?: () => void;
1518
+ /**
1519
+ * Bring the panel holding the placed App back into view (open it, or widen
1520
+ * it from a sliver): the conversation's card for an App that is only full
1521
+ * screen calls it.
1522
+ */
1523
+ reveal?: () => void;
1506
1524
  }
1507
1525
  declare const WidgetFullscreenPlacementContext: react.Context<WidgetFullscreenPlacement | null>;
1508
1526
 
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, callViewWebmcpTool, applyToolResultPolicy, openAIDisplayModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod, appToolSourceFor, discoverViewAppTools, listViewWebmcpTools } from '@mcpjam/sdk/widget-runtime';
4
+ import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, callViewWebmcpTool, applyToolResultPolicy, openAIDisplayModes, inlineThenMoveModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod, shouldMoveToPanel, inlineThenMoveStart, 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';
@@ -1267,8 +1267,9 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1267
1267
  );
1268
1268
  const sandboxProxyUrl = preparedView.required ? preparedView.result?.proxyUrl : legacyProxyUrl;
1269
1269
  const sandboxProxyOrigin = useMemo(() => {
1270
+ if (!sandboxProxyUrl) return null;
1270
1271
  try {
1271
- return new URL(sandboxProxyUrl ?? "about:blank").origin;
1272
+ return new URL(sandboxProxyUrl).origin;
1272
1273
  } catch {
1273
1274
  return "*";
1274
1275
  }
@@ -1277,7 +1278,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1277
1278
  ref,
1278
1279
  () => ({
1279
1280
  postMessage: (data) => {
1280
- if (sandboxProxyUrl) outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1281
+ if (sandboxProxyOrigin) outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1281
1282
  },
1282
1283
  getIframeElement: () => outerRef.current
1283
1284
  }),
@@ -1382,7 +1383,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1382
1383
  if (!proxyReady) lastResourceReadyKeyRef.current = null;
1383
1384
  }, [proxyReady]);
1384
1385
  useEffect(() => {
1385
- if (!proxyReady || !html) return;
1386
+ if (!proxyReady || !html || !sandboxProxyOrigin) return;
1386
1387
  const resourceTargetKey = `${sandboxProxyOrigin}\0${resourceReadyKey}`;
1387
1388
  if (lastResourceReadyKeyRef.current === resourceTargetKey) return;
1388
1389
  lastResourceReadyKeyRef.current = resourceTargetKey;
@@ -1426,7 +1427,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1426
1427
  });
1427
1428
  }, [proxyReady, html, resourceReadyKey, sandboxProxyOrigin]);
1428
1429
  useEffect(() => {
1429
- if (!proxyReady || !colorScheme) return;
1430
+ if (!proxyReady || !colorScheme || !sandboxProxyOrigin) return;
1430
1431
  outerRef.current?.contentWindow?.postMessage(
1431
1432
  {
1432
1433
  jsonrpc: "2.0",
@@ -1686,6 +1687,51 @@ function useSandboxProxyGeneration({
1686
1687
  return { generation, onReady };
1687
1688
  }
1688
1689
  var WidgetFullscreenPlacementContext = createContext(null);
1690
+ var SETTLED_TOOL_STATES = /* @__PURE__ */ new Set([
1691
+ "output-available",
1692
+ "output-error",
1693
+ "output-denied"
1694
+ ]);
1695
+ function isErrorResult(output) {
1696
+ return typeof output === "object" && output !== null && "isError" in output && output.isError === true;
1697
+ }
1698
+ function useInlineThenMove(args) {
1699
+ const latest = useRef(args);
1700
+ useLayoutEffect(() => {
1701
+ latest.current = args;
1702
+ });
1703
+ const on = args.behavior?.start === "inline-then-move";
1704
+ const attempt = on && args.ready && SETTLED_TOOL_STATES.has(args.toolState ?? "");
1705
+ const tried = useRef(false);
1706
+ useEffect(() => {
1707
+ if (!attempt || tried.current) return;
1708
+ tried.current = true;
1709
+ const now = latest.current;
1710
+ const toolResultOk = now.toolState === "output-available" && !isErrorResult(now.toolOutput);
1711
+ if (!now.fullscreen && !now.preferInline() && shouldMoveToPanel({
1712
+ modes: now.modes,
1713
+ preferred: now.preferred,
1714
+ toolResultOk,
1715
+ panelAvailable: now.panelAvailable
1716
+ }))
1717
+ now.moveToPanel();
1718
+ }, [attempt]);
1719
+ const startMode = useCallback(
1720
+ (negotiated) => {
1721
+ const now = latest.current;
1722
+ if (now.behavior?.start !== "inline-then-move") return void 0;
1723
+ const start = inlineThenMoveStart(negotiated);
1724
+ return start === "fullscreen" && !now.panelAvailable ? void 0 : start;
1725
+ },
1726
+ []
1727
+ );
1728
+ const showPanel = useCallback(() => latest.current.revealPanel?.(), []);
1729
+ return {
1730
+ startMode,
1731
+ panelCard: on && args.placed && !args.modes.includes("inline"),
1732
+ showPanel
1733
+ };
1734
+ }
1689
1735
  function McpAppsModal({
1690
1736
  open,
1691
1737
  onOpenChange,
@@ -2660,6 +2706,7 @@ function MCPAppsRendererSurface({
2660
2706
  onExitFullscreen,
2661
2707
  onModelContextUpdate,
2662
2708
  onAppSupportedDisplayModesChange,
2709
+ onFixedDisplayModeUnsupported,
2663
2710
  onRequestTeardown,
2664
2711
  onConfirmDownload,
2665
2712
  isOffline,
@@ -2811,7 +2858,14 @@ function MCPAppsRendererSurface({
2811
2858
  const fixedDisplayMode = host.surface.fixedDisplayMode;
2812
2859
  const fixedDisplayModeRef = useRef(fixedDisplayMode);
2813
2860
  fixedDisplayModeRef.current = fixedDisplayMode;
2814
- const openAIRules = host.surface.openAIDisplayModes === true;
2861
+ const onFixedDisplayModeUnsupportedRef = useRef(
2862
+ onFixedDisplayModeUnsupported
2863
+ );
2864
+ onFixedDisplayModeUnsupportedRef.current = onFixedDisplayModeUnsupported;
2865
+ const displayBehavior = host.surface.displayBehavior;
2866
+ const displayBehaviorRef = useRef(displayBehavior);
2867
+ displayBehaviorRef.current = displayBehavior;
2868
+ const openAIRules = displayBehavior?.start === "hint-first";
2815
2869
  const openAIRulesRef = useRef(openAIRules);
2816
2870
  openAIRulesRef.current = openAIRules;
2817
2871
  const displayModesFor = useCallback(
@@ -2819,6 +2873,8 @@ function MCPAppsRendererSurface({
2819
2873
  const fixed = fixedDisplayModeRef.current;
2820
2874
  if (openAIRulesRef.current)
2821
2875
  return openAIDisplayModes(hostModes, hints, appModes, fixed);
2876
+ if (displayBehaviorRef.current?.start === "inline-then-move" && !fixed)
2877
+ return inlineThenMoveModes(hostModes, appModes);
2822
2878
  return fixed && hostModes.includes(fixed) ? [fixed] : negotiateResourceDisplayModes([...hostModes], hints, appModes);
2823
2879
  },
2824
2880
  []
@@ -2958,7 +3014,8 @@ function MCPAppsRendererSurface({
2958
3014
  });
2959
3015
  const lastForcedDisplayModeRef = useRef(null);
2960
3016
  const fullscreenPlacement = useContext(WidgetFullscreenPlacementContext);
2961
- const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !fullscreenDismissal.collapsed && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
3017
+ const panelAvailable = !hostManagedPresentation && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement;
3018
+ const placedFullscreen = panelAvailable && effectiveDisplayMode === "fullscreen" && !fullscreenDismissal.collapsed && !!fullscreenPlacement?.rect;
2962
3019
  const fullscreenPlacementRef = useRef(fullscreenPlacement);
2963
3020
  fullscreenPlacementRef.current = fullscreenPlacement;
2964
3021
  const placedExitRef = useRef(() => {
@@ -2991,6 +3048,20 @@ function MCPAppsRendererSurface({
2991
3048
  const [reinitCount, setReinitCount] = useState(0);
2992
3049
  const [loadError, setLoadError] = useState(null);
2993
3050
  useInitialRenderOutcome(isReady, loadError !== null, onInitialRenderOutcome);
3051
+ const inlineThenMove = useInlineThenMove({
3052
+ behavior: displayBehavior,
3053
+ ready: isReady,
3054
+ toolState,
3055
+ toolOutput,
3056
+ modes: effectiveAvailableDisplayModes,
3057
+ preferred: resourceDisplayHints?.preferredDisplayMode,
3058
+ panelAvailable,
3059
+ fullscreen: effectiveDisplayMode === "fullscreen",
3060
+ placed: placedFullscreen,
3061
+ preferInline: () => userPreferInlineRef.current,
3062
+ moveToPanel: () => setDisplayModeRef.current("fullscreen"),
3063
+ revealPanel: fullscreenPlacement?.reveal
3064
+ });
2994
3065
  const [firstCspBlock, setFirstCspBlock] = useState(null);
2995
3066
  const [widgetHtml, setWidgetHtml] = useState(null);
2996
3067
  const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
@@ -3255,7 +3326,8 @@ function MCPAppsRendererSurface({
3255
3326
  mimeTypeWarning: warning,
3256
3327
  mimeTypeValid: valid,
3257
3328
  prefersBorder: prefersBorder2,
3258
- resourceDisplayHints: resourceHints,
3329
+ resourceDisplayHints: openAIHints,
3330
+ uiDisplayHints,
3259
3331
  declaredDomain: serverDeclaredDomain,
3260
3332
  viewOriginLabel: serverViewOriginLabel,
3261
3333
  sourceReceipt: serverSourceReceipt,
@@ -3304,6 +3376,7 @@ function MCPAppsRendererSurface({
3304
3376
  setBridgeTransportReady(false);
3305
3377
  hasRenderedLiveRef.current = true;
3306
3378
  liveRenderIdentityRef.current = liveRenderIdentityKey;
3379
+ const resourceHints = displayBehaviorRef.current?.hints === "ui" ? uiDisplayHints : openAIHints;
3307
3380
  const allowed = displayModesFor(
3308
3381
  hostAvailableDisplayModesRef.current,
3309
3382
  resourceHints
@@ -3313,7 +3386,7 @@ function MCPAppsRendererSurface({
3313
3386
  return false;
3314
3387
  }
3315
3388
  setResourceDisplayHints(resourceHints);
3316
- const initialMode = openAIRulesRef.current ? pickOpenAIDisplayMode(allowed, resourceHints) : resourceHints?.preferredDisplayMode;
3389
+ const initialMode = openAIRulesRef.current ? pickOpenAIDisplayMode(allowed, resourceHints) : displayBehaviorRef.current?.start === "inline-then-move" ? void 0 : resourceHints?.preferredDisplayMode;
3317
3390
  if (initialMode && allowed.includes(initialMode) && !(openAIRulesRef.current && initialMode === effectiveDisplayModeRef.current)) {
3318
3391
  setDisplayMode(initialMode);
3319
3392
  }
@@ -4090,6 +4163,15 @@ function MCPAppsRendererSurface({
4090
4163
  wasReady
4091
4164
  });
4092
4165
  const declaredAppModes = appCaps?.availableDisplayModes;
4166
+ const fixedMode = fixedDisplayModeRef.current;
4167
+ const unsupported = onFixedDisplayModeUnsupportedRef.current;
4168
+ if (fixedMode && unsupported && declaredAppModes && !declaredAppModes.includes(fixedMode)) {
4169
+ setIsReady(false);
4170
+ isReadyRef.current = false;
4171
+ void b.close();
4172
+ unsupported(declaredAppModes);
4173
+ return;
4174
+ }
4093
4175
  const negotiated = displayModesFor(
4094
4176
  hostAvailableDisplayModesRef.current,
4095
4177
  resourceDisplayHintsRef.current,
@@ -4106,11 +4188,11 @@ function MCPAppsRendererSurface({
4106
4188
  void b.close();
4107
4189
  return;
4108
4190
  }
4109
- if (openAIRulesRef.current && !negotiated.includes(effectiveDisplayModeRef.current)) {
4110
- const next = pickOpenAIDisplayMode(
4191
+ if (!negotiated.includes(effectiveDisplayModeRef.current)) {
4192
+ const next = openAIRulesRef.current ? pickOpenAIDisplayMode(
4111
4193
  negotiated,
4112
4194
  resourceDisplayHintsRef.current
4113
- );
4195
+ ) : inlineThenMove.startMode(negotiated);
4114
4196
  if (next) setDisplayModeRef.current(next);
4115
4197
  }
4116
4198
  if (wasReady) {
@@ -4996,7 +5078,15 @@ function MCPAppsRendererSurface({
4996
5078
  }
4997
5079
  );
4998
5080
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4999
- fullscreenDismissal.collapsed && /* @__PURE__ */ jsx("button", { className: "rounded-md border border-border px-3 py-2 text-sm text-foreground", disabled: fullscreenDismissal.pending, onClick: fullscreenDismissal.open, children: fullscreenDismissal.pending ? "App is waiting for input" : "Open App" }),
5081
+ (fullscreenDismissal.collapsed || inlineThenMove.panelCard) && /* @__PURE__ */ jsx(
5082
+ "button",
5083
+ {
5084
+ className: "rounded-md border border-border px-3 py-2 text-sm text-foreground",
5085
+ disabled: fullscreenDismissal.pending,
5086
+ onClick: fullscreenDismissal.collapsed ? fullscreenDismissal.open : inlineThenMove.showPanel,
5087
+ children: fullscreenDismissal.pending ? "App is waiting for input" : "Open App"
5088
+ }
5089
+ ),
5000
5090
  /* @__PURE__ */ jsxs(
5001
5091
  "div",
5002
5092
  {