feat: MCP apps render and run inline in threads (#16236)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-07 09:44:08 -07:00
1 parent 6ecb82dc42
commit 4d976d1fc2
83 files changed
+4990 -55

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
import { describe, expect, it } from "vite-plus/test";
import {
injectMcpAppCsp,
mcpAppContentSecurityPolicy,
mcpAppToolCallableByApp,
readMcpAppCsp,
readMcpAppReference,
readMcpAppResourceUri,
} from "./mcpApp.ts";
describe("mcpAppContentSecurityPolicy", () => {
it("blocks the network and T3's own origin when the app declares nothing", () => {
const policy = mcpAppContentSecurityPolicy(undefined);
expect(policy).toContain("default-src 'none'");
expect(policy).toContain("connect-src 'none'");
expect(policy).toContain("frame-src 'none'");
expect(policy).not.toContain("'self'");
});
it("allows exactly the declared origins", () => {
const policy = mcpAppContentSecurityPolicy({
connectDomains: ["https://api.weather.test"],
resourceDomains: ["https://*.cdn.test"],
});
expect(policy).toContain("connect-src https://api.weather.test");
expect(policy).toContain("script-src 'unsafe-inline' https://*.cdn.test");
expect(policy).toContain("img-src data: blob: https://*.cdn.test");
});
});
describe("injectMcpAppCsp", () => {
it("puts the policy after the doctype and ahead of every script", () => {
const html = "<!DOCTYPE html><html><head><script>x()</script></head></html>";
const injected = injectMcpAppCsp(html, undefined);
expect(injected.startsWith('<!DOCTYPE html><meta http-equiv="Content-Security-Policy"')).toBe(
true,
);
expect(injected.indexOf("connect-src 'none'")).toBeLessThan(injected.indexOf("<script>"));
expect(injectMcpAppCsp("<p>hi</p>", undefined).startsWith("<!doctype html><meta")).toBe(true);
});
});
describe("readMcpAppCsp", () => {
it("drops entries that could widen or break the policy", () => {
expect(
readMcpAppCsp({
connectDomains: [
"https://ok.test",
"*",
"'self'",
"https://evil.test; script-src *",
"http://localhost:3000",
"javascript:alert(1)",
],
resourceDomains: "https://not-an-array.test",
}),
).toEqual({ connectDomains: ["https://ok.test", "http://localhost:3000"] });
expect(readMcpAppCsp({ connectDomains: ["*"] })).toBeUndefined();
});
});
describe("readMcpAppReference", () => {
it("requires a ui:// resource and the owning server and tool", () => {
const reference = {
attachmentId: "thread-1-abc-html",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
};
expect(readMcpAppReference(reference)).toEqual(reference);
expect(readMcpAppReference({ ...reference, resourceUri: "https://x.test" })).toBeUndefined();
expect(readMcpAppReference({ ...reference, server: "" })).toBeUndefined();
});
});
describe("tool metadata", () => {
it("reads the resource URI from either spelling and honors app visibility", () => {
expect(readMcpAppResourceUri({ ui: { resourceUri: "ui://a/b" } })).toBe("ui://a/b");
expect(readMcpAppResourceUri({ "ui/resourceUri": "ui://a/c" })).toBe("ui://a/c");
expect(readMcpAppResourceUri({ ui: { resourceUri: "https://a" } })).toBeUndefined();
expect(mcpAppToolCallableByApp(undefined)).toBe(true);
expect(mcpAppToolCallableByApp({ ui: { visibility: ["model"] } })).toBe(false);
expect(mcpAppToolCallableByApp({ ui: { visibility: ["model", "app"] } })).toBe(true);
});
});
describe("mcpAppFromToolItem", () => {
it("reads the app from both the stored output and its compact wire form", async () => {
const { compactDynamicToolOutput, mcpAppFromToolItem } = await import("./toolOutput.ts");
const app = {
attachmentId: "thread-1-abc-html",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
};
const stored = { t3McpApp: app, result: { content: [] } };
const toolName = "weather.get_weather";
expect(mcpAppFromToolItem({ toolName, output: stored })).toEqual(app);
expect(mcpAppFromToolItem({ toolName, output: compactDynamicToolOutput(stored) })).toEqual(app);
});
it("ignores a reference naming a server or tool other than the item's own", async () => {
const { mcpAppFromToolItem } = await import("./toolOutput.ts");
// A tool result shaped like an app reference, claiming another server.
const forged = {
t3McpApp: {
attachmentId: "thread-1-abc-html",
server: "bank",
tool: "transfer",
resourceUri: "ui://bank/app",
},
};
expect(mcpAppFromToolItem({ toolName: "evil.lookup", output: forged })).toBeUndefined();
expect(mcpAppFromToolItem({ toolName: "bank.transfer", output: forged })).toBeDefined();
});
it("keeps an app whose resource URI is longer than a name", async () => {
const { compactDynamicToolOutput } = await import("./toolOutput.ts");
const resourceUri = `ui://weather/${"segment/".repeat(60)}dashboard`;
const output = compactDynamicToolOutput({
t3McpApp: {
attachmentId: "thread-1-abc-html",
server: "weather",
tool: "get_weather",
resourceUri,
},
});
expect(output?.t3McpApp?.resourceUri).toBe(resourceUri);
});
it("keeps the compact app reference within the wire budget", async () => {
const { compactDynamicToolOutput } = await import("./toolOutput.ts");
const domains = Array.from(
{ length: 32 },
(_, index) => `https://${"a".repeat(200)}${index}.test`,
);
const output = compactDynamicToolOutput({
t3McpApp: {
attachmentId: "thread-1-abc-html",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
csp: { connectDomains: domains, resourceDomains: domains },
},
});
expect(new TextEncoder().encode(JSON.stringify(output)).byteLength).toBeLessThanOrEqual(8_192);
expect(output?.t3McpApp?.server).toBe("weather");
});
});
+236
View File
@@ -0,0 +1,236 @@
import * as Predicate from "effect/Predicate";
/**
* MCP Apps (https://github.com/modelcontextprotocol/ext-apps, spec 2026-01-26):
* an MCP tool can name a `ui://` HTML resource that hosts render as an
* interactive view of its result. T3 snapshots the resource when the tool call
* completes, stores it as a thread attachment, and records an `McpAppReference`
* in the tool item's output; clients host it in an opaque-origin frame and
* speak the spec's JSON-RPC bridge with it.
*/
export const MCP_APP_PROTOCOL_VERSION = "2026-01-26";
export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
/** The MCP extension id a client declares to receive UI resources. */
export const MCP_APP_EXTENSION_ID = "io.modelcontextprotocol/ui";
export const MCP_APP_RESOURCE_SCHEME = "ui://";
/** Where T3 records the app reference inside a tool item's output object. */
export const MCP_APP_OUTPUT_KEY = "t3McpApp";
const MCP_APP_MIN_HEIGHT = 80;
export const MCP_APP_DEFAULT_HEIGHT = 320;
export const MCP_APP_MAX_HEIGHT = 2000;
/** Largest app document T3 stores. */
export const MCP_APP_MAX_HTML_BYTES = 5 * 1024 * 1024;
const MAX_DOMAINS = 32;
const MAX_DOMAIN_LENGTH = 256;
const MAX_NAME_LENGTH = 256;
// A `ui://` URI can carry a path and query; the compact wire budget still
// bounds the whole reference.
const MAX_RESOURCE_URI_LENGTH = 4096;
/** `_meta.ui.csp` on a UI resource: origins the app needs, by kind. */
export interface McpAppCsp {
readonly connectDomains?: ReadonlyArray<string>;
readonly resourceDomains?: ReadonlyArray<string>;
readonly frameDomains?: ReadonlyArray<string>;
readonly baseUriDomains?: ReadonlyArray<string>;
}
/** `_meta.ui.permissions` on a UI resource. */
export interface McpAppPermissions {
readonly camera?: Record<string, never>;
readonly microphone?: Record<string, never>;
readonly geolocation?: Record<string, never>;
readonly clipboardWrite?: Record<string, never>;
}
/** What a tool item's output carries so clients can host the app. */
export interface McpAppReference {
readonly attachmentId: string;
/** The MCP server the tool belongs to, as the provider names it. */
readonly server: string;
readonly tool: string;
readonly resourceUri: string;
readonly csp?: McpAppCsp;
readonly permissions?: McpAppPermissions;
readonly prefersBorder?: boolean;
}
// Only scheme-qualified origins, optionally with a leading `*.` subdomain
// wildcard, survive. Anything else (keywords, paths, quotes, whitespace) could
// widen or break the generated policy, so it is dropped.
const DOMAIN_PATTERN = /^(?:https?|wss?):\/\/(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*(?::\d{1,5})?$/i;
function readDomains(value: unknown): ReadonlyArray<string> | undefined {
if (!Array.isArray(value)) return undefined;
const domains = value
.filter(
(domain): domain is string =>
typeof domain === "string" &&
domain.length <= MAX_DOMAIN_LENGTH &&
DOMAIN_PATTERN.test(domain),
)
.slice(0, MAX_DOMAINS);
return domains.length === 0 ? undefined : domains;
}
/** The well-formed part of a resource's declared `_meta.ui.csp`. */
export function readMcpAppCsp(value: unknown): McpAppCsp | undefined {
if (!Predicate.isObject(value)) return undefined;
const csp: {
connectDomains?: ReadonlyArray<string>;
resourceDomains?: ReadonlyArray<string>;
frameDomains?: ReadonlyArray<string>;
baseUriDomains?: ReadonlyArray<string>;
} = {};
for (const key of [
"connectDomains",
"resourceDomains",
"frameDomains",
"baseUriDomains",
] as const) {
const domains = readDomains(value[key]);
if (domains !== undefined) csp[key] = domains;
}
return Object.keys(csp).length === 0 ? undefined : csp;
}
const PERMISSION_KEYS = ["camera", "microphone", "geolocation", "clipboardWrite"] as const;
export function readMcpAppPermissions(value: unknown): McpAppPermissions | undefined {
if (!Predicate.isObject(value)) return undefined;
const permissions: Partial<Record<(typeof PERMISSION_KEYS)[number], Record<string, never>>> = {};
for (const key of PERMISSION_KEYS) {
if (Predicate.isObject(value[key])) permissions[key] = {};
}
return Object.keys(permissions).length === 0 ? undefined : permissions;
}
const boundedName = (value: unknown) =>
typeof value === "string" && value.trim() !== "" && value.length <= MAX_NAME_LENGTH
? value
: undefined;
export function readMcpAppReference(value: unknown): McpAppReference | undefined {
if (!Predicate.isObject(value)) return undefined;
const attachmentId = boundedName(value.attachmentId);
const server = boundedName(value.server);
const tool = boundedName(value.tool);
const resourceUri =
typeof value.resourceUri === "string" && value.resourceUri.length <= MAX_RESOURCE_URI_LENGTH
? value.resourceUri
: undefined;
if (
attachmentId === undefined ||
server === undefined ||
tool === undefined ||
resourceUri === undefined ||
!resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)
) {
return undefined;
}
const csp = readMcpAppCsp(value.csp);
const permissions = readMcpAppPermissions(value.permissions);
return {
attachmentId,
server,
tool,
resourceUri,
...(csp === undefined ? {} : { csp }),
...(permissions === undefined ? {} : { permissions }),
...(typeof value.prefersBorder === "boolean" ? { prefersBorder: value.prefersBorder } : {}),
};
}
export function mcpAppReferencesEqual(left: McpAppReference, right: McpAppReference): boolean {
return (
left.attachmentId === right.attachmentId &&
left.server === right.server &&
left.tool === right.tool &&
left.resourceUri === right.resourceUri
);
}
/** The tool's `_meta.ui.resourceUri` (or the deprecated flat key), if it names a UI resource. */
export function readMcpAppResourceUri(meta: unknown): string | undefined {
if (!Predicate.isObject(meta)) return undefined;
const nested = Predicate.isObject(meta.ui) ? meta.ui.resourceUri : undefined;
const uri = nested ?? meta["ui/resourceUri"];
return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined;
}
/**
* Whether the tool's `_meta.ui.visibility` lets an app call it. The spec
* defaults to visible to both the model and apps.
*/
export function mcpAppToolCallableByApp(meta: unknown): boolean {
const visibility =
Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;
return !Array.isArray(visibility) || visibility.includes("app");
}
/**
* The Content-Security-Policy for an app document, per the spec's
* construction: undeclared origins stay blocked, and nothing loads from the
* host's own origin ('self' would reach T3's API).
*/
export function mcpAppContentSecurityPolicy(csp: McpAppCsp | undefined): string {
const resources = csp?.resourceDomains?.join(" ") ?? "";
const list = (domains: ReadonlyArray<string> | undefined, fallback: string) =>
domains === undefined || domains.length === 0 ? fallback : domains.join(" ");
return [
"default-src 'none'",
`script-src 'unsafe-inline' ${resources}`.trim(),
`style-src 'unsafe-inline' ${resources}`.trim(),
`img-src data: blob: ${resources}`.trim(),
`font-src data: ${resources}`.trim(),
`media-src data: blob: ${resources}`.trim(),
`connect-src ${list(csp?.connectDomains, "'none'")}`,
`frame-src ${list(csp?.frameDomains, "'none'")}`,
"object-src 'none'",
`base-uri ${list(csp?.baseUriDomains, "'none'")}`,
"form-action 'none'",
].join("; ");
}
const escapeAttribute = (value: string) =>
value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
/**
* Puts the app's policy at the top of its document as a CSP meta tag, ahead of
* any script. The asset route's `sandbox` header already makes the origin
* opaque; browsers enforce both policies, so the document can only tighten
* this one, never widen it.
*/
export function injectMcpAppCsp(html: string, csp: McpAppCsp | undefined): string {
const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(
mcpAppContentSecurityPolicy(csp),
)}">`;
// After a leading doctype, so the document stays in standards mode; the
// parser moves the tag into the head it opens.
const doctype = /^\uFEFF?\s*<!doctype[^>]*>/i.exec(html);
return doctype
? `${doctype[0]}${meta}${html.slice(doctype[0].length)}`
: `<!doctype html>${meta}${html}`;
}
/** The iframe `allow` attribute for the permissions an app declared. */
export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {
const features: Array<string> = [];
if (permissions?.camera) features.push("camera");
if (permissions?.microphone) features.push("microphone");
if (permissions?.geolocation) features.push("geolocation");
if (permissions?.clipboardWrite) features.push("clipboard-write");
return features.join("; ");
}
export function clampMcpAppHeight(height: number): number {
if (!Number.isFinite(height)) return MCP_APP_DEFAULT_HEIGHT;
return Math.round(Math.min(MCP_APP_MAX_HEIGHT, Math.max(MCP_APP_MIN_HEIGHT, height)));
}
export function mcpAppFileName(reference: McpAppReference): string {
const name = reference.tool.replace(/[^\w.-]+/g, "-").slice(0, 80) || "app";
return `${name}.html`;
}
+31 -1
View File
@@ -9,6 +9,7 @@ import {
readHtmlRenderReference,
type HtmlRenderReference,
} from "./htmlRender.ts";
import { MCP_APP_OUTPUT_KEY, readMcpAppReference, type McpAppReference } from "./mcpApp.ts";
import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
const MAX_PARSED_BYTES = 16_384;
@@ -39,6 +40,7 @@ interface CompactToolOutput {
scheduledTaskId?: string;
status?: "rolled_back";
htmlRender?: HtmlRenderReference;
[MCP_APP_OUTPUT_KEY]?: McpAppReference;
thread?: { threadId: string };
threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
}
@@ -124,6 +126,9 @@ export function compactDynamicToolOutput(value: unknown): CompactToolOutput | un
if (data.status === "rolled_back") output.status = "rolled_back";
const htmlRender = readHtmlRenderReference(data.htmlRender);
if (htmlRender !== undefined) output.htmlRender = htmlRender;
const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
// Kept under its stored key, so the compact wire output reads back the same way.
if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
const nestedThreadId = Predicate.isObject(data.thread)
? boundedId(data.thread.threadId)
: undefined;
@@ -159,11 +164,21 @@ export function compactDynamicToolOutput(value: unknown): CompactToolOutput | un
}
}
}
if (encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES) {
const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
if (oversized()) {
delete output.threads;
delete output.threadId;
delete output.status;
}
// An app's declared origins are the only unbounded-ish part of its
// reference; hosting works without them (the stored document carries its
// own policy), so they go before the app does.
const app = output[MCP_APP_OUTPUT_KEY];
if (app?.csp !== undefined && oversized()) {
const { csp: _csp, ...rest } = app;
output[MCP_APP_OUTPUT_KEY] = rest;
}
if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
return Object.keys(output).length === 0 ? undefined : output;
}
@@ -177,6 +192,21 @@ export function htmlRenderFromToolItem(item: {
return output?.isError ? undefined : output?.htmlRender;
}
/**
* The MCP App a completed tool call carries, if any. The adapter that captured
* it put the reference in the output, beside the tool's own result. A tool's
* result can imitate that shape, so the reference only counts when it names
* the very server and tool the item records: a server can then only ever
* point at an app of its own.
*/
export function mcpAppFromToolItem(item: {
readonly toolName: string | null | undefined;
readonly output?: unknown;
}): McpAppReference | undefined {
const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;
}
/** Some providers report completion even when command output describes a failure. */
export function toolOutputIndicatesFailure(text: string): boolean {
return (