Open History to see the last commit
1---
2title: MCP Apps
3id: mcp-apps
4order: 12
5description: "Render interactive ui:// widget resources returned by MCP servers — static display via UIResourcePart and full interactivity via createMcpAppCallHandler and createMcpAppBridge."
6keywords:
7 - tanstack ai
8 - mcp
9 - mcp apps
10 - ui resource
11 - UIResourcePart
12 - MCPAppResource
13 - createMcpAppCallHandler
14 - createMcpAppBridge
15 - useMcpAppBridge
16 - interactive widgets
17---
18
19**MCP Apps** is a ratified MCP extension (standardized 2026-01-26) that lets MCP servers return interactive `ui://` resource widgets alongside normal tool results. Instead of the model receiving raw JSON, the server embeds a resource URI that TanStack AI fetches and streams to the client as a `UIResourcePart` — ready to render as a full interactive iframe widget.
20
21There are two levels of MCP Apps support:
22
23- **Static** — the MCP tool result contains a `ui://` resource. TanStack AI reads it during the `chat()` run and surfaces it as a `UIResourcePart` on the assistant `UIMessage`. No extra routes needed; render it with `MCPAppResource`.
24- **Interactive** — the widget's iframe posts tool-call or prompt actions back. You mount a server handler (`createMcpAppCallHandler`) at a route and wire a client bridge (`createMcpAppBridge`) so those actions reach the right MCP server.
25
26## Static Widgets
27
28When an MCP tool's result carries a `ui://` resource, TanStack AI emits a `UIResourcePart` on the assistant `UIMessage`. The part is added to the message's `parts` array **alongside** the normal `ToolResultPart` — it never enters model input.
29
30### The `UIResourcePart` shape
31
32```ts
33import type { UIResourcePart } from '@tanstack/ai'
34
35// Arrives on the assistant UIMessage alongside ToolCallPart / ToolResultPart:
36// {
37// type: 'ui-resource'
38// resource: { uri: string; mimeType: string; text?: string; blob?: string }
39// serverId?: string // pool prefix / config key — routes interactive calls
40// toolCallId: string // links to the originating tool call
41// toolName: string // MCP tool name whose UI this resource renders
42// meta?: Record<string, unknown> // reserved — currently always undefined
43// }
44```
45
46No server-side changes are needed beyond connecting an MCP server that returns `ui://` resources. The resource is read eagerly during the chat run. If the read fails (network error, missing resource), the tool result still flows to the model — the widget is simply absent (**fail-soft**).
47
48### Server route
49
50```ts ignore
51// src/routes/api.chat.ts (TanStack Start)
52import { createFileRoute } from '@tanstack/react-router'
53import { chat, toServerSentEventsResponse } from '@tanstack/ai'
54import { openaiText } from '@tanstack/ai-openai'
55import { createMCPClient } from '@tanstack/ai-mcp'
56
57export const Route = createFileRoute('/api/chat')({
58 server: {
59 handlers: {
60 POST: async ({ request }) => {
61 const { messages } = await request.json()
62
63 const mcp = await createMCPClient({
64 transport: {
65 type: 'http',
66 url: process.env.MCP_URL!,
67 },
68 })
69
70 const stream = chat({
71 adapter: openaiText('gpt-5.5'),
72 messages,
73 mcp: { clients: [mcp] },
74 })
75
76 return toServerSentEventsResponse(stream)
77 },
78 },
79 },
80})
81```
82
83### React client — rendering a static widget
84
85Install the optional peer dependency:
86
87<!-- ::start:tabs variant="package-manager" mode="install" -->
88
89react: @mcp-ui/client
90preact: @mcp-ui/client
91
92<!-- ::end:tabs -->
93
94Then render each `ui-resource` part from the assistant message.
95
96> **What is `sandbox`?** `sandbox.url` points to a small static **sandbox-proxy HTML page that you host** (e.g. `mcp-sandbox.html` on your own origin). `AppRenderer` loads that page in an isolated iframe and renders the widget inside it — it's the security boundary, so it's a **deploy-time constant, the same for every widget**. It is *not* the widget's address: the widget's identity and HTML come from the message part (`part.resource`, a `ui://…` resource). See [`@mcp-ui/client`](https://mcpui.dev) for the proxy page.
97
98```tsx
99// src/components/Chat.tsx
100import { useChat } from '@tanstack/ai-react'
101import { fetchServerSentEvents } from '@tanstack/ai-client'
102import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
103import type { UIResourcePart } from '@tanstack/ai'
104
105export function Chat() {
106 const { messages, sendMessage, status } = useChat({
107 connection: fetchServerSentEvents('/api/chat'),
108 })
109
110 return (
111 <div>
112 {messages.map((m) => (
113 <div key={m.id}>
114 {m.parts.map((part, i) => {
115 if (part.type === 'text') {
116 return <p key={i}>{part.content}</p>
117 }
118 if (part.type === 'ui-resource') {
119 return (
120 <MCPAppResource
121 key={i}
122 part={part}
123 // your hosted sandbox-proxy page (a host constant, not the widget URL)
124 sandbox={{ url: new URL('https://your-app.example.com/mcp-sandbox.html') }}
125 />
126 )
127 }
128 return null
129 })}
130 </div>
131 ))}
132 <button
133 onClick={() => sendMessage({ content: 'Show me the weather widget' })}
134 disabled={status === 'streaming'}
135 >
136 Send
137 </button>
138 </div>
139 )
140}
141```
142
143`MCPAppResource` is powered by `@mcp-ui/client`'s `AppRenderer` under the hood. Without a `bridge` prop the widget renders in display-only mode — user interactions inside the iframe that trigger tool calls or prompts are ignored.
144
145> **Framework support:** React and Preact are shipped (`@tanstack/ai-react/mcp-apps` and `@tanstack/ai-preact/mcp-apps`). Preact requires a `preact/compat` alias. Solid, Vue, Svelte, and Angular wrappers are deferred — `@mcp-ui/client` v7's `AppRenderer` is React-only and a framework-agnostic renderer SDK is future work.
146
147## Interactive Widgets
148
149For widgets that need to call tools or send prompts back to the model, you wire two extra pieces:
150
1511. **Server** — mount `createMcpAppCallHandler` at a POST route. The widget's iframe calls this route.
1522. **Client** — create a `createMcpAppBridge` and pass it to `MCPAppResource`. The bridge routes the iframe's actions (tool calls, prompts, links) to the correct handler.
153
154### Installation
155
156<!-- ::start:tabs variant="package-manager" mode="install" -->
157
158react: @tanstack/ai-mcp @tanstack/ai-client @mcp-ui/client
159preact: @tanstack/ai-mcp @tanstack/ai-client @mcp-ui/client
160
161<!-- ::end:tabs -->
162
163### Server — the call handler route
164
165`createMcpAppCallHandler` from `@tanstack/ai-mcp/apps` accepts the MCP client(s) you already created (a single `MCPClient`, an `MCPClients` pool, or an array of either) and returns a request handler that:
166
167- Resolves each client's transport descriptor via `client.getInfo()` / `pool.getServers()` (pure config — no live socket needed).
168- Reconnects to the MCP server per call using that descriptor (stateless; serverless-safe by default).
169- Checks that the requested `toolName` is actually exposed by that server (same-server allowlist).
170- Calls the tool and returns `{ ok: true, result }` or `{ ok: false, error }`.
171
172```ts ignore
173// src/routes/api.mcp-apps-call.ts (TanStack Start)
174import { createFileRoute } from '@tanstack/react-router'
175import { createMCPClients } from '@tanstack/ai-mcp'
176import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
177
178// Reuse the same pool you pass to chat({ mcp: { clients: [mcp] } }).
179const mcp = await createMCPClients({
180 weather: {
181 transport: {
182 type: 'http',
183 url: process.env.WEATHER_MCP_URL!,
184 headers: { Authorization: `Bearer ${process.env.WEATHER_MCP_TOKEN ?? ''}` },
185 },
186 },
187})
188
189// clients: a single MCPClient, an MCPClients pool, or an array of either.
190// The handler reads each client's transport descriptor via getInfo()/getServers()
191// and reconnects per call — works in long-lived servers and serverless alike.
192const handler = createMcpAppCallHandler({ clients: mcp })
193
194export const Route = createFileRoute('/api/mcp-apps/call')({
195 server: {
196 handlers: {
197 POST: async ({ request }) => {
198 const body = await request.json()
199 // body: { threadId, serverId, toolName, args?, messageId? }
200 const result = await handler(body)
201 return new Response(JSON.stringify(result), {
202 headers: { 'Content-Type': 'application/json' },
203 })
204 },
205 },
206 },
207})
208```
209
210> **`link` actions need an `onLink` handler.** If the widget emits a `link` action and no `onLink` handler is wired in the bridge, the bridge drops the link (logging a warning) and `openLink` returns `{ isError: true }` — the call does not hang, and the widget cannot open arbitrary URLs in the host page. Pass `onLink` explicitly to opt in.
211>
212> Even with an `onLink` handler, the bridge only forwards `http:`, `https:`, and `mailto:` URLs. Unsafe schemes (`javascript:`, `data:`, `file:`, …) are **always rejected** before your handler runs, so a sandboxed widget can't smuggle a script-executing or local-resource URL through.
213
214#### Same-server allowlist
215
216`createMcpAppCallHandler` always verifies that `toolName` is in the list of tools the target server actually exposes. A request for a tool the server does not know about returns `{ ok: false, error: "Tool not allowed: <name>" }` without ever executing it. This server-exposure check is unconditional and cannot be bypassed.
217
218The handler also uses the [tool policy](../tools/mcp#limit-and-gate-tools) of each client:
219
220- `toolFilter`: a tool that the filter hides returns `Tool not allowed: <name>`.
221- `needsApproval`: a widget call has no approval step. A tool that `needsApproval` marks returns `{ ok: false, error: "Tool needs approval: <name>" }`.
222
223Use the `allowTool` option to add a further restriction on top. A request must satisfy **both** the server-exposure check and `allowTool` — it is AND-ed, not a replacement for the server check:
224
225```ts
226import { createMCPClients } from '@tanstack/ai-mcp'
227import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
228
229const mcp = await createMCPClients({
230 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
231})
232
233const handler = createMcpAppCallHandler({
234 clients: mcp,
235 // Additional restriction: even if the server exposes more tools,
236 // only allow this specific one through the call handler.
237 allowTool: (req) => req.toolName === 'place_order',
238})
239```
240
241### Chat route — wire the `serverId`
242
243The `serverId` on a `UIResourcePart` comes from the `prefix` you gave the MCP client. Use the same key in both places:
244
245> **Multi-server routing:** interactive calls route by `serverId`, which is each client's `prefix`. `createMCPClients` defaults every server's prefix to its config key, so routing works out of the box. If you pass multiple servers and disable prefixing on one (`prefix: ''`), that server has no `serverId` and its widgets can't make interactive calls — give each interactive server a distinct prefix (the default is fine).
246
247
248```ts ignore
249// src/routes/api.chat.ts
250import { createFileRoute } from '@tanstack/react-router'
251import { chat, toServerSentEventsResponse } from '@tanstack/ai'
252import { openaiText } from '@tanstack/ai-openai'
253import { createMCPClients } from '@tanstack/ai-mcp'
254
255export const Route = createFileRoute('/api/chat')({
256 server: {
257 handlers: {
258 POST: async ({ request }) => {
259 const body = await request.json()
260
261 // The pool key "weather" becomes the serverId on every UIResourcePart
262 // emitted by this server — must match the key used when constructing
263 // the pool passed to createMcpAppCallHandler.
264 const pool = await createMCPClients({
265 weather: {
266 transport: { type: 'http', url: process.env.WEATHER_MCP_URL! },
267 },
268 })
269
270 const stream = chat({
271 adapter: openaiText('gpt-5.5'),
272 messages: body.messages,
273 mcp: { clients: [pool] },
274 })
275
276 return toServerSentEventsResponse(stream)
277 },
278 },
279 },
280})
281```
282
283### Client — bridge + interactive render
284
285`createMcpAppBridge` from `@tanstack/ai-client` returns an action handler you pass to `MCPAppResource`. It routes:
286
287- `tool` actions → POST to `callEndpoint` with the tool call payload.
288- `prompt` actions → `chat.sendMessage(prompt)`.
289- `link` actions → `onLink(url)` if provided; dropped (with a warning) otherwise.
290
291In React (or Preact), use the `useMcpAppBridge` hook — it returns a **stable**
292bridge for the given `threadId`/`callEndpoint` and always calls your latest
293`sendMessage`/`onLink`, so you don't hand-write `useMemo` or fight
294`exhaustive-deps`. (The underlying `createMcpAppBridge` from
295`@tanstack/ai-client` is framework-agnostic if you need it directly.)
296
297```tsx
298// src/components/Chat.tsx
299import { useChat, useMcpAppBridge } from '@tanstack/ai-react'
300import { fetchServerSentEvents } from '@tanstack/ai-client'
301import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
302
303export function Chat() {
304 // A stable id correlating widget calls back to this conversation.
305 const threadId = 'weather-chat'
306 const { messages, sendMessage, status } = useChat({
307 connection: fetchServerSentEvents('/api/chat'),
308 })
309
310 const bridge = useMcpAppBridge({
311 threadId,
312 callEndpoint: '/api/mcp-apps/call',
313 chat: { sendMessage: (content, body) => sendMessage(content, { body }) },
314 // Opt in to link navigation — absent means links are blocked.
315 onLink: (url) => window.open(url, '_blank', 'noopener'),
316 })
317
318 return (
319 <div>
320 {messages.map((m) => (
321 <div key={m.id}>
322 {m.parts.map((part, i) => {
323 if (part.type === 'text') {
324 return <p key={i}>{part.content}</p>
325 }
326 if (part.type === 'ui-resource') {
327 return (
328 <MCPAppResource
329 key={i}
330 part={part}
331 bridge={bridge}
332 // your hosted sandbox-proxy page (a host constant, not the widget URL)
333 sandbox={{ url: new URL('https://your-app.example.com/mcp-sandbox.html') }}
334 />
335 )
336 }
337 return null
338 })}
339 </div>
340 ))}
341 <button
342 onClick={() => sendMessage({ content: 'Show me the weather widget' })}
343 disabled={status === 'streaming'}
344 >
345 Send
346 </button>
347 </div>
348 )
349}
350```
351
352> **Writeback is client-side.** Widget tool calls do **not** append to the thread's chat history by default. The conversation state writeback path is out of scope for the current release. Each widget interaction is self-contained.
353
354## Session Persistence
355
356The call handler reconnects to the MCP server on every widget action using the transport descriptor it reads from `client.getInfo()` / `pool.getServers()` (**reconnect-per-call** — stateless, serverless-safe). For stateful MCP transports that require a persistent session, opt in to an in-memory session store:
357
358```ts
359import { createMCPClients } from '@tanstack/ai-mcp'
360import {
361 createMcpAppCallHandler,
362 inMemoryMcpSessionStore,
363} from '@tanstack/ai-mcp/apps'
364
365const mcp = await createMCPClients({
366 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
367})
368
369// In-memory store: one Node.js process, no cross-instance sharing.
370// Shape matches the McpSessionStore interface — SQL / KV stores
371// can be dropped in later with no API change.
372const store = inMemoryMcpSessionStore({ ttlMs: 30 * 60_000 })
373
374const handler = createMcpAppCallHandler({ clients: mcp, store })
375```
376
377> **Current limitation:** `inMemoryMcpSessionStore` is single-instance (one Node.js process). It does not survive serverless restarts or scale across replicas. The `McpSessionStore` interface is the persistence extension point — persistent backends (database, KV store) can be dropped in without any API changes.
378
379## API Reference
380
381### `createMcpAppCallHandler` (`@tanstack/ai-mcp/apps`)
382
383```ts
384import { createMCPClients } from '@tanstack/ai-mcp'
385import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
386import type { McpAppCallHandlerOptions } from '@tanstack/ai-mcp/apps'
387
388const mcp = await createMCPClients({
389 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
390})
391
392const options: McpAppCallHandlerOptions = {
393 // Pass the MCP client(s) you already created:
394 // - a single MCPClient
395 // - an MCPClients pool (pool key = serverId on UIResourcePart)
396 // - an array of either
397 // The handler reads each client's transport descriptor via
398 // client.getInfo() / pool.getServers() (pure config, no live socket)
399 // and reconnects per call — serverless-safe by default.
400 clients: mcp,
401
402 // Dynamic session store (opt-in for stateful transports)
403 // store: inMemoryMcpSessionStore(),
404
405 // Custom tool allowlist — default: server's own exposed tools only
406 // AND-ed on top of the always-on same-server exposure check.
407 allowTool: (req) => req.toolName === 'get_weather',
408}
409
410// Returns: (req) => Promise<{ ok: true; result: unknown } | { ok: false; error: string }>
411const handler = createMcpAppCallHandler(options)
412```
413
414### `inMemoryMcpSessionStore` (`@tanstack/ai-mcp/apps`)
415
416```ts
417import { inMemoryMcpSessionStore } from '@tanstack/ai-mcp/apps'
418
419const store = inMemoryMcpSessionStore({
420 ttlMs: 30 * 60_000, // optional; default: 30 minutes
421})
422```
423
424### `createMcpAppBridge` (`@tanstack/ai-client`)
425
426```ts
427import { createMcpAppBridge } from '@tanstack/ai-client'
428import type { CreateMcpAppBridgeOptions } from '@tanstack/ai-client'
429
430const options: CreateMcpAppBridgeOptions = {
431 threadId: 'weather-chat', // identifies the thread for the call handler
432 callEndpoint: '/api/mcp-apps/call', // POST route mounting createMcpAppCallHandler
433 chat: {
434 sendMessage: async (content, body) => {
435 console.log(content, body)
436 },
437 }, // prompt-intent path
438 fetchImpl: fetch, // optional; injectable for testing
439 onLink: (url) => window.open(url, '_blank'), // absent → link is dropped (warned), openLink returns { isError: true }
440}
441
442// Returns an McpAppBridge with callTool / sendPrompt / openLink methods.
443const bridge = createMcpAppBridge(options)
444```
445
446### `useMcpAppBridge` (`@tanstack/ai-react` / `@tanstack/ai-preact`)
447
448The React/Preact wrapper around `createMcpAppBridge`. Returns a bridge that is
449**stable** for a given `threadId`/`callEndpoint` (so it won't churn `MCPAppResource`
450on every render) while always invoking the latest `chat.sendMessage`/`onLink`.
451Takes the same options as `createMcpAppBridge`.
452
453```tsx
454import { useChat, useMcpAppBridge } from '@tanstack/ai-react'
455import { fetchServerSentEvents } from '@tanstack/ai-client'
456
457function useBridge(threadId: string) {
458 const { sendMessage } = useChat({
459 connection: fetchServerSentEvents('/api/chat'),
460 })
461 return useMcpAppBridge({
462 threadId,
463 callEndpoint: '/api/mcp-apps/call',
464 chat: { sendMessage: (content, body) => sendMessage(content, { body }) },
465 onLink: (url) => window.open(url, '_blank', 'noopener'),
466 })
467}
468```
469
470### `MCPAppResource` (`@tanstack/ai-react/mcp-apps`)
471
472```tsx
473import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
474// `part` is a UIResourcePart from the assistant message; `bridge` is a
475// createMcpAppBridge result — both supplied by your component (see examples above).
476import { part, bridge } from './chat-context'
477
478const widget = (
479 <MCPAppResource
480 part={part} // UIResourcePart from the assistant message (carries the toolName)
481 sandbox={{ url: new URL('https://your-app.example.com/mcp-sandbox.html') }} // your hosted sandbox-proxy page (host constant; not the widget's ui:// URL)
482 bridge={bridge} // omit for static, display-only rendering
483 toolInput={{ city: 'Brooklyn' }} // optional tool input for the renderer context
484 />
485)
486```
487
488Preact: identical API from `@tanstack/ai-preact/mcp-apps` (requires `preact/compat` alias).