Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import { makeMcpAppHost, McpAppHostRefusal, type McpAppHostContext } from "./host.ts";
4
5const app = {
6 attachmentId: "thread-1-app",
7 server: "weather",
8 tool: "get_weather",
9 resourceUri: "ui://weather/dashboard",
10 csp: { connectDomains: ["https://api.weather.test"] },
11};
12
13const context = (
14 theme: "light" | "dark" = "dark",
15 displayMode: "inline" | "fullscreen" = "inline",
16): McpAppHostContext => ({
17 theme,
18 styles: { variables: { "--color-background-primary": theme === "dark" ? "#000" : "#fff" } },
19 displayMode,
20 availableDisplayModes: ["inline", "fullscreen"],
21 containerDimensions: { width: 600, maxHeight: 2000 },
22 platform: "web",
23});
24
25const flush = () => new Promise<void>((resolve) => queueMicrotask(resolve)).then(() => undefined);
26
27const initialize = (
28 host: ReturnType<typeof makeMcpAppHost>,
29 appCapabilities: Record<string, unknown> = {},
30) => {
31 host.receive({
32 jsonrpc: "2.0",
33 id: "init",
34 method: "ui/initialize",
35 params: { appCapabilities },
36 });
37 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
38};
39
40function setup(overrides: Partial<Parameters<typeof makeMcpAppHost>[0]> = {}) {
41 const sent: Array<Record<string, unknown>> = [];
42 let theme: "light" | "dark" = "dark";
43 let mode: "inline" | "fullscreen" = "inline";
44 const host = makeMcpAppHost({
45 app,
46 hostVersion: "1.0.0",
47 post: (message) => sent.push(message as Record<string, unknown>),
48 hostContext: () => context(theme, mode),
49 callTool: async (input) => ({ content: [{ type: "text", text: `called ${input.name}` }] }),
50 readResource: async () => ({ contents: [] }),
51 openLink: async () => undefined,
52 sendMessage: async () => undefined,
53 updateModelContext: async () => undefined,
54 requestDisplayMode: async (next) => {
55 mode = next === "fullscreen" ? "fullscreen" : "inline";
56 return mode;
57 },
58 downloadFile: async () => undefined,
59 onRequestTeardown: () => undefined,
60 onSizeChanged: () => undefined,
61 ...overrides,
62 });
63 return {
64 host,
65 sent,
66 setTheme: (next: "light" | "dark") => {
67 theme = next;
68 },
69 };
70}
71
72describe("makeMcpAppHost", () => {
73 it("initializes, then replays the tool input and result after initialized", () => {
74 const { host, sent } = setup();
75 host.setToolCall({
76 arguments: { city: "Oslo" },
77 result: { content: [{ type: "text", text: "Sunny" }] },
78 });
79 host.receive({
80 jsonrpc: "2.0",
81 id: 1,
82 method: "ui/initialize",
83 params: { protocolVersion: "2026-01-26", appInfo: { name: "a", version: "1" } },
84 });
85 expect(sent[0]).toMatchObject({
86 id: 1,
87 result: {
88 protocolVersion: "2026-01-26",
89 hostCapabilities: { serverTools: {}, sandbox: { csp: app.csp } },
90 hostContext: { theme: "dark", displayMode: "inline" },
91 },
92 });
93 expect(sent).toHaveLength(1);
94
95 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} });
96 expect(sent.slice(1)).toEqual([
97 {
98 jsonrpc: "2.0",
99 method: "ui/notifications/tool-input",
100 params: { arguments: { city: "Oslo" } },
101 },
102 {
103 jsonrpc: "2.0",
104 method: "ui/notifications/tool-result",
105 params: { content: [{ type: "text", text: "Sunny" }] },
106 },
107 ]);
108 });
109
110 it("replays a tool call that arrives after initialization, once", () => {
111 const { host, sent } = setup();
112 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
113 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
114 sent.length = 0;
115 host.setToolCall({ arguments: { city: "Oslo" }, result: undefined });
116 host.setToolCall({ arguments: { city: "Bergen" }, result: undefined });
117 expect(sent).toEqual([
118 {
119 jsonrpc: "2.0",
120 method: "ui/notifications/tool-input",
121 params: { arguments: { city: "Oslo" } },
122 },
123 ]);
124 });
125
126 it("drops null fields providers report, which the MCP Apps SDK rejects", async () => {
127 const { host, sent } = setup({
128 callTool: async () => ({ content: [], structuredContent: null, _meta: null }),
129 });
130 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
131 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
132 host.setToolCall({
133 arguments: {},
134 result: {
135 content: [{ type: "text", text: "t" }],
136 structuredContent: { time: "t" },
137 _meta: null,
138 },
139 });
140 host.receive({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "get-time" } });
141 await flush();
142 expect(sent.find((m) => m.method === "ui/notifications/tool-result")?.params).toEqual({
143 content: [{ type: "text", text: "t" }],
144 structuredContent: { time: "t" },
145 });
146 expect(sent.find((m) => m.id === 2)?.result).toEqual({ content: [] });
147 });
148
149 it("accepts ui/message as one text block or the SDK's block array", async () => {
150 const messages: Array<string> = [];
151 const { host, sent } = setup({ sendMessage: async (text) => void messages.push(text) });
152 host.receive({
153 jsonrpc: "2.0",
154 id: 1,
155 method: "ui/message",
156 params: { role: "user", content: { type: "text", text: "one" } },
157 });
158 host.receive({
159 jsonrpc: "2.0",
160 id: 2,
161 method: "ui/message",
162 params: { role: "user", content: [{ type: "text", text: "two" }] },
163 });
164 host.receive({
165 jsonrpc: "2.0",
166 id: 3,
167 method: "ui/message",
168 params: { role: "user", content: [{ type: "image", data: "x" }] },
169 });
170 host.receive({
171 jsonrpc: "2.0",
172 id: 4,
173 method: "ui/message",
174 params: { role: "user", content: { type: "text", text: " " } },
175 });
176 await flush();
177 expect(messages).toEqual(["one", "two"]);
178 expect(sent.find((m) => m.id === 3)?.error).toMatchObject({ code: -32602 });
179 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
180 });
181
182 it("sends only changed context fields, and nothing before initialization", () => {
183 const { host, sent, setTheme } = setup();
184 setTheme("light");
185 host.updateHostContext();
186 expect(sent).toHaveLength(0);
187
188 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
189 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
190 sent.length = 0;
191 setTheme("dark");
192 host.updateHostContext();
193 expect(sent).toEqual([
194 {
195 jsonrpc: "2.0",
196 method: "ui/notifications/host-context-changed",
197 params: { theme: "dark", styles: context("dark").styles },
198 },
199 ]);
200 host.updateHostContext();
201 expect(sent).toHaveLength(1);
202 });
203
204 it("catches the app up on context that changed while it was initializing", () => {
205 const { host, sent, setTheme } = setup();
206 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
207 setTheme("light");
208 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
209 expect(sent.at(-1)).toEqual({
210 jsonrpc: "2.0",
211 method: "ui/notifications/host-context-changed",
212 params: { theme: "light", styles: context("light").styles },
213 });
214 });
215
216 it("proxies tools/call and reports a refusal as a JSON-RPC error", async () => {
217 const { host, sent } = setup({
218 callTool: async (input) => {
219 if (input.name === "delete_everything")
220 throw new McpAppHostRefusal("Declined by the user.");
221 return { content: [], structuredContent: { ok: true } };
222 },
223 });
224 host.receive({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "refresh" } });
225 host.receive({
226 jsonrpc: "2.0",
227 id: 8,
228 method: "tools/call",
229 params: { name: "delete_everything", arguments: {} },
230 });
231 await flush();
232 expect(sent).toContainEqual({
233 jsonrpc: "2.0",
234 id: 7,
235 result: { content: [], structuredContent: { ok: true } },
236 });
237 expect(sent).toContainEqual({
238 jsonrpc: "2.0",
239 id: 8,
240 error: { code: -32000, message: "Declined by the user." },
241 });
242 });
243
244 it("rejects malformed requests and unsupported methods", () => {
245 const { host, sent } = setup();
246 host.receive({
247 jsonrpc: "2.0",
248 id: 1,
249 method: "ui/open-link",
250 params: { url: "javascript:x" },
251 });
252 host.receive({ jsonrpc: "2.0", id: 3, method: "sampling/createMessage", params: {} });
253 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant" } });
254 expect(sent.map((message) => (message.error as { code: number }).code)).toEqual([
255 -32602, -32601, -32602,
256 ]);
257 });
258
259 it("refuses requests past the in-flight limit and posts nothing after dispose", async () => {
260 let release: () => void = () => undefined;
261 const gate = new Promise<void>((resolve) => {
262 release = resolve;
263 });
264 const { host, sent } = setup({
265 callTool: async () => {
266 await gate;
267 return { content: [] };
268 },
269 });
270 for (let id = 0; id < 17; id++) {
271 host.receive({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "slow" } });
272 }
273 expect(sent).toEqual([
274 { jsonrpc: "2.0", id: 16, error: { code: -32000, message: "Too many requests in flight." } },
275 ]);
276 host.dispose();
277 release();
278 await flush();
279 expect(sent).toHaveLength(1);
280 });
281
282 it("switches display mode only to one both sides offer, and tells the app", async () => {
283 const { host, sent } = setup();
284 initialize(host, { availableDisplayModes: ["inline", "fullscreen"] });
285 sent.length = 0;
286 host.receive({
287 jsonrpc: "2.0",
288 id: 1,
289 method: "ui/request-display-mode",
290 params: { mode: "pip" },
291 });
292 host.receive({
293 jsonrpc: "2.0",
294 id: 2,
295 method: "ui/request-display-mode",
296 params: { mode: "fullscreen" },
297 });
298 await flush();
299 host.updateHostContext();
300 expect(sent.find((m) => m.id === 1)?.result).toEqual({ mode: "inline" });
301 expect(sent.find((m) => m.id === 2)?.result).toEqual({ mode: "fullscreen" });
302 expect(sent.find((m) => m.method === "ui/notifications/host-context-changed")?.params).toEqual({
303 displayMode: "fullscreen",
304 });
305
306 const declined = setup();
307 initialize(declined.host, { availableDisplayModes: ["inline"] });
308 declined.host.receive({
309 jsonrpc: "2.0",
310 id: 3,
311 method: "ui/request-display-mode",
312 params: { mode: "fullscreen" },
313 });
314 await flush();
315 expect(declined.sent.find((m) => m.id === 3)?.result).toEqual({ mode: "inline" });
316 });
317
318 it("forwards model context and download requests, and declares both", async () => {
319 const contexts: Array<unknown> = [];
320 const downloads: Array<unknown> = [];
321 const { host, sent } = setup({
322 updateModelContext: async (update) => void contexts.push(update),
323 downloadFile: async (files) => {
324 downloads.push(files);
325 if (files.length > 1) throw new McpAppHostRefusal("Declined by the user.");
326 },
327 });
328 initialize(host);
329 const capabilities = (
330 sent[0]?.result as { hostCapabilities: Record<string, unknown> } | undefined
331 )?.hostCapabilities;
332 expect(capabilities?.updateModelContext).toEqual({ text: {}, structuredContent: {} });
333 expect(capabilities?.downloadFile).toEqual({});
334
335 host.receive({
336 jsonrpc: "2.0",
337 id: 1,
338 method: "ui/update-model-context",
339 params: { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
340 });
341 const embedded = {
342 type: "resource",
343 resource: { uri: "file:///report.csv", mimeType: "text/csv", text: "a,b" },
344 };
345 host.receive({
346 jsonrpc: "2.0",
347 id: 2,
348 method: "ui/download-file",
349 params: { contents: [embedded] },
350 });
351 host.receive({
352 jsonrpc: "2.0",
353 id: 3,
354 method: "ui/download-file",
355 params: {
356 contents: [embedded, { type: "resource_link", uri: "ui://todos/export", name: "x" }],
357 },
358 });
359 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/download-file", params: { contents: [{}] } });
360 await flush();
361 expect(contexts).toEqual([
362 { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
363 ]);
364 expect(downloads[0]).toEqual([
365 {
366 _tag: "embedded",
367 name: "report.csv",
368 mimeType: "text/csv",
369 bytes: new TextEncoder().encode("a,b"),
370 },
371 ]);
372 expect(sent.find((m) => m.id === 2)?.result).toEqual({});
373 expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
374 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
375 });
376
377 it("tears down after the app answers, or after the timeout, and passes on its own request", async () => {
378 vi.useFakeTimers();
379 try {
380 let closeRequested = false;
381 const { host, sent } = setup({ onRequestTeardown: () => (closeRequested = true) });
382 host.receive({ jsonrpc: "2.0", method: "ui/notifications/request-teardown" });
383 expect(closeRequested).toBe(true);
384
385 await host.teardown();
386 expect(sent.some((m) => m.method === "ui/resource-teardown")).toBe(false);
387
388 const answered = setup();
389 initialize(answered.host);
390 let done = false;
391 void answered.host.teardown().then(() => (done = true));
392 const request = answered.sent.find((m) => m.method === "ui/resource-teardown");
393 expect(request).toBeDefined();
394 answered.host.receive({ jsonrpc: "2.0", id: request?.id, result: {} });
395 await vi.runAllTimersAsync();
396 expect(done).toBe(true);
397
398 const silent = setup();
399 initialize(silent.host);
400 let timedOut = false;
401 void silent.host.teardown().then(() => (timedOut = true));
402 await vi.advanceTimersByTimeAsync(1999);
403 expect(timedOut).toBe(false);
404 await vi.advanceTimersByTimeAsync(1);
405 expect(timedOut).toBe(true);
406 const before = silent.sent.length;
407 silent.host.updateHostContext();
408 expect(silent.sent).toHaveLength(before);
409 } finally {
410 vi.useRealTimers();
411 }
412 });
413});