Open History to see the last commit
1import { test, expect } from './fixtures'
2
3/**
4 * MCP Apps end-to-end — proves OUR plumbing for both planes, NOT any
5 * third-party widget renderer.
6 *
7 * - DATA plane (`api.mcp-apps-chat`): a `show_widget` MCP tool that links a
8 * `ui://show_widget` resource produces a `ui-resource` CUSTOM event on the
9 * stream. The event carries the resource HTML (token MCP_APPS_WIDGET_OK),
10 * which a client reconciles into a `UIResourcePart`. We assert the event
11 * reaches the client; we do NOT assert the iframe widget mounts.
12 * - INTERACTIVE plane (`api.mcp-apps-call`): POSTs to the route mounting
13 * `createMcpAppCallHandler` return both ordinary and task-required MCP
14 * tool results (tokens MCP_APPS_CALL_OK and MCP_APPS_TASK_CALL_OK).
15 * - ALLOWLIST: a call for a tool the server does not expose returns
16 * `{ ok: false }`.
17 */
18
19// The fields these tests read off SSE events. Tool-call events carry the tool
20// name in `toolCallName`. ui-resource CUSTOM events carry a `value`. All fields
21// are optional, because a parsed event can be any AG-UI event.
22type StreamEvent = {
23 type: string
24 name?: string
25 toolCallName?: string
26 value?: UiResourceValue
27}
28
29type UiResourceValue = {
30 resource?: { uri?: string; mimeType?: string; text?: string }
31 serverId?: string
32 toolCallId?: string
33}
34
35function parseSse(body: string): Array<StreamEvent> {
36 const events: Array<StreamEvent> = []
37 for (const line of body.split('\n')) {
38 const trimmed = line.trim()
39 if (!trimmed.startsWith('data:')) continue
40 const json = trimmed.slice('data:'.length).trim()
41 if (!json) continue
42 try {
43 const parsed: unknown = JSON.parse(json)
44 if (isStreamEvent(parsed)) events.push(parsed)
45 } catch {
46 // Ignore non-JSON keepalive lines.
47 }
48 }
49 return events
50}
51
52function isStreamEvent(value: unknown): value is StreamEvent {
53 return (
54 typeof value === 'object' &&
55 value !== null &&
56 'type' in value &&
57 typeof value.type === 'string'
58 )
59}
60
61// The JSON shape the call handler returns (mirrors createMcpAppCallHandler).
62type CallHandlerResponse = {
63 ok: boolean
64 result?: unknown
65 error?: string
66}
67
68function parseCallResponse(body: string): CallHandlerResponse {
69 const parsed: unknown = JSON.parse(body)
70 if (
71 typeof parsed !== 'object' ||
72 parsed === null ||
73 !('ok' in parsed) ||
74 typeof parsed.ok !== 'boolean'
75 ) {
76 throw new Error(`expected a { ok: boolean } response, got: ${body}`)
77 }
78 return {
79 ok: parsed.ok,
80 result: 'result' in parsed ? parsed.result : undefined,
81 error:
82 'error' in parsed && typeof parsed.error === 'string'
83 ? parsed.error
84 : undefined,
85 }
86}
87
88test.describe('mcp-apps — data + interactive planes', () => {
89 test('STATIC: a ui-linked MCP tool emits a ui-resource part over the stream', async ({
90 request,
91 testId,
92 aimockPort,
93 }) => {
94 const res = await request.post('/api/mcp-apps-chat', {
95 headers: { 'Content-Type': 'application/json' },
96 data: {
97 threadId: `mcp-apps-thread-${testId}`,
98 runId: `mcp-apps-run-${testId}`,
99 state: {},
100 messages: [
101 {
102 id: 'mcp-apps-msg-1',
103 role: 'user',
104 content: '[mcp-apps] show me the widget',
105 },
106 ],
107 tools: [],
108 context: [],
109 forwardedProps: { testId, aimockPort },
110 },
111 })
112
113 const body = await res.text()
114 expect(
115 res.ok(),
116 `mcp-apps-chat route failed (${res.status()}): ${body}`,
117 ).toBe(true)
118
119 const events = parseSse(body)
120
121 // The agentic loop must have invoked the ui-linked tool.
122 const toolStart = events.find(
123 (e) => e.type === 'TOOL_CALL_START' && e.toolCallName === 'show_widget',
124 )
125 expect(toolStart, 'expected a TOOL_CALL_START for show_widget').toBeTruthy()
126
127 // The data-plane assertion: a ui-resource CUSTOM event reached the client.
128 // The HTML (MCP_APPS_WIDGET_OK) originates ONLY from the MCP server's
129 // ui://show_widget resource, so finding it here proves the linked resource
130 // was read and streamed (the read → CUSTOM event path).
131 const uiResource = events.find(
132 (e) => e.type === 'CUSTOM' && e.name === 'ui-resource',
133 )
134 expect(
135 uiResource,
136 'expected a ui-resource CUSTOM event on the stream',
137 ).toBeTruthy()
138
139 const value = uiResource?.value
140 expect(value?.resource?.uri).toBe('ui://show_widget')
141 expect(value?.resource?.mimeType).toBe('text/html')
142 expect(value?.resource?.text ?? '').toContain('MCP_APPS_WIDGET_OK')
143 expect(
144 value?.toolCallId,
145 'ui-resource must reference its tool call',
146 ).toBeTruthy()
147
148 // The run completed cleanly.
149 expect(events.some((e) => e.type === 'RUN_ERROR')).toBe(false)
150 expect(events.some((e) => e.type === 'RUN_FINISHED')).toBe(true)
151 })
152
153 test('INTERACTIVE: a POST to the call handler returns the MCP tool result', async ({
154 request,
155 testId,
156 }) => {
157 const res = await request.post('/api/mcp-apps-call', {
158 headers: { 'Content-Type': 'application/json' },
159 data: {
160 threadId: `mcp-apps-thread-${testId}`,
161 serverId: 'widgets',
162 toolName: 'show_widget',
163 args: { title: 'from-test' },
164 },
165 })
166
167 const body = await res.text()
168 expect(res.ok(), `mcp-apps-call failed (${res.status()}): ${body}`).toBe(
169 true,
170 )
171
172 const json = parseCallResponse(body)
173 expect(json.ok, `expected ok:true, got: ${body}`).toBe(true)
174 // The result carries MCP_APPS_CALL_OK, which only the MCP server produces —
175 // proving callTool actually executed against the in-process server.
176 expect(JSON.stringify(json.result)).toContain('MCP_APPS_CALL_OK')
177 })
178
179 test('INTERACTIVE TASK: the call handler executes a task-required tool', async ({
180 request,
181 testId,
182 }) => {
183 const res = await request.post('/api/mcp-apps-call', {
184 headers: { 'Content-Type': 'application/json' },
185 data: {
186 threadId: `mcp-apps-task-thread-${testId}`,
187 serverId: 'widgets',
188 toolName: 'run_widget_task',
189 args: { action: 'refresh' },
190 },
191 })
192
193 const body = await res.text()
194 expect(res.ok(), `mcp-apps-call failed (${res.status()}): ${body}`).toBe(
195 true,
196 )
197
198 const json = parseCallResponse(body)
199 expect(json.ok, `expected ok:true, got: ${body}`).toBe(true)
200 expect(JSON.stringify(json.result)).toContain(
201 'MCP_APPS_TASK_CALL_OK:refresh',
202 )
203 })
204
205 test('ALLOWLIST: a call for a tool the server does not expose returns ok:false', async ({
206 request,
207 testId,
208 }) => {
209 const res = await request.post('/api/mcp-apps-call', {
210 headers: { 'Content-Type': 'application/json' },
211 data: {
212 threadId: `mcp-apps-thread-${testId}`,
213 serverId: 'widgets',
214 toolName: 'delete_everything',
215 args: {},
216 },
217 })
218
219 const body = await res.text()
220 // The route returns the handler's JSON verbatim with a 200 status; the
221 // rejection is in the body, not the HTTP status.
222 expect(res.ok(), `mcp-apps-call failed (${res.status()}): ${body}`).toBe(
223 true,
224 )
225
226 const json = parseCallResponse(body)
227 expect(json.ok, `expected ok:false for disallowed tool, got: ${body}`).toBe(
228 false,
229 )
230 expect(
231 json.error,
232 `expected error message to mention 'not allowed', got: ${body}`,
233 ).toContain('not allowed')
234 })
235
236 test('APPROVAL: a widget call for a tool that needs approval returns ok:false', async ({
237 request,
238 testId,
239 }) => {
240 const res = await request.post('/api/mcp-apps-call', {
241 headers: { 'Content-Type': 'application/json' },
242 data: {
243 threadId: `mcp-apps-thread-${testId}`,
244 serverId: 'widgets',
245 toolName: 'show_widget',
246 args: { title: 'from-test' },
247 needsApproval: true,
248 },
249 })
250
251 const body = await res.text()
252 expect(res.ok(), `mcp-apps-call failed (${res.status()}): ${body}`).toBe(
253 true,
254 )
255
256 const json = parseCallResponse(body)
257 expect(json.ok, `expected ok:false, got: ${body}`).toBe(false)
258 expect(json.error).toBe('Tool needs approval: show_widget')
259 })
260})