feat(apps): render running MCP Apps end-to-end (#1370) (#1403)

* feat(apps): render running MCP Apps end-to-end (#1370)

Wire the v2 Apps screen so clicking Open App actually runs an MCP App.
Previously App.tsx stubbed the three load-bearing pieces (sandbox URL,
bridge factory, action handlers), so the iframe loaded about:blank and
nothing crossed the bridge.

- Add useSandboxUrl hook (core/react) to read sandboxUrl from GET
  /api/config and thread it down as sandboxPath; render an "MCP Apps
  unavailable" state instead of a blank iframe when absent.
- Add createAppBridgeFactory: builds a host-side ext-apps AppBridge over
  the active client's SDK client, reads the tool's UI resource on the
  sandbox handshake and pushes it into the proxy, handles openLinks, and
  connects a PostMessageTransport.
- AppRenderer: pass the tool to the bridge factory; buffer tool
  input/result and release them once the view signals `initialized`
  (input before result, latest-wins).
- Move the AppRenderer handle ref to App.tsx so onOpenApp issues
  tools/call with the form values and delivers input + result to the
  running app via the bridge; onCloseApp tears the bridge/iframe down.
- Stories: themed sandbox placeholder (visible in light/dark), an
  echo-bridge running story, and an unavailable story. New unit tests
  for the factory, the buffering, useSandboxUrl, and the empty state.

The listChanged indicator badge wiring is tracked separately in #1402.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(apps): make MCP Apps render in dev — single bridge + result passthrough

Two bugs kept apps (e.g. NightRider's MIDI Pattern Editor) stuck on an empty
shell even though the host fetched the resource and called the tool correctly.

1. StrictMode double-mounted the bridge. The dev-only effect setup→cleanup→
   setup built TWO host bridges/transports, double-loaded the sandbox, and
   raced the app's ui/initialize handshake (it timed out, so `initialized`
   never fired and buffered input/result were never flushed). AppRenderer now
   defers bridge disposal to a microtask and, when the effect re-runs
   synchronously with identical inputs, cancels the disposal and reuses the
   live bridge — so a single bridge survives the double-invoke. The pending
   input/result buffer is no longer cleared on a transient cleanup.

2. The SDK rejected the server's result. callTool() validates structuredContent
   against the tool's outputSchema and throws on a mismatch — but an MCP App is
   a passthrough: the host must forward whatever the server returned to the
   running view (which legacy hosts render fine). InspectorClient.callTool gains
   a `skipOutputValidation` option that routes through client.request() (no
   wrapper validation); onOpenApp uses it.

Verified end-to-end against a real app via Playwright: the editor now renders
its grid + pattern data identically to the v1 inspector.

Tests: AppRenderer StrictMode single-bridge/no-dispose case; a get_temp_extra
test-server fixture (returns an extra structuredContent property) with
integration tests covering both the throwing default path and the
skipOutputValidation passthrough.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps): warn (toast) when an app's result violates its outputSchema

The skipOutputValidation passthrough keeps schema-mismatched apps rendering,
but that silently hid a real spec problem from server developers. Now the
host still renders, but surfaces the mismatch.

- InspectorClient.callTool runs the SDK's own Ajv output validation on the
  skipOutputValidation path NON-fatally and returns the message as
  `outputValidationError` on the ToolCallInvocation (and the
  toolCallResultChange event); the result is still delivered.
- App.tsx onOpenApp shows a yellow toast when outputValidationError is set,
  explaining strict MCP clients may not render the app.

Tests: integration cases asserting outputValidationError is set for a
schema-violating result (get_temp_extra) and unset for a valid one (get_temp).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps): summarize output-schema warning in toast + details modal

The previous toast dumped the full (very long) validation error and
overflowed. Now the toast shows a one-line summary with a "View validation
details" link that opens a modal containing the full error in a read-only,
scrollable textarea.

