Render MCP App UI resources inline in chat with a sandboxed iframe and a JSON-RPC bridge.
MCP Apps lets an MCP server ship a UI resource alongside a tool: a self-contained HTML widget that the chat host renders inline when the tool is called. assistant-ui ships a native renderer. It mounts the widget in a sandboxed iframe through SafeContentFrame and runs a JSON-RPC postMessage bridge, so the widget can call tools, send messages, request a display mode, and read host context.
This page assumes the model already reaches an MCP server through your route (server-side MCP). It adds the widget on top. Servers the browser connects to (user-managed MCP) do not pass a tool's _meta.ui on, so their tools render with your regular tool UI.
How it works
- An MCP tool carries
_meta.ui.resourceUri, aui://URI whose resource has the MIME typetext/html;profile=mcp-app. - The AI SDK forwards that metadata through the message stream, and
@assistant-ui/ai-sdkputs it on the tool-call part aspart.mcp.app. - For such a part, the renderer asks your route for the resource, then mounts it in the iframe. The MCP client stays on the server, so credentials and transport stay out of the browser.
- The widget talks back to the host through the bridge: it can call tools, read resources, and more, all through your route.
The renderer acts only on URIs that start with ui://. A tool whose resourceUri uses another scheme falls through to your regular tool UI. When several renderers could handle a part, a renderer for the tool's name (a toolkit entry or by_name) wins over the MCP App renderer.
Setup
Expose the app tools from the chat route
The AI SDK's tools() already attaches each tool's _meta.ui to the call, so with an MCP-Apps-capable server the part shape needs no extra wiring. The widget comes from the server's metadata, not the model, so every model provider works the same way.
Two things to check on the chat route:
-
Keep app-only tools away from the model. A tool whose
_meta.ui.visibilityis["app"]is for the widget only. With a client you manage, filter withsplitMCPAppTools:import { splitMCPAppTools } from "@ai-sdk/mcp"; const { modelVisible } = splitMCPAppTools(await client.listTools()); const result = streamText({ abortSignal: req.signal, model: openai("gpt-6-luna"), tools: client.toolsFromDefinitions(modelVisible), // ... });AISDKToolkitcallsclient.tools(), which does not apply visibility. Hide an app-only tool there withtools: { name: { disabled: true } }on itsdefineMcpToolkitentry. The widget still reaches it through the host route below. -
Advertise MCP Apps support. A server may return its UI tools only to a client that declares the MCP Apps extension. With your own client, pass
capabilities: mcpAppClientCapabilities(from@ai-sdk/mcp) tocreateMCPClient.AISDKToolkitdoes not pass capabilities, so against such a server use a client you create.
The serverId routing key (see Multiple MCP servers) comes only from callProviderMetadata.mcp.app. A serverId in tool metadata or result _meta is ignored.
Add the host route
The renderer POSTs { method, params } to a route you expose, and the route dispatches to your MCP client. Install the client the route uses:
npm install @ai-sdk/mcpimport { createMCPClient, mcpAppClientCapabilities } from "@ai-sdk/mcp";
const serverUrls = new Map([
["search", process.env.SEARCH_MCP_SERVER_URL!],
["calendar", process.env.CALENDAR_MCP_SERVER_URL!],
]);
const fallbackServerUrl = process.env.MCP_SERVER_URL!;
const clientPromises = new Map<string, ReturnType<typeof createMCPClient>>();
type UiMeta = {
ui?: { visibility?: string[]; [key: string]: unknown };
};
const getClient = (serverId?: string) => {
const url = serverId ? serverUrls.get(serverId) : fallbackServerUrl;
if (!url) throw new Error(`Unknown MCP server: ${serverId}`);
let clientPromise = clientPromises.get(url);
if (!clientPromise) {
clientPromise = createMCPClient({
transport: { type: "http", url },
capabilities: mcpAppClientCapabilities,
}).catch((error) => {
clientPromises.delete(url);
throw error;
});
clientPromises.set(url, clientPromise);
}
return clientPromise;
};
const findListedResource = async (
client: Awaited<ReturnType<typeof createMCPClient>>,
uri: string,
) => {
const seenCursors = new Set<string>();
let cursor: string | undefined;
try {
while (true) {
const result = await client.listResources(
cursor ? { params: { cursor } } : undefined,
);
const match = result.resources.find((resource) => resource.uri === uri);
if (match) return match;
const nextCursor = result.nextCursor;
if (!nextCursor || seenCursors.has(nextCursor)) return undefined;
seenCursors.add(nextCursor);
cursor = nextCursor;
}
} catch {
return undefined;
}
};
export async function POST(req: Request) {
const { method, params } = await req.json();
const client = await getClient(params?.serverId);
switch (method) {
case "mcp-apps/read-resource": {
const { contents } = await client.readResource({ uri: params.uri });
const c = contents.find((x: { uri: string }) => x.uri === params.uri);
const readMeta = (c?._meta as UiMeta | undefined)?.ui;
const listed = readMeta
? undefined
: await findListedResource(client, params.uri);
return Response.json({
uri: params.uri,
mimeType: "text/html;profile=mcp-app",
html: c?.text ?? "",
meta: readMeta ?? (listed?._meta as UiMeta | undefined)?.ui,
});
}
case "tools/call": {
const { tools } = await client.listTools();
const tool = tools.find((t) => t.name === params.name);
const visibility = (tool?._meta as UiMeta | undefined)?.ui?.visibility;
if (!tool || (visibility && !visibility.includes("app"))) {
return Response.json({ error: "Tool not callable" }, { status: 403 });
}
return Response.json(
await client.callTool({
name: params.name,
arguments: params.arguments ?? {},
}),
);
}
case "resources/read":
return Response.json(await client.readResource({ uri: params.uri }));
case "resources/list": {
const { serverId: _, ...listParams } = params ?? {};
return Response.json(await client.listResources({ params: listParams }));
}
default:
return Response.json({ error: "Unsupported method" }, { status: 400 });
}
}The renderer sends exactly four methods: mcp-apps/read-resource, tools/call, resources/read, and resources/list. Reject anything else, and apply your own auth and rate limiting here.
The client declares mcpAppClientCapabilities, because a server may list its UI tools only to a client that supports MCP Apps. tools/call refuses a tool whose _meta.ui.visibility leaves out "app", as the MCP Apps spec requires of a host; a tool with no visibility is callable by both the model and the app. The sample reads only the first page of listTools(); follow nextCursor if your server paginates.
Return the resource's _meta.ui object as meta. Metadata on the resources/read content item overrides the matching resources/list entry, so fall back to the list entry only when the content item has none. The renderer enforces the csp declaration before any widget code runs. connectDomains, resourceDomains, frameDomains, and baseUriDomains accept HTTP(S) origins (connectDomains also accepts WebSocket origins), and malformed entries are ignored. A declaration you omit stays restricted, including connect-src 'none' and frame-src 'none'.
Mount the renderer
Compose McpAppRenderer({ ... }) into your Tools resource and point host at the route. Any tool-call part carrying mcp.app then renders its widget:
import {
AuiConfig,
AuiProvider,
Tools,
McpAppRenderer,
McpAppsRemoteHost,
useAui,
} from "@assistant-ui/react";
function MyAssistant({ children }) {
const aui = useAui();
const config = AuiConfig({
tools: Tools({
toolkit: myToolkit,
mcpApp: McpAppRenderer({
host: McpAppsRemoteHost({ url: "/api/mcp-apps" }),
hostInfo: { name: "my-app", version: "1.0.0" },
hostContext: { theme: "light" },
}),
}),
});
return (
<AuiProvider extends={aui} config={config}>
{children}
</AuiProvider>
);
}McpAppsRemoteHost({ url, headers, fetch }) is the default host. Changes to headers or fetch apply to later requests without reloading the widget. When the account or workspace changes, key the host so its resource reloads. This needs @assistant-ui/tap:
import { withKey } from "@assistant-ui/tap";
const mcpApp = McpAppRenderer({
host: withKey(
workspaceId,
McpAppsRemoteHost({
url: "/api/mcp-apps",
headers: () => getWorkspaceHeaders(workspaceId),
}),
),
});To fetch some other way (a client-side MCP client, say), write a resource that returns the McpAppsHost shape: { loadResource, callTool, readResource, listResources }. Keep its identity stable across renders; an unstable host identity keeps the widget in loadingFallback while it refetches on every parent render.
Renderer options
| Option | Purpose |
|---|---|
host | Required. Where the data comes from (see above). |
hostInfo | { name, version } sent to the widget in ui/initialize. |
hostContext | { theme, displayMode, availableDisplayModes, ... }. Sent on initialize and again whenever it changes. |
handlers | Widget interaction and lifecycle callbacks, below. |
sandbox | Iframe options, see Sandbox. |
maxHeight | Upper bound in pixels for the widget-driven auto-resize. Defaults to 800. |
fallback, loadingFallback, errorFallback | Rendered when the part has no app, while the resource loads (defaults to fallback), and when loading fails (a node or (error) => node, defaults to fallback). |
forPart | Resolve options for one app, see Per-app options. |
Handlers
openLink defaults to window.open(url, "_blank", "noopener,noreferrer"). sendMessage defaults to appending the text to the thread composer, after any draft, for the user to review and send. It reads the MCP Apps { role, content } params (joining each text block with a newline) or the legacy string, { prompt }, { text }, and { message } forms. Non-text blocks are dropped, and a request with no text resolves to { isError: true }.
Pass handlers for host-side UI or lifecycle callbacks. The capabilities are advertised during mount, so provide them before the widget initializes:
McpAppRenderer({
host: McpAppsRemoteHost({ url: "/api/mcp-apps" }),
handlers: {
allowedTools: ["refresh_map"],
requestDisplayMode: ({ mode }) => applyHostDisplayMode(mode),
updateModelContext: applyHostModelContext,
},
});Your handlers override the default openLink and sendMessage, and can add requestDisplayMode, updateModelContext, allowedTools, and the lifecycle hooks onInitialized, onSizeChange, onLog, onError, and onRequestTeardown. callTool, readResource, and listResources stay bound to host; use a custom host to change them.
requestDisplayMode should update the host chrome and return the mode it actually honored. Echoing { mode } without applying it tells the widget the change worked while the host stays inline. If changing modes moves the app between layout regions, follow the state-preserving placement guidance so the iframe does not reload.
Per-app options
One renderer serves every app in the thread, so hostContext, handlers, and the other options are thread-wide defaults. forPart runs for each MCP-app tool call, and every option it returns replaces the thread-wide one for that app alone. handlers is the exception: it merges per key, because its keys are capabilities negotiated with the widget, and replacing the whole bag to add one would withdraw the rest with nothing to observe it by.
const [modes, setModes] = useState<Record<string, McpAppDisplayMode>>({});
const declaredModes = useRef(
new Map<string, McpAppDisplayMode[] | undefined>(),
);
const grantedModes = useRef(new Map<string, McpAppDisplayMode>());
McpAppRenderer({
host: McpAppsRemoteHost({ url: "/api/mcp-apps" }),
hostInfo: { name: "my-app", version: "1.0.0" },
hostContext: { theme },
forPart: (part) => ({
hostContext: {
theme,
displayMode: modes[part.toolCallId] ?? "inline",
availableDisplayModes: ["inline", "fullscreen", "pip"],
},
handlers: {
onInitialized: ({ appCapabilities }) => {
declaredModes.current.set(
part.toolCallId,
appCapabilities?.availableDisplayModes,
);
},
requestDisplayMode: ({ mode }) => {
const declared = declaredModes.current.get(part.toolCallId);
if (declared && !declared.includes(mode)) {
return {
mode: grantedModes.current.get(part.toolCallId) ?? "inline",
};
}
grantedModes.current.set(part.toolCallId, mode);
setModes((current) => ({ ...current, [part.toolCallId]: mode }));
return { mode };
},
},
}),
});The resolver closes over the part, so requestDisplayMode knows which app asked, and the granted mode reaches that app alone through notifications/host_context/changed. A host context that is structurally unchanged never reaches the widget, so rebuilding it every render is fine.
onInitialized receives what the app sent in ui/initialize, including appCapabilities.availableDisplayModes. The spec forbids switching an app into a mode missing from that list, so the example answers such a request with the last granted mode. The declared and granted modes live in refs because an app can send its next request before the host re-renders.
forPart resolves before a part's first render. A later change reaches the widget as follows: hostContext is delivered again whenever it changes; handlers are called through live references, but which handler keys exist is fixed when the frame mounts, so return the same keys for a part on every render; hostInfo and the sandbox frame settings (apart from className and style) are read once at mount, so changing them does nothing until the app's resource URI changes and the frame is rebuilt.
Multiple MCP servers
When a part carries mcp.app.serverId, the renderer forwards it to the host operations as params.serverId, so your route can pick the client that owns the resource or tool. With @ag-ui/mcp-apps-middleware, assistant-ui uses the configured serverId and falls back to serverHash when serverId is absent or empty. Match the route's map keys to whichever identity your setup emits: configure an explicit serverId per middleware server, or key the map by the emitted hashes. A part with no serverId uses the fallback client, as in the route example.
OpenAI Apps SDK servers
OpenAI Apps SDK servers use a different convention for the same ui:// template. The pointer is _meta["openai/outputTemplate"] on the tool definition, not _meta.ui.resourceUri, and the resource is served as text/html+skybridge. @ai-sdk/mcp does not read openai/outputTemplate, so it never fills toolMetadata.app and the renderer stays idle.
The renderer needs no change; you surface the pointer. assistant-ui also reads result._meta.ui.resourceUri (and the deprecated flat "ui/resourceUri") off tool results, so the smallest bridge copies the template onto each result by tool name:
import type { Tool } from "ai";
// Reuse the listTools() result from the chat route; no second round-trip.
const templateByTool = new Map(
tools.tools
.filter((t) => typeof t._meta?.["openai/outputTemplate"] === "string")
.map((t) => [t.name, t._meta["openai/outputTemplate"] as string]),
);
const withTemplateUri = (tool: Tool, name: string): Tool => {
const uri = templateByTool.get(name);
const exec = tool.execute;
if (!uri || !exec) return tool;
return {
...tool,
execute: async (args, options) => {
const result = (await exec(args, options)) as { _meta?: Record<string, unknown> };
return {
...result,
_meta: {
...result._meta,
ui: { ...(result._meta?.["ui"] as Record<string, unknown>), resourceUri: uri },
},
};
},
} satisfies Tool;
};
const aiTools = await client.tools();
const wrappedTools = Object.fromEntries(
Object.entries(aiTools).map(([name, t]) => [name, withTemplateUri(t, name)]),
);
// pass wrappedTools to streamTextIn the mcp-apps/read-resource handler, return mimeType: "text/html;profile=mcp-app" and keep the server's HTML in html. Do not forward the raw text/html+skybridge value, which McpAppResource rejects. If a later @ai-sdk/mcp includes the pointer in tool metadata, @assistant-ui/ai-sdk forwards it as toolMetadata.app and this bridge is unnecessary.
AG-UI integration
With @assistant-ui/react-ag-ui, the backend ties an MCP App to a tool call through an ACTIVITY_SNAPSHOT. Include the tool call ID, the app's ui:// URI, and the server identity when you route across several servers:
{
"type": "ACTIVITY_SNAPSHOT",
"activityType": "mcp-apps",
"content": {
"toolCallId": "call-1",
"resourceUri": "ui://maps/result.html",
"serverId": "maps",
"result": {
"content": [{ "type": "text", "text": "Map ready" }],
"structuredContent": { "center": [37.77, -122.42] },
"_meta": { "initialView": "street" },
"isError": false
}
}
}serverId is optional, and the runtime accepts serverHash as a fallback. Older middleware may omit toolCallId, in which case the snapshot applies to the last resolved tool call; new integrations should include it so concurrent calls stay correlated. Emit the snapshot after the call's TOOL_CALL_START. A snapshot naming a tool call restored from history applies to that message directly, so re-emitting it after a MESSAGES_SNAPSHOT rehydrates the widget. A snapshot for a tool call ID the runtime has never seen is ignored without a warning.
Also send the normal TOOL_CALL_RESULT with a short summary for the model:
{ "type": "TOOL_CALL_RESULT", "toolCallId": "call-1", "content": "Map ready" }The snapshot's result becomes the widget-visible part.result. The content string stays with the model as part.modelContent, a text content-part array ([{ "type": "text", "text": "Map ready" }]).
Alternatively, put the MCP host fields on TOOL_CALL_RESULT itself:
{
"type": "TOOL_CALL_RESULT",
"toolCallId": "call-1",
"content": "Map ready",
"structuredContent": { "center": [37.77, -122.42] },
"_meta": { "initialView": "street" },
"isError": false
}The runtime then builds a CallToolResult-shaped part.result from content, structuredContent, _meta, and isError. At least one of structuredContent or _meta must be present; with neither, the enriched path does not activate and the result is the plain content string. The _meta can carry the app pointer itself (ui.resourceUri, or the deprecated flat "ui/resourceUri"), so no snapshot is needed to activate the widget. A snapshot remains the only carrier for serverId, and when both supply a resourceUri, the snapshot wins.
The visibility split follows the MCP Apps contract: content is model-visible, while structuredContent and _meta reach only the host and widget. When assistant-ui serializes history into a later AG-UI request, it sends the saved model-visible text and omits both.
Bridge protocol
The bridge speaks the MCP UI JSON-RPC protocol over window.postMessage. It accepts a message only when event.source is this widget's window and event.origin is the cross-origin domain SafeContentFrame issued for the render. Anything else is dropped without a response.
Capabilities follow the handlers you provide. A request for a missing handler returns JSON-RPC -32601, bad params return -32602, and ui/initialize reports the capability as unavailable.
Widget to host requests
| Method | Notes |
|---|---|
ui/initialize | Returns { protocolVersion, host, hostContext, capabilities }. Always supported. |
tools/call | Sent to your route as tools/call. handlers.allowedTools, when set, rejects other names. A non-object arguments returns -32602. |
resources/read | Sent to your route as resources/read. |
resources/list | Sent to your route as resources/list. |
openLink | Rejects non-http(s) URLs with -32602. |
sendMessage | Needs the sendMessage handler (provided by default). |
requestDisplayMode | Needs handlers.requestDisplayMode. Modes: inline, fullscreen, pip. |
updateModelContext | Needs handlers.updateModelContext. |
Host to widget notifications
notifications/tools/call/input: sent wheneverpart.args(the streaming tool input) changes.notifications/tools/call/result: sent when the result lands, including error envelopes.notifications/host_context/changed: sent whenhostContextchanges, for example when the user toggles the theme.
Widget to host notifications
The widget sends notifications/initialized, notifications/size_changed, notifications/log, notifications/error, and notifications/request_teardown. Handle them with onInitialized, onSizeChange, onLog, onError, and onRequestTeardown. onInitialized receives the app's ui/initialize params as McpAppInitializeParams (appInfo, appCapabilities, protocolVersion); a malformed field is omitted, and availableDisplayModes keeps only modes the bridge recognizes. If the widget never sends notifications/initialized, the host flushes its queued notifications after 5 seconds so the iframe does not look hung.
Sandbox and security
Each widget is served from its own hashed cross-origin domain through SafeContentFrame, so it cannot reach the host page. The iframe always has the allow-same-origin allow-scripts sandbox flags, and sandbox.sandbox adds more. How Safe Content Frame works covers how the domain is chosen.
McpAppRenderer({
// ...
sandbox: {
sandbox: ["allow-popups"],
enableBrowserCaching: true,
className: "my-mcp-app",
},
});enableBrowserCaching derives the hash salt from the content; without it each render uses a random salt.
- Your host route is the auth boundary. The renderer trusts what the route returns. Apply session checks and rate limits there.
- A widget can call tools through your route.
tools/callreaches your MCP client, so without a limit a widget can invoke any tool the route allows, not only its own. Restrict it withhandlers.allowedToolsin the renderer and a per-tool allowlist in the route. - Preserve
_meta.ui.csp. The renderer enforces it inside the widget document. Omitted or malformed declarations get restrictive defaults. - Treat
openLinkURLs as untrusted. The bridge rejects non-http(s)schemes, but a handler you write should still open links withnoopener,noreferrer. - A widget's HTML and tool results are untrusted input to the model and the user.
sendMessageonly fills the composer for the user to review, andupdateModelContextis a handler you choose to provide.
Troubleshooting
| Symptom or message | Cause and fix |
|---|---|
| Nothing renders, and the regular tool UI shows | The part has no mcp.app. The tool lacks _meta.ui.resourceUri, its URI does not start with ui://, or the metadata did not reach the part (an OpenAI Apps SDK server, see above). |
| The tool renders your own component instead | A renderer registered for the tool name wins over the MCP App renderer. Remove it. |
MCP App host request "mcp-apps/read-resource" to "/api/mcp-apps" failed with 500: ... | The route threw. The route's error message follows the status. |
Invalid MCP App host response "mcp-apps/read-resource" from "...": expected a resource with non-empty string "uri" and "html" fields | The route returned an empty html, often because the content item has a blob instead of text, or its uri does not match. |
Invalid MCP App host response "...": expected valid JSON | The route returned HTML or text, for example a login redirect. |
The widget stays on loadingFallback and refetches | The host identity changes on every render. Keep it stable. |
| The widget loads but its network calls or images are blocked | The resource omits that origin from _meta.ui.csp. Add it to connectDomains or resourceDomains, and return meta from the route. |
tool 'name' is not allowed for this app | The widget called a tool outside handlers.allowedTools. |
openLink only accepts http(s) URLs | The widget asked to open another scheme. |
requestDisplayMode is not supported by this host or updateModelContext is not supported by this host | The widget called a method whose handler you did not provide. Add it to handlers. |
| An AG-UI widget never appears | The snapshot's toolCallId is unknown to the runtime, or it arrived before TOOL_CALL_START. |