Skip to content

Commit 5fb2b50

Browse files
cliffhallclaude
andauthored
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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 440b194 commit 5fb2b50

24 files changed

Lines changed: 1683 additions & 66 deletions

‎clients/web/src/App.tsx‎

Lines changed: 160 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2-
import { useComputedColorScheme, useMantineColorScheme } from "@mantine/core";
2+
import {
3+
Anchor,
4+
Stack,
5+
Text,
6+
useComputedColorScheme,
7+
useMantineColorScheme,
8+
} from "@mantine/core";
39
import { notifications } from "@mantine/notifications";
410
import type {
511
InitializeResult,
612
LoggingLevel,
713
LoggingMessageNotification,
814
Tool,
915
} from "@modelcontextprotocol/sdk/types.js";
10-
import type { AppBridge } from "@modelcontextprotocol/ext-apps/app-bridge";
1116
import { InspectorClient } from "@inspector/core/mcp/index.js";
1217
import type { JsonValue } from "@inspector/core/mcp/index.js";
1318
import type {
@@ -49,18 +54,21 @@ import { useManagedRequestorTasks } from "@inspector/core/react/useManagedReques
4954
import { useResourceSubscriptions } from "@inspector/core/react/useResourceSubscriptions.js";
5055
import { useMessageLog } from "@inspector/core/react/useMessageLog.js";
5156
import { useFetchRequestLog } from "@inspector/core/react/useFetchRequestLog.js";
57+
import { useSandboxUrl } from "@inspector/core/react/useSandboxUrl.js";
5258
import { InspectorView } from "./components/views/InspectorView/InspectorView";
5359
import type { ToolCallState } from "./components/screens/ToolsScreen/ToolsScreen";
5460
import type { GetPromptState } from "./components/screens/PromptsScreen/PromptsScreen";
5561
import type { ReadResourceState } from "./components/screens/ResourcesScreen/ResourcesScreen";
56-
import type { BridgeFactory } from "./components/elements/AppRenderer/AppRenderer";
62+
import type { AppRendererHandle } from "./components/elements/AppRenderer/AppRenderer";
63+
import { createAppBridgeFactory } from "./components/elements/AppRenderer/createAppBridgeFactory";
5764
import type { LogEntryData } from "./components/elements/LogEntry/LogEntry";
5865
import {
5966
ServerConfigModal,
6067
type ServerConfigModalMode,
6168
} from "./components/groups/ServerConfigModal/ServerConfigModal";
6269
import { ServerSettingsModal } from "./components/groups/ServerSettingsModal/ServerSettingsModal";
6370
import { ConnectionInfoModal } from "./components/groups/ConnectionInfoModal/ConnectionInfoModal";
71+
import { OutputValidationModal } from "./components/groups/OutputValidationModal/OutputValidationModal";
6472
import type { OAuthDetails } from "./components/groups/ConnectionInfoContent/ConnectionInfoContent";
6573
import { ServerRemoveConfirmModal } from "./components/groups/ServerRemoveConfirmModal/ServerRemoveConfirmModal";
6674
import { buildExportFilename, downloadJsonFile } from "./lib/downloadFile";
@@ -126,23 +134,6 @@ function getAuthToken(): string | undefined {
126134
}
127135
}
128136

129-
// MCP Apps sandbox — the iframe URL the parent should embed, plus the
130-
// per-tool bridge factory. The dev backend serves `sandbox_proxy.html` on
131-
// the sandbox controller port; the factory will eventually wrap the SDK
132-
// client. For now neither is wired (the Apps tab uses these props but does
133-
// not yet round-trip tool input through a live bridge — that's a follow-up
134-
// alongside the AppRenderer integration). Keep these as stable references
135-
// so InspectorView's effect deps don't churn.
136-
const STUB_SANDBOX_PATH = "about:blank";
137-
const stubBridgeFactory: BridgeFactory = () =>
138-
({
139-
sendToolInput: async () => {},
140-
sendToolResult: async () => {},
141-
sendToolCancelled: async () => {},
142-
teardownResource: async () => ({}),
143-
close: async () => {},
144-
}) as unknown as AppBridge;
145-
146137
// Derive `LogEntryData[]` from the MessageLog by filtering for the
147138
// `notifications/message` notifications the server emits in response to
148139
// `logging/setLevel`. The Logs screen renders these; we transform here
@@ -177,6 +168,26 @@ const EMPTY_SETTINGS: InspectorServerSettings = {
177168
requestTimeout: 0,
178169
};
179170

