Skip to content

Commit b999703

Browse files
fix: MCP apps are bound to their own server and document
Review findings from round 1 (GPT-6.1 Sol): - An app reference only counts when it names the server and tool the item records, so a tool result imitating one cannot point another server's requests at its app. - A frame that navigates away from the captured document loses the bridge, on web and mobile; mobile's relay is signed with a per-view secret, since Android exposes the native bridge to every frame. - A turn that is interrupted or fails cancels app captures still reading their resource and settles their tool rows before its terminal event. - Approved app messages on mobile go to the thread on screen, not the thread a forked app came from. - Oversized app documents are refused before they are decoded. - The compact app reference stays within the wire metadata budget. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 0524618 commit b999703

9 files changed

Lines changed: 293 additions & 49 deletions

File tree

‎apps/mobile/src/features/threads/McpAppWebView.tsx‎

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
mcpAppFileName,
1616
type McpAppReference,
1717
} from "@t3tools/shared/mcpApp";
18+
import * as Predicate from "effect/Predicate";
1819
import Constants from "expo-constants";
1920
import { useEffect, useMemo, useRef, useState } from "react";
2021
import { ActivityIndicator, Alert, Platform, View } from "react-native";
@@ -45,15 +46,24 @@ export function mcpAppRowHeight() {
4546
// `event.source` of host replies are a real window, which the MCP Apps SDK
4647
// requires. The outer page only relays: app → React Native, and host
4748
// replies (injected as `__t3McpAppReceive(...)`) → app.
48-
function outerDocument(src: string, allow: string) {
49+
//
50+
// Android exposes `ReactNativeWebView` to every frame, so a frame nested in
51+
// the app could post to React Native directly. The outer page therefore wraps
52+
// what it relays with a secret only it holds, and React Native drops anything
53+
// else. The bridge belongs to the captured document: once the app frame loads
54+
// a second time (it navigated itself), the outer page stops relaying and says
55+
// so, rather than handing a document T3 never served the bridge.
56+
function outerDocument(src: string, allow: string, secret: string) {
4957
const attribute = (value: string) =>
5058
value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
5159
return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
5260
<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head>
5361
<body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}" src="${attribute(src)}"></iframe>
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>`;
62+
<script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;
63+
var send=function(m){window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,message:m}));};
64+
frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});
65+
window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);});
66+
window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};})();</script></body></html>`;
5767
}
5868

5969
const commandFailure = (result: {
@@ -76,7 +86,10 @@ const confirm = (title: string, message: string, action: string) =>
7686
/** A captured MCP App in the thread feed, hosted in a WebView over the MCP Apps bridge. */
7787
export function ThreadMcpApp(props: {
7888
readonly environmentId: EnvironmentId;
89+
/** The thread that produced the app, which its requests run against. */
7990
readonly threadId: ThreadId;
91+
/** The thread on screen, which approved app messages are sent to. */
92+
readonly conversationThreadId: ThreadId;
8093
readonly itemId: TurnItemId;
8194
readonly revision: string;
8295
readonly app: McpAppReference;
@@ -111,6 +124,9 @@ export function ThreadMcpApp(props: {
111124
const [uri, setUri] = useState<string | null>(null);
112125
if (uri === null && asset._tag === "Success") setUri(asset.url);
113126
const [loaded, setLoaded] = useState(false);
127+
const [navigatedAway, setNavigatedAway] = useState(false);
128+
// Minted per view, so only this view's outer page can speak for its app.
129+
const [secret] = useState(uuidv4);
114130

115131
// The feed omits tool input and output; the app needs both.
116132
const detail = useEnvironmentQuery(
@@ -208,7 +224,7 @@ export function ThreadMcpApp(props: {
208224
// connection; the thread's own settings fill in when it sends.
209225
await enqueueThreadOutboxMessage({
210226
environmentId: latest.current.props.environmentId,
211-
threadId: latest.current.props.threadId,
227+
threadId: latest.current.props.conversationThreadId,
212228
messageId: MessageId.make(uuidv4()),
213229
commandId: CommandId.make(uuidv4()),
214230
text,
@@ -241,13 +257,21 @@ export function ThreadMcpApp(props: {
241257

242258
const source = useMemo(
243259
() =>
244-
uri === null ? null : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions)) },
245-
[uri, app.permissions],
260+
uri === null
261+
? null
262+
: { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) },
263+
[uri, app.permissions, secret],
246264
);
247265

248266
return (
249267
<View style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}>
250-
{uri !== null ? (
268+
{navigatedAway ? (
269+
<View className="flex-1 items-center justify-center">
270+
<Text className="text-sm text-foreground-muted">
271+
The {app.server} app left its page and was stopped
272+
</Text>
273+
</View>
274+
) : uri !== null ? (
251275
<WebView<object>
252276
ref={webView}
253277
source={source!}
@@ -262,11 +286,20 @@ export function ThreadMcpApp(props: {
262286
setSupportMultipleWindows={false}
263287
onLoadEnd={() => setLoaded(true)}
264288
onMessage={(event: WebViewMessageEvent) => {
289+
let envelope: unknown;
265290
try {
266-
hostRef.current?.receive(JSON.parse(event.nativeEvent.data));
291+
envelope = JSON.parse(event.nativeEvent.data);
267292
} catch {
268-
// Not JSON: not a bridge message.
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;
269301
}
302+
hostRef.current?.receive(message);
270303
}}
271304
/>
272305
) : asset._tag === "Failure" ? (

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,6 +1596,7 @@ function renderFeedEntry(
15961596
<ThreadMcpApp
15971597
environmentId={props.environmentId}
15981598
threadId={entry.sourceThreadId}
1599+
conversationThreadId={props.threadId}
15991600
itemId={entry.itemId}
16001601
revision={entry.revision}
16011602
app={entry.app}

‎apps/server/src/mcpApps/McpAppRequests.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,11 @@ function makeLayer(input: {
7979
Effect.succeed(
8080
input.live === false
8181
? Option.none()
82-
: Option.some({
83-
...(input.mcpApps === undefined ? {} : { mcpApps: input.mcpApps }),
84-
} as ProviderAdapterV2SessionRuntime),
82+
: Option.some(
83+
(input.mcpApps === undefined
84+
? {}
85+
: { mcpApps: input.mcpApps }) as ProviderAdapterV2SessionRuntime,
86+
),
8587
),
8688
}),
8789
),

‎apps/server/src/mcpApps/McpAppSnapshot.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,31 @@ const encoder = new TextEncoder();
2020
/**
2121
* The HTML document in a `resources/read` result, with the `_meta.ui` the
2222
* resource declared. Only `text/html;profile=mcp-app` content counts; a blob is
23-
* base64 per MCP.
23+
* base64 per MCP. A null document is one too large to store.
2424
*/
2525
function readMcpAppDocument(
2626
contents: ReadonlyArray<unknown>,
2727
uri: string,
28-
): { readonly html: string; readonly meta: unknown } | undefined {
28+
): { readonly html: string | null; readonly meta: unknown } | undefined {
2929
for (const content of contents) {
3030
if (!Predicate.isObject(content)) continue;
3131
if (content.uri !== undefined && content.uri !== uri) continue;
3232
const mimeType = typeof content.mimeType === "string" ? content.mimeType : "";
3333
if (mimeType.replace(/\s+/g, "").toLowerCase() !== MCP_APP_MIME_TYPE) continue;
34+
// Sizes are checked before decoding, so an oversized resource is
35+
// refused without first being copied: a string's UTF-8 form is at least
36+
// its length, and base64 decodes to three quarters of its own.
3437
const html =
3538
typeof content.text === "string"
36-
? content.text
39+
? content.text.length > MCP_APP_MAX_HTML_BYTES
40+
? null
41+
: content.text
3742
: typeof content.blob === "string"
38-
? Buffer.from(content.blob, "base64").toString("utf8")
43+
? content.blob.length > Math.ceil(MCP_APP_MAX_HTML_BYTES / 3) * 4
44+
? null
45+
: Buffer.from(content.blob, "base64").toString("utf8")
3946
: undefined;
47+
if (html === null) return { html: null, meta: undefined };
4048
if (html === undefined || html.trim() === "") continue;
4149
const meta = Predicate.isObject(content._meta) ? content._meta.ui : undefined;
4250
return { html, meta };
@@ -61,7 +69,7 @@ export const snapshotMcpApp = Effect.fn("McpAppSnapshot.snapshot")(function* (in
6169
if (!input.resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)) return undefined;
6270
const document = readMcpAppDocument(input.contents, input.resourceUri);
6371
if (document === undefined) return undefined;
64-
if (encoder.encode(document.html).byteLength > MCP_APP_MAX_HTML_BYTES) {
72+
if (document.html === null || encoder.encode(document.html).byteLength > MCP_APP_MAX_HTML_BYTES) {
6573
yield* Effect.logWarning("MCP app document exceeds the size limit.", {
6674
server: input.server,
6775
resourceUri: input.resourceUri,
@@ -78,10 +86,11 @@ export const snapshotMcpApp = Effect.fn("McpAppSnapshot.snapshot")(function* (in
7886
relativePath: `${attachmentId}.html`,
7987
});
8088
if (attachmentId === null || filePath === null) return undefined;
89+
const html = document.html;
8190
const ui = Predicate.isObject(document.meta) ? document.meta : {};
8291
const csp = readMcpAppCsp(ui.csp);
8392
const fileSystem = yield* FileSystem.FileSystem;
84-
yield* fileSystem.writeFileString(filePath, injectMcpAppCsp(document.html, csp));
93+
yield* fileSystem.writeFileString(filePath, injectMcpAppCsp(html, csp));
8594
const permissions = readMcpAppPermissions(ui.permissions);
8695
return {
8796
attachmentId,

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6276,6 +6276,92 @@ describe("CodexAdapterV2 post-settle continuation", () => {
62766276
),
62776277
);
62786278

6279+
// The turn fails while the app's resource read is still outstanding (Codex
6280+
// never answers it), so the capture must be cancelled and its tool row
6281+
// settled before the terminal event closes ingestion.
6282+
const failedMcpAppTranscript = makeCodexReplayTranscript({
6283+
scenario: "codex-mcp-app-capture-failed-turn",
6284+
entries: [
6285+
...codexReplayPreamble({
6286+
nativeThreadId: MCP_APP_NATIVE_THREAD,
6287+
nativeTurnId: MCP_APP_NATIVE_TURN,
6288+
prompt: MCP_APP_PROMPT,
6289+
}),
6290+
{
6291+
type: "emit_inbound",
6292+
label: "item/completed/app-tool",
6293+
frame: {
6294+
method: "item/completed",
6295+
params: {
6296+
item: mcpAppToolItem("completed"),
6297+
threadId: MCP_APP_NATIVE_THREAD,
6298+
turnId: MCP_APP_NATIVE_TURN,
6299+
completedAtMs: 1782622441500,
6300+
},
6301+
},
6302+
},
6303+
{
6304+
type: "expect_outbound",
6305+
label: "mcpServer/resource/read",
6306+
frame: {
6307+
id: 4,
6308+
method: "mcpServer/resource/read",
6309+
params: { threadId: MCP_APP_NATIVE_THREAD, server: "weather", uri: MCP_APP_RESOURCE },
6310+
},
6311+
},
6312+
{
6313+
type: "emit_inbound",
6314+
label: "turn/completed",
6315+
frame: {
6316+
method: "turn/completed",
6317+
params: {
6318+
threadId: MCP_APP_NATIVE_THREAD,
6319+
turn: {
6320+
...makeCodexReplayTurn({ id: MCP_APP_NATIVE_TURN, status: "failed" }),
6321+
error: { message: "provider failed mid-capture" },
6322+
},
6323+
},
6324+
},
6325+
},
6326+
],
6327+
});
6328+
6329+
it.effect("settles a pending MCP app capture before a failed turn's terminal event", () =>
6330+
Effect.scoped(
6331+
Effect.gen(function* () {
6332+
const harness = yield* makeCodexReplayHarness(failedMcpAppTranscript);
6333+
const now = yield* DateTime.now;
6334+
6335+
yield* harness.runtime.startTurn(
6336+
makeCodexTestTurnInput({
6337+
threadId: harness.threadId,
6338+
providerThread: harness.providerThread,
6339+
now,
6340+
attemptId: RunAttemptId.make("attempt-codex-mcp-app-failed"),
6341+
text: MCP_APP_PROMPT,
6342+
}),
6343+
);
6344+
yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal");
6345+
assert.equal(harness.terminalEvents()[0]?.status, "failed");
6346+
6347+
const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
6348+
const rows = harness.events.flatMap((event, index) =>
6349+
event.type === "turn_item.updated" &&
6350+
event.turnItem.type === "dynamic_tool" &&
6351+
event.turnItem.status === "completed"
6352+
? [{ index, turnItem: event.turnItem }]
6353+
: [],
6354+
);
6355+
// Settled once, as a plain tool row, ahead of the terminal event.
6356+
assert.lengthOf(rows, 1);
6357+
assert.isBelow(rows[0]!.index, terminalIndex);
6358+
const output = rows[0]!.turnItem.type === "dynamic_tool" ? rows[0]!.turnItem.output : null;
6359+
assert.isUndefined((output as Record<string, unknown> | null)?.[MCP_APP_OUTPUT_KEY]);
6360+
assert.isFalse(yield* harness.hasPendingBackgroundWork);
6361+
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
6362+
),
6363+
);
6364+
62796365
const ORPHAN_WAIT_SCENARIO = "codex-orphaned-dynamic-tool";
62806366
const ORPHAN_WAIT_NATIVE_THREAD = "native-codex-orphan-wait-thread";
62816367
const ORPHAN_WAIT_NATIVE_TURN = "native-codex-orphan-wait-turn";

0 commit comments

Comments
 (0)