Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { Check, Loader2, Send, Square } from 'lucide-react'
4import ReactMarkdown from 'react-markdown'
5import rehypeRaw from 'rehype-raw'
6import rehypeSanitize from 'rehype-sanitize'
7import rehypeHighlight from 'rehype-highlight'
8import remarkGfm from 'remark-gfm'
9import {
10 fetchServerSentEvents,
11 useChat,
12 useMcpAppBridge,
13} from '@tanstack/ai-react'
14import { MCPAppResource } from '@tanstack/ai-react/mcp-apps'
15import type { McpAppBridge, UIMessage } from '@tanstack/ai-react'
16import { MCP_PROVIDERS, type McpProvider } from '@/lib/mcp-providers'
17import {
18 MCP_APP_SUGGESTIONS,
19 SANDBOX_PROXY_URL,
20 WEATHER_PREFIX,
21} from '@/lib/mcp-apps'
22
23type Part = UIMessage['parts'][number]
24type UIResource = Extract<Part, { type: 'ui-resource' }>
25
26function isRecord(value: unknown): value is Record<string, unknown> {
27 return typeof value === 'object' && value !== null && !Array.isArray(value)
28}
29
30/**
31 * The structured args the model passed to the tool whose UI this resource
32 * renders — forwarded to the widget so it can draw itself (e.g. the Three.js
33 * widget reads `{ code, height }`). Seeded from the sibling tool-call part that
34 * shares the resource's `toolCallId`.
35 */
36function toolInputFor(
37 parts: Array<Part>,
38 toolCallId: string,
39): Record<string, unknown> | undefined {
40 for (const p of parts) {
41 if (p.type !== 'tool-call' || p.id !== toolCallId) continue
42 if (isRecord(p.input)) return p.input
43 if (typeof p.arguments === 'string') {
44 try {
45 const parsed: unknown = JSON.parse(p.arguments)
46 if (isRecord(parsed)) return parsed
47 } catch {
48 // ignore malformed partial JSON mid-stream
49 }
50 }
51 }
52 return undefined
53}
54
55const SANDBOX = { url: new URL(SANDBOX_PROXY_URL) }
56
57function Widget({
58 part,
59 parts,
60 bridge,
61}: {
62 part: UIResource
63 parts: Array<Part>
64 bridge: McpAppBridge
65}) {
66 // The static weather card is display-only, so we withhold the bridge. The
67 // interactive widgets (storefront, Three.js) get it and can call tools back.
68 const interactive = part.serverId !== WEATHER_PREFIX
69 return (
70 <div className="my-2 overflow-hidden rounded-lg border border-orange-500/20 bg-gray-900/40">
71 <MCPAppResource
72 part={part}
73 sandbox={SANDBOX}
74 bridge={interactive ? bridge : undefined}
75 toolInput={toolInputFor(parts, part.toolCallId)}
76 />
77 </div>
78 )
79}
80
81function Messages({
82 messages,
83 bridge,
84}: {
85 messages: Array<UIMessage>
86 bridge: McpAppBridge
87}) {
88 const visible = messages.filter((m) =>
89 m.parts.some(
90 (p) =>
91 (p.type === 'text' && p.content.trim()) ||
92 p.type === 'ui-resource' ||
93 p.type === 'tool-call',
94 ),
95 )
96
97 if (!visible.length) {
98 return (
99 <div className="flex-1 overflow-y-auto px-4 py-8">
100 <div className="mx-auto max-w-2xl text-center text-sm text-gray-400">
101 Pick a suggestion below to render a static or interactive MCP App.
102 </div>
103 </div>
104 )
105 }
106
107 return (
108 <div className="flex-1 overflow-y-auto px-4 py-4">
109 {visible.map((message) => (
110 <div
111 key={message.id}
112 className={`mb-2 rounded-lg p-4 ${
113 message.role === 'assistant'
114 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
115 : 'bg-transparent'
116 }`}
117 >
118 <div className="flex items-start gap-4">
119 <div
120 className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-sm font-medium text-white ${
121 message.role === 'assistant'
122 ? 'bg-linear-to-r from-orange-500 to-red-600'
123 : 'bg-gray-700'
124 }`}
125 >
126 {message.role === 'assistant' ? 'AI' : 'U'}
127 </div>
128 <div className="min-w-0 flex-1">
129 {message.parts.map((part, index) => {
130 if (part.type === 'text' && part.content) {
131 return (
132 <div
133 key={`text-${index}`}
134 className="prose dark:prose-invert max-w-none text-white"
135 >
136 <ReactMarkdown
137 rehypePlugins={[
138 rehypeRaw,
139 rehypeSanitize,
140 rehypeHighlight,
141 ]}
142 remarkPlugins={[remarkGfm]}
143 >
144 {part.content}
145 </ReactMarkdown>
146 </div>
147 )
148 }
149
150 if (part.type === 'ui-resource') {
151 return (
152 <Widget
153 key={`ui-${index}`}
154 part={part}
155 parts={message.parts}
156 bridge={bridge}
157 />
158 )
159 }
160
161 // A compact note for the UI-linked tool: spinner while it runs,
162 // check once it's done (the widget renders from the sibling
163 // ui-resource part).
164 if (part.type === 'tool-call') {
165 const done =
166 part.state === 'complete' || part.output !== undefined
167 return (
168 <div
169 key={`tool-${index}`}
170 className="my-1 flex items-center gap-2 text-xs text-gray-400"
171 >
172 {done ? (
173 <Check className="h-3 w-3 text-green-400" />
174 ) : (
175 <Loader2 className="h-3 w-3 animate-spin" />
176 )}
177 <span className="font-mono">{part.name}</span>
178 </div>
179 )
180 }
181
182 return null
183 })}
184 </div>
185 </div>
186 </div>
187 ))}
188 </div>
189 )
190}
191
192function McpAppsPage() {
193 const [provider, setProvider] = useState<McpProvider>('openai')
194 const threadId = `mcp-apps-${provider}`
195
196 const { messages, sendMessage, isLoading, error, stop } = useChat({
197 threadId,
198 connection: fetchServerSentEvents('/api/mcp-apps-chat'),
199 body: { provider },
200 })
201
202 // One stable bridge per thread: routes the widget's tool calls to the
203 // interactive endpoint and its prompt/link actions back into this chat.
204 const bridge = useMcpAppBridge({
205 threadId,
206 callEndpoint: '/api/mcp-apps-call',
207 chat: { sendMessage: async (content) => void sendMessage(content) },
208 onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
209 })
210
211 const [input, setInput] = useState('')
212 const send = (text: string) => {
213 if (!text.trim() || isLoading) return
214 sendMessage(text.trim())
215 setInput('')
216 }
217
218 return (
219 <div className="flex h-[calc(100vh-72px)] flex-col bg-gray-900">
220 <div className="shrink-0 border-b border-orange-500/20 bg-gray-800 px-4 py-3">
221 <p className="mb-3 text-xs text-gray-400">
222 MCP Apps render server-provided UI in the chat. The{' '}
223 <strong className="text-gray-200">weather card</strong> is a static,
224 display-only widget served in-process; the{' '}
225 <strong className="text-gray-200">3D scene</strong> is the official
226 Three.js MCP server (run on :3001 by <code>npm run dev</code>) and is
227 interactive. Set your provider's API key in the environment.
228 </p>
229 <div className="flex flex-wrap items-center gap-2">
230 <span className="text-xs uppercase tracking-wide text-gray-500">
231 Provider
232 </span>
233 {MCP_PROVIDERS.map((p) => (
234 <label
235 key={p.value}
236 className={`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-1.5 text-sm transition-colors ${
237 provider === p.value
238 ? 'border-cyan-500 bg-cyan-500/10 text-cyan-300'
239 : 'border-gray-600 bg-gray-700/50 text-gray-300 hover:border-cyan-500/50'
240 }`}
241 >
242 <input
243 type="radio"
244 name="mcp-apps-provider"
245 value={p.value}
246 checked={provider === p.value}
247 onChange={() => setProvider(p.value)}
248 className="sr-only"
249 />
250 <span className="font-medium">{p.label}</span>
251 </label>
252 ))}
253 </div>
254 </div>
255
256 <Messages messages={messages} bridge={bridge} />
257
258 {error && (
259 <div className="mx-4 mt-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
260 {error.message}
261 </div>
262 )}
263
264 <div className="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm">
265 <div className="w-full space-y-2 px-4 py-3">
266 {/* Suggestion pills — trigger a static vs. dynamic MCP App. */}
267 <div className="flex flex-wrap gap-2">
268 {MCP_APP_SUGGESTIONS.map((s) => (
269 <button
270 key={s.kind}
271 onClick={() => send(s.prompt)}
272 disabled={isLoading}
273 className="rounded-full border border-orange-500/30 bg-orange-500/10 px-3 py-1.5 text-xs text-orange-200 transition-colors hover:bg-orange-500/20 disabled:opacity-50"
274 >
275 {s.label}
276 </button>
277 ))}
278 </div>
279
280 {isLoading && (
281 <div className="flex items-center justify-center">
282 <button
283 onClick={stop}
284 className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700"
285 >
286 <Square className="h-4 w-4 fill-current" />
287 Stop
288 </button>
289 </div>
290 )}
291
292 <div className="relative flex items-end gap-2">
293 <div className="relative flex-1">
294 <textarea
295 value={input}
296 onChange={(e) => setInput(e.target.value)}
297 placeholder="Ask for a weather card or a 3D scene..."
298 className="w-full resize-none overflow-hidden rounded-lg border border-orange-500/20 bg-gray-800/50 py-3 pl-4 pr-12 text-sm text-white placeholder-gray-400 shadow-lg focus:border-transparent focus:outline-none focus:ring-2 focus:ring-orange-500/50"
299 rows={1}
300 style={{ minHeight: '44px', maxHeight: '200px' }}
301 disabled={isLoading}
302 onKeyDown={(e) => {
303 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
304 e.preventDefault()
305 send(input)
306 }
307 }}
308 />
309 <button
310 onClick={() => send(input)}
311 disabled={!input.trim() || isLoading}
312 className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-orange-500 transition-colors hover:text-orange-400 focus:outline-none disabled:text-gray-500"
313 >
314 <Send className="h-4 w-4" />
315 </button>
316 </div>
317 </div>
318 </div>
319 </div>
320 </div>
321 )
322}
323
324export const Route = createFileRoute('/mcp-apps')({
325 component: McpAppsPage,
326})