Skip to content

Commit b891d82

Browse files
committed
fix(client): apply host color scheme to saved MCP apps
1 parent 29e09df commit b891d82

9 files changed

Lines changed: 247 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ export function ThreadMcpApp(props: {
163163
fileName: mcpAppFileName(app),
164164
mimeType: "text/html",
165165
disposition: "inline" as const,
166+
renderIntent: "mcp-app" as const,
166167
}),
167168
[app],
168169
);

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -903,6 +903,49 @@ describe("AssetAccess", () => {
903903
}).pipe(Effect.provide(layerTest)),
904904
);
905905

906+
it.effect("signs MCP render intent only for inline HTML attachments", () =>
907+
Effect.gen(function* () {
908+
const config = yield* ServerConfig.ServerConfig;
909+
const fs = yield* FileSystem.FileSystem;
910+
const path = yield* Path.Path;
911+
yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
912+
for (const extension of ["html", "pdf"]) {
913+
const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
914+
yield* fs.writeFileString(
915+
path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
916+
"capture",
917+
);
918+
for (const disposition of ["inline", "attachment"] as const) {
919+
const result = yield* issueAssetUrl({
920+
resource: {
921+
_tag: "attachment",
922+
attachmentId,
923+
disposition,
924+
renderIntent: "mcp-app",
925+
},
926+
});
927+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
928+
const separator = suffix.indexOf("/");
929+
const asset = yield* resolveAsset(
930+
suffix.slice(0, separator),
931+
suffix.slice(separator + 1),
932+
);
933+
if (asset?.kind !== "file") throw new Error("Expected attachment file");
934+
expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
935+
extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
936+
);
937+
// Changing signed claims cannot opt an ordinary download into rendering.
938+
const token = suffix.slice(0, separator);
939+
const [payload, signature] = token.split(".");
940+
const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
941+
claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
942+
const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
943+
expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
944+
}
945+
}
946+
}).pipe(Effect.provide(layerTest)),
947+
);
948+
906949
it.effect("issues exact attachment capabilities by attachment id", () =>
907950
Effect.gen(function* () {
908951
const config = yield* ServerConfig.ServerConfig;

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ const AssetClaimsSchema = Schema.Union([
128128
download filename and Content-Type. */
129129
fileName: Schema.optionalKey(Schema.String),
130130
mimeType: Schema.optionalKey(Schema.String),
131+
renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
131132
expiresAt: Schema.Number,
132133
}),
133134
Schema.Struct({
@@ -180,6 +181,7 @@ export type ResolvedAsset =
180181
readonly fileName?: string;
181182
readonly mimeType?: string;
182183
readonly file?: OpenMediaFile;
184+
readonly renderIntent?: "mcp-app";
183185
}
184186
| {
185187
readonly kind: "bytes";
@@ -622,6 +624,9 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
622624
: input.resource.mimeType !== undefined
623625
? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
624626
: {}),
627+
...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
628+
? { renderIntent: "mcp-app" as const }
629+
: {}),
625630
expiresAt,
626631
};
627632
fileName = input.resource.fileName ?? path.basename(attachmentPath);
@@ -853,6 +858,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
853858
...(claims.download ? { download: true } : {}),
854859
...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
855860
...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
861+
...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
856862
} satisfies ResolvedAsset)
857863
: null;
858864
}

‎apps/server/src/http.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ import * as Tracer from "effect/Tracer";
1616
import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http";
1717
import { openMediaFile } from "./assets/MediaFile.ts";
1818

19+
import {
20+
injectMcpAppCsp,
21+
injectMcpAppThemeBootstrap,
22+
MCP_APP_MAX_HTML_BYTES,
23+
} from "@t3tools/shared/mcpApp";
1924
import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
2025

2126
import * as ServerConfig from "./config.ts";
@@ -30,6 +35,70 @@ import {
3035
} from "./http.ts";
3136
import * as ServerHttp from "./http.ts";
3237