171+
// Body of the output-schema-mismatch warning toast: a one-line summary plus a
172+
// link that opens the full validation details in a modal (the raw error is far
173+
// too long for a toast).
174+
const OutputValidationToastMessage = ({
175+
onViewDetails,
176+
}: {
177+
onViewDetails: () => void;
178+
}) => (
179+
<Stack gap={4}>
180+
<Text size="sm">
181+
The tool result&apos;s structuredContent doesn&apos;t match the
182+
tool&apos;s outputSchema. The inspector renders it anyway, but strict MCP
183+
clients may not.
184+
</Text>
185+
<Anchor component="button" type="button" size="sm" onClick={onViewDetails}>
186+
View validation details
187+
</Anchor>
188+
</Stack>
189+
);
190+
180191
function App() {
181192
// Theme toggle plumbing (preserved from the pre-wire placeholder).
182193
const { setColorScheme } = useMantineColorScheme();
@@ -214,6 +225,11 @@ function App() {
214225
>(undefined);
215226
const [connectionInfoModalOpen, setConnectionInfoModalOpen] = useState(false);
216227
const [removeTarget, setRemoveTarget] = useState<ServerEntry | null>(null);
228+
// Details for the output-schema-mismatch modal opened from the warning toast.
229+
const [outputValidationDetails, setOutputValidationDetails] = useState<{
230+
toolName: string;
231+
message: string;
232+
} | null>(null);
217233

218234
// The active connection target. `null` between sessions; set as soon as
219235
// the user toggles a server card on. Drives state-manager lifetime.
@@ -226,6 +242,33 @@ function App() {
226242
// next switch happens (or when the component unmounts).
227243
const [inspectorClient, setInspectorClient] =
228244
useState<InspectorClient | null>(null);
245+
246+
// MCP Apps runtime wiring. `sandboxUrl` is the inspector's sandbox-proxy page
247+
// (the trusted outer iframe); `appRendererRef` lets the app handlers push tool
248+
// input/result into the running app and tear it down. The bridge factory wraps
249+
// the active client's underlying SDK client so the running view can call the
250+
// server, and reads the tool's UI resource into the sandbox on handshake.
251+
const appRendererRef = useRef<AppRendererHandle>(null);
252+
const { sandboxUrl } = useSandboxUrl({
253+
baseUrl:
254+
typeof window !== "undefined"
255+
? window.location.origin
256+
: "http://localhost",
257+
authToken: getAuthToken(),
258+
});
259+
const sandboxBridgeFactory = useMemo(
260+
() =>
261+
createAppBridgeFactory({
262+
getClient: () => inspectorClient?.getAppRendererClient() ?? null,
263+
readResource: async (uri) => {
264+
if (!inspectorClient) throw new Error("No MCP client connected.");
265+
const invocation = await inspectorClient.readResource(uri);
266+
return invocation.result;
267+
},
268+
}),
269+
[inspectorClient],
270+
);
271+
229272
const [managedToolsState, setManagedToolsState] =
230273
useState<ManagedToolsState | null>(null);
231274
const [managedPromptsState, setManagedPromptsState] =
@@ -875,6 +918,88 @@ function App() {
875918
setToolCallState(undefined);
876919
}, []);
877920

921+
// --- MCP Apps handlers. Unlike onCallTool (which feeds the Tools panel),
922+
// these route the tool input/result into the running app via the renderer's
923+
// imperative handle. ---
924+
925+
// Surfaces bridge/runtime failures (factory throw — e.g. no client after a
926+
// disconnect — late bridge rejection, or a failed tools/call) that would
927+
// otherwise leave a silently blank app iframe.
928+
const onAppError = useCallback((err: Error) => {
929+
notifications.show({
930+
title: "MCP App error",
931+
message: err.message,
932+
color: "red",
933+
});
934+
}, []);
935+
936+
// Selection is owned by AppsScreen's local state; App.tsx has nothing to do
937+
// on select, but the prop is required so the screen stays prop-driven.
938+
const onSelectApp = useCallback(() => {}, []);
939+
940+
const onOpenApp = useCallback(
941+
async (name: string, args: Record<string, unknown>) => {
942+
if (!inspectorClient) return;
943+
const tool = tools.find((t: Tool) => t.name === name);
944+
if (!tool) return;
945+
// AppsScreen flips `running` -> mounts AppRenderer in the same tick it
946+
// calls this, so the renderer handle isn't wired yet. Yield one microtask
947+
// (after React commits the mount) before pushing input; the renderer then
948+
// buffers it until the view's `initialized` event, releasing input before
949+
// result.
950+
await Promise.resolve();
951+
void appRendererRef.current?.sendToolInput(args);
952+
try {
953+
// skipOutputValidation: the result is forwarded verbatim to the running
954+
// app (the real consumer), so the host must not reject it on its own
955+
// outputSchema validation — that would deny the app a result the server
956+
// actually returned and legacy hosts render fine.
957+
const invocation = await inspectorClient.callTool(
958+
tool,
959+
args as Record<string, JsonValue>,
960+
undefined,
961+
undefined,
962+
undefined,
963+
{ skipOutputValidation: true },
964+
);
965+
if (invocation.success && invocation.result) {
966+
void appRendererRef.current?.sendToolResult(invocation.result);
967+
}
968+
// Leniency above keeps the app rendering, but surface the schema
969+
// mismatch so a server developer knows strict MCP clients may refuse
970+
// to render this app. The full validation error is too long for a
971+
// toast, so summarize and link to a modal with the details.
972+
if (invocation.outputValidationError) {
973+
const details = {
974+
toolName: tool.name,
975+
message: invocation.outputValidationError,
976+
};
977+
notifications.show({
978+
// Don't auto-dismiss: the message is advisory and the details modal
979+
// is one click away — let the user close it when they've read it.
980+
autoClose: false,
981+
title: "App output doesn't match its schema",
982+
color: "yellow",
983+
message: (
984+
<OutputValidationToastMessage
985+
onViewDetails={() => setOutputValidationDetails(details)}
986+
/>
987+
),
988+
});
989+
}
990+
} catch (err) {
991+
// Transport-level failure (the call never returned a result). Surface it
992+
// so the user isn't left staring at a blank/partial app frame.
993+
onAppError(err instanceof Error ? err : new Error(String(err)));
994+
}
995+
},
996+
[inspectorClient, tools, onAppError],
997+
);
998+
999+
const onCloseApp = useCallback(() => {
1000+
void appRendererRef.current?.teardown();
1001+
}, []);
1002+
8781003
const onGetPrompt = useCallback(
8791004
async (name: string, args: Record<string, string>) => {
8801005
if (!inspectorClient) return;
@@ -1224,8 +1349,9 @@ function App() {
12241349
getPromptState={getPromptState}
12251350
readResourceState={effectiveReadResourceState}
12261351
currentLogLevel={currentLogLevel}
1227-
sandboxPath={STUB_SANDBOX_PATH}
1228-
bridgeFactory={stubBridgeFactory}
1352+
sandboxPath={sandboxUrl}
1353+
bridgeFactory={sandboxBridgeFactory}
1354+
appRendererRef={appRendererRef}
12291355
onToggleTheme={onToggleTheme}
12301356
onToggleConnection={(id) => {
12311357
void onToggleConnection(id);
@@ -1274,9 +1400,12 @@ function App() {
12741400
onTogglePinHistory={todoNoop}
12751401
onClearNetwork={onClearNetwork}
12761402
onExportNetwork={onExportNetwork}
1277-
onSelectApp={todoNoop}
1278-
onOpenApp={todoNoop}
1279-
onCloseApp={todoNoop}
1403+
onSelectApp={onSelectApp}
1404+
onOpenApp={(name, args) => {
1405+
void onOpenApp(name, args);
1406+
}}
1407+
onCloseApp={onCloseApp}
1408+
onAppError={onAppError}
12801409
onRefreshApps={onRefreshTools}
12811410
/>
12821411
<ServerConfigModal
@@ -1310,6 +1439,12 @@ function App() {
13101439
onCancel={() => setRemoveTarget(null)}
13111440
onConfirm={onConfirmRemove}
13121441
/>
1442+
<OutputValidationModal
1443+
opened={outputValidationDetails !== null}
1444+
toolName={outputValidationDetails?.toolName}
1445+
message={outputValidationDetails?.message}
1446+
onClose={() => setOutputValidationDetails(null)}
1447+
/>
13131448
</>
13141449
);
13151450
}

0 commit comments

Comments
 (0)