|
| 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); |
0 commit comments