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

+8
View File
@@ -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();
}
});
});
+576
View File
@@ -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,
}),
};
}