Skip to content

Commit b9d1d84

Browse files
committed
refactor(server): prepare MCP app documents through an asset service
1 parent f516c79 commit b9d1d84

7 files changed

Lines changed: 90 additions & 27 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
3232
import { assetFileResponse } from "../http.ts";
3333
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
3434
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
35+
import * as McpAppDocument from "./McpAppDocument.ts";
3536
import { openMediaFile } from "./MediaFile.ts";
3637
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
3738
import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
@@ -117,6 +118,7 @@ const layerTest = Layer.mergeAll(
117118
Layer.provide(T3ProjectFileLoader.layer),
118119
),
119120
NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
121+
McpAppDocument.layer,
120122
ServerSecretStore.layer.pipe(Layer.provide(layerConfig)),
121123
).pipe(Layer.provideMerge(NodeServices.layer));
122124

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

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,6 @@ import {
3636
PROJECT_FAVICON_FALLBACK_MARKER,
3737
} from "@t3tools/shared/projectFavicon";
3838
import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
39-
import { injectMcpAppCookieBootstrap, MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
40-
import * as Stream from "effect/Stream";
4139
import * as Clock from "effect/Clock";
4240
import * as Crypto from "effect/Crypto";
4341
import * as Effect from "effect/Effect";
@@ -817,28 +815,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
817815
};
818816
});
819817

820-
/** Read and prepare a saved MCP document without trusting its file length. */
821-
export const readMcpAppDocument = Effect.fn("AssetAccess.readMcpAppDocument")(function* (
822-
path: string,
823-
) {
824-
const fs = yield* FileSystem.FileSystem;
825-
// Saved captures also contain a bounded CSP meta tag added after the raw HTML limit.
826-
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
827-
const chunks = yield* fs.stream(path, { bytesToRead: limit + 1 }).pipe(Stream.runCollect);
828-
const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
829-
if (size > limit) return { _tag: "TooLarge" as const };
830-
const bytes = new Uint8Array(size);
831-
let offset = 0;
832-
for (const chunk of chunks) {
833-
bytes.set(chunk, offset);
834-
offset += chunk.byteLength;
835-
}
836-
return {
837-
_tag: "Document" as const,
838-
html: injectMcpAppCookieBootstrap(new TextDecoder().decode(bytes)),
839-
};
840-
});
841-
842818
export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
843819
token: string,
844820
relativePath: string,
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { expect, it } from "@effect/vitest";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Path from "effect/Path";
6+
import * as McpAppDocument from "./McpAppDocument.ts";
7+
8+
it.effect("preserves filesystem failures as typed MCP document read errors", () =>
9+
Effect.gen(function* () {
10+
const fileSystem = yield* FileSystem.FileSystem;
11+
const path = yield* Path.Path;
12+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-document-" });
13+
const missingPath = path.join(directory, "missing.html");
14+
const documents = yield* McpAppDocument.McpAppDocument;
15+
const error = yield* documents.read(missingPath).pipe(Effect.flip);
16+
expect(error).toBeInstanceOf(McpAppDocument.McpAppDocumentReadError);
17+
expect(error.path).toBe(missingPath);
18+
expect(error.cause).toMatchObject({ _tag: "PlatformError", reason: { _tag: "NotFound" } });
19+
}).pipe(Effect.provide(McpAppDocument.layer), Effect.provide(NodeServices.layer)),
20+
);
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { injectMcpAppCookieBootstrap, MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
2+
import * as Context from "effect/Context";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Layer from "effect/Layer";
6+
import * as Schema from "effect/Schema";
7+
import * as Stream from "effect/Stream";
8+
9+
export class McpAppDocumentReadError extends Schema.TaggedError<McpAppDocumentReadError>()(
10+
"McpAppDocumentReadError",
11+
{ path: Schema.String, cause: Schema.Defect() },
12+
) {
13+
override get message(): string {
14+
return "Failed to read the MCP App document.";
15+
}
16+
}
17+
18+
export class McpAppDocument extends Context.Service<
19+
McpAppDocument,
20+
{
21+
readonly read: (
22+
path: string,
23+
) => Effect.Effect<
24+
{ readonly _tag: "Document"; readonly html: string } | { readonly _tag: "TooLarge" },
25+
McpAppDocumentReadError
26+
>;
27+
}
28+
>()("t3/assets/McpAppDocument") {}
29+
30+
const make = Effect.gen(function* () {
31+
const fileSystem = yield* FileSystem.FileSystem;
32+
33+
/** Read and prepare a saved MCP document without trusting its file length. */
34+
const read = Effect.fn("McpAppDocument.read")(function* (path: string) {
35+
// Saved captures also contain a bounded CSP meta tag added after the raw HTML limit.
36+
const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
37+
const chunks = yield* fileSystem.stream(path, { bytesToRead: limit + 1 }).pipe(
38+
Stream.runCollect,
39+
Effect.mapError((cause) => new McpAppDocumentReadError({ path, cause })),
40+
);
41+
const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
42+
if (size > limit) return { _tag: "TooLarge" as const };
43+
const bytes = new Uint8Array(size);
44+
let offset = 0;
45+
for (const chunk of chunks) {
46+
bytes.set(chunk, offset);
47+
offset += chunk.byteLength;
48+
}
49+
return {
50+
_tag: "Document" as const,
51+
html: injectMcpAppCookieBootstrap(new TextDecoder().decode(bytes)),
52+
};
53+
});
54+
55+
return McpAppDocument.of({ read });
56+
});
57+
58+
export const layer = Layer.effect(McpAppDocument, make);

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as Queue from "effect/Queue";
2020
import * as Tracer from "effect/Tracer";
2121
import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http";
2222
import { openMediaFile } from "./assets/MediaFile.ts";
23+
import * as McpAppDocument from "./assets/McpAppDocument.ts";
2324

2425
import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
2526

@@ -120,7 +121,9 @@ describe("browser API CORS", () => {
120121
});
121122
});
122123

