Open History to see the last commit
1// @vitest-environment jsdom
2import type { UIResourcePart } from '@tanstack/ai'
3import type { McpAppBridge } from '@tanstack/ai-client'
4import type { AppRendererProps } from '@mcp-ui/client'
5import { render } from '@testing-library/react'
6import { beforeEach, describe, expect, it, vi } from 'vitest'
7import { MCPAppResource } from '../src/mcp-apps'
8
9// The handler return type, derived from AppRenderer's own prop type so the
10// test depends on `@mcp-ui/client` only (not the MCP SDK directly).
11type CallToolResult = Awaited<
12 ReturnType<NonNullable<AppRendererProps['onCallTool']>>
13>
14
15// Capture the props AppRenderer was called with. The component renders
16// AppRenderer with AppRendererProps, so the mock receives that exact shape.
17let capturedProps: Partial<AppRendererProps> = {}
18
19vi.mock('@mcp-ui/client', () => ({
20 AppRenderer: (props: Partial<AppRendererProps>) => {
21 capturedProps = props
22 return null
23 },
24}))
25
26const fakePart: UIResourcePart = {
27 type: 'ui-resource',
28 resource: {
29 uri: 'ui://test-server/my-tool',
30 mimeType: 'text/html',
31 text: '<html><body>hello</body></html>',
32 },
33 serverId: 'test-server',
34 toolCallId: 'tc-1',
35 toolName: 'show',
36}
37
38const fakeSandbox = { url: new URL('https://sandbox.example.com') }
39
40function makeBridge(overrides?: Partial<McpAppBridge>): McpAppBridge {
41 return {
42 callTool: vi.fn().mockResolvedValue({ price: 1999 }),
43 sendPrompt: vi.fn().mockResolvedValue(undefined),
44 openLink: vi.fn().mockReturnValue({ isError: false }),
45 ...overrides,
46 }
47}
48
49/** Render the component and return the props captured from AppRenderer. The
50 * required handlers are read off the captured props with their real types. */
51function renderAndCapture(props: {
52 bridge?: McpAppBridge
53 toolInput?: Record<string, unknown>
54}) {
55 capturedProps = {}
56 render(
57 <MCPAppResource
58 part={fakePart}
59 bridge={props.bridge}
60 sandbox={fakeSandbox}
61 toolInput={props.toolInput}
62 />,
63 )
64 return capturedProps
65}
66
67/** The text of the first content block, asserting it is a text block. */
68function firstText(result: CallToolResult): string {
69 const block = result.content[0]
70 expect(block?.type).toBe('text')
71 if (block?.type !== 'text') throw new Error('expected a text content block')
72 return block.text
73}
74
75describe('MCPAppResource', () => {
76 beforeEach(() => {
77 capturedProps = {}
78 })
79
80 it('renders AppRenderer with the correct static props', () => {
81 const props = renderAndCapture({ bridge: makeBridge() })
82
83 // toolName is sourced from the part, not a separate prop
84 expect(props.toolName).toBe(fakePart.toolName)
85 expect(props.sandbox).toBe(fakeSandbox)
86 expect(props.html).toBe(fakePart.resource.text)
87 expect(props.toolResourceUri).toBe(fakePart.resource.uri)
88 expect(props.toolInput).toBeUndefined()
89 })
90
91 it('passes toolInput when provided', () => {
92 const props = renderAndCapture({
93 bridge: makeBridge(),
94 toolInput: { qty: 3 },
95 })
96
97 expect(props.toolInput).toEqual({ qty: 3 })
98 })
99
100 it('onCallTool calls bridge.callTool and wraps result in CallToolResult shape', async () => {
101 const bridge = makeBridge()
102 const { onCallTool } = renderAndCapture({ bridge })
103
104 const result = await onCallTool!(
105 { name: 't', arguments: { a: 1 } },
106 extra(),
107 )
108
109 expect(bridge.callTool).toHaveBeenCalledWith({
110 serverId: fakePart.serverId,
111 toolName: 't',
112 args: { a: 1 },
113 })
114
115 expect(result.content).toHaveLength(1)
116 expect(firstText(result)).toBe(JSON.stringify({ price: 1999 }))
117 expect(result.structuredContent).toEqual({ price: 1999 })
118 })
119
120 it('onCallTool wraps a string result as-is in the text field', async () => {
121 const bridge = makeBridge({ callTool: vi.fn().mockResolvedValue('ok') })
122 const { onCallTool } = renderAndCapture({ bridge })
123
124 const result = await onCallTool!({ name: 't', arguments: {} }, extra())
125 expect(firstText(result)).toBe('ok')
126 expect(result.structuredContent).toBeUndefined()
127 })
128
129 it('onCallTool coalesces an undefined-serializing result to the string "null"', async () => {
130 const bridge = makeBridge({
131 callTool: vi.fn().mockResolvedValue(undefined),
132 })
133 const { onCallTool } = renderAndCapture({ bridge })
134
135 const result = await onCallTool!({ name: 't', arguments: {} }, extra())
136 // JSON.stringify(undefined) is the value undefined; the coalesce keeps text a string
137 expect(firstText(result)).toBe('null')
138 })
139
140 it('onMessage extracts text content and calls bridge.sendPrompt', async () => {
141 const bridge = makeBridge()
142 const { onMessage } = renderAndCapture({ bridge })
143
144 const result = await onMessage!(
145 { role: 'user', content: [{ type: 'text', text: 'hi' }] },
146 extra(),
147 )
148
149 expect(bridge.sendPrompt).toHaveBeenCalledWith('hi')
150 expect(result).toEqual({})
151 })
152
153 it('onMessage concatenates multiple text content blocks', async () => {
154 const bridge = makeBridge()
155 const { onMessage } = renderAndCapture({ bridge })
156
157 await onMessage!(
158 {
159 role: 'user',
160 content: [
161 { type: 'text', text: 'hello' },
162 { type: 'image', data: '', mimeType: 'image/png' },
163 { type: 'text', text: ' world' },
164 ],
165 },
166 extra(),
167 )
168
169 expect(bridge.sendPrompt).toHaveBeenCalledWith('hello world')
170 })
171
172 it('onMessage does not call bridge.sendPrompt when there is no text content', async () => {
173 const bridge = makeBridge()
174 const { onMessage } = renderAndCapture({ bridge })
175
176 const result = await onMessage!(
177 {
178 role: 'user',
179 content: [{ type: 'image', data: '', mimeType: 'image/png' }],
180 },
181 extra(),
182 )
183
184 expect(bridge.sendPrompt).not.toHaveBeenCalled()
185 expect(result).toEqual({})
186 })
187
188 it('onOpenLink calls bridge.openLink with the URL string', async () => {
189 const bridge = makeBridge()
190 const { onOpenLink } = renderAndCapture({ bridge })
191
192 const result = await onOpenLink!({ url: 'https://example.com' }, extra())
193
194 expect(bridge.openLink).toHaveBeenCalledWith('https://example.com')
195 expect(result).toEqual({ isError: false })
196 })
197
198 it('display-only mode (no bridge) passes undefined callbacks', () => {
199 const props = renderAndCapture({})
200
201 expect(props.toolName).toBe(fakePart.toolName)
202 expect(props.onCallTool).toBeUndefined()
203 expect(props.onMessage).toBeUndefined()
204 expect(props.onOpenLink).toBeUndefined()
205 })
206})
207
208/** The `extra` argument the AppRenderer handlers receive. The handlers under
209 * test ignore it; this builds the required fields so no cast is needed. */
210function extra(): Parameters<NonNullable<AppRendererProps['onCallTool']>>[1] {
211 return {
212 signal: new AbortController().signal,
213 requestId: 1,
214 sendNotification: async () => {},
215 sendRequest: async () => {
216 throw new Error('not implemented in test')
217 },
218 }
219}