- New OutputValidationModal group component (+ story + tests).
- App.tsx: toast message is a summary + link; clicking it opens the modal
  populated with the tool name and the full outputValidationError.

Verified via Playwright against the NightRider MIDI editor: toast is concise,
link opens the modal with the scrollable details.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(apps): address PR review — theme stability, onError, validation polish

Responds to the automated PR review on #1403.

- Theme toggle no longer rebuilds a running app's bridge. createAppBridgeFactory
  reads the resolved theme from the DOM (Mantine's data-mantine-color-scheme) at
  bridge-build time instead of capturing isDark in the factory deps, so the
  factory identity is stable across theme flips. (#1)
- Wire AppRenderer's onError through AppsScreen -> InspectorView -> App.tsx,
  surfacing bridge/runtime failures (no client, late rejection, failed
  tools/call) as a red toast instead of a silent blank iframe. (#2)
- Extract validateToolOutput into a pure, unit-tested helper covering the
  matching / extra-property / missing-structuredContent / error / bad-schema
  cases (the no-structuredContent branch can't be produced via the SDK server,
  which rejects it before sending). (#4)
- useSandboxUrl aborts its in-flight fetch on unmount (cancelled flag) to avoid
  setState after unmount. (#5)
- Schema-mismatch toast: autoClose:false (details modal is one click away). (note)
- AppRenderer: add a state-machine comment block documenting the bridge
  lifecycle refs. (#6)
- inspectorClient: note why the `as CallToolResult` casts are safe. (note)

Tests: AppsScreen onError surface; validateToolOutput unit suite; factory theme
read from DOM. validate + test:storybook green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(apps): clarify theme attribute + useSandboxUrl fetch comments

Re-review follow-ups (non-blocking):
- createAppBridgeFactory: note that Mantine's data-mantine-color-scheme is only
  ever light/dark (auto is resolved before paint), so no `auto` branch is needed
  and matchMedia only covers an absent attribute.
- useSandboxUrl: correct the doc to say it fetches on mount AND re-fetches on
  baseUrl/authToken change (idempotent), not "once on mount".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cliff Hall 2026-06-01 18:01:44 -04:00 • committed by GitHub
commit 5fb2b503f4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -0,0 +1,165 @@
import {
AppBridge,
PostMessageTransport,
getToolUiResourceUri,
} from "@modelcontextprotocol/ext-apps/app-bridge";
import type {
McpUiHostCapabilities,
McpUiResourceMeta,
} from "@modelcontextprotocol/ext-apps/app-bridge";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import type {
Implementation,
ReadResourceResult,
} from "@modelcontextprotocol/sdk/types.js";
import type { BridgeFactory } from "./AppRenderer";
/**
* Host identity advertised to MCP Apps during the bridge handshake. Static —
* the value is informational (shown by some apps), not a protocol version.
*/
export const HOST_INFO: Implementation = {
name: "MCP Inspector",
version: "2.0.0",
};
/**
* Capabilities the inspector host offers a running MCP App. Constructed WITH an
* MCP client (see {@link createAppBridgeFactory}), so the bridge auto-forwards
* tools/resources/prompts to the view; we only declare the host-side features
* we actually back: external links (handled below), tool/resource list-change
* forwarding, and logging passthrough.
*/
export const HOST_CAPABILITIES: McpUiHostCapabilities = {
openLinks: {},
serverTools: { listChanged: true },
serverResources: { listChanged: true },
logging: {},
};
export interface AppBridgeFactoryDeps {
/** The connected SDK client to back the bridge, or null when disconnected. */
getClient: () => Client | null;
/** Reads a UI resource (resources/read) and returns the SDK result. */
readResource: (uri: string) => Promise<ReadResourceResult>;
}
/**
* Resolve the host theme from the DOM at bridge-build time. Mantine writes the
* resolved color scheme to `<html data-mantine-color-scheme>`. Reading it here
* (rather than capturing React state in the factory deps) keeps the factory's
* identity stable across theme toggles — the AppRenderer treats a new factory
* identity as "rebuild the bridge", which would reload a running app's iframe on
* every theme flip. The theme is read once per bridge build (the value at open
* time); pushing live theme updates to an already-open app would need an
* AppBridge.setHostContext follow-up.
*
* The attribute is only ever `"light"` or `"dark"` — Mantine resolves
* `defaultColorScheme="auto"` to the system value before paint and never writes
* `"auto"` here, so no `auto` branch is needed. The matchMedia fallback only
* covers the attribute being absent (e.g. a hydration race).
*/
function currentTheme(): "light" | "dark" {
if (typeof document !== "undefined") {
const attr = document.documentElement.getAttribute(
"data-mantine-color-scheme",
);
if (attr === "dark" || attr === "light") return attr;
}
if (
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-color-scheme: dark)").matches
) {
return "dark";
}
return "light";
}
/** First text content block of a UI resource, plus its `_meta` (sandbox hints). */
function extractHtmlAndMeta(result: ReadResourceResult): {
html: string;
meta: McpUiResourceMeta | undefined;
} {
for (const content of result.contents) {
const text = (content as { text?: unknown }).text;
if (typeof text === "string") {
return {
html: text,
meta: content._meta as McpUiResourceMeta | undefined,
};
}
}
throw new Error("UI resource has no text (HTML) content");
}
/**
* Builds the {@link BridgeFactory} the AppRenderer uses to bring a sandbox
* iframe to life. For each mounted iframe + tool it:
*
* 1. constructs a host-side {@link AppBridge} over the SDK client (so the view
* can call tools/resources/prompts directly),
* 2. on the sandbox proxy's `sandboxready` signal, reads the tool's UI
* resource and pushes its HTML + sandbox/permissions into the inner iframe,
* 3. handles `openLinks` by opening http(s) URLs in a new tab,
* 4. connects a {@link PostMessageTransport} to the iframe and returns the
* live bridge.
*
* Host-initiated tool input/result are pushed separately through the renderer's
* imperative handle (see `AppRenderer`), gated on the view's `initialized`
* event. The factory throws when no client is connected; AppRenderer routes
* that to its `onError` so the user sees a clear failure instead of a blank
* frame.
*/
export function createAppBridgeFactory(
deps: AppBridgeFactoryDeps,
): BridgeFactory {
return async (iframe, tool) => {
const client = deps.getClient();
if (!client) {
throw new Error("Cannot render MCP App: no connected MCP client.");
}
const targetWindow = iframe.contentWindow;
if (!targetWindow) {
throw new Error("Cannot render MCP App: sandbox iframe has no window.");
}
const bridge = new AppBridge(client, HOST_INFO, HOST_CAPABILITIES, {
hostContext: { theme: currentTheme() },
});
// The double-iframe proxy posts `sandboxready` once it can receive content.
// Read the tool's UI resource and hand its HTML (plus any sandbox/permission
// hints from the resource _meta) to the inner sandboxed iframe. Swallow
// failures: a read error leaves an empty (but live) app frame rather than
// tearing down the bridge mid-handshake.
bridge.addEventListener("sandboxready", () => {
void (async () => {
try {
const uri = getToolUiResourceUri(tool);
if (!uri) return;
const result = await deps.readResource(uri);
const { html, meta } = extractHtmlAndMeta(result);
await bridge.sendSandboxResourceReady({
html,
permissions: meta?.permissions,
csp: meta?.csp,
});
} catch {
/* read/post failed (or bridge closed) — leave the frame empty */
}
})();
});
bridge.onopenlink = async ({ url }) => {
if (/^https?:\/\//i.test(url)) {
window.open(url, "_blank", "noopener,noreferrer");
return { isError: false };
}
return { isError: true };
};
const transport = new PostMessageTransport(targetWindow, targetWindow);
await bridge.connect(transport);
return bridge;
};
}