38+
describe("MCP app asset responses", () => {
39+
it.effect(
40+
"transforms existing snapshots only with explicit render intent and fresh metadata",
41+
() =>
42+
Effect.gen(function* () {
43+
const fs = yield* FileSystem.FileSystem;
44+
const path = yield* Path.Path;
45+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-" });
46+
const file = path.join(directory, "app.html");
47+
const html = injectMcpAppCsp(
48+
"<html><head><script>vendor()</script></head><body>☃</body></html>",
49+
undefined,
50+
);
51+
yield* fs.writeFileString(file, html);
52+
for (const method of ["GET", "HEAD"] as const) {
53+
const response = HttpServerResponse.toWeb(
54+
yield* assetFileResponse(
55+
{ path: file, mimeType: "text/html", renderIntent: "mcp-app" },
56+
"bytes=0-1",
57+
undefined,
58+
method,
59+
),
60+
);
61+
const expected = injectMcpAppThemeBootstrap(html);
62+
expect(response.status).toBe(200);
63+
expect(response.headers.get("content-length")).toBe(
64+
String(new TextEncoder().encode(expected).byteLength),
65+
);
66+
expect(response.headers.get("etag")).toBeNull();
67+
expect(response.headers.get("last-modified")).toBeNull();
68+
expect(response.headers.get("content-security-policy")).toBe(
69+
"sandbox allow-scripts allow-forms allow-popups allow-downloads",
70+
);
71+
expect(yield* Effect.promise(() => response.text())).toBe(
72+
method === "HEAD" ? "" : expected,
73+
);
74+
}
75+
for (const download of [false, true]) {
76+
const response = HttpServerResponse.toWeb(
77+
yield* assetFileResponse({
78+
path: file,
79+
mimeType: "text/html",
80+
download,
81+
...(download ? { renderIntent: "mcp-app" as const } : {}),
82+
}),
83+
);
84+
expect(yield* Effect.promise(() => response.text())).toBe(html);
85+
}
86+
}).pipe(Effect.provide(layerFileResponse)),
87+
);
88+
89+
it.effect("rejects oversized captures before transforming them", () =>
90+
Effect.gen(function* () {
91+
const fs = yield* FileSystem.FileSystem;
92+
const path = yield* Path.Path;
93+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-size-" });
94+
const file = path.join(directory, "app.html");
95+
yield* fs.writeFileString(file, "x".repeat(MCP_APP_MAX_HTML_BYTES + 128 * 1024 + 1));
96+
const response = yield* assetFileResponse({ path: file, renderIntent: "mcp-app" });
97+
expect(response.status).toBe(413);
98+
}).pipe(Effect.provide(layerFileResponse)),
99+
);
100+
});
101+
33102
describe("untraced requests", () => {
34103
it.effect("drops the HTTP server span for browser trace exports, query string included", () => {
35104
const spanNames: Array<string> = [];

‎apps/server/src/http.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
EnvironmentHttpApi,
66
} from "@t3tools/contracts";
77
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8+
import { injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
89
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
910
import * as Data from "effect/Data";
1011
import * as Effect from "effect/Effect";
@@ -167,12 +168,41 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
167168
readonly fileName?: string;
168169
readonly mimeType?: string;
169170
readonly file?: OpenMediaFile;
171+
readonly renderIntent?: "mcp-app";
170172
},
171173
rangeHeader?: string,
172174
ifRangeHeader?: string,
173175
method: "GET" | "HEAD" = "GET",
174176
) {
175177
const headers = assetResponseHeaders(asset.path, asset);
178+
if (
179+
asset.renderIntent === "mcp-app" &&
180+
!asset.download &&
181+
headers["Content-Type"] === "text/html; charset=utf-8"
182+
) {
183+
const fs = yield* FileSystem.FileSystem;
184+
// Stored snapshots also contain a bounded CSP meta tag (up to 32 domains
185+
// per directive). Bound the read even if the attachment grows after minting.
186+
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
187+
const chunks = yield* Stream.runCollect(fs.stream(asset.path, { bytesToRead: limit + 1 }));
188+
const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
189+
if (size > limit) {
190+
return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });
191+
}
192+
const bytes = new Uint8Array(size);
193+
let position = 0;
194+
for (const chunk of chunks) {
195+
bytes.set(chunk, position);
196+
position += chunk.byteLength;
197+
}
198+
const body = new TextEncoder().encode(
199+
injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes)),
200+
);
201+
headers["Content-Length"] = String(body.byteLength);
202+
return method === "HEAD"
203+
? HttpServerResponse.empty({ status: 200, headers })
204+
: HttpServerResponse.uint8Array(body, { headers });
205+
}
176206
const mediaFile = asset.file;
177207
const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
178208
const isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? "");

‎apps/web/src/components/chat/McpAppFrame.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ export function McpAppFrame(props: {
117117
fileName: mcpAppFileName(app),
118118
mimeType: "text/html",
119119
disposition: "inline" as const,
120+
renderIntent: "mcp-app" as const,
120121
}),
121122
[app],
122123
);

‎packages/contracts/src/assets.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ export const AssetResource = Schema.Union([
4040
/** Generic attachments download by default. Document viewers opt into an
4141
inline response after deciding the file type is safe to preview. */
4242
disposition: Schema.optionalKey(Schema.Literals(["inline", "attachment"])),
43+
/** Render an MCP App snapshot with the host theme bootstrap. */
44+
renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
4345
}),
4446
// An image a tool returned inline, such as a device screenshot, by its order
4547
// in the stored output. The timeline never carries these bytes.

‎packages/shared/src/mcpApp.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import * as NodeVM from "node:vm";
12
import { describe, expect, it } from "vite-plus/test";
23

