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 mcpAppToolCallableByApp(meta: unknown): boolean {
135 const visibility =
136 Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;
137 return !Array.isArray(visibility) || visibility.includes("app");
138}
139
140/** Block undeclared origins, including self, which would expose T3's API. */
141export function mcpAppContentSecurityPolicy(csp: McpAppCsp | undefined): string {
142 const resources = csp?.resourceDomains?.join(" ") ?? "";
143 const list = (domains: ReadonlyArray<string> | undefined, fallback: string) =>
144 domains === undefined || domains.length === 0 ? fallback : domains.join(" ");
145 return [
146 "default-src 'none'",
147 `script-src 'unsafe-inline' ${resources}`.trim(),
148 `style-src 'unsafe-inline' ${resources}`.trim(),
149 `img-src data: blob: ${resources}`.trim(),
150 `font-src data: ${resources}`.trim(),
151 `media-src data: blob: ${resources}`.trim(),
152 `connect-src ${list(csp?.connectDomains, "'none'")}`,
153 `frame-src ${list(csp?.frameDomains, "'none'")}`,
154 "object-src 'none'",
155 `base-uri ${list(csp?.baseUriDomains, "'none'")}`,
156 "form-action 'none'",
157 ].join("; ");
158}
159
160const escapeAttribute = (value: string) =>
161 value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
162
163/** The route's sandbox header keeps origins opaque; the document CSP can only tighten it. */
164export function injectMcpAppCsp(html: string, csp: McpAppCsp | undefined): string {
165 const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(
166 mcpAppContentSecurityPolicy(csp),
167 )}">`;
168 // Insert after the doctype to preserve standards mode; the parser moves it into the head.
169 const doctype = /^\uFEFF?\s*<!doctype[^>]*>/i.exec(html);
170 return doctype
171 ? `${doctype[0]}${meta}${html.slice(doctype[0].length)}`
172 : `<!doctype html>${meta}${html}`;
173}
174
175/** Opaque origins require authenticating bridge messages by parent window. */
176export function injectMcpAppThemeBootstrap(html: string): string {
177 const script = `<script>
178(() => {
179 window.addEventListener("message", (event) => {
180 if (event.source !== window.parent) return;
181 const message = event.data;
182 if (!message || message.jsonrpc !== "2.0") return;
183 const theme = message.method === "ui/notifications/host-context-changed"
184 ? message.params?.theme
185 : message.id !== undefined && message.method === undefined
186 ? message.result?.hostContext?.theme
187 : undefined;
188 if (theme === "light" || theme === "dark") {
189 document.documentElement.style.colorScheme = theme;
190 }
191 });
192})();
193</script>`;
194 const prefix =
195 /^\uFEFF?\s*<!doctype[^>]*>\s*(?:<meta\s+http-equiv="Content-Security-Policy"[^>]*>)?/i.exec(
196 html,
197 );
198 return prefix
199 ? `${prefix[0]}${script}${html.slice(prefix[0].length)}`
200 : `<!doctype html>${script}${html}`;
201}
202
203/** Opaque documents throw on cookie reads; analytics startup often expects an empty string instead. */
204export function injectMcpAppCookieBootstrap(html: string): string {
205 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>`;
206 // Preserve captured CSP ahead of executable code, including this bootstrap.
207 const prefix =
208 /^(?:\uFEFF?\s*<!doctype[^>]*>\s*)?(?:<meta http-equiv="Content-Security-Policy" content="[^"]*">)?/i.exec(
209 html,
210 )![0];
211 return `${prefix}${bootstrap}${html.slice(prefix.length)}`;
212}
213
214export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {
215 const features: Array<string> = [];
216 if (permissions?.camera) features.push("camera");
217 if (permissions?.microphone) features.push("microphone");
218 if (permissions?.geolocation) features.push("geolocation");
219 if (permissions?.clipboardWrite) features.push("clipboard-write");
220 return features.join("; ");
221}
222
223export function clampMcpAppHeight(height: number): number {
224 if (!Number.isFinite(height)) return MCP_APP_DEFAULT_HEIGHT;
225 return Math.round(Math.min(MCP_APP_MAX_HEIGHT, Math.max(MCP_APP_MIN_HEIGHT, height)));
226}
227
228export function mcpAppFileName(reference: McpAppReference): string {
229 const name = reference.tool.replace(/[^\w.-]+/g, "-").slice(0, 80) || "app";
230 return `${name}.html`;
231}