Skip to content

Commit 5503139

Browse files
committed
refactor(server): keep bounded MCP HTML reads in asset access
1 parent b891d82 commit 5503139

3 files changed

Lines changed: 84 additions & 16 deletions

File tree

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

Lines changed: 60 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> = [];

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

Lines changed: 20 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,
@@ -224,6 +226,24 @@ const optionOnNotFound = <A, R>(
224226
}),
225227
);
226228

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+
227247
/**
228248
* Decodes one image a tool returned inline; null when the stored item has no
229249
* such image, or it is larger than a provider turn accepts.

‎apps/server/src/http.ts‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +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";
8+
import { injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";
99
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
1010
import * as Data from "effect/Data";
1111
import * as Effect from "effect/Effect";
@@ -29,7 +29,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
2929
import { OtlpTracer, OtlpSerialization } from "effect/observability";
3030

3131
import * as ServerConfig from "./config.ts";
32-
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
32+
import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts";
3333
import { githubMediaResponse } from "./assets/GitHubMediaFetch.ts";
3434
import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
3535
import {
@@ -180,21 +180,10 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
180180
!asset.download &&
181181
headers["Content-Type"] === "text/html; charset=utf-8"
182182
) {
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) {
183+
const bytes = yield* readMcpAppHtml(asset.path);
184+
if (bytes === null) {
190185
return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });
191186
}
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-
}
198187
const body = new TextEncoder().encode(
199188
injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes)),
200189
);

0 commit comments

Comments
 (0)