Open History to see the last commit
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>;
23}
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>;
30}
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;
40}
41
42// Accept only scheme-qualified origins with optional subdomain wildcards to prevent policy widening.
43const DOMAIN_PATTERN = /^(?:https?|wss?):\/\/(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*(?::\d{1,5})?$/i;
44
45function readDomains(value: unknown): ReadonlyArray<string> | undefined {
46 if (!Array.isArray(value)) return undefined;
47 const domains = value
48 .filter(
49 (domain): domain is string =>
50 typeof domain === "string" &&
51 domain.length <= MAX_DOMAIN_LENGTH &&
52 DOMAIN_PATTERN.test(domain),
53 )
54 .slice(0, MAX_DOMAINS);
55 return domains.length === 0 ? undefined : domains;
56}
57
58export function readMcpAppCsp(value: unknown): McpAppCsp | undefined {
59 if (!Predicate.isObject(value)) return undefined;
60 const csp: {
61 connectDomains?: ReadonlyArray<string>;
62 resourceDomains?: ReadonlyArray<string>;
63 frameDomains?: ReadonlyArray<string>;
64 baseUriDomains?: ReadonlyArray<string>;
65 } = {};
66 for (const key of [
67 "connectDomains",
68 "resourceDomains",
69 "frameDomains",
70 "baseUriDomains",
71 ] as const) {
72 const domains = readDomains(value[key]);
73 if (domains !== undefined) csp[key] = domains;
74 }
75 return Object.keys(csp).length === 0 ? undefined : csp;
76}
77
78const PERMISSION_KEYS = ["camera", "microphone", "geolocation", "clipboardWrite"] as const;
79
80export function readMcpAppPermissions(value: unknown): McpAppPermissions | undefined {
81 if (!Predicate.isObject(value)) return undefined;
82 const permissions: Partial<Record<(typeof PERMISSION_KEYS)[number], Record<string, never>>> = {};
83 for (const key of PERMISSION_KEYS) {
84 if (Predicate.isObject(value[key])) permissions[key] = {};
85 }
86 return Object.keys(permissions).length === 0 ? undefined : permissions;
87}
88
89const boundedName = (value: unknown) =>
90 typeof value === "string" && value.trim() !== "" && value.length <= MAX_NAME_LENGTH
91 ? value
92 : undefined;
93
94export function readMcpAppReference(value: unknown): McpAppReference | undefined {
95 if (!Predicate.isObject(value)) return undefined;
96 const attachmentId = boundedName(value.attachmentId);
97 const server = boundedName(value.server);
98 const tool = boundedName(value.tool);
99 const resourceUri =
100 typeof value.resourceUri === "string" && value.resourceUri.length <= MAX_RESOURCE_URI_LENGTH
101 ? value.resourceUri
102 : undefined;
103 if (
104 attachmentId === undefined ||
105 server === undefined ||
106 tool === undefined ||
107 resourceUri === undefined ||
108 !resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)
109 ) {
110 return undefined;
111 }
112 const csp = readMcpAppCsp(value.csp);
113 const permissions = readMcpAppPermissions(value.permissions);
114 return {
115 attachmentId,
116 server,
117 tool,
118 resourceUri,
119 ...(csp === undefined ? {} : { csp }),
120 ...(permissions === undefined ? {} : { permissions }),
121 ...(typeof value.prefersBorder === "boolean" ? { prefersBorder: value.prefersBorder } : {}),
122 };
123}
124
125export function mcpAppReferencesEqual(left: McpAppReference, right: McpAppReference): boolean {
126 return (
127 left.attachmentId === right.attachmentId &&
128 left.server === right.server &&
129 left.tool === right.tool &&
130 left.resourceUri === right.resourceUri
131 );
132}
133
134export function readMcpAppResourceUri(meta: unknown): string | undefined {
135 if (!Predicate.isObject(meta)) return undefined;
136 const nested = Predicate.isObject(meta.ui) ? meta.ui.resourceUri : undefined;
137 const uri = nested ?? meta["ui/resourceUri"];
138 return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined;
139}
140
141export function mcpAppToolCallableByApp(meta: unknown): boolean {
142 const visibility =
143 Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;
144 return !Array.isArray(visibility) || visibility.includes("app");
145}
146
147/** Block undeclared origins, including self, which would expose T3's API. */
148export function mcpAppContentSecurityPolicy(csp: McpAppCsp | undefined): string {
149 const resources = csp?.resourceDomains?.join(" ") ?? "";
150 const list = (domains: ReadonlyArray<string> | undefined, fallback: string) =>
151 domains === undefined || domains.length === 0 ? fallback : domains.join(" ");
152 return [
153 "default-src 'none'",
154 `script-src 'unsafe-inline' ${resources}`.trim(),
155 `style-src 'unsafe-inline' ${resources}`.trim(),
156 `img-src data: blob: ${resources}`.trim(),
157 `font-src data: ${resources}`.trim(),
158 `media-src data: blob: ${resources}`.trim(),
159 `connect-src ${list(csp?.connectDomains, "'none'")}`,
160 `frame-src ${list(csp?.frameDomains, "'none'")}`,
161 "object-src 'none'",
162 `base-uri ${list(csp?.baseUriDomains, "'none'")}`,
163 "form-action 'none'",
164 ].join("; ");
165}
166
167const escapeAttribute = (value: string) =>
168 value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
169
170/** The route's sandbox header keeps origins opaque; the document CSP can only tighten it. */
171export function injectMcpAppCsp(html: string, csp: McpAppCsp | undefined): string {
172 const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(
173 mcpAppContentSecurityPolicy(csp),
174 )}">`;
175 // Insert after the doctype to preserve standards mode; the parser moves it into the head.
176 const doctype = /^\uFEFF?\s*<!doctype[^>]*>/i.exec(html);
177 return doctype
178 ? `${doctype[0]}${meta}${html.slice(doctype[0].length)}`
179 : `<!doctype html>${meta}${html}`;
180}
181
182/** Opaque origins require authenticating bridge messages by parent window. */
183export function injectMcpAppThemeBootstrap(html: string): string {
184 const script = `<script>
185(() => {
186 window.addEventListener("message", (event) => {
187 if (event.source !== window.parent) return;
188 const message = event.data;
189 if (!message || message.jsonrpc !== "2.0") return;
190 const theme = message.method === "ui/notifications/host-context-changed"
191 ? message.params?.theme
192 : message.id !== undefined && message.method === undefined
193 ? message.result?.hostContext?.theme
194 : undefined;
195 if (theme === "light" || theme === "dark") {
196 document.documentElement.style.colorScheme = theme;
197 }
198 });
199})();
200</script>`;
201 const prefix =
202 /^\uFEFF?\s*<!doctype[^>]*>\s*(?:<meta\s+http-equiv="Content-Security-Policy"[^>]*>)?/i.exec(
203 html,
204 );
205 return prefix
206 ? `${prefix[0]}${script}${html.slice(prefix[0].length)}`
207 : `<!doctype html>${script}${html}`;
208}
209
210/** Opaque documents throw on cookie reads; analytics startup often expects an empty string instead. */
211export function injectMcpAppCookieBootstrap(html: string): string {
212 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>`;
213 // Preserve captured CSP ahead of executable code, including this bootstrap.
214 const prefix =
215 /^(?:\uFEFF?\s*<!doctype[^>]*>\s*)?(?:<meta http-equiv="Content-Security-Policy" content="[^"]*">)?/i.exec(
216 html,
217 )![0];
218 return `${prefix}${bootstrap}${html.slice(prefix.length)}`;
219}
220
221export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {
222 const features: Array<string> = [];
223 if (permissions?.camera) features.push("camera");
224 if (permissions?.microphone) features.push("microphone");
225 if (permissions?.geolocation) features.push("geolocation");
226 if (permissions?.clipboardWrite) features.push("clipboard-write");
227 return features.join("; ");
228}
229
230export function clampMcpAppHeight(height: number): number {
231 if (!Number.isFinite(height)) return MCP_APP_DEFAULT_HEIGHT;
232 return Math.round(Math.min(MCP_APP_MAX_HEIGHT, Math.max(MCP_APP_MIN_HEIGHT, height)));
233}
234
235export function mcpAppFileName(reference: McpAppReference): string {
236 const name = reference.tool.replace(/[^\w.-]+/g, "-").slice(0, 80) || "app";
237 return `${name}.html`;
238}