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

mcpApp.ts

255 lines9.5 KB

1import * as Predicate from "effect/Predicate";
2​
3export const MCP_APP_PROTOCOL_VERSION = "2026-01-26";
4export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
5export const MCP_APP_EXTENSION_ID = "io.modelcontextprotocol/ui";
6export const MCP_APP_RESOURCE_SCHEME = "ui://";
7export const MCP_APP_OUTPUT_KEY = "t3McpApp";
8​
9const MCP_APP_MIN_HEIGHT = 80;
10export const MCP_APP_DEFAULT_HEIGHT = 320;
11export const MCP_APP_MAX_HEIGHT = 2000;
12export const MCP_APP_MAX_HTML_BYTES = 5 * 1024 * 1024;
13const MAX_DOMAINS = 32;
14const MAX_DOMAIN_LENGTH = 256;
15const MAX_NAME_LENGTH = 256;
16const MAX_RESOURCE_URI_LENGTH = 4096;
17​
18export interface McpAppCsp {
19 readonly connectDomains?: ReadonlyArray<string>;
20 readonly resourceDomains?: ReadonlyArray<string>;
21 readonly frameDomains?: ReadonlyArray<string>;
22 readonly baseUriDomains?: ReadonlyArray<string>;
24​
25export interface McpAppPermissions {
26 readonly camera?: Record<string, never>;
27 readonly microphone?: Record<string, never>;
28 readonly geolocation?: Record<string, never>;
29 readonly clipboardWrite?: Record<string, never>;
31​
32export interface McpAppReference {
33 readonly attachmentId: string;
34 readonly server: string;
35 readonly tool: string;
36 readonly resourceUri: string;
37 readonly csp?: McpAppCsp;
38 readonly permissions?: McpAppPermissions;
39 readonly prefersBorder?: boolean;
41​
42// Only scheme-qualified origins, optionally with a leading `*.` subdomain
43// wildcard, survive. Anything else (keywords, paths, quotes, whitespace) could
44// widen or break the generated policy, so it is dropped.
45const DOMAIN_PATTERN = /^(?:https?|wss?):\/\/(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*(?::\d{1,5})?$/i;
46​
47function readDomains(value: unknown): ReadonlyArray<string> | undefined {
48 if (!Array.isArray(value)) return undefined;
49 const domains = value
50 .filter(
51 (domain): domain is string =>
52 typeof domain === "string" &&
53 domain.length <= MAX_DOMAIN_LENGTH &&
54 DOMAIN_PATTERN.test(domain),
55 )
56 .slice(0, MAX_DOMAINS);
57 return domains.length === 0 ? undefined : domains;
59​
60export function readMcpAppCsp(value: unknown): McpAppCsp | undefined {
61 if (!Predicate.isObject(value)) return undefined;
62 const csp: {
63 connectDomains?: ReadonlyArray<string>;
64 resourceDomains?: ReadonlyArray<string>;
65 frameDomains?: ReadonlyArray<string>;
66 baseUriDomains?: ReadonlyArray<string>;
67 } = {};
68 for (const key of [
69 "connectDomains",
70 "resourceDomains",
71 "frameDomains",
72 "baseUriDomains",
73 ] as const) {
74 const domains = readDomains(value[key]);
75 if (domains !== undefined) csp[key] = domains;
76 }
77 return Object.keys(csp).length === 0 ? undefined : csp;
79​
80const PERMISSION_KEYS = ["camera", "microphone", "geolocation", "clipboardWrite"] as const;
81​
82export function readMcpAppPermissions(value: unknown): McpAppPermissions | undefined {
83 if (!Predicate.isObject(value)) return undefined;
84 const permissions: Partial<Record<(typeof PERMISSION_KEYS)[number], Record<string, never>>> = {};
85 for (const key of PERMISSION_KEYS) {
86 if (Predicate.isObject(value[key])) permissions[key] = {};
87 }
88 return Object.keys(permissions).length === 0 ? undefined : permissions;
90​
91const boundedName = (value: unknown) =>
92 typeof value === "string" && value.trim() !== "" && value.length <= MAX_NAME_LENGTH
93 ? value
94 : undefined;
95​
96export function readMcpAppReference(value: unknown): McpAppReference | undefined {
97 if (!Predicate.isObject(value)) return undefined;
98 const attachmentId = boundedName(value.attachmentId);
99 const server = boundedName(value.server);
100 const tool = boundedName(value.tool);
101 const resourceUri =
102 typeof value.resourceUri === "string" && value.resourceUri.length <= MAX_RESOURCE_URI_LENGTH
103 ? value.resourceUri
104 : undefined;
105 if (
106 attachmentId === undefined ||
107 server === undefined ||
108 tool === undefined ||
109 resourceUri === undefined ||
110 !resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)
111 ) {
112 return undefined;
113 }
114 const csp = readMcpAppCsp(value.csp);
115 const permissions = readMcpAppPermissions(value.permissions);
116 return {
117 attachmentId,
118 server,
119 tool,
120 resourceUri,
121 ...(csp === undefined ? {} : { csp }),
122 ...(permissions === undefined ? {} : { permissions }),
123 ...(typeof value.prefersBorder === "boolean" ? { prefersBorder: value.prefersBorder } : {}),
124 };
126​
127export function mcpAppReferencesEqual(left: McpAppReference, right: McpAppReference): boolean {
128 return (
129 left.attachmentId === right.attachmentId &&
130 left.server === right.server &&
131 left.tool === right.tool &&
132 left.resourceUri === right.resourceUri
133 );
135​
136export function readMcpAppResourceUri(meta: unknown): string | undefined {
137 if (!Predicate.isObject(meta)) return undefined;
138 const nested = Predicate.isObject(meta.ui) ? meta.ui.resourceUri : undefined;
139 const uri = nested ?? meta["ui/resourceUri"];
140 return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined;
142​
143export function mcpAppToolCallableByApp(meta: unknown): boolean {
144 const visibility =
145 Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;
146 return !Array.isArray(visibility) || visibility.includes("app");
148​
149/**
150 * The Content-Security-Policy for an app document, per the spec's
151 * construction: undeclared origins stay blocked, and nothing loads from the
152 * host's own origin ('self' would reach T3's API).
153 */
154export function mcpAppContentSecurityPolicy(csp: McpAppCsp | undefined): string {
155 const resources = csp?.resourceDomains?.join(" ") ?? "";
156 const list = (domains: ReadonlyArray<string> | undefined, fallback: string) =>
157 domains === undefined || domains.length === 0 ? fallback : domains.join(" ");
158 return [
159 "default-src 'none'",
160 `script-src 'unsafe-inline' ${resources}`.trim(),
161 `style-src 'unsafe-inline' ${resources}`.trim(),
162 `img-src data: blob: ${resources}`.trim(),
163 `font-src data: ${resources}`.trim(),
164 `media-src data: blob: ${resources}`.trim(),
165 `connect-src ${list(csp?.connectDomains, "'none'")}`,
166 `frame-src ${list(csp?.frameDomains, "'none'")}`,
167 "object-src 'none'",
168 `base-uri ${list(csp?.baseUriDomains, "'none'")}`,
169 "form-action 'none'",
170 ].join("; ");
172​
173const escapeAttribute = (value: string) =>
174 value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
175​
176/**
177 * The asset route's `sandbox` header already makes the origin opaque; browsers
178 * enforce both policies, so the document can only tighten this one, never widen
179 * it.
180 */
181export function injectMcpAppCsp(html: string, csp: McpAppCsp | undefined): string {
182 const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(
183 mcpAppContentSecurityPolicy(csp),
184 )}">`;
185 // After a leading doctype, so the document stays in standards mode; the
186 // parser moves the tag into the head it opens.
187 const doctype = /^\uFEFF?\s*<!doctype[^>]*>/i.exec(html);
188 return doctype
189 ? `${doctype[0]}${meta}${html.slice(doctype[0].length)}`
190 : `<!doctype html>${meta}${html}`;
192​
193/**
194 * The bridge uses an opaque origin, so authenticate messages by parent window.
195 */
196export function injectMcpAppThemeBootstrap(html: string): string {
197 const script = `<script>
198(() => {
199 window.addEventListener("message", (event) => {
200 if (event.source !== window.parent) return;
201 const message = event.data;
202 if (!message || message.jsonrpc !== "2.0") return;
203 const theme = message.method === "ui/notifications/host-context-changed"
204 ? message.params?.theme
205 : message.id !== undefined && message.method === undefined
206 ? message.result?.hostContext?.theme
207 : undefined;
208 if (theme === "light" || theme === "dark") {
209 document.documentElement.style.colorScheme = theme;
210 }
211 });
212})();
213</script>`;
214 const prefix =
215 /^\uFEFF?\s*<!doctype[^>]*>\s*(?:<meta\s+http-equiv="Content-Security-Policy"[^>]*>)?/i.exec(
216 html,
217 );
218 return prefix
219 ? `${prefix[0]}${script}${html.slice(prefix[0].length)}`
220 : `<!doctype html>${script}${html}`;
222​
223/**
224 * Analytics libraries often read cookies during startup. An opaque document
225 * has none, but browsers throw instead of returning an empty cookie string.
226 */
227export function injectMcpAppCookieBootstrap(html: string): string {
228 const bootstrap = `<script>(function(){try{void document.cookie;}catch(error){if(error&&error.name==="SecurityError"){Object.defineProperty(document,"cookie",{configurable:true,get:function(){return "";},set:function(){}});}}})();</script>`;
229 // Saved captures begin with the CSP inserted by injectMcpAppCsp. Keep it
230 // ahead of executable code, including this bootstrap, without rewriting it.
231 const prefix =
232 /^(?:\uFEFF?\s*<!doctype[^>]*>\s*)?(?:<meta http-equiv="Content-Security-Policy" content="[^"]*">)?/i.exec(
233 html,
234 )![0];
235 return `${prefix}${bootstrap}${html.slice(prefix.length)}`;
237​
238export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {
239 const features: Array<string> = [];
240 if (permissions?.camera) features.push("camera");
241 if (permissions?.microphone) features.push("microphone");
242 if (permissions?.geolocation) features.push("geolocation");
243 if (permissions?.clipboardWrite) features.push("clipboard-write");
244 return features.join("; ");
246​
247export function clampMcpAppHeight(height: number): number {
248 if (!Number.isFinite(height)) return MCP_APP_DEFAULT_HEIGHT;
249 return Math.round(Math.min(MCP_APP_MAX_HEIGHT, Math.max(MCP_APP_MIN_HEIGHT, height)));
251​
252export function mcpAppFileName(reference: McpAppReference): string {
253 const name = reference.tool.replace(/[^\w.-]+/g, "-").slice(0, 80) || "app";
254 return `${name}.html`;