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

mcpApp.ts

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