34
import {
45
injectMcpAppCsp,
6+
injectMcpAppThemeBootstrap,
57
mcpAppContentSecurityPolicy,
68
mcpAppToolCallableByApp,
79
readMcpAppCsp,
@@ -41,6 +43,65 @@ describe("injectMcpAppCsp", () => {
4143
});
4244
});
4345

46+
describe("injectMcpAppThemeBootstrap", () => {
47+
it("keeps stored CSP before the bootstrap and vendor scripts after it", () => {
48+
const snapshot = injectMcpAppCsp(
49+
"<html><head><script>vendor()</script></head></html>",
50+
undefined,
51+
);
52+
const html = injectMcpAppThemeBootstrap(snapshot);
53+
expect(html.indexOf("Content-Security-Policy")).toBeLessThan(html.indexOf("<script>"));
54+
expect(html.indexOf("window.addEventListener")).toBeLessThan(html.indexOf("vendor()"));
55+
expect(html.endsWith(snapshot.slice(snapshot.indexOf("<html>")))).toBe(true);
56+
});
57+
58+
it("applies parent initialize and theme changes while ignoring unrelated or invalid messages", () => {
59+
const html = injectMcpAppThemeBootstrap(injectMcpAppCsp("<p>app</p>", undefined));
60+
const script = html.slice(html.indexOf("<script>") + 8, html.indexOf("</script>"));
61+
const parent = {};
62+
const style = { colorScheme: "normal" };
63+
let receive: ((event: { source: object; data: unknown }) => void) | undefined;
64+
NodeVM.runInNewContext(script, {
65+
window: {
66+
parent,
67+
addEventListener: (_type: string, callback: typeof receive) => {
68+
receive = callback;
69+
},
70+
},
71+
document: { documentElement: { style } },
72+
});
73+
const send = (data: unknown, source = parent) => receive?.({ source, data });
74+
const initialized = { jsonrpc: "2.0", id: 1, result: { hostContext: { theme: "dark" } } };
75+
send(initialized, {});
76+
expect(style.colorScheme).toBe("normal");
77+
send(initialized);
78+
expect(style.colorScheme).toBe("dark");
79+
for (const data of [
80+
null,
81+
"bad",
82+
{},
83+
{ ...initialized, jsonrpc: "1.0" },
84+
{ jsonrpc: "2.0", method: "other", params: { theme: "light" } },
85+
{
86+
jsonrpc: "2.0",
87+
method: "ui/notifications/host-context-changed",
88+
params: { theme: "normal" },
89+
},
90+
{ jsonrpc: "2.0", result: { hostContext: { theme: "light" } } },
91+
])
92+
send(data);
93+
expect(style.colorScheme).toBe("dark");
94+
send({
95+
jsonrpc: "2.0",
96+
method: "ui/notifications/host-context-changed",
97+
params: { theme: "light" },
98+
});
99+
expect(style.colorScheme).toBe("light");
100+
send(initialized);
101+
expect(style.colorScheme).toBe("dark");
102+
});
103+
});
104+
44105
describe("readMcpAppCsp", () => {
45106
it("drops entries that could widen or break the policy", () => {
46107
expect(

‎packages/shared/src/mcpApp.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,40 @@ export function injectMcpAppCsp(html: string, csp: McpAppCsp | undefined): strin
215215
: `<!doctype html>${meta}${html}`;
216216
}
217217

218+
/**
219+
* Installed before vendor scripts so apps that omit their own theme handling
220+
* still give their document canvas and native controls the host's appearance.
221+
* The bridge uses an opaque origin, so authenticate messages by parent window.
222+
*/
223+
export function injectMcpAppThemeBootstrap(html: string): string {
224+
const script = `<script>
225+
(() => {
226+
window.addEventListener("message", (event) => {
227+
if (event.source !== window.parent) return;
228+
const message = event.data;
229+
if (!message || message.jsonrpc !== "2.0") return;
230+
const theme = message.method === "ui/notifications/host-context-changed"
231+
? message.params?.theme
232+
: message.id !== undefined && message.method === undefined
233+
? message.result?.hostContext?.theme
234+
: undefined;
235+
if (theme === "light" || theme === "dark") {
236+
document.documentElement.style.colorScheme = theme;
237+
}
238+
});
239+
})();
240+
</script>`;
241+
// Snapshots start with our doctype and CSP meta. Keep that policy ahead of
242+
// the bootstrap, rather than letting an injected script precede it.
243+
const prefix =
244+
/^\uFEFF?\s*<!doctype[^>]*>\s*(?:<meta\s+http-equiv="Content-Security-Policy"[^>]*>)?/i.exec(
245+
html,
246+
);
247+
return prefix
248+
? `${prefix[0]}${script}${html.slice(prefix[0].length)}`
249+
: `<!doctype html>${script}${html}`;
250+
}
251+
218252
/** The iframe `allow` attribute for the permissions an app declared. */
219253
export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {
220254
const features: Array<string> = [];

0 commit comments

Comments
 (0)