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