Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

apps.md

437 lines15.8 KB

1---
2title: MCP Apps
3id: mcp-apps
4order: 12
5description: "Show the interactive ui:// widgets that MCP servers return. Render them with MCPAppResource, and let a widget call tools with createMcpAppCallHandler and useMcpAppBridge."
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​
19An MCP App is a widget returned with a tool result. Render that widget in the chat next to the text.
20​
21TanStack AI reads the widget during the `chat()` run and puts it on the assistant message as a `ui-resource` part. Render that part with `MCPAppResource`.
22​
23## Quick setup
24​
25You need a chat with an MCP server first. If you do not have one, start with [MCP Server Tools](../tools/mcp). This setup uses React. Preact has the same API.
26​
271. Install the widget renderer:
28​
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30​
31react: @tanstack/ai-mcp @mcp-ui/client
32preact: @tanstack/ai-mcp @mcp-ui/client
33​
34<!-- ::end:tabs -->
35​
362. Connect your chat route to the MCP server. You need no extra server code for widgets:
37​
38```ts ignore
39// src/routes/api.chat.ts (TanStack Start)
40import { createFileRoute } from '@tanstack/react-router'
41import { chat, toServerSentEventsResponse } from '@tanstack/ai'
42import { openaiText } from '@tanstack/ai-openai'
43import { createMCPClient } from '@tanstack/ai-mcp'
44​
45export const Route = createFileRoute('/api/chat')({
46 server: {
47 handlers: {
48 POST: async ({ request }) => {
49 const { messages, threadId } = await request.json()
50​
51 const mcp = await createMCPClient({
52 transport: {
53 type: 'http',
54 url: process.env.MCP_URL ?? '',
55 },
56 })
57​
58 const stream = chat({
59 adapter: openaiText('gpt-6.1-sol'),
60 messages,
61 threadId,
62 mcp: { clients: [mcp] },
63 })
64​
65 return toServerSentEventsResponse(stream)
66 },
67 },
68 },
69})
70```
71​
723. Host a sandbox proxy page on your own origin, for example `/mcp-sandbox.html`. The [`@mcp-ui/client`](https://mcpui.dev) docs have this page.
73​
744. Render each `ui-resource` part with `MCPAppResource`:
75​
76```tsx
77// src/components/Chat.tsx
78import { useChat } from '@tanstack/ai-react'
79import { fetchServerSentEvents } from '@tanstack/ai-client'
80import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
81​
82export function Chat() {
83 const { messages, sendMessage, status } = useChat({
84 connection: fetchServerSentEvents('/api/chat'),
85 threadId: 'support-chat',
86 })
87​
88 return (
89 <div>
90 {messages.map((m) => (
91 <div key={m.id}>
92 {m.parts.map((part, i) => {
93 if (part.type === 'text') {
94 return <p key={i}>{part.content}</p>
95 }
96 if (part.type === 'ui-resource') {
97 return (
98 <MCPAppResource
99 key={i}
100 part={part}
101 sandbox={{ url: new URL('https://your-app.example.com/mcp-sandbox.html') }}
102 />
103 )
104 }
105 return null
106 })}
107 </div>
108 ))}
109 <button
110 onClick={() => sendMessage({ content: 'Show me the weather widget' })}
111 disabled={status === 'streaming'}
112 >
113 Send
114 </button>
115 </div>
116 )
118```
119​
120Send the message. When the model calls a tool that has a widget, the widget shows in the chat.
121​
122## How it works
123​
124MCP Apps is an MCP extension, standardized on 2026-01-26. An MCP server links a tool to a `ui://` resource that holds the widget.
125​
1261. The model calls the tool during the `chat()` run.
1272. TanStack AI reads the `ui://` resource of that tool.
1283. It adds a `UIResourcePart` to the `parts` of the assistant message, next to the normal tool result. The part never goes to the model.
1294. `MCPAppResource` loads your sandbox page in an isolated iframe, and renders the widget inside it.
130​
131The sandbox URL is the security boundary. It is the same for every widget, so you set it once, at deploy time. The widget HTML comes from `part.resource`, not from this URL.
132​
133Without a `bridge` prop, the widget is display only. A click in the widget that calls a tool or sends a prompt does nothing. To make it work, see the next section.
134​
135To link a tool to its widget on your own TanStack MCP server, see [Tell the host what a tool does](./server#tell-the-host-what-a-tool-does).
136​
137## Make a widget interactive
138​
139A widget can call tools on its MCP server, send a prompt to the model, or open a link. For that, you add two pieces:
140​
141- **Server:** a route with `createMcpAppCallHandler`. The widget calls this route to run a tool.
142- **Client:** a bridge from `useMcpAppBridge`. It sends each widget action to the right place.
143​
1441. Install the packages:
145​
146<!-- ::start:tabs variant="package-manager" mode="install" -->
147​
148react: @tanstack/ai-mcp @tanstack/ai-client @mcp-ui/client
149preact: @tanstack/ai-mcp @tanstack/ai-client @mcp-ui/client
150​
151<!-- ::end:tabs -->
152​
1532. In your chat route, use `createMCPClients`. The key (`weather`) becomes the `serverId` on each widget part:
154​
155```ts ignore
156// src/routes/api.chat.ts
157import { createFileRoute } from '@tanstack/react-router'
158import { chat, toServerSentEventsResponse } from '@tanstack/ai'
159import { openaiText } from '@tanstack/ai-openai'
160import { createMCPClients } from '@tanstack/ai-mcp'
161​
162export const Route = createFileRoute('/api/chat')({
163 server: {
164 handlers: {
165 POST: async ({ request }) => {
166 const body = await request.json()
167​
168 const pool = await createMCPClients({
169 weather: {
170 transport: { type: 'http', url: process.env.WEATHER_MCP_URL ?? '' },
171 },
172 })
173​
174 const stream = chat({
175 adapter: openaiText('gpt-6.1-sol'),
176 messages: body.messages,
177 threadId: body.threadId,
178 mcp: { clients: [pool] },
179 })
180​
181 return toServerSentEventsResponse(stream)
182 },
183 },
184 },
185})
186```
187​
1883. Add the call handler route. Use the same key as in the chat route:
189​
190```ts ignore
191// src/routes/api.mcp-apps-call.ts (TanStack Start)
192import { createFileRoute } from '@tanstack/react-router'
193import { createMCPClients } from '@tanstack/ai-mcp'
194import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
195​
196const mcp = await createMCPClients({
197 weather: {
198 transport: {
199 type: 'http',
200 url: process.env.WEATHER_MCP_URL ?? '',
201 headers: { Authorization: `Bearer ${process.env.WEATHER_MCP_TOKEN ?? ''}` },
202 },
203 },
204})
205​
206const handler = createMcpAppCallHandler({ clients: mcp })
207​
208export const Route = createFileRoute('/api/mcp-apps/call')({
209 server: {
210 handlers: {
211 POST: async ({ request }) => {
212 // body: { threadId, serverId, toolName, args?, messageId? }
213 const body = await request.json()
214 const result = await handler(body)
215 return new Response(JSON.stringify(result), {
216 headers: { 'Content-Type': 'application/json' },
217 })
218 },
219 },
220 },
221})
222```
223​
2244. In the client, create a bridge and pass it to `MCPAppResource`:
225​
226```tsx
227// src/components/Chat.tsx
228import { useChat, useMcpAppBridge } from '@tanstack/ai-react'
229import { fetchServerSentEvents } from '@tanstack/ai-client'
230import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
231​
232export function Chat() {
233 // A stable id that links widget calls to this conversation.
234 const threadId = 'weather-chat'
235 const { messages, sendMessage, status } = useChat({
236 connection: fetchServerSentEvents('/api/chat'),
237 threadId,
238 })
239​
240 const bridge = useMcpAppBridge({
241 threadId,
242 callEndpoint: '/api/mcp-apps/call',
243 chat: { sendMessage: (content, body) => sendMessage(content, { body }) },
244 // Without onLink, the bridge blocks links.
245 onLink: (url) => window.open(url, '_blank', 'noopener'),
246 })
247​
248 return (
249 <div>
250 {messages.map((m) => (
251 <div key={m.id}>
252 {m.parts.map((part, i) => {
253 if (part.type === 'text') {
254 return <p key={i}>{part.content}</p>
255 }
256 if (part.type === 'ui-resource') {
257 return (
258 <MCPAppResource
259 key={i}
260 part={part}
261 bridge={bridge}
262 sandbox={{ url: new URL('https://your-app.example.com/mcp-sandbox.html') }}
263 />
264 )
265 }
266 return null
267 })}
268 </div>
269 ))}
270 <button
271 onClick={() => sendMessage({ content: 'Show me the weather widget' })}
272 disabled={status === 'streaming'}
273 >
274 Send
275 </button>
276 </div>
277 )
279```
280​
281Now a click in the widget runs the tool on the MCP server, and the widget shows the result. A prompt from the widget goes to the chat as a new message.
282​
283The bridge sends each widget action to one place:
284​
285- `tool` actions: a POST to `callEndpoint`.
286- `prompt` actions: `chat.sendMessage(prompt)`.
287- `link` actions: `onLink(url)`, if you pass it.
288​
289## Framework support
290​
291`MCPAppResource` and `useMcpAppBridge` ship for React and Preact:
292​
293- React: `@tanstack/ai-react/mcp-apps`.
294- Preact: `@tanstack/ai-preact/mcp-apps`. It needs a `preact/compat` alias.
295​
296Solid, Vue, Svelte, and Angular have no widget component yet. The `AppRenderer` of `@mcp-ui/client` v7 is React-only. `createMcpAppBridge` from `@tanstack/ai-client` works in any framework.
297​
298## Advanced
299​
300### The `UIResourcePart` shape
301​
302```ts
303import type { UIResourcePart } from '@tanstack/ai'
304​
305// {
306// type: 'ui-resource'
307// resource: { uri: string; mimeType: string; text?: string; blob?: string }
308// serverId?: string // pool prefix or config key. Routes interactive calls.
309// toolCallId: string // links the part to its tool call
310// toolName: string // MCP tool name whose UI this resource renders
311// meta?: Record<string, unknown> // reserved. Always undefined for now.
312// }
313```
314​
315TanStack AI reads the resource during the chat run. If the read fails (a network error, a missing resource), the tool result still goes to the model, and the message has no widget.
316​
317### What the call handler allows
318​
319`createMcpAppCallHandler` accepts a single `MCPClient`, an `MCPClients` pool, or an array of either. For each call, it:
320​
3211. Reads the transport descriptor of the client with `client.getInfo()` or `pool.getServers()`. This needs no live socket.
3222. Connects to the MCP server again for this call. This works on serverless hosts.
3233. Makes sure that the server exposes `toolName`. If it does not, the result is `{ ok: false, error: "Tool not allowed: <name>" }`, and the tool does not run. You cannot turn this check off.
3244. Runs the tool and returns `{ ok: true, result }` or `{ ok: false, error }`.
325​
326The handler also uses the [tool policy](../tools/mcp-advanced#limit-and-gate-tools) of each client:
327​
328- `toolFilter`: a tool that the filter hides returns `Tool not allowed: <name>`.
329- `needsApproval`: a widget call has no approval step. A tool that `needsApproval` marks returns `{ ok: false, error: "Tool needs approval: <name>" }`.
330​
331To limit the tools more, pass `allowTool`. A request must pass both the server check and `allowTool`:
332​
333```ts
334import { createMCPClients } from '@tanstack/ai-mcp'
335import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
336​
337const mcp = await createMCPClients({
338 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
339})
340​
341const handler = createMcpAppCallHandler({
342 clients: mcp,
343 // The server can expose more tools. Only this one goes through.
344 allowTool: (req) => req.toolName === 'place_order',
345})
346```
347​
348### Log call failures
349​
350The handler returns `{ ok: false, error }` to the widget and logs nothing. To see why a call failed, pass `onError`. The handler calls it (and awaits it) before it returns the result:
351​
352```ts
353import { createMCPClients } from '@tanstack/ai-mcp'
354import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
355​
356const mcp = await createMCPClients({
357 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
358})
359​
360const handler = createMcpAppCallHandler({
361 clients: mcp,
362 onError: (error, { phase, req }) => {
363 console.error('MCP app call failed', phase, req.toolName, error)
364 },
365})
366```
367​
368`phase` is `'call'` for a failure to connect, find, or run the tool. It is `'close'` for a failure to close the client after the call. A `'close'` failure does not change the result.
369​
370### Links from a widget
371​
372- If you pass no `onLink`, the bridge drops the link and logs a warning. `openLink` returns `{ isError: true }`, and the call does not hang.
373- With `onLink`, the bridge forwards only `http:`, `https:`, and `mailto:` URLs. It always rejects other schemes (`javascript:`, `data:`, `file:`) before your handler runs.
374​
375### More than one server
376​
377Interactive calls go to the server whose `prefix` matches the `serverId` of the part. `createMCPClients` sets the prefix of each server to its config key by default.
378​
379If you set `prefix: ''` on one server in a pool of many, that server has no `serverId`. Its widgets cannot make interactive calls. Give each interactive server its own prefix (the default is fine).
380​
381### Widget calls and chat history
382​
383A widget tool call does not add to the chat history of the thread. Each widget action stands alone.
384​
385### Keep sessions for stateful servers
386​
387By default the handler connects again for each widget action. If your MCP server needs a session that lasts, pass a session store:
388​
389```ts
390import { createMCPClients } from '@tanstack/ai-mcp'
391import {
392 createMcpAppCallHandler,
393 inMemoryMcpSessionStore,
394} from '@tanstack/ai-mcp/apps'
395​
396const mcp = await createMCPClients({
397 weather: { transport: { type: 'http', url: process.env.MCP_URL ?? '' } },
398})
399​
400const store = inMemoryMcpSessionStore({ ttlMs: 30 * 60_000 })
401​
402const handler = createMcpAppCallHandler({ clients: mcp, store })
403```
404​
405- When the store has an entry for a thread and a `serverId`, the store wins. On a miss, the handler uses `clients`.
406- `ttlMs` is optional. The default is 30 minutes.
407- `inMemoryMcpSessionStore` lives in one Node.js process. It does not survive a serverless restart, and replicas do not share it. To share sessions, write your own store with the `McpSessionStore` interface.
408​
409### API reference
410​
411`createMcpAppCallHandler(options)` from `@tanstack/ai-mcp/apps` returns `(req) => Promise<{ ok: true; result: unknown } | { ok: false; error: string }>`.
412​
413| Option | Type | Description |
414| --- | --- | --- |
415| `clients` | `MCPClient`, `MCPClients`, or an array of either | The clients that you pass to `chat()`. Required. |
416| `store` | `McpSessionStore` | Session store for stateful servers. |
417| `allowTool` | `(req) => boolean \| Promise<boolean>` | An extra check on top of the server check. |
418| `onError` | `(error, { phase, req }) => void \| Promise<void>` | Called with each failure. |
419​
420`createMcpAppBridge(options)` from `@tanstack/ai-client` returns an `McpAppBridge` with `callTool`, `sendPrompt`, and `openLink`. `useMcpAppBridge` from `@tanstack/ai-react` and `@tanstack/ai-preact` takes the same options. It returns a bridge that stays the same for one `threadId` and `callEndpoint`, and it always calls your latest `sendMessage` and `onLink`.
421​
422| Option | Type | Description |
423| --- | --- | --- |
424| `threadId` | `string` | Names the thread for the call handler. Required. |
425| `callEndpoint` | `string` | The POST route of the call handler. Required. |
426| `chat.sendMessage` | `(content, body?) => Promise<void>` | Sends a prompt from the widget. Required. |
427| `fetchImpl` | `typeof fetch` | Replaces `fetch`, for example in tests. |
428| `onLink` | `(url) => void` | Opens a link. Without it, links are dropped. |
429​
430`MCPAppResource` from `@tanstack/ai-react/mcp-apps` or `@tanstack/ai-preact/mcp-apps`:
431​
432| Prop | Type | Description |
433| --- | --- | --- |
434| `part` | `UIResourcePart` | The `ui-resource` part from the assistant message. Required. |
435| `sandbox` | `{ url: URL }` | The URL of your sandbox proxy page. Required. |
436| `bridge` | `McpAppBridge` | Omit it for a display-only widget. |
437| `toolInput` | `Record<string, unknown>` | Tool input that the widget gets when it is ready. |