Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

host.test.ts

391 lines12.9 KB

1import { describe, expect, it } 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 };
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("drops null fields providers report, which the MCP Apps SDK rejects", async () => {
111 const { host, sent } = setup({
112 callTool: async () => ({ content: [], structuredContent: null, _meta: null }),
113 });
114 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
115 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
116 host.setToolCall({
117 arguments: {},
118 result: {
119 content: [{ type: "text", text: "t" }],
120 structuredContent: { time: "t" },
121 _meta: null,
122 },
123 });
124 host.receive({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "get-time" } });
125 await flush();
126 expect(sent.find((m) => m.method === "ui/notifications/tool-result")?.params).toEqual({
127 content: [{ type: "text", text: "t" }],
128 structuredContent: { time: "t" },
129 });
130 expect(sent.find((m) => m.id === 2)?.result).toEqual({ content: [] });
131 });
132​
133 it("sends a later result for a call that had none, without repeating its input", () => {
134 const { host, sent } = setup();
135 initialize(host);
136 sent.length = 0;
137 host.setToolCall({ arguments: { city: "Oslo" }, result: undefined });
138 host.setToolCall({
139 arguments: { city: "Oslo" },
140 result: { content: [{ type: "text", text: "Sunny" }] },
141 });
142 host.setToolCall({
143 arguments: { city: "Bergen" },
144 result: { content: [{ type: "text", text: "Rain" }] },
145 });
146 expect(sent).toEqual([
147 {
148 jsonrpc: "2.0",
149 method: "ui/notifications/tool-input",
150 params: { arguments: { city: "Oslo" } },
151 },
152 {
153 jsonrpc: "2.0",
154 method: "ui/notifications/tool-result",
155 params: { content: [{ type: "text", text: "Sunny" }] },
156 },
157 ]);
158 });
159​
160 it("accepts ui/message as one text block or the SDK's block array", async () => {
161 const messages: Array<string> = [];
162 const { host, sent } = setup({ sendMessage: async (text) => void messages.push(text) });
163 host.receive({
164 jsonrpc: "2.0",
165 id: 1,
166 method: "ui/message",
167 params: { role: "user", content: { type: "text", text: "one" } },
168 });
169 host.receive({
170 jsonrpc: "2.0",
171 id: 2,
172 method: "ui/message",
173 params: { role: "user", content: [{ type: "text", text: "two" }] },
174 });
175 host.receive({
176 jsonrpc: "2.0",
177 id: 3,
178 method: "ui/message",
179 params: { role: "user", content: [{ type: "image", data: "x" }] },
180 });
181 host.receive({
182 jsonrpc: "2.0",
183 id: 4,
184 method: "ui/message",
185 params: { role: "user", content: { type: "text", text: " " } },
186 });
187 await flush();
188 expect(messages).toEqual(["one", "two"]);
189 expect(sent.find((m) => m.id === 3)?.error).toMatchObject({ code: -32602 });
190 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
191 });
192​
193 it("catches the app up on context that changed while it was initializing", () => {
194 const { host, sent, setTheme } = setup();
195 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
196 setTheme("light");
197 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
198 expect(sent.at(-1)).toEqual({
199 jsonrpc: "2.0",
200 method: "ui/notifications/host-context-changed",
201 params: { theme: "light", styles: context("light").styles },
202 });
203 });
204​
205 it("proxies tools/call and reports a refusal as a JSON-RPC error", async () => {
206 const received: unknown[] = [];
207 const { host, sent } = setup({
208 callTool: async (input) => {
209 if (input.name === "delete_everything")
210 throw new McpAppHostRefusal({ message: "Declined by the user." });
211 received.push(input.arguments);
212 return { content: [], structuredContent: { ok: true } };
213 },
214 });
215 host.receive({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "refresh" } });
216 host.receive({
217 jsonrpc: "2.0",
218 id: 8,
219 method: "tools/call",
220 params: { name: "delete_everything", arguments: {} },
221 });
222 // postMessage's structured clone keeps undefined properties, which JSON cannot carry.
223 host.receive({
224 jsonrpc: "2.0",
225 id: 9,
226 method: "tools/call",
227 params: {
228 name: "poll",
229 arguments: { since: undefined, nested: { a: undefined, b: 1 }, list: [1, undefined] },
230 },
231 });
232 await flush();
233 expect(received).toStrictEqual([{}, { nested: { b: 1 }, list: [1, null] }]);
234 expect(sent).toContainEqual({
235 jsonrpc: "2.0",
236 id: 7,
237 result: { content: [], structuredContent: { ok: true } },
238 });
239 expect(sent).toContainEqual({
240 jsonrpc: "2.0",
241 id: 8,
242 error: { code: -32000, message: "Declined by the user." },
243 });
244 });
245​
246 it("rejects malformed requests and unsupported methods", () => {
247 const { host, sent } = setup();
248 host.receive({
249 jsonrpc: "2.0",
250 id: 1,
251 method: "ui/open-link",
252 params: { url: "javascript:x" },
253 });
254 host.receive({ jsonrpc: "2.0", id: 3, method: "sampling/createMessage", params: {} });
255 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant" } });
256 host.receive({
257 jsonrpc: "2.0",
258 id: 5,
259 method: "tools/call",
260 params: { name: "poll", arguments: { since: 1n } },
261 });
262 expect(sent.map((message) => (message.error as { code: number }).code)).toEqual([
263 -32602, -32601, -32602, -32602,
264 ]);
265 });
266​
267 it("refuses requests past the in-flight limit and posts nothing after dispose", async () => {
268 let release: () => void = () => undefined;
269 const gate = new Promise<void>((resolve) => {
270 release = resolve;
271 });
272 const { host, sent } = setup({
273 callTool: async () => {
274 await gate;
275 return { content: [] };
276 },
277 });
278 for (let id = 0; id < 17; id++) {
279 host.receive({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "slow" } });
280 }
281 expect(sent).toEqual([
282 { jsonrpc: "2.0", id: 16, error: { code: -32000, message: "Too many requests in flight." } },
283 ]);
284 host.dispose();
285 release();
286 await flush();
287 expect(sent).toHaveLength(1);
288 });
289​
290 it("switches display mode only to one both sides offer, and tells the app", async () => {
291 const { host, sent } = setup();
292 initialize(host, { availableDisplayModes: ["inline", "fullscreen"] });
293 sent.length = 0;
294 host.receive({
295 jsonrpc: "2.0",
296 id: 1,
297 method: "ui/request-display-mode",
298 params: { mode: "pip" },
299 });
300 host.receive({
301 jsonrpc: "2.0",
302 id: 2,
303 method: "ui/request-display-mode",
304 params: { mode: "fullscreen" },
305 });
306 await flush();
307 host.updateHostContext();
308 expect(sent.find((m) => m.id === 1)?.result).toEqual({ mode: "inline" });
309 expect(sent.find((m) => m.id === 2)?.result).toEqual({ mode: "fullscreen" });
310 expect(sent.find((m) => m.method === "ui/notifications/host-context-changed")?.params).toEqual({
311 displayMode: "fullscreen",
312 });
313​
314 const declined = setup();
315 initialize(declined.host, { availableDisplayModes: ["inline"] });
316 declined.host.receive({
317 jsonrpc: "2.0",
318 id: 3,
319 method: "ui/request-display-mode",
320 params: { mode: "fullscreen" },
321 });
322 await flush();
323 expect(declined.sent.find((m) => m.id === 3)?.result).toEqual({ mode: "inline" });
324 });
325​
326 it("forwards model context and download requests, and declares both", async () => {
327 const contexts: Array<unknown> = [];
328 const downloads: Array<ReadonlyArray<{ readonly name: string }>> = [];
329 const { host, sent } = setup({
330 updateModelContext: async (update) => void contexts.push(update),
331 downloadFile: async (files) => {
332 downloads.push(files);
333 if (files.length > 1) throw new McpAppHostRefusal({ message: "Declined by the user." });
334 },
335 });
336 initialize(host);
337 const capabilities = (
338 sent[0]?.result as { hostCapabilities: Record<string, unknown> } | undefined
339 )?.hostCapabilities;
340 expect(capabilities?.updateModelContext).toEqual({ text: {}, structuredContent: {} });
341 expect(capabilities?.downloadFile).toEqual({});
342​
343 host.receive({
344 jsonrpc: "2.0",
345 id: 1,
346 method: "ui/update-model-context",
347 params: {
348 content: [{ type: "text", text: "2 overdue" }],
349 structuredContent: { overdue: 2, since: undefined },
350 },
351 });
352 const longName = `${"a".repeat(199)}😀.csv`;
353 const embedded = {
354 type: "resource",
355 resource: { uri: "file:///report.csv", mimeType: "text/csv", text: "a,b" },
356 };
357 host.receive({
358 jsonrpc: "2.0",
359 id: 2,
360 method: "ui/download-file",
361 params: { contents: [embedded] },
362 });
363 host.receive({
364 jsonrpc: "2.0",
365 id: 3,
366 method: "ui/download-file",
367 params: {
368 contents: [embedded, { type: "resource_link", uri: "ui://todos/export", name: longName }],
369 },
370 });
371 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/download-file", params: { contents: [{}] } });
372 await flush();
373 expect(contexts).toStrictEqual([
374 { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
375 ]);
376 expect(downloads[0]).toEqual([
377 {
378 _tag: "embedded",
379 name: "report.csv",
380 mimeType: "text/csv",
381 bytes: new TextEncoder().encode("a,b"),
382 },
383 ]);
384 const capped = downloads[1]?.[1]?.name ?? "";
385 expect(capped.length).toBeLessThanOrEqual(200);
386 expect(capped.isWellFormed()).toBe(true);
387 expect(sent.find((m) => m.id === 2)?.result).toEqual({});
388 expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
389 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
390 });
391});