Skip to content

Commit 2e19207

Browse files
authored
fix(client): apply host color scheme to saved MCP apps (pingdotgg#17026)
1 parent b147dc9 commit 2e19207

9 files changed

Lines changed: 317 additions & 2 deletions

File tree

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

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

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

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
TurnItemId,
1010
} from "@t3tools/contracts";
1111
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
12+
import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
1213
import { describe, expect, it } from "@effect/vitest";
1314
import * as Crypto from "effect/Crypto";
1415
import * as DateTime from "effect/DateTime";
@@ -30,7 +31,7 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
3031
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
3132
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
3233
import { assetFileResponse } from "../http.ts";
33-
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
34+
import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
3435
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
3536
import { openMediaFile } from "./MediaFile.ts";
3637
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
@@ -121,6 +122,64 @@ const layerTest = Layer.mergeAll(
121122
).pipe(Layer.provideMerge(NodeServices.layer));
122123

123124
describe("AssetAccess", () => {
125+
describe("readMcpAppHtml", () => {
126+
it.effect("accepts snapshots at the stored HTML byte limit", () =>
127+
Effect.gen(function* () {
128+
const fileSystem = yield* FileSystem.FileSystem;
129+
const path = yield* Path.Path;
130+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
131+
const file = path.join(directory, "app.html");
132+
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
133+
yield* fileSystem.writeFile(file, new Uint8Array(limit).fill(120));
134+
135+
const bytes = yield* readMcpAppHtml(file);
136+
expect(bytes?.byteLength).toBe(limit);
137+
expect(bytes?.every((byte) => byte === 120)).toBe(true);
138+
}).pipe(Effect.provide(NodeServices.layer)),
139+
);
140+
141+
it.effect("rejects snapshots one byte past the limit and much larger files", () =>
142+
Effect.gen(function* () {
143+
const fileSystem = yield* FileSystem.FileSystem;
144+
const path = yield* Path.Path;
145+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
146+
const file = path.join(directory, "app.html");
147+
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
148+
for (const size of [limit + 1, limit * 2]) {
149+
yield* fileSystem.writeFile(file, new Uint8Array(size).fill(120));
150+
expect(yield* readMcpAppHtml(file)).toBeNull();
151+
}
152+
}).pipe(Effect.provide(NodeServices.layer)),
153+
);
154+
155+
it.effect("preserves UTF-8 bytes across stream chunks and accepts empty snapshots", () =>
156+
Effect.gen(function* () {
157+
const fileSystem = yield* FileSystem.FileSystem;
158+
const path = yield* Path.Path;
159+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
160+
const file = path.join(directory, "app.html");
161+
for (const html of ["", "<body>" + "☃".repeat(100_000) + "</body>"]) {
162+
const expected = new TextEncoder().encode(html);
163+
yield* fileSystem.writeFile(file, expected);
164+
const bytes = yield* readMcpAppHtml(file);
165+
expect(bytes?.byteLength).toBe(expected.byteLength);
166+
expect(bytes && new TextDecoder().decode(bytes)).toBe(html);
167+
}
168+
}).pipe(Effect.provide(NodeServices.layer)),
169+
);
170+
171+
it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
172+
Effect.gen(function* () {
173+
const fileSystem = yield* FileSystem.FileSystem;
174+
const path = yield* Path.Path;
175+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
176+
const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
177+
expect(error._tag).toBe("PlatformError");
178+
expect(error.reason._tag).toBe("NotFound");
179+
}).pipe(Effect.provide(NodeServices.layer)),
180+
);
181+
});
182+
124183
it.effect("loads private media immediately after login with the GitHub credential", () => {
125184
let lookups = 0;
126185
const authorizations: Array<string | undefined> = [];
@@ -903,6 +962,49 @@ describe("AssetAccess", () => {
903962
}).pipe(Effect.provide(layerTest)),
904963
);
905964

965+
it.effect("signs MCP render intent only for inline HTML attachments", () =>
966+
Effect.gen(function* () {
967+
const config = yield* ServerConfig.ServerConfig;
968+
const fs = yield* FileSystem.FileSystem;
969+
const path = yield* Path.Path;
970+
yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
971+
for (const extension of ["html", "pdf"]) {
972+
const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
973+
yield* fs.writeFileString(
974+
path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
975+
"capture",
976+
);
977+
for (const disposition of ["inline", "attachment"] as const) {
978+
const result = yield* issueAssetUrl({
979+
resource: {
980+
_tag: "attachment",
981+
attachmentId,
982+
disposition,
983+
renderIntent: "mcp-app",
984+
},
985+
});
986+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
987+
const separator = suffix.indexOf("/");
988+
const asset = yield* resolveAsset(
989+
suffix.slice(0, separator),
990+
suffix.slice(separator + 1),
991+
);
992+
if (asset?.kind !== "file") throw new Error("Expected attachment file");
993+
expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
994+
extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
995+
);
996+
// Changing signed claims cannot opt an ordinary download into rendering.
997+
const token = suffix.slice(0, separator);
998+
const [payload, signature] = token.split(".");
999+
const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1000+
claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1001+
const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1002+
expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1003+
}
1004+
}
1005+
}).pipe(Effect.provide(layerTest)),
1006+
);
1007+
9061008
it.effect("issues exact attachment capabilities by attachment id", () =>
9071009
Effect.gen(function* () {
9081010
const config = yield* ServerConfig.ServerConfig;

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
type ImageDimensions,
3232
} from "@t3tools/shared/imageDimensions";
3333
import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";
34+
import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
3435
import {
3536
isProjectFaviconPath,
3637
PROJECT_FAVICON_FALLBACK_MARKER,
@@ -45,6 +46,7 @@ import * as Option from "effect/Option";
4546
import * as Path from "effect/Path";
4647
import * as PlatformError from "effect/PlatformError";
4748
import * as Schema from "effect/Schema";
49+
import * as Stream from "effect/Stream";
4850

4951
import {
5052
base64UrlDecodeUtf8,
@@ -128,6 +130,7 @@ const AssetClaimsSchema = Schema.Union([
128130
download filename and Content-Type. */
129131
fileName: Schema.optionalKey(Schema.String),
130132
mimeType: Schema.optionalKey(Schema.String),
133+
renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
131134
expiresAt: Schema.Number,
132135
}),
133136
Schema.Struct({
@@ -180,6 +183,7 @@ export type ResolvedAsset =
180183
readonly fileName?: string;
181184
readonly mimeType?: string;
182185
readonly file?: OpenMediaFile;
186+
readonly renderIntent?: "mcp-app";
183187
}
184188
| {
185189
readonly kind: "bytes";
@@ -222,6 +226,24 @@ const optionOnNotFound = <A, R>(
222226
}),
223227
);
224228

229+
/** Reads a stored MCP HTML snapshot; null means it exceeds the preview limit. */
230+
export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
231+
const fileSystem = yield* FileSystem.FileSystem;
232+
// Stored snapshots also contain a bounded CSP meta tag (up to 32 domains
233+
// per directive). Bound the read even if the attachment grows after minting.
234+
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
235+
const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
236+
const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
237+
if (size > limit) return null;
238+
const bytes = new Uint8Array(size);
239+
let position = 0;
240+
for (const chunk of chunks) {
241+
bytes.set(chunk, position);
242+
position += chunk.byteLength;
243+
}
244+
return bytes;
245+
});
246+
225247
/**
226248
* Decodes one image a tool returned inline; null when the stored item has no
227249
* such image, or it is larger than a provider turn accepts.
@@ -622,6 +644,9 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
622644
: input.resource.mimeType !== undefined
623645
? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
624646
: {}),
647+
...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
648+
? { renderIntent: "mcp-app" as const }
649+
: {}),
625650
expiresAt,
626651
};
627652
fileName = input.resource.fileName ?? path.basename(attachmentPath);
@@ -853,6 +878,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
853878
...(claims.download ? { download: true } : {}),
854879
...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
855880
...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
881+
...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
856882
} satisfies ResolvedAsset)
857883
: null;
858884
}

‎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: 20 additions & 1 deletion
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 } 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";
@@ -28,7 +29,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
2829
import { OtlpTracer, OtlpSerialization } from "effect/observability";
2930

3031
import * as ServerConfig from "./config.ts";
31-
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
32+
import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts";
3233
import { githubMediaResponse } from "./assets/GitHubMediaFetch.ts";
3334
import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
3435
import {
@@ -167,12 +168,30 @@ 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 bytes = yield* readMcpAppHtml(asset.path);
184+
if (bytes === null) {
185+
return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });
186+
}
187+
const body = new TextEncoder().encode(
188+
injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes)),
189+
);
190+
headers["Content-Length"] = String(body.byteLength);
191+
return method === "HEAD"
192+
? HttpServerResponse.empty({ status: 200, headers })
193+
: HttpServerResponse.uint8Array(body, { headers });
194+
}
176195
const mediaFile = asset.file;
177196
const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
178197
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.

0 commit comments

Comments
 (0)