feat: MCP apps render and run inline in threads #16236
Mergedjuliusmarmingemerged 26 commits into
main fromrefs/pull/16236/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- apps/server/src/mcpApps/McpAppSnapshot.ts lines 36 to 38OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +18,21 @@18+const encoder = new TextEncoder();19+20+/**21+ * The HTML document in a `resources/read` result, with the `_meta.ui` the22+ * resource declared. Only `text/html;profile=mcp-app` content counts; a blob is23+ * base64 per MCP.24+ */25+function readMcpAppDocument(26+ contents: ReadonlyArray<unknown>,27+ uri: string,28+): { readonly html: string; readonly meta: unknown } | undefined {29+ for (const content of contents) {30+ if (!Predicate.isObject(content)) continue;31+ if (content.uri !== undefined && content.uri !== uri) continue;32+ const mimeType = typeof content.mimeType === "string" ? content.mimeType : "";33+ if (mimeType.replace(/\s+/g, "").toLowerCase() !== MCP_APP_MIME_TYPE) continue;34+ const html =35+ typeof content.text === "string"36+ ? content.text37+ : typeof content.blob === "string"38+ ? Buffer.from(content.blob, "base64").toString("utf8")apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts line 4771Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4479,3 +4610,6 @@4479461044804611 if (payload.item.type === "mcpToolCall" || payload.item.type === "dynamicToolCall") {44814612 yield* clearRunningDynamicTool(payload.turnId, payload.item.id);4613+ const appResourceUri = codexMcpAppResourceUri(payload.item);4614+ if (appResourceUri !== undefined && payload.item.type === "mcpToolCall") {4615+ yield* captureMcpApp(context, payload.turnId, payload.item, appResourceUri);apps/mobile/src/features/threads/McpAppWebView.tsx line 260OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +240,21 @@240+ }, [toolCall, uri]);241+242+ const source = useMemo(243+ () =>244+ uri === null ? null : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions)) },245+ [uri, app.permissions],246+ );247+248+ return (249+ <View style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}>250+ {uri !== null ? (251+ <WebView<object>252+ ref={webView}253+ source={source!}254+ accessibilityLabel={`${app.server} app`}255+ style={{ flex: 1, backgroundColor: "transparent" }}256+ nestedScrollEnabled257+ originWhitelist={["*"]}258+ // Only the outer page loads at the top; the app opens links through the bridge.259+ onShouldStartLoadWithRequest={(request) =>260+ request.isTopFrame === false || request.url === "about:blank"
- apps/mobile/src/features/threads/McpAppWebView.tsx lines 87 to 100Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +54,21 @@54+<script>(function(){var frame=document.getElementById("app");55+window.addEventListener("message",function(e){if(e.source===frame.contentWindow)window.ReactNativeWebView.postMessage(JSON.stringify(e.data));});56+window.__t3McpAppReceive=function(m){frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};})();</script></body></html>`;57+}58+59+const commandFailure = (result: {60+ readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];61+}) => {62+ const error = squashAtomCommandFailure(result);63+ return new McpAppHostRefusal(64+ error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",65+ );66+};67+68+const confirm = (title: string, message: string, action: string) =>69+ new Promise<boolean>((resolve) => {70+ Alert.alert(title, message, [71+ { text: "Cancel", style: "cancel", onPress: () => resolve(false) },72+ { text: action, onPress: () => resolve(true) },73+ ]);74+ });apps/web/src/components/chat/McpAppFrame.tsx lines 143 to 146OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ const scope = () => {127+ const { environmentId, threadId, itemId } = latest.current.props;128+ return { environmentId, input: { threadId, itemId } };129+ };130+ const host = makeMcpAppHost({131+ app,132+ hostVersion: APP_VERSION,133+ // The document's origin is opaque, so "*" is the only target that reaches it;134+ // the window reference itself is what scopes delivery to this frame.135+ post: (message) => target()?.postMessage(message, "*"),136+ hostContext,137+ callTool: async ({ name, arguments: args }) => {138+ const { environmentId, input } = scope();139+ const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });140+ if (info._tag !== "Success") throw commandFailure(info);141+ if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");142+ if (!info.value.readOnly) {143+ const approved = await requestConfirmDialog(144+ `Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,145+ );146+ if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");packages/client-runtime/src/mcpApps/host.ts lines 308 to 317Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +208,21 @@208+ if (typeof url !== "string" || !/^https?:\/\//i.test(url)) {209+ fail(id, -32602, "Only http(s) links can be opened.");210+ return;211+ }212+ answer(id, () => options.openLink(url).then(() => ({})));213+ return;214+ }215+ case "ui/message": {216+ // The SDK sends an array of content blocks; the spec text shows one block.217+ const blocks = Array.isArray(params.content) ? params.content : [params.content];218+ const texts = blocks.map((block) =>219+ Predicate.isObject(block) && block.type === "text" && typeof block.text === "string"220+ ? block.text221+ : undefined,222+ );223+ if (params.role !== "user" || texts.length === 0 || texts.includes(undefined)) {224+ fail(id, -32602, "Only text messages from the user role are supported.");225+ return;226+ }227+ const text = texts.join("\n").trim();228+ answer(id, () => options.sendMessage(text).then(() => ({})));
- apps/web/src/components/chat/McpAppFrame.tsx line 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+ const observer = new ResizeObserver(([entry]) => {66+ if (entry) setWidth(Math.round(entry.contentRect.width));67+ });68+ observer.observe(box);69+ return () => observer.disconnect();70+ }, []);71+72+ const resource = useMemo(73+ () => ({74+ _tag: "attachment" as const,75+ attachmentId: app.attachmentId,76+ fileName: mcpAppFileName(app),77+ mimeType: "text/html",78+ disposition: "inline" as const,79+ }),80+ [app],81+ );82+ const asset = useAssetUrlState(props.environmentId, resource);83+ // The frame keeps its first URL: a re-minted one would reload the app.84+ const [src, setSrc] = useState<string | null>(null);85+ if (src === null && asset._tag === "Success") setSrc(asset.url);apps/mobile/src/features/threads/McpAppWebView.tsx line 358Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +194,21 @@194+ ))195+ ) {196+ throw new McpAppHostRefusal("Declined by the user.");197+ }198+ const result = await latest.current.callTool({199+ environmentId,200+ input: { ...input, name, arguments: args },201+ });202+ if (result._tag !== "Success") throw commandFailure(result);203+ return result.value;204+ },205+ readResource: async ({ uri: resourceUri }) => {206+ const { environmentId, input } = scope();207+ const result = await latest.current.readResource({208+ environmentId,209+ input: { ...input, uri: resourceUri },210+ });211+ if (result._tag !== "Success") throw commandFailure(result);212+ return result.value;213+ },214+ openLink: async (url) => {
- @@ -0,0 +280,21 @@280+ nestedScrollEnabled281+ originWhitelist={["*"]}282+ // Only the outer page loads at the top; the app opens links through the bridge.283+ onShouldStartLoadWithRequest={(request) =>284+ request.isTopFrame === false || request.url === "about:blank"285+ }286+ setSupportMultipleWindows={false}287+ onLoadEnd={() => setLoaded(true)}288+ onMessage={(event: WebViewMessageEvent) => {289+ let envelope: unknown;290+ try {291+ envelope = JSON.parse(event.nativeEvent.data);292+ } catch {293+ return; // Not JSON: not a bridge message.294+ }295+ if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;296+ const message = envelope.message;297+ if (Predicate.isObject(message) && message.t3 === "navigated") {298+ hostRef.current?.dispose();299+ setNavigatedAway(true);300+ return;
- @@ -0,0 +287,21 @@287+ <Text className="text-sm text-foreground-muted">288+ The {app.server} app left its page and was stopped289+ </Text>290+ </View>291+ ) : uri !== null && !crashed ? (292+ <WebView<object>293+ key={generation}294+ ref={webView}295+ onContentProcessDidTerminate={restart}296+ onRenderProcessGone={restart}297+ source={source!}298+ accessibilityLabel={`${app.server} app`}299+ style={{ flex: 1, backgroundColor: "transparent" }}300+ nestedScrollEnabled301+ originWhitelist={["*"]}302+ // Only the outer page loads at the top; the app opens links through the bridge.303+ onShouldStartLoadWithRequest={(request) =>304+ request.isTopFrame === false || request.url === "about:blank"305+ }306+ setSupportMultipleWindows={false}307+ onLoadEnd={() => setLoaded(true)}
- apps/mobile/src/features/threads/McpAppWebView.tsx line 182Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +112,21 @@112+ attachmentId: app.attachmentId,113+ fileName: mcpAppFileName(app),114+ mimeType: "text/html",115+ disposition: "inline" as const,116+ }),117+ [app],118+ );119+ const asset = useAssetUrlState(props.environmentId, resource);120+ // The view keeps its first URL: a re-minted one would reload the app.121+ const [uri, setUri] = useState<string | null>(null);122+ if (uri === null && asset._tag === "Success") setUri(asset.url);123+ const [loaded, setLoaded] = useState(false);124+ const [navigatedAway, setNavigatedAway] = useState(false);125+ // Bumped when the OS reclaims the web process: a fresh view, document and126+ // host, so the reloaded app is initialized and replayed again. Once only, so127+ // an app that keeps crashing its process is not reloaded forever.128+ const [generation, setGeneration] = useState(0);129+ const [crashed, setCrashed] = useState(false);130+ const restart = () => {131+ if (generation > 0) {132+ setCrashed(true);
- @@ -0,0 +43,21 @@43+// replies (injected as `__t3McpAppReceive(...)`) → app.44+//45+// Android exposes `ReactNativeWebView` to every frame, so a frame nested in46+// the app could post to React Native directly. The outer page therefore wraps47+// what it relays with a secret only it holds, and React Native drops anything48+// else. The bridge belongs to the captured document: once the app frame loads49+// a second time (it navigated itself), the outer page stops relaying and says50+// so, rather than letting a page T3 never served pose as the app. This is not51+// a confidentiality boundary: a frame can always navigate itself, so the app52+// could carry anything it read out in a URL either way.53+function outerDocument(src: string, allow: string, secret: string) {54+ const attribute = (value: string) =>55+ value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");56+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">57+<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head>58+<body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}" src="${attribute(src)}"></iframe>59+<script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;60+var send=function(m){window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,message:m}));};61+frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});62+window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);});63+window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};})();</script></body></html>`;
- @@ -0,0 +326,21 @@326+ try {327+ envelope = JSON.parse(event.nativeEvent.data);328+ } catch {329+ return; // Not JSON: not a bridge message.330+ }331+ if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;332+ const message = envelope.message;333+ if (Predicate.isObject(message) && message.t3 === "navigated") {334+ hostRef.current?.dispose();335+ setNavigatedAway(true);336+ return;337+ }338+ hostRef.current?.receive(message);339+ }}340+ />341+ ) : asset._tag === "Failure" || crashed ? (342+ <View className="flex-1 items-center justify-center">343+ <Text className="text-sm text-foreground-muted">Unable to load the {app.server} app</Text>344+ </View>345+ ) : null}346+ {uri !== null && !loaded ? (
- @@ -0,0 +97,21 @@97+98+export function readMcpAppPermissions(value: unknown): McpAppPermissions | undefined {99+ if (!Predicate.isObject(value)) return undefined;100+ const permissions: Partial<Record<(typeof PERMISSION_KEYS)[number], Record<string, never>>> = {};101+ for (const key of PERMISSION_KEYS) {102+ if (Predicate.isObject(value[key])) permissions[key] = {};103+ }104+ return Object.keys(permissions).length === 0 ? undefined : permissions;105+}106+107+const boundedName = (value: unknown) =>108+ typeof value === "string" && value.trim() !== "" && value.length <= MAX_NAME_LENGTH109+ ? value110+ : undefined;111+112+export function readMcpAppReference(value: unknown): McpAppReference | undefined {113+ if (!Predicate.isObject(value)) return undefined;114+ const attachmentId = boundedName(value.attachmentId);115+ const server = boundedName(value.server);116+ const tool = boundedName(value.tool);117+ const resourceUri = boundedName(value.resourceUri);packages/client-runtime/src/mcpApps/host.ts line 392Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +235,21 @@235+ answer(id, () => options.sendMessage(text).then(() => ({})));236+ return;237+ }238+ case "ui/request-display-mode":239+ // Inline is the only mode this host offers, so every request resolves to it.240+ respond(id, { mode: "inline" });241+ return;242+ case "ui/update-model-context":243+ fail(id, -32601, "This host does not accept model context updates.");244+ return;245+ default:246+ fail(id, -32601, `Method not found: ${method}`);247+ }248+ };249+250+ const handleNotification = (method: string, params: Record<PropertyKey, unknown>) => {251+ switch (method) {252+ case "ui/notifications/initialized": {253+ if (initialized) return;254+ initialized = true;255+ sendToolCall();
- apps/mobile/src/features/threads/McpAppWebView.tsx line 432OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +412,21 @@412+ },413+ onRequestTeardown: () => {414+ const current = latest.current.props;415+ if (current.displayMode === "fullscreen") {416+ void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());417+ } else {418+ setClosed(true);419+ }420+ },421+ // Both modes are fixed boxes, so the app's own height only decides422+ // whether it scrolls inside one.423+ onSizeChanged: () => undefined,424+ });425+ hostRef.current = next;426+ return () => {427+ // An unmount cannot wait: the request goes out before the view does.428+ void next.teardown();429+ hostRef.current = null;430+ };431+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.432+ }, [uri, app, generation]);
- apps/web/src/components/chat/McpAppFrame.tsx lines 101 to 101OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +81,21 @@81+ const boxRef = useRef<HTMLDivElement>(null);82+ const [width, setWidth] = useState(0);83+ const [height, setHeight] = useState(MCP_APP_DEFAULT_HEIGHT);84+ const [navigatedAway, setNavigatedAway] = useState(false);85+ const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");86+ // The app asked to be closed; the row falls back to its plain tool call.87+ const [closed, setClosed] = useState(false);88+ // Counts the app documents this row has shown. Reopening a closed app loads89+ // a new one, which needs its own host and its own load tracking.90+ const [documentGeneration, setDocumentGeneration] = useState(0);91+ const [viewport, setViewport] = useState({ width: 0, height: 0 });92+ useLayoutEffect(() => {93+ const box = boxRef.current;94+ if (!box) return;95+ setWidth(box.clientWidth);96+ const observer = new ResizeObserver(([entry]) => {97+ if (entry) setWidth(Math.round(entry.contentRect.width));98+ });99+ observer.observe(box);100+ return () => observer.disconnect();101+ }, []);
- @@ -0,0 +434,21 @@434+ },435+ onRequestTeardown: () => {436+ const current = latest.current.props;437+ if (current.displayMode === "fullscreen") {438+ void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());439+ } else {440+ void hostRef.current?.teardown().then(() => setClosed(true));441+ }442+ },443+ // Both modes are fixed boxes, so the app's own height only decides444+ // whether it scrolls inside one.445+ onSizeChanged: () => undefined,446+ });447+ hostRef.current = next;448+ return () => {449+ // An unmount cannot wait: the request goes out before the view does.450+ void next.teardown();451+ hostRef.current = null;452+ };453+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.454+ }, [uri, app, generation, documentKey]);
- apps/web/src/components/chat/McpAppFrame.tsx line 379Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +329,21 @@329+ },330+ sendMessage: async (text) => {331+ const send = latest.current.props.onSendMessage;332+ if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");333+ const approved = await ask(`Send this message from ${app.server}?\n${text}`);334+ if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");335+ await send(text);336+ },337+ updateModelContext: async (context) => {338+ const { environmentId, input } = scope();339+ const result = await latest.current.updateModelContext({340+ environmentId,341+ input: {342+ ...input,343+ ...context,344+ conversationThreadId: latest.current.props.conversationThreadId,345+ },346+ });347+ if (result._tag !== "Success") throw commandFailure(result);348+ },349+ requestDisplayMode: async (mode) => {
- packages/client-runtime/src/mcpApps/host.ts lines 482 to 482Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +456,21 @@456+ teardown: () =>457+ new Promise<void>((resolve) => {458+ let timer: ReturnType<typeof setTimeout> | undefined;459+ const finish = () => {460+ clearTimeout(timer);461+ disposed = true;462+ resolve();463+ };464+ // Before initialization the app has nothing to save and may not be465+ // listening; the spec only asks for teardown after it.466+ if (disposed || !initialized) {467+ finish();468+ return;469+ }470+ const id = `t3-host-${nextHostRequestId++}`;471+ hostRequests.set(id, finish);472+ timer = setTimeout(() => {473+ hostRequests.delete(id);474+ finish();475+ }, TEARDOWN_TIMEOUT_MS);476+ post({ jsonrpc: "2.0", id, method: "ui/resource-teardown", params: {} });apps/server/src/mcpApps/McpAppRequests.ts line 213OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +193,21 @@193+194+ const updateModelContext = Effect.fn("McpAppRequests.updateModelContext")(function* (195+ input: McpAppUpdateModelContextInput,196+ ) {197+ const { app } = yield* resolveApp(input);198+ // Context belongs to the conversation on screen, which only shows this app199+ // when it is the app's own thread or one forked from it.200+ if (!(yield* descendsFrom(input.conversationThreadId, input.threadId))) {201+ return yield* fail(input.threadId, "not-an-app");202+ }203+ const texts: Array<string> = [];204+ for (const block of input.content ?? []) {205+ if (!Predicate.isObject(block) || block.type !== "text" || typeof block.text !== "string") {206+ return yield* fail(input.threadId, "unsupported-content");207+ }208+ texts.push(block.text);209+ }210+ if (input.structuredContent !== undefined) {211+ texts.push(encodeJson(input.structuredContent));212+ }213+ const text = texts.join("\n").trim();apps/web/src/confirmDialog.ts lines 106 to 106OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -101,3 +101,6 @@101101 return confirmation;102102 }103103104+/** True while a confirmation is shown or waiting to be. */105+export function isConfirmDialogActive(): boolean {106+ return activeConfirmation !== null || queuedConfirmations.length > 0;apps/web/src/components/chat/MessagesTimeline.tsx lines 980 to 991Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -959,4 +975,17 @@959975 onManualNavigation,960976 });961977 const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);962- const alwaysRender = citationAlwaysRender ?? restoringAlwaysRender;978+ const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);979+ // Only the row that holds the pin can release it.980+ const onAppFullscreenChange = useCallback((rowId: string, fullscreen: boolean) => {981+ setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));982+ }, []);983+ // Every pin holds at once, so navigating to a citation or restoring a984+ // position never drops a full-screen app's row. The app is pinned by key,985+ // which stays right as earlier rows load in.986+ const alwaysRender = useMemo(() => {987+ const indices = restoringAlwaysRender?.indices ?? [];988+ const keys = [989+ ...(citationAlwaysRender?.keys ?? []),990+ ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),991+ ];
- apps/server/src/mcpApps/McpAppRequests.ts line 185Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +162,21 @@162+ input: McpAppReadResourceInput,163+ ) {164+ const resolved = yield* resolve(input);165+ return yield* resolved.mcpApps166+ .readResource({167+ providerThread: resolved.providerThread,168+ server: resolved.app.server,169+ uri: input.uri,170+ })171+ .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));172+ });173+174+ // Context is state for the agent's next turn, so it needs the app but not a175+ // live session. Text blocks are kept as written and structured content as176+ // JSON; other content kinds are not declared by the host.177+ /** Whether `threadId` is `ancestorId` or forked from it, however many forks deep. */178+ const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (179+ threadId: ThreadId,180+ ancestorId: ThreadId,181+ ) {182+ let current: ThreadId | null = threadId;
juliusmarminge merged this4d976d1
juliusmarminge closed this
Sign in to join this conversation.





















Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
611132c· PR result:b36084f· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.