MCP Apps
Render interactive UI components from MCP servers directly in your chat interface.
What is this?
MCP Apps are MCP servers that expose tools with associated UI resources. When the agent calls one of these tools, CopilotKit automatically fetches the resource and renders its UI (the widget) in the chat. You do not write any frontend code for it.
Key benefits:
- Zero frontend code: the MCP server serves the widgets
- Full interactivity: widgets can use HTML, CSS, and JavaScript
- Secure sandboxing: widgets run in isolated iframes
- Thread persistence: MCP Apps are stored in conversation history and restored on reconnect
Wire the runtime to your MCP server(s)
Add your MCP server to mcpApps.servers on CopilotRuntime:
// Dedicated runtime for the MCP Apps demo.
//
// `mcpApps.servers` auto-applies the MCP Apps middleware to every registered
// agent: the middleware exposes the remote MCP server's tools to the agent at
// request time and emits the activity events that CopilotKit's built-in
// `MCPAppsActivityRenderer` renders inline as a sandboxed iframe.
const runtime = new CopilotRuntime({
agents: {
"mcp-apps": createMcpAppsAgent(),
// headless-complete shares this runtime because its cell also exercises
// MCP Apps rendering (via a hand-rolled useRenderActivityMessage in
// use-rendered-messages.tsx). Mirrors the LGP reference route.
"headless-complete": createBuiltInAgent(),
},
runner: new InMemoryAgentRunner(),
mcpApps: {
servers: [
{
type: "http",
url: process.env.MCP_SERVER_URL || "https://mcp.excalidraw.com",
// Always pin a stable serverId — without it CopilotKit hashes the URL
// and a URL change silently breaks restoration of persisted MCP apps.
serverId: "excalidraw",
},
],
},
});The runtime adds the MCP Apps middleware to every agent. When an agent calls a
tool with a UI resource, the middleware fetches the resource. The built-in
MCPAppsActivityRenderer then renders the widget in the chat as a sandboxed
iframe.
On an Intelligence runtime, keep mcpApps as it is. See
MCP Apps with Intelligence.
Always pin a serverId
In production, always provide a stable serverId. Without it, CopilotKit
hashes the server URL, and a URL change (for example between environments)
silently breaks restoration of MCP Apps persisted in earlier conversation
threads.
No frontend renderer needed
Unlike custom activity types, the MCP Apps renderer is already registered by
CopilotKit. A plain <CopilotChat /> is enough;
no renderActivityMessages prop, no manual
useRenderActivityMessage wiring.
// No `renderActivityMessages`, no `useRenderActivityMessage` — the
// CopilotKitProvider auto-registers the built-in `MCPAppsActivityRenderer`
// for the "mcp-apps" activity type. A plain <CopilotChat /> is enough.
return (
<CopilotKit runtimeUrl="/api/copilotkit-mcp-apps" agent="mcp-apps">
<div className="flex justify-center items-center h-screen w-full">
<div className="h-full w-full max-w-4xl">
<Chat />
</div>
</div>
</CopilotKit>
);The demo's Chat component renders <CopilotChat agentId="mcp-apps" /> and adds suggestion pills. In your app, render <CopilotChat /> in its place.
To check the setup, ask the agent to draw a flowchart with Excalidraw. The Excalidraw widget renders in the chat as an interactive iframe.
MCP Apps with Intelligence
The mcpApps option works the same way on a runtime connected to
Intelligence. The two options do different jobs:
mcpAppsconfigures the agent side. On every run, the runtime attaches the MCP Apps middleware to the agent.intelligencereplaces the runner. Intelligence stores the threads and runs, so the MCP Apps in a conversation are restored when the thread is loaded.
To move an existing MCP Apps runtime to Intelligence, keep mcpApps as it is.
Remove runner, then add intelligence and identifyUser:
import {
BuiltInAgent,
CopilotKitIntelligence,
CopilotRuntime,
createCopilotRuntimeHandler,
} from "@copilotkit/runtime/v2";
const agent = new BuiltInAgent({
model: "openai/gpt-6-luna",
prompt: "You are a helpful assistant.",
});
const runtime = new CopilotRuntime({
agents: { default: agent },
// Intelligence stores threads and runs. Do not pass `runner` as well.
intelligence: new CopilotKitIntelligence({
apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
}),
// Replace this fixed user with the user from your verified session.
identifyUser: () => ({ id: "demo-user", name: "Demo User" }),
// Unchanged from the in-memory setup.
mcpApps: {
servers: [
{
type: "http",
url: "https://mcp.excalidraw.com/mcp",
serverId: "excalidraw",
},
],
},
});
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
});
export const GET = handler;
export const POST = handler;
export const PATCH = handler;
export const DELETE = handler;Keep the same serverId values when you move to Intelligence. The stored MCP
Apps in a thread refer to the server by that ID.
To give a server to one agent only, add agentId to its entry in
mcpApps.servers. On an Intelligence runtime, prefer this to attaching
MCPAppsMiddleware to the agent yourself: the runtime then checks each request
from an MCP App against the servers of that agent.
For the API key, user identity, and route protection, follow the Intelligence quickstart.
Sandbox and widget storage
Each widget runs in a sandboxed iframe with an opaque origin. Inside the sandbox, a widget:
- cannot read the cookies, storage, or DOM of your page.
- cannot read responses from your APIs, unless an API allows cross-origin
requests (for example with
Access-Control-Allow-Origin: *). - can still send requests. Protect state-changing endpoints against cross-site request forgery, as you do for any other site.
- cannot use
localStorage,sessionStorage,IndexedDB, or cookies of its own.
Requests a widget makes that need CORS, such as <script type="module"> and
fetch, are sent with Origin: null. Serve public widget assets with
Access-Control-Allow-Origin: *. Classic <script src> tags don't need CORS.
To avoid CORS entirely, bundle the widget into a single HTML file, as the
ext-apps examples
do with vite-plugin-singlefile.
The MCP Apps spec pairs allow-same-origin with a sandbox served from a
separate origin. CopilotKit loads the sandbox inline, so it leaves
allow-same-origin off rather than give widgets your page's origin.
If you wrote a widget yourself and it needs storage, you can restore
allow-same-origin:
<CopilotKit runtimeUrl="/api/copilotkit" mcpApps={{ allowSameOriginFallback: true }}>
{children}
</CopilotKit>Only for widgets you trust
If you connect a third-party MCP server, do not set
allowSameOriginFallback. With this option, every widget runs with the
origin of your page. A widget from any connected MCP server can then read
your cookies and storage and act as the signed-in user.
Transport types
The middleware supports two transport types:
HTTP
Use this format to connect to an MCP server that accepts standard HTTP requests:
{
type: "http",
url: "http://localhost:3101/mcp",
serverId: "my-http-server"
}SSE
Use this format to connect to an MCP server that streams events over a persistent connection:
{
type: "sse",
url: "https://mcp.example.com/sse",
headers: {
"Authorization": "Bearer token"
},
serverId: "my-sse-server"
}Let a widget tell the model what the user is looking at
A widget can share its state with the model through
ui/update-model-context: a selection, the filters it shows, a cart. Nothing
appears in the chat and no run starts; the latest state rides along with the
next turns of the conversation.
await app.updateModelContext({
content: [{ type: "text", text: "The user is looking at the Lyon station." }],
structuredContent: { stationId: "lyon", filter: "available" },
});
// Optionally, start a turn that uses it.
await app.sendMessage({
role: "user",
content: [{ type: "text", text: "Which departures are available?" }],
});It is off by default. Turn it on with mcpApps.modelContext in React and
Vue, or provideMCPApps({ modelContext: true }) in Angular:
<CopilotKit runtimeUrl="/api/copilotkit" mcpApps={{ modelContext: true }}>
{children}
</CopilotKit>While it is off, CopilotKit does not announce the capability and answers the request with "method not found".
Only for MCP servers you trust
With modelContext, the widget of any MCP server your agent uses can write
into the system prompt of the built-in agent, as soon as it loads and
without any action from the user, who does not see what it wrote. Don't
enable it if you connect third-party MCP servers.
Once it is on:
- Each update replaces the widget's previous state. There is one state per
widget in a conversation: two different widgets keep separate states, and
two instances of the same widget share one. Sending no content and no
structuredContentclears it. - Text blocks and
structuredContentare supported. Images, audio and resources are refused with an error, and so is a state whose serialized JSON is longer than 32,768 characters (measured on the string's length, not its byte size). - The state belongs to the conversation the widget was opened in and is never sent to another one. It stays in memory while the page is open, survives the widget leaving the screen, and is removed when the conversation is deleted. It is not restored after a page reload.
- The state is sent to the agent in the run's
context. The built-in agent adds it to its prompt; another agent has to readRunAgentInput.contextto use it.
Example MCP servers
Try these open-source MCP Apps servers to get started:
- Excalidraw: collaborative whiteboard rendered in-chat
- modelcontextprotocol/ext-apps: canonical reference implementations
Free course: See this pattern built end-to-end in Build Interactive Agents with Generative UI. This free DeepLearning.AI short course is taught by CopilotKit's CEO. It covers the full Generative UI spectrum (Controlled, Declarative, and Open-Ended).
Choose your AI backend
LangGraph (Python)
LangGraph (TypeScript)
LangGraph (FastAPI)
Langchain DeepAgents
Google ADK
Mastra
CrewAI Flows
PydanticAI
Google Antigravity
OpenAI Agents SDK (Python)
Claude Agent SDK (Python)
Claude Agent SDK (TypeScript)
Agno
AG2
LlamaIndex
AWS Strands (Python)
AWS Strands (TypeScript)
MS Agent Framework (Python)
MS Agent Framework (.NET)
MS Agent Harness (.NET)
How is this guide?