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:
1 parent
6ecb82dc42
commit
4d976d1fc2
83 files changed
+4990
-55
No files matched your search
@@ -390,6 +390,14 @@
|
||||
"./device/duo-control": {
|
||||
"types": "./src/device/duoControl.ts",
|
||||
"default": "./src/device/duoControl.ts"
|
||||
},
|
||||
"./mcp-apps": {
|
||||
"types": "./src/mcpApps/host.ts",
|
||||
"default": "./src/mcpApps/host.ts"
|
||||
},
|
||||
"./state/mcp-apps": {
|
||||
"types": "./src/state/mcpApps.ts",
|
||||
"default": "./src/state/mcpApps.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { makeMcpAppHost, McpAppHostRefusal, type McpAppHostContext } from "./host.ts";
|
||||
|
||||
const app = {
|
||||
attachmentId: "thread-1-app",
|
||||
server: "weather",
|
||||
tool: "get_weather",
|
||||
resourceUri: "ui://weather/dashboard",
|
||||
csp: { connectDomains: ["https://api.weather.test"] },
|
||||
};
|
||||
|
||||
const context = (
|
||||
theme: "light" | "dark" = "dark",
|
||||
displayMode: "inline" | "fullscreen" = "inline",
|
||||
): McpAppHostContext => ({
|
||||
theme,
|
||||
styles: { variables: { "--color-background-primary": theme === "dark" ? "#000" : "#fff" } },
|
||||
displayMode,
|
||||
availableDisplayModes: ["inline", "fullscreen"],
|
||||
containerDimensions: { width: 600, maxHeight: 2000 },
|
||||
platform: "web",
|
||||
});
|
||||
|
||||
// Lets the host settle the promises its callbacks return.
|
||||
const flush = () => new Promise<void>((resolve) => queueMicrotask(resolve)).then(() => undefined);
|
||||
|
||||
const initialize = (
|
||||
host: ReturnType<typeof makeMcpAppHost>,
|
||||
appCapabilities: Record<string, unknown> = {},
|
||||
) => {
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: "init",
|
||||
method: "ui/initialize",
|
||||
params: { appCapabilities },
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
};
|
||||
|
||||
function setup(overrides: Partial<Parameters<typeof makeMcpAppHost>[0]> = {}) {
|
||||
const sent: Array<Record<string, unknown>> = [];
|
||||
let theme: "light" | "dark" = "dark";
|
||||
let mode: "inline" | "fullscreen" = "inline";
|
||||
const host = makeMcpAppHost({
|
||||
app,
|
||||
hostVersion: "1.0.0",
|
||||
post: (message) => sent.push(message as Record<string, unknown>),
|
||||
hostContext: () => context(theme, mode),
|
||||
callTool: async (input) => ({ content: [{ type: "text", text: `called ${input.name}` }] }),
|
||||
readResource: async () => ({ contents: [] }),
|
||||
openLink: async () => undefined,
|
||||
sendMessage: async () => undefined,
|
||||
updateModelContext: async () => undefined,
|
||||
requestDisplayMode: async (next) => {
|
||||
mode = next === "fullscreen" ? "fullscreen" : "inline";
|
||||
return mode;
|
||||
},
|
||||
downloadFile: async () => undefined,
|
||||
onRequestTeardown: () => undefined,
|
||||
onSizeChanged: () => undefined,
|
||||
...overrides,
|
||||
});
|
||||
return {
|
||||
host,
|
||||
sent,
|
||||
setTheme: (next: "light" | "dark") => {
|
||||
theme = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("makeMcpAppHost", () => {
|
||||
it("initializes, then replays the tool input and result after initialized", () => {
|
||||
const { host, sent } = setup();
|
||||
host.setToolCall({
|
||||
arguments: { city: "Oslo" },
|
||||
result: { content: [{ type: "text", text: "Sunny" }] },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "ui/initialize",
|
||||
params: { protocolVersion: "2026-01-26", appInfo: { name: "a", version: "1" } },
|
||||
});
|
||||
expect(sent[0]).toMatchObject({
|
||||
id: 1,
|
||||
result: {
|
||||
protocolVersion: "2026-01-26",
|
||||
hostCapabilities: { serverTools: {}, sandbox: { csp: app.csp } },
|
||||
hostContext: { theme: "dark", displayMode: "inline" },
|
||||
},
|
||||
});
|
||||
expect(sent).toHaveLength(1);
|
||||
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} });
|
||||
expect(sent.slice(1)).toEqual([
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "ui/notifications/tool-input",
|
||||
params: { arguments: { city: "Oslo" } },
|
||||
},
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "ui/notifications/tool-result",
|
||||
params: { content: [{ type: "text", text: "Sunny" }] },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("replays a tool call that arrives after initialization, once", () => {
|
||||
const { host, sent } = setup();
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
sent.length = 0;
|
||||
host.setToolCall({ arguments: { city: "Oslo" }, result: undefined });
|
||||
host.setToolCall({ arguments: { city: "Bergen" }, result: undefined });
|
||||
expect(sent).toEqual([
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "ui/notifications/tool-input",
|
||||
params: { arguments: { city: "Oslo" } },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops null fields providers report, which the MCP Apps SDK rejects", async () => {
|
||||
const { host, sent } = setup({
|
||||
callTool: async () => ({ content: [], structuredContent: null, _meta: null }),
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
host.setToolCall({
|
||||
arguments: {},
|
||||
result: {
|
||||
content: [{ type: "text", text: "t" }],
|
||||
structuredContent: { time: "t" },
|
||||
_meta: null,
|
||||
},
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "get-time" } });
|
||||
await flush();
|
||||
expect(sent.find((m) => m.method === "ui/notifications/tool-result")?.params).toEqual({
|
||||
content: [{ type: "text", text: "t" }],
|
||||
structuredContent: { time: "t" },
|
||||
});
|
||||
expect(sent.find((m) => m.id === 2)?.result).toEqual({ content: [] });
|
||||
});
|
||||
|
||||
it("accepts ui/message as one text block or the SDK's block array", async () => {
|
||||
const messages: Array<string> = [];
|
||||
const { host, sent } = setup({ sendMessage: async (text) => void messages.push(text) });
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "ui/message",
|
||||
params: { role: "user", content: { type: "text", text: "one" } },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
method: "ui/message",
|
||||
params: { role: "user", content: [{ type: "text", text: "two" }] },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 3,
|
||||
method: "ui/message",
|
||||
params: { role: "user", content: [{ type: "image", data: "x" }] },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 4,
|
||||
method: "ui/message",
|
||||
params: { role: "user", content: { type: "text", text: " " } },
|
||||
});
|
||||
await flush();
|
||||
expect(messages).toEqual(["one", "two"]);
|
||||
expect(sent.find((m) => m.id === 3)?.error).toMatchObject({ code: -32602 });
|
||||
// Blank text would ask to send an empty message.
|
||||
expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
|
||||
});
|
||||
|
||||
it("sends only changed context fields, and nothing before initialization", () => {
|
||||
const { host, sent, setTheme } = setup();
|
||||
setTheme("light");
|
||||
host.updateHostContext();
|
||||
expect(sent).toHaveLength(0);
|
||||
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
sent.length = 0;
|
||||
setTheme("dark");
|
||||
host.updateHostContext();
|
||||
expect(sent).toEqual([
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "ui/notifications/host-context-changed",
|
||||
params: { theme: "dark", styles: context("dark").styles },
|
||||
},
|
||||
]);
|
||||
host.updateHostContext();
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("catches the app up on context that changed while it was initializing", () => {
|
||||
const { host, sent, setTheme } = setup();
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
|
||||
setTheme("light");
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
expect(sent.at(-1)).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
method: "ui/notifications/host-context-changed",
|
||||
params: { theme: "light", styles: context("light").styles },
|
||||
});
|
||||
});
|
||||
|
||||
it("proxies tools/call and reports a refusal as a JSON-RPC error", async () => {
|
||||
const { host, sent } = setup({
|
||||
callTool: async (input) => {
|
||||
if (input.name === "delete_everything")
|
||||
throw new McpAppHostRefusal("Declined by the user.");
|
||||
return { content: [], structuredContent: { ok: true } };
|
||||
},
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "refresh" } });
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 8,
|
||||
method: "tools/call",
|
||||
params: { name: "delete_everything", arguments: {} },
|
||||
});
|
||||
await flush();
|
||||
expect(sent).toContainEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: 7,
|
||||
result: { content: [], structuredContent: { ok: true } },
|
||||
});
|
||||
expect(sent).toContainEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: 8,
|
||||
error: { code: -32000, message: "Declined by the user." },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects malformed requests and unsupported methods", () => {
|
||||
const { host, sent } = setup();
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "ui/open-link",
|
||||
params: { url: "javascript:x" },
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", id: 3, method: "sampling/createMessage", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant" } });
|
||||
expect(sent.map((message) => (message.error as { code: number }).code)).toEqual([
|
||||
-32602, -32601, -32602,
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses requests past the in-flight limit and posts nothing after dispose", async () => {
|
||||
let release: () => void = () => undefined;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const { host, sent } = setup({
|
||||
callTool: async () => {
|
||||
await gate;
|
||||
return { content: [] };
|
||||
},
|
||||
});
|
||||
for (let id = 0; id < 17; id++) {
|
||||
host.receive({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "slow" } });
|
||||
}
|
||||
expect(sent).toEqual([
|
||||
{ jsonrpc: "2.0", id: 16, error: { code: -32000, message: "Too many requests in flight." } },
|
||||
]);
|
||||
host.dispose();
|
||||
release();
|
||||
await flush();
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("switches display mode only to one both sides offer, and tells the app", async () => {
|
||||
const { host, sent } = setup();
|
||||
initialize(host, { availableDisplayModes: ["inline", "fullscreen"] });
|
||||
sent.length = 0;
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "ui/request-display-mode",
|
||||
params: { mode: "pip" },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
method: "ui/request-display-mode",
|
||||
params: { mode: "fullscreen" },
|
||||
});
|
||||
await flush();
|
||||
host.updateHostContext();
|
||||
expect(sent.find((m) => m.id === 1)?.result).toEqual({ mode: "inline" });
|
||||
expect(sent.find((m) => m.id === 2)?.result).toEqual({ mode: "fullscreen" });
|
||||
expect(sent.find((m) => m.method === "ui/notifications/host-context-changed")?.params).toEqual({
|
||||
displayMode: "fullscreen",
|
||||
});
|
||||
|
||||
// An app that declared only inline stays inline.
|
||||
const declined = setup();
|
||||
initialize(declined.host, { availableDisplayModes: ["inline"] });
|
||||
declined.host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 3,
|
||||
method: "ui/request-display-mode",
|
||||
params: { mode: "fullscreen" },
|
||||
});
|
||||
await flush();
|
||||
expect(declined.sent.find((m) => m.id === 3)?.result).toEqual({ mode: "inline" });
|
||||
});
|
||||
|
||||
it("forwards model context and download requests, and declares both", async () => {
|
||||
const contexts: Array<unknown> = [];
|
||||
const downloads: Array<unknown> = [];
|
||||
const { host, sent } = setup({
|
||||
updateModelContext: async (update) => void contexts.push(update),
|
||||
downloadFile: async (files) => {
|
||||
downloads.push(files);
|
||||
if (files.length > 1) throw new McpAppHostRefusal("Declined by the user.");
|
||||
},
|
||||
});
|
||||
initialize(host);
|
||||
const capabilities = (
|
||||
sent[0]?.result as { hostCapabilities: Record<string, unknown> } | undefined
|
||||
)?.hostCapabilities;
|
||||
expect(capabilities?.updateModelContext).toEqual({ text: {}, structuredContent: {} });
|
||||
expect(capabilities?.downloadFile).toEqual({});
|
||||
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "ui/update-model-context",
|
||||
params: { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
|
||||
});
|
||||
const embedded = {
|
||||
type: "resource",
|
||||
resource: { uri: "file:///report.csv", mimeType: "text/csv", text: "a,b" },
|
||||
};
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
method: "ui/download-file",
|
||||
params: { contents: [embedded] },
|
||||
});
|
||||
host.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: 3,
|
||||
method: "ui/download-file",
|
||||
params: {
|
||||
contents: [embedded, { type: "resource_link", uri: "ui://todos/export", name: "x" }],
|
||||
},
|
||||
});
|
||||
host.receive({ jsonrpc: "2.0", id: 4, method: "ui/download-file", params: { contents: [{}] } });
|
||||
await flush();
|
||||
expect(contexts).toEqual([
|
||||
{ content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
|
||||
]);
|
||||
expect(downloads[0]).toEqual([
|
||||
{
|
||||
_tag: "embedded",
|
||||
name: "report.csv",
|
||||
mimeType: "text/csv",
|
||||
bytes: new TextEncoder().encode("a,b"),
|
||||
},
|
||||
]);
|
||||
expect(sent.find((m) => m.id === 2)?.result).toEqual({});
|
||||
// A refused download is reported in the result, as the draft defines.
|
||||
expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
|
||||
expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
|
||||
});
|
||||
|
||||
it("tears down after the app answers, or after the timeout, and passes on its own request", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let closeRequested = false;
|
||||
const { host, sent } = setup({ onRequestTeardown: () => (closeRequested = true) });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/request-teardown" });
|
||||
expect(closeRequested).toBe(true);
|
||||
|
||||
// Before initialization there is nothing to ask.
|
||||
await host.teardown();
|
||||
expect(sent.some((m) => m.method === "ui/resource-teardown")).toBe(false);
|
||||
|
||||
const answered = setup();
|
||||
initialize(answered.host);
|
||||
let done = false;
|
||||
void answered.host.teardown().then(() => (done = true));
|
||||
const request = answered.sent.find((m) => m.method === "ui/resource-teardown");
|
||||
expect(request).toBeDefined();
|
||||
answered.host.receive({ jsonrpc: "2.0", id: request?.id, result: {} });
|
||||
await vi.runAllTimersAsync();
|
||||
expect(done).toBe(true);
|
||||
|
||||
const silent = setup();
|
||||
initialize(silent.host);
|
||||
let timedOut = false;
|
||||
void silent.host.teardown().then(() => (timedOut = true));
|
||||
await vi.advanceTimersByTimeAsync(1999);
|
||||
expect(timedOut).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(timedOut).toBe(true);
|
||||
// A torn-down host posts nothing more.
|
||||
const before = silent.sent.length;
|
||||
silent.host.updateHostContext();
|
||||
expect(silent.sent).toHaveLength(before);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,576 @@
|
||||
// @effect-diagnostics globalTimers:off - The bridge runs in the client, outside an Effect runtime.
|
||||
import { MCP_APP_PROTOCOL_VERSION, type McpAppReference } from "@t3tools/shared/mcpApp";
|
||||
import * as Base64 from "effect/encoding/Base64";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
/**
|
||||
* The host side of the MCP Apps bridge (spec 2026-01-26, plus the draft
|
||||
* additions the current SDK sends: `ui/download-file` and
|
||||
* `ui/notifications/request-teardown`): JSON-RPC 2.0 over postMessage between a
|
||||
* client and one app document. It is transport-free so web (an iframe) and
|
||||
* mobile (a WebView) share every protocol rule; each platform supplies how to
|
||||
* post a message and how to reach the environment.
|
||||
*/
|
||||
|
||||
const MAX_MESSAGE_BYTES = 256 * 1024;
|
||||
/** Requests an app may have in flight at once; more are refused, not queued. */
|
||||
const MAX_PENDING_REQUESTS = 16;
|
||||
/** How long the host waits for an app to answer `ui/resource-teardown`. */
|
||||
const TEARDOWN_TIMEOUT_MS = 2000;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
type JsonRpcId = string | number;
|
||||
|
||||
export type McpAppDisplayMode = "inline" | "fullscreen" | "pip";
|
||||
|
||||
export interface McpAppHostContext {
|
||||
readonly theme: "light" | "dark";
|
||||
readonly styles: { readonly variables: Readonly<Record<string, string>> };
|
||||
readonly displayMode: McpAppDisplayMode;
|
||||
readonly availableDisplayModes: ReadonlyArray<McpAppDisplayMode>;
|
||||
/**
|
||||
* `maxHeight` when the host sizes the frame to the app's reported height,
|
||||
* `height` when the frame is a fixed box the app must fit (spec
|
||||
* "Container Dimensions").
|
||||
*/
|
||||
readonly containerDimensions:
|
||||
| { readonly width: number; readonly maxHeight: number }
|
||||
| { readonly width: number; readonly height: number };
|
||||
readonly platform: "web" | "desktop" | "mobile";
|
||||
readonly locale?: string;
|
||||
readonly timeZone?: string;
|
||||
readonly userAgent?: string;
|
||||
readonly deviceCapabilities?: { readonly touch?: boolean; readonly hover?: boolean };
|
||||
readonly safeAreaInsets?: {
|
||||
readonly top: number;
|
||||
readonly right: number;
|
||||
readonly bottom: number;
|
||||
readonly left: number;
|
||||
};
|
||||
/** The tool call that created the app: the server's MCP `Tool` definition. */
|
||||
readonly toolInfo?: { readonly tool: unknown };
|
||||
}
|
||||
|
||||
/** A file an app asked the host to save (`ui/download-file`): embedded, or linked on its server. */
|
||||
export type McpAppDownload =
|
||||
| {
|
||||
readonly _tag: "embedded";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "link";
|
||||
readonly name: string;
|
||||
readonly uri: string;
|
||||
readonly mimeType?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bytes of an MCP resource's contents: `text` as UTF-8, `blob` decoded
|
||||
* from base64. Undefined when it has neither or the base64 is malformed.
|
||||
*/
|
||||
export function mcpResourceBytes(content: unknown): Uint8Array | undefined {
|
||||
if (!Predicate.isObject(content)) return undefined;
|
||||
if (typeof content.text === "string") return encoder.encode(content.text);
|
||||
if (typeof content.blob === "string") {
|
||||
const decoded = Base64.decode(content.blob);
|
||||
return Result.isSuccess(decoded) ? decoded.success : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface McpAppCallToolResult {
|
||||
readonly content: ReadonlyArray<unknown>;
|
||||
readonly structuredContent?: unknown;
|
||||
readonly isError?: boolean | undefined;
|
||||
readonly _meta?: unknown;
|
||||
}
|
||||
|
||||
/** Thrown by host callbacks to refuse a request with a message the app can show. */
|
||||
export class McpAppHostRefusal extends Error {}
|
||||
|
||||
export interface McpAppHostOptions {
|
||||
readonly app: McpAppReference;
|
||||
readonly hostVersion: string;
|
||||
/** Posts one JSON-RPC message to the app document. */
|
||||
readonly post: (message: unknown) => void;
|
||||
readonly hostContext: () => McpAppHostContext;
|
||||
|
||||
readonly callTool: (input: {
|
||||
readonly name: string;
|
||||
readonly arguments: Record<string, unknown>;
|
||||
}) => Promise<McpAppCallToolResult>;
|
||||
readonly readResource: (input: { readonly uri: string }) => Promise<unknown>;
|
||||
readonly openLink: (url: string) => Promise<void>;
|
||||
readonly sendMessage: (text: string) => Promise<void>;
|
||||
/** Replaces what this app tells the agent on its next turn; undefined content clears it. */
|
||||
readonly updateModelContext: (context: {
|
||||
readonly content?: ReadonlyArray<unknown>;
|
||||
readonly structuredContent?: Record<string, unknown>;
|
||||
}) => Promise<void>;
|
||||
/**
|
||||
* Switches the app to a mode the host and the app both offer, returning the
|
||||
* resulting mode. The host has already checked both lists.
|
||||
*/
|
||||
readonly requestDisplayMode: (mode: McpAppDisplayMode) => Promise<McpAppDisplayMode>;
|
||||
readonly downloadFile: (files: ReadonlyArray<McpAppDownload>) => Promise<void>;
|
||||
/** The app asked to be closed (`ui/notifications/request-teardown`). */
|
||||
readonly onRequestTeardown: () => void;
|
||||
readonly onSizeChanged: (size: { readonly width?: number; readonly height?: number }) => void;
|
||||
}
|
||||
|
||||
export interface McpAppHost {
|
||||
/** Handles one message the app posted; the caller has already checked its source. */
|
||||
readonly receive: (data: unknown) => void;
|
||||
/**
|
||||
* Supplies the original tool call's arguments and result. They reach the
|
||||
* app once it has initialized, whichever happens last, and only once.
|
||||
*/
|
||||
readonly setToolCall: (call: {
|
||||
readonly arguments: unknown;
|
||||
readonly result: McpAppCallToolResult | undefined;
|
||||
}) => void;
|
||||
/** Sends `host-context-changed` with the fields that differ from what the app last saw. */
|
||||
readonly updateHostContext: () => void;
|
||||
/**
|
||||
* Asks the app to wrap up before its document goes away (`ui/resource-teardown`),
|
||||
* resolving once it answers or after a short timeout, then disposes the host.
|
||||
*/
|
||||
readonly teardown: () => Promise<void>;
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
function jsonBytes(value: unknown): number {
|
||||
try {
|
||||
return encoder.encode(JSON.stringify(value) ?? "").byteLength;
|
||||
} catch {
|
||||
return Number.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
function isId(value: unknown): value is JsonRpcId {
|
||||
return typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* A `CallToolResult` as the spec's schema accepts it. Providers can report
|
||||
* absent fields as null (Codex sends `_meta: null`), which the MCP Apps SDK
|
||||
* rejects, dropping the whole notification or response.
|
||||
*/
|
||||
function normalizeMcpAppToolResult(result: McpAppCallToolResult): McpAppCallToolResult {
|
||||
return {
|
||||
content: Array.isArray(result.content) ? result.content : [],
|
||||
...(Predicate.isObject(result.structuredContent)
|
||||
? { structuredContent: result.structuredContent }
|
||||
: {}),
|
||||
...(result.isError === true ? { isError: true } : {}),
|
||||
...(Predicate.isObject(result._meta) ? { _meta: result._meta } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const errorMessage = (error: unknown) =>
|
||||
error instanceof McpAppHostRefusal
|
||||
? error.message
|
||||
: error instanceof Error && error.message.trim() !== ""
|
||||
? error.message
|
||||
: "Request failed.";
|
||||
|
||||
export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost {
|
||||
let initialized = false;
|
||||
let disposed = false;
|
||||
let toolCall:
|
||||
| { readonly arguments: unknown; readonly result: McpAppCallToolResult | undefined }
|
||||
| undefined;
|
||||
let toolCallSent = false;
|
||||
let pending = 0;
|
||||
let sentContext: McpAppHostContext | undefined;
|
||||
/** Modes the app declared at initialize; undefined when it declared none. */
|
||||
let appDisplayModes: ReadonlyArray<string> | undefined;
|
||||
let nextHostRequestId = 0;
|
||||
const hostRequests = new Map<string, () => void>();
|
||||
|
||||
const post = (message: unknown) => {
|
||||
if (!disposed) options.post(message);
|
||||
};
|
||||
const notify = (method: string, params: unknown) => post({ jsonrpc: "2.0", method, params });
|
||||
const respond = (id: JsonRpcId, result: unknown) => post({ jsonrpc: "2.0", id, result });
|
||||
const fail = (id: JsonRpcId, code: number, message: string) =>
|
||||
post({ jsonrpc: "2.0", id, error: { code, message } });
|
||||
|
||||
const sendToolCall = () => {
|
||||
if (!initialized || toolCall === undefined || toolCallSent) return;
|
||||
toolCallSent = true;
|
||||
notify("ui/notifications/tool-input", {
|
||||
arguments: Predicate.isObject(toolCall.arguments) ? toolCall.arguments : {},
|
||||
});
|
||||
if (toolCall.result !== undefined) {
|
||||
notify("ui/notifications/tool-result", normalizeMcpAppToolResult(toolCall.result));
|
||||
}
|
||||
};
|
||||
|
||||
const answer = (id: JsonRpcId, run: () => Promise<unknown>) => {
|
||||
if (pending >= MAX_PENDING_REQUESTS) {
|
||||
fail(id, -32000, "Too many requests in flight.");
|
||||
return;
|
||||
}
|
||||
pending += 1;
|
||||
void run().then(
|
||||
(result) => {
|
||||
pending -= 1;
|
||||
respond(id, result);
|
||||
},
|
||||
(error: unknown) => {
|
||||
pending -= 1;
|
||||
fail(id, -32000, errorMessage(error));
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleRequest = (id: JsonRpcId, method: string, params: Record<PropertyKey, unknown>) => {
|
||||
switch (method) {
|
||||
case "ui/initialize": {
|
||||
const requested = params.protocolVersion;
|
||||
const declared = Predicate.isObject(params.appCapabilities)
|
||||
? params.appCapabilities.availableDisplayModes
|
||||
: undefined;
|
||||
appDisplayModes = Array.isArray(declared)
|
||||
? declared.filter((mode): mode is string => typeof mode === "string")
|
||||
: undefined;
|
||||
sentContext = options.hostContext();
|
||||
respond(id, {
|
||||
protocolVersion:
|
||||
requested === MCP_APP_PROTOCOL_VERSION ? requested : MCP_APP_PROTOCOL_VERSION,
|
||||
hostInfo: { name: "t3-code", version: options.hostVersion },
|
||||
hostCapabilities: {
|
||||
openLinks: {},
|
||||
serverTools: {},
|
||||
serverResources: {},
|
||||
logging: {},
|
||||
message: { text: {} },
|
||||
updateModelContext: { text: {}, structuredContent: {} },
|
||||
downloadFile: {},
|
||||
sandbox: {
|
||||
...(options.app.csp === undefined ? {} : { csp: options.app.csp }),
|
||||
...(options.app.permissions === undefined
|
||||
? {}
|
||||
: { permissions: options.app.permissions }),
|
||||
},
|
||||
},
|
||||
hostContext: sentContext,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "ping":
|
||||
respond(id, {});
|
||||
return;
|
||||
case "tools/call": {
|
||||
const name = params.name;
|
||||
const args = params.arguments ?? {};
|
||||
if (typeof name !== "string" || name.trim() === "" || !Predicate.isObject(args)) {
|
||||
fail(id, -32602, "tools/call needs a tool name and object arguments.");
|
||||
return;
|
||||
}
|
||||
answer(id, () =>
|
||||
options
|
||||
.callTool({ name, arguments: args as Record<string, unknown> })
|
||||
.then(normalizeMcpAppToolResult),
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "resources/read": {
|
||||
const uri = params.uri;
|
||||
if (typeof uri !== "string" || uri.trim() === "") {
|
||||
fail(id, -32602, "resources/read needs a uri.");
|
||||
return;
|
||||
}
|
||||
answer(id, () => options.readResource({ uri }));
|
||||
return;
|
||||
}
|
||||
case "ui/open-link": {
|
||||
const url = params.url;
|
||||
if (typeof url !== "string" || !/^https?:\/\//i.test(url)) {
|
||||
fail(id, -32602, "Only http(s) links can be opened.");
|
||||
return;
|
||||
}
|
||||
answer(id, () => options.openLink(url).then(() => ({})));
|
||||
return;
|
||||
}
|
||||
case "ui/message": {
|
||||
// The SDK sends an array of content blocks; the spec text shows one block.
|
||||
const blocks = Array.isArray(params.content) ? params.content : [params.content];
|
||||
const texts = blocks.map((block) =>
|
||||
Predicate.isObject(block) && block.type === "text" && typeof block.text === "string"
|
||||
? block.text
|
||||
: undefined,
|
||||
);
|
||||
if (params.role !== "user" || texts.length === 0 || texts.includes(undefined)) {
|
||||
fail(id, -32602, "Only text messages from the user role are supported.");
|
||||
return;
|
||||
}
|
||||
const text = texts.join("\n").trim();
|
||||
if (text === "") {
|
||||
fail(id, -32602, "ui/message needs non-empty text.");
|
||||
return;
|
||||
}
|
||||
answer(id, () => options.sendMessage(text).then(() => ({})));
|
||||
return;
|
||||
}
|
||||
case "ui/request-display-mode": {
|
||||
const current = options.hostContext().displayMode;
|
||||
const mode = params.mode;
|
||||
// A mode the host lacks, or the app did not declare, leaves the
|
||||
// current one; the spec has the host answer with whichever applies.
|
||||
const allowed =
|
||||
typeof mode === "string" &&
|
||||
options.hostContext().availableDisplayModes.includes(mode as McpAppDisplayMode) &&
|
||||
(appDisplayModes === undefined || appDisplayModes.includes(mode));
|
||||
if (!allowed || mode === current) {
|
||||
respond(id, { mode: current });
|
||||
return;
|
||||
}
|
||||
answer(id, () =>
|
||||
options
|
||||
.requestDisplayMode(mode as McpAppDisplayMode)
|
||||
.then((result) => ({ mode: result })),
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "ui/update-model-context": {
|
||||
const content = params.content;
|
||||
const structured = params.structuredContent;
|
||||
if (
|
||||
(content !== undefined && !Array.isArray(content)) ||
|
||||
(structured !== undefined && !Predicate.isObject(structured))
|
||||
) {
|
||||
fail(
|
||||
id,
|
||||
-32602,
|
||||
"Model context needs content blocks or an object of structured content.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
answer(id, () =>
|
||||
options
|
||||
.updateModelContext({
|
||||
...(content === undefined ? {} : { content }),
|
||||
...(structured === undefined
|
||||
? {}
|
||||
: { structuredContent: structured as Record<string, unknown> }),
|
||||
})
|
||||
.then(() => ({})),
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "ui/download-file": {
|
||||
const files = readDownloads(params.contents);
|
||||
if (files === undefined) {
|
||||
fail(id, -32602, "ui/download-file needs embedded resources or resource links.");
|
||||
return;
|
||||
}
|
||||
answer(id, () =>
|
||||
options.downloadFile(files).then(
|
||||
() => ({}),
|
||||
// The draft reports a refused or failed download in the result.
|
||||
(error: unknown) =>
|
||||
error instanceof McpAppHostRefusal ? { isError: true } : Promise.reject(error),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
fail(id, -32601, `Method not found: ${method}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNotification = (method: string, params: Record<PropertyKey, unknown>) => {
|
||||
switch (method) {
|
||||
case "ui/notifications/initialized": {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
sendToolCall();
|
||||
// The theme or size may have changed since the initialize response.
|
||||
hostHandle.updateHostContext();
|
||||
return;
|
||||
}
|
||||
case "ui/notifications/size-changed": {
|
||||
const width = typeof params.width === "number" ? params.width : undefined;
|
||||
const height = typeof params.height === "number" ? params.height : undefined;
|
||||
if (width !== undefined || height !== undefined) {
|
||||
options.onSizeChanged({
|
||||
...(width === undefined ? {} : { width }),
|
||||
...(height === undefined ? {} : { height }),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "ui/notifications/request-teardown":
|
||||
options.onRequestTeardown();
|
||||
return;
|
||||
default:
|
||||
// notifications/message (logging) and unknown notifications are ignored.
|
||||
}
|
||||
};
|
||||
|
||||
/** A response to a request the host sent the app. */
|
||||
const handleResponse = (id: JsonRpcId) => {
|
||||
const settle = hostRequests.get(String(id));
|
||||
if (settle === undefined) return;
|
||||
hostRequests.delete(String(id));
|
||||
settle();
|
||||
};
|
||||
|
||||
const hostHandle: McpAppHost = {
|
||||
receive: (data) => {
|
||||
if (disposed || !Predicate.isObject(data) || data.jsonrpc !== "2.0") return;
|
||||
if (jsonBytes(data) > MAX_MESSAGE_BYTES) {
|
||||
if (isId(data.id) && typeof data.method === "string") {
|
||||
fail(data.id, -32600, "Message too large.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const method = data.method;
|
||||
if (typeof method !== "string") {
|
||||
if (isId(data.id) && ("result" in data || "error" in data)) handleResponse(data.id);
|
||||
return;
|
||||
}
|
||||
const params = Predicate.isObject(data.params) ? data.params : {};
|
||||
if (isId(data.id)) handleRequest(data.id, method, params);
|
||||
else handleNotification(method, params);
|
||||
},
|
||||
setToolCall: (call) => {
|
||||
toolCall ??= call;
|
||||
sendToolCall();
|
||||
},
|
||||
updateHostContext: () => {
|
||||
// The spec forbids messages before the app finishes initializing; it
|
||||
// reads the then-current context from the initialize response anyway.
|
||||
if (!initialized || sentContext === undefined) return;
|
||||
const next = options.hostContext();
|
||||
const changes: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(next) as Array<keyof McpAppHostContext>) {
|
||||
if (JSON.stringify(next[key]) !== JSON.stringify(sentContext[key])) {
|
||||
changes[key] = next[key];
|
||||
}
|
||||
}
|
||||
sentContext = next;
|
||||
if (Object.keys(changes).length > 0) {
|
||||
notify("ui/notifications/host-context-changed", changes);
|
||||
}
|
||||
},
|
||||
teardown: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const finish = () => {
|
||||
clearTimeout(timer);
|
||||
disposed = true;
|
||||
resolve();
|
||||
};
|
||||
// Before initialization the app has nothing to save and may not be
|
||||
// listening; the spec only asks for teardown after it.
|
||||
if (disposed || !initialized) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
const id = `t3-host-${nextHostRequestId++}`;
|
||||
hostRequests.set(id, finish);
|
||||
timer = setTimeout(() => {
|
||||
hostRequests.delete(id);
|
||||
finish();
|
||||
}, TEARDOWN_TIMEOUT_MS);
|
||||
post({ jsonrpc: "2.0", id, method: "ui/resource-teardown", params: {} });
|
||||
}),
|
||||
dispose: () => {
|
||||
disposed = true;
|
||||
},
|
||||
};
|
||||
return hostHandle;
|
||||
}
|
||||
|
||||
const MAX_DOWNLOAD_NAME = 200;
|
||||
|
||||
/** The file name an app gave a download, or the last part of its URI. */
|
||||
function downloadName(uri: unknown, name: unknown): string {
|
||||
const raw =
|
||||
typeof name === "string" && name.trim() !== ""
|
||||
? name
|
||||
: typeof uri === "string"
|
||||
? (uri.split(/[/?#]/).findLast(Boolean) ?? "download")
|
||||
: "download";
|
||||
// Path separators, reserved characters, and control characters.
|
||||
const safe = Array.from(raw, (char) =>
|
||||
/[\\/:*?"<>|]/.test(char) || char.charCodeAt(0) < 32 ? "-" : char,
|
||||
).join("");
|
||||
return safe.slice(0, MAX_DOWNLOAD_NAME) || "download";
|
||||
}
|
||||
|
||||
/** `ui/download-file` contents: MCP embedded resources and resource links. */
|
||||
function readDownloads(contents: unknown): ReadonlyArray<McpAppDownload> | undefined {
|
||||
if (!Array.isArray(contents) || contents.length === 0) return undefined;
|
||||
const files: Array<McpAppDownload> = [];
|
||||
for (const entry of contents) {
|
||||
if (!Predicate.isObject(entry)) return undefined;
|
||||
if (entry.type === "resource" && Predicate.isObject(entry.resource)) {
|
||||
const resource = entry.resource;
|
||||
const bytes = mcpResourceBytes(resource);
|
||||
if (bytes === undefined) return undefined;
|
||||
files.push({
|
||||
_tag: "embedded",
|
||||
name: downloadName(resource.uri, resource.name),
|
||||
mimeType:
|
||||
typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream",
|
||||
bytes,
|
||||
});
|
||||
} else if (entry.type === "resource_link" && typeof entry.uri === "string") {
|
||||
files.push({
|
||||
_tag: "link",
|
||||
name: downloadName(entry.uri, entry.name),
|
||||
uri: entry.uri,
|
||||
...(typeof entry.mimeType === "string" ? { mimeType: entry.mimeType } : {}),
|
||||
});
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps T3's resolved theme variables to the spec's standardized style names, so
|
||||
* apps written for any MCP Apps host pick up the thread's colors and fonts.
|
||||
*/
|
||||
export function mcpAppStyleVariables(
|
||||
theme: Readonly<Record<string, string>>,
|
||||
): Record<string, string> {
|
||||
const pick = (name: string) => theme[name];
|
||||
const pairs: ReadonlyArray<readonly [string, string | undefined]> = [
|
||||
["--color-background-primary", pick("--background")],
|
||||
["--color-background-secondary", pick("--card")],
|
||||
["--color-background-tertiary", pick("--muted")],
|
||||
["--color-background-inverse", pick("--foreground")],
|
||||
["--color-background-info", pick("--info")],
|
||||
["--color-background-danger", pick("--destructive-surface")],
|
||||
["--color-background-warning", pick("--warning-surface")],
|
||||
["--color-text-primary", pick("--foreground")],
|
||||
["--color-text-secondary", pick("--muted-foreground")],
|
||||
["--color-text-tertiary", pick("--muted-foreground")],
|
||||
["--color-text-inverse", pick("--background")],
|
||||
["--color-text-info", pick("--info-foreground")],
|
||||
["--color-text-danger", pick("--destructive-foreground")],
|
||||
["--color-text-success", pick("--success-foreground")],
|
||||
["--color-text-warning", pick("--warning-foreground")],
|
||||
["--color-border-primary", pick("--border")],
|
||||
["--color-border-secondary", pick("--input")],
|
||||
["--color-border-danger", pick("--destructive")],
|
||||
["--color-ring-primary", pick("--ring")],
|
||||
["--font-sans", pick("--font-sans")],
|
||||
["--font-mono", pick("--font-mono")],
|
||||
["--border-radius-md", pick("--radius")],
|
||||
];
|
||||
const variables: Record<string, string> = {};
|
||||
for (const [name, value] of pairs) {
|
||||
if (value !== undefined && value !== "") variables[name] = value;
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import type { Atom } from "effect/reactivity";
|
||||
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
import { createEnvironmentRpcCommand } from "./runtime.ts";
|
||||
|
||||
/**
|
||||
* RPC commands an MCP App host makes on an app's behalf. Each client
|
||||
* instantiates them with its own connection runtime (`mcpAppEnvironment` in
|
||||
* web and mobile).
|
||||
*/
|
||||
export function createMcpAppEnvironmentAtoms<R, E>(
|
||||
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
|
||||
) {
|
||||
return {
|
||||
callTool: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:mcp-apps:call-tool",
|
||||
tag: WS_METHODS.mcpAppsCallTool,
|
||||
}),
|
||||
toolInfo: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:mcp-apps:tool-info",
|
||||
tag: WS_METHODS.mcpAppsToolInfo,
|
||||
}),
|
||||
readResource: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:mcp-apps:read-resource",
|
||||
tag: WS_METHODS.mcpAppsReadResource,
|
||||
}),
|
||||
updateModelContext: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:mcp-apps:update-model-context",
|
||||
tag: WS_METHODS.mcpAppsUpdateModelContext,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -49,6 +49,7 @@ export * from "./filesystem.ts";
|
||||
export * from "./agentSessions.ts";
|
||||
export * from "./assets.ts";
|
||||
export * from "./review.ts";
|
||||
export * from "./mcpApps.ts";
|
||||
export * from "./browserImport.ts";
|
||||
export * from "./browserProfile.ts";
|
||||
export * from "./device.ts";
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
|
||||
|
||||
/**
|
||||
* Requests an MCP App makes of its own MCP server, through the environment.
|
||||
* Each names the tool call that produced the app; the environment resolves the
|
||||
* app's server from that item, so an app can only reach the server it came from.
|
||||
*/
|
||||
const McpAppTarget = {
|
||||
threadId: ThreadId,
|
||||
itemId: TurnItemId,
|
||||
};
|
||||
|
||||
export const McpAppCallToolInput = Schema.Struct({
|
||||
...McpAppTarget,
|
||||
name: TrimmedNonEmptyString,
|
||||
arguments: Schema.Record(Schema.String, Schema.Unknown),
|
||||
});
|
||||
export type McpAppCallToolInput = typeof McpAppCallToolInput.Type;
|
||||
|
||||
/** MCP `CallToolResult`, passed through to the app unchanged. */
|
||||
export const McpAppCallToolResult = Schema.Struct({
|
||||
content: Schema.Array(Schema.Unknown),
|
||||
structuredContent: Schema.optional(Schema.Unknown),
|
||||
isError: Schema.optional(Schema.Boolean),
|
||||
_meta: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type McpAppCallToolResult = typeof McpAppCallToolResult.Type;
|
||||
|
||||
export const McpAppToolInfoInput = Schema.Struct({
|
||||
...McpAppTarget,
|
||||
name: TrimmedNonEmptyString,
|
||||
});
|
||||
export type McpAppToolInfoInput = typeof McpAppToolInfoInput.Type;
|
||||
|
||||
/**
|
||||
* What a client needs to decide whether to ask before a call: whether the tool
|
||||
* exists for apps and whether its server declares it read-only.
|
||||
*/
|
||||
export const McpAppToolInfo = Schema.Struct({
|
||||
callable: Schema.Boolean,
|
||||
readOnly: Schema.Boolean,
|
||||
title: Schema.optional(Schema.String),
|
||||
/** The server's MCP `Tool` definition, which the host passes to the app as `toolInfo`. */
|
||||
tool: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type McpAppToolInfo = typeof McpAppToolInfo.Type;
|
||||
|
||||
export const McpAppReadResourceInput = Schema.Struct({
|
||||
...McpAppTarget,
|
||||
uri: TrimmedNonEmptyString,
|
||||
});
|
||||
export type McpAppReadResourceInput = typeof McpAppReadResourceInput.Type;
|
||||
|
||||
/** MCP `ReadResourceResult`, passed through to the app unchanged. */
|
||||
export const McpAppReadResourceResult = Schema.Struct({
|
||||
contents: Schema.Array(Schema.Unknown),
|
||||
});
|
||||
export type McpAppReadResourceResult = typeof McpAppReadResourceResult.Type;
|
||||
|
||||
/**
|
||||
* What an app wants the agent to know on its next turn (`ui/update-model-context`).
|
||||
* Each update replaces the app's previous one; no content clears it.
|
||||
*/
|
||||
export const McpAppUpdateModelContextInput = Schema.Struct({
|
||||
...McpAppTarget,
|
||||
/**
|
||||
* The thread whose next turn gets the context: the one on screen, which is
|
||||
* the app's own thread or a fork that shows it.
|
||||
*/
|
||||
conversationThreadId: ThreadId,
|
||||
content: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
structuredContent: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
});
|
||||
export type McpAppUpdateModelContextInput = typeof McpAppUpdateModelContextInput.Type;
|
||||
|
||||
export const McpAppRequestErrorReason = Schema.Literals([
|
||||
"not-an-app",
|
||||
"provider-unsupported",
|
||||
"session-stopped",
|
||||
"tool-not-callable",
|
||||
"unsupported-content",
|
||||
"request-failed",
|
||||
]);
|
||||
export type McpAppRequestErrorReason = typeof McpAppRequestErrorReason.Type;
|
||||
|
||||
export class McpAppRequestError extends Schema.TaggedError<McpAppRequestError>()(
|
||||
"McpAppRequestError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
reason: McpAppRequestErrorReason,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
switch (this.reason) {
|
||||
case "not-an-app":
|
||||
return "This tool call has no MCP app.";
|
||||
case "provider-unsupported":
|
||||
return "This thread's provider cannot run MCP app requests.";
|
||||
case "session-stopped":
|
||||
// A forked thread shows its source's apps, so this names the thread
|
||||
// that made the app rather than the one on screen.
|
||||
return "The app's thread is not running. Send a message in the thread that created it to use the app again.";
|
||||
case "tool-not-callable":
|
||||
return "This app cannot call that tool.";
|
||||
case "unsupported-content":
|
||||
return "Only text and structured content are supported.";
|
||||
case "request-failed":
|
||||
return "The app's MCP server request failed.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,14 @@
|
||||
import { OrchestrationDispatchCommandError } from "./orchestrationDispatch.ts";
|
||||
import {
|
||||
McpAppCallToolInput,
|
||||
McpAppCallToolResult,
|
||||
McpAppReadResourceInput,
|
||||
McpAppReadResourceResult,
|
||||
McpAppRequestError,
|
||||
McpAppToolInfo,
|
||||
McpAppToolInfoInput,
|
||||
McpAppUpdateModelContextInput,
|
||||
} from "./mcpApps.ts";
|
||||
import {
|
||||
ChatGptReconnectProfileInput,
|
||||
ChatGptReconnectProfile,
|
||||
@@ -367,6 +377,12 @@ export const WS_METHODS = {
|
||||
attachmentsCreateUploadUrl: "attachments.createUploadUrl",
|
||||
attachmentsDelete: "attachments.delete",
|
||||
|
||||
// MCP Apps methods
|
||||
mcpAppsCallTool: "mcpApps.callTool",
|
||||
mcpAppsToolInfo: "mcpApps.toolInfo",
|
||||
mcpAppsReadResource: "mcpApps.readResource",
|
||||
mcpAppsUpdateModelContext: "mcpApps.updateModelContext",
|
||||
|
||||
// Provider methods
|
||||
providerUploadFeedback: "provider.uploadFeedback",
|
||||
providerAuthStart: "provider.auth.start",
|
||||
@@ -1232,6 +1248,29 @@ const WsAttachmentsDeleteRpc = Rpc.make(WS_METHODS.attachmentsDelete, {
|
||||
error: EnvironmentAuthorizationError,
|
||||
});
|
||||
|
||||
const WsMcpAppsCallToolRpc = Rpc.make(WS_METHODS.mcpAppsCallTool, {
|
||||
payload: McpAppCallToolInput,
|
||||
success: McpAppCallToolResult,
|
||||
error: Schema.Union([McpAppRequestError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
const WsMcpAppsToolInfoRpc = Rpc.make(WS_METHODS.mcpAppsToolInfo, {
|
||||
payload: McpAppToolInfoInput,
|
||||
success: McpAppToolInfo,
|
||||
error: Schema.Union([McpAppRequestError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
const WsMcpAppsUpdateModelContextRpc = Rpc.make(WS_METHODS.mcpAppsUpdateModelContext, {
|
||||
payload: McpAppUpdateModelContextInput,
|
||||
error: Schema.Union([McpAppRequestError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
const WsMcpAppsReadResourceRpc = Rpc.make(WS_METHODS.mcpAppsReadResource, {
|
||||
payload: McpAppReadResourceInput,
|
||||
success: McpAppReadResourceResult,
|
||||
error: Schema.Union([McpAppRequestError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
const WsProviderUploadFeedbackRpc = Rpc.make(WS_METHODS.providerUploadFeedback, {
|
||||
payload: ProviderUploadFeedbackInput,
|
||||
success: ProviderUploadFeedbackResult,
|
||||
@@ -1856,6 +1895,10 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsAssetsPersistChatAttachmentsRpc,
|
||||
WsAttachmentsCreateUploadUrlRpc,
|
||||
WsAttachmentsDeleteRpc,
|
||||
WsMcpAppsCallToolRpc,
|
||||
WsMcpAppsToolInfoRpc,
|
||||
WsMcpAppsReadResourceRpc,
|
||||
WsMcpAppsUpdateModelContextRpc,
|
||||
WsProviderUploadFeedbackRpc,
|
||||
WsSubscribeVcsStatusRpc,
|
||||
WsSubscribeWorktreeSetupRpc,
|
||||
|
||||
@@ -402,6 +402,10 @@
|
||||
"./codexAuthHandoff": {
|
||||
"types": "./src/codexAuthHandoff.ts",
|
||||
"import": "./src/codexAuthHandoff.ts"
|
||||
},
|
||||
"./mcpApp": {
|
||||
"types": "./src/mcpApp.ts",
|
||||
"import": "./src/mcpApp.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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, "&").replace(/"/g, """).replace(/</g, "<");
|
||||
|
||||
/**
|
||||
* 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`;
|
||||
}
|
||||
@@ -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 (
|
||||
|
||||
Reference in new issue
Block a user