123-
const layerFileResponse = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
124+
const layerFileResponse = Layer.merge(NodeHttpPlatform.layer, McpAppDocument.layer).pipe(
125+
Layer.provideMerge(NodeServices.layer),
126+
);
124127

125128
const makeStaticRequest = Effect.fn("HttpTest.makeStaticRequest")(function* (staticDir: string) {
126129
const config = yield* ServerConfig.ServerConfig;

‎apps/server/src/http.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
2828
import { OtlpTracer, OtlpSerialization } from "effect/observability";
2929

3030
import * as ServerConfig from "./config.ts";
31-
import { ASSET_ROUTE_PREFIX, readMcpAppDocument, resolveAsset } from "./assets/AssetAccess.ts";
31+
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
32+
import * as McpAppDocument from "./assets/McpAppDocument.ts";
3233
import { githubMediaResponse } from "./assets/GitHubMediaFetch.ts";
3334
import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
3435
import {
@@ -179,7 +180,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
179180
!asset.download &&
180181
headers["Content-Type"] === "text/html; charset=utf-8"
181182
) {
182-
const document = yield* readMcpAppDocument(asset.path);
183+
const mcpAppDocument = yield* McpAppDocument.McpAppDocument;
184+
const document = yield* mcpAppDocument.read(asset.path);
183185
if (document._tag === "TooLarge") {
184186
return HttpServerResponse.text("MCP App is too large to preview.", { status: 413 });
185187
}

‎apps/server/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
2828
import * as ServerConfig from "./config.ts";
2929
import { withUntracedRequests } from "./http.ts";
3030
import * as ServerHttp from "./http.ts";
31+
import * as McpAppDocument from "./assets/McpAppDocument.ts";
3132
import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
3233
import { fixPath } from "./os-jank.ts";
3334
import * as Ws from "./ws.ts";
@@ -1087,6 +1088,7 @@ const layerMakeServer = Layer.unwrap(
10871088
);
10881089

10891090
return layerServerApplication.pipe(
1091+
Layer.provide(McpAppDocument.layer),
10901092
// The connect routes and the startup/shutdown link work share one instance.
10911093
Layer.provide(CloudLink.layer),
10921094
Layer.provideMerge(layerRuntimeServices),

0 commit comments

Comments
 (0)