Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppSnapshot.ts

97 lines3.9 KB

1import type { ThreadId } from "@t3tools/contracts";
2import {
3 injectMcpAppCsp,
4 MCP_APP_MAX_HTML_BYTES,
5 MCP_APP_MIME_TYPE,
6 MCP_APP_RESOURCE_SCHEME,
7 readMcpAppCsp,
8 readMcpAppPermissions,
9 type McpAppReference,
10} from "@t3tools/shared/mcpApp";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Predicate from "effect/Predicate";
14​
15import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
16import { createAttachmentId } from "../attachmentStore.ts";
17​
18const encoder = new TextEncoder();
19​
20function readMcpAppDocument(
21 contents: ReadonlyArray<unknown>,
22 uri: string,
23): { readonly html: string | null; readonly meta: unknown } | undefined {
24 for (const content of contents) {
25 if (!Predicate.isObject(content)) continue;
26 if (content.uri !== undefined && content.uri !== uri) continue;
27 const mimeType = typeof content.mimeType === "string" ? content.mimeType : "";
28 if (mimeType.replace(/\s+/g, "").toLowerCase() !== MCP_APP_MIME_TYPE) continue;
29 // Sizes are checked before decoding, so an oversized resource is
30 // refused without first being copied: a string's UTF-8 form is at least
31 // its length, and base64 decodes to three quarters of its own.
32 const html =
33 typeof content.text === "string"
34 ? content.text.length > MCP_APP_MAX_HTML_BYTES
35 ? null
36 : content.text
37 : typeof content.blob === "string"
38 ? content.blob.length > Math.ceil(MCP_APP_MAX_HTML_BYTES / 3) * 4
39 ? null
40 : Buffer.from(content.blob, "base64").toString("utf8")
41 : undefined;
42 if (html === null) return { html: null, meta: undefined };
43 if (html === undefined || html.trim() === "") continue;
44 const meta = Predicate.isObject(content._meta) ? content._meta.ui : undefined;
45 return { html, meta };
46 }
47 return undefined;
49​
50export const snapshotMcpApp = Effect.fn("McpAppSnapshot.snapshot")(function* (input: {
51 readonly attachmentsDir: string;
52 readonly threadId: ThreadId;
53 readonly server: string;
54 readonly tool: string;
55 readonly resourceUri: string;
56 readonly contents: ReadonlyArray<unknown>;
57}) {
58 if (!input.resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)) return undefined;
59 const document = readMcpAppDocument(input.contents, input.resourceUri);
60 if (document === undefined) return undefined;
61 if (document.html === null || encoder.encode(document.html).byteLength > MCP_APP_MAX_HTML_BYTES) {
62 yield* Effect.logWarning("MCP app document exceeds the size limit.", {
63 server: input.server,
64 resourceUri: input.resourceUri,
65 });
66 return undefined;
67 }
68 // The `-html` suffix makes the asset route serve it as a sandboxed document.
69 const attachmentId = createAttachmentId(input.threadId, "html");
70 const filePath =
71 attachmentId === null
72 ? null
73 : resolveAttachmentRelativePath({
74 attachmentsDir: input.attachmentsDir,
75 relativePath: `${attachmentId}.html`,
76 });
77 if (attachmentId === null || filePath === null) return undefined;
78 const html = document.html;
79 const ui = Predicate.isObject(document.meta) ? document.meta : {};
80 const csp = readMcpAppCsp(ui.csp);
81 const fileSystem = yield* FileSystem.FileSystem;
82 // Only the returned reference lets thread deletion find the document, so a
83 // write that fails or is interrupted removes it.
84 yield* fileSystem
85 .writeFileString(filePath, injectMcpAppCsp(html, csp))
86 .pipe(Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)));
87 const permissions = readMcpAppPermissions(ui.permissions);
88 return {
89 attachmentId,
90 server: input.server,
91 tool: input.tool,
92 resourceUri: input.resourceUri,
93 ...(csp === undefined ? {} : { csp }),
94 ...(permissions === undefined ? {} : { permissions }),
95 ...(typeof ui.prefersBorder === "boolean" ? { prefersBorder: ui.prefersBorder } : {}),
96 } satisfies McpAppReference;
97});