Open History to see the last commit
1import { AppRenderer } from '@mcp-ui/client'
2import type { UIResourcePart } from '@tanstack/ai'
3import type { McpAppBridge } from '@tanstack/ai-client'
4import type { JSX } from 'react'
5
6export interface MCPAppResourceProps {
7 /** The ui-resource part from a UIMessage assistant part. */
8 part: UIResourcePart
9 /**
10 * Framework-agnostic bridge for tool calls, prompt sending, and link opening.
11 * Omit it to render the widget in display-only mode — iframe interactions
12 * that would trigger tool calls or prompts are ignored.
13 */
14 bridge?: McpAppBridge
15 /** Sandbox iframe configuration — must include the proxy page URL. */
16 sandbox: { url: URL }
17 /** Optional structured arguments forwarded to the guest UI once it's ready. */
18 toolInput?: Record<string, unknown>
19}
20
21function isRecord(value: unknown): value is Record<string, unknown> {
22 return typeof value === 'object' && value !== null && !Array.isArray(value)
23}
24
25/**
26 * Coalesce an arbitrary bridge result into the `string` required by the
27 * `CallToolResult` text content block. `JSON.stringify` is typed to return
28 * `string` but actually returns `undefined` for inputs like `undefined` or a
29 * function, so we narrow explicitly to avoid `text: undefined`.
30 */
31function resultToText(result: unknown): string {
32 if (typeof result === 'string') return result
33 // `JSON.stringify`'s lib signature claims `string`, but it returns
34 // `undefined` for `undefined`/function inputs; type the call honestly.
35 const stringify: (value: unknown) => string | undefined = JSON.stringify
36 return stringify(result) ?? 'null'
37}
38
39export function MCPAppResource(props: MCPAppResourceProps): JSX.Element {
40 const { bridge } = props
41 return (
42 <AppRenderer
43 toolName={props.part.toolName}
44 sandbox={props.sandbox}
45 html={props.part.resource.text}
46 toolResourceUri={props.part.resource.uri}
47 toolInput={props.toolInput}
48 onCallTool={
49 bridge
50 ? async ({ name, arguments: args }) => {
51 const result = await bridge.callTool({
52 serverId: props.part.serverId,
53 toolName: name,
54 args,
55 })
56 const structuredContent = isRecord(result) ? result : undefined
57 return {
58 content: [
59 {
60 type: 'text' as const,
61 text: resultToText(result),
62 },
63 ],
64 structuredContent,
65 }
66 }
67 : undefined
68 }
69 onMessage={
70 bridge
71 ? async ({ content }) => {
72 const text = content
73 .filter(
74 (c): c is { type: 'text'; text: string } => c.type === 'text',
75 )
76 .map((c) => c.text)
77 .join('')
78 if (text) await bridge.sendPrompt(text)
79 return {}
80 }
81 : undefined
82 }
83 onOpenLink={
84 bridge ? ({ url }) => Promise.resolve(bridge.openLink(url)) : undefined
85 }
86 />
87 )
88}