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

host.test.ts

365 lines12.0 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 { host, sent } = setup({
207 callTool: async (input) => {
208 if (input.name === "delete_everything")
209 throw new McpAppHostRefusal({ message: "Declined by the user." });
210 return { content: [], structuredContent: { ok: true } };
211 },
212 });
213 host.receive({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "refresh" } });
214 host.receive({
215 jsonrpc: "2.0",
216 id: 8,
217 method: "tools/call",
218 params: { name: "delete_everything", arguments: {} },
219 });
220 await flush();
221 expect(sent).toContainEqual({
222 jsonrpc: "2.0",
223 id: 7,
224 result: { content: [], structuredContent: { ok: true } },
225 });
226 expect(sent).toContainEqual({
227 jsonrpc: "2.0",
228 id: 8,
229 error: { code: -32000, message: "Declined by the user." },
230 });
231 });
232​
233 it("rejects malformed requests and unsupported methods", () => {
234 const { host, sent } = setup();
235 host.receive({
236 jsonrpc: "2.0",
237 id: 1,
238 method: "ui/open-link",
239 params: { url: "javascript:x" },
240 });
241 host.receive({ jsonrpc: "2.0", id: 3, method: "sampling/createMessage", params: {} });
242 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant" } });
243 expect(sent.map((message) => (message.error as { code: number }).code)).toEqual([
244 -32602, -32601, -32602,
245 ]);
246 });
247​
248 it("refuses requests past the in-flight limit and posts nothing after dispose", async () => {
249 let release: () => void = () => undefined;
250 const gate = new Promise<void>((resolve) => {
251 release = resolve;
252 });
253 const { host, sent } = setup({
254 callTool: async () => {
255 await gate;
256 return { content: [] };
257 },
258 });
259 for (let id = 0; id < 17; id++) {
260 host.receive({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "slow" } });
261 }
262 expect(sent).toEqual([
263 { jsonrpc: "2.0", id: 16, error: { code: -32000, message: "Too many requests in flight." } },
264 ]);
265 host.dispose();
266 release();
267 await flush();
268 expect(sent).toHaveLength(1);
269 });
270​
271 it("switches display mode only to one both sides offer, and tells the app", async () => {
272 const { host, sent } = setup();
273 initialize(host, { availableDisplayModes: ["inline", "fullscreen"] });
274 sent.length = 0;
275 host.receive({
276 jsonrpc: "2.0",
277 id: 1,
278 method: "ui/request-display-mode",
279 params: { mode: "pip" },
280 });
281 host.receive({
282 jsonrpc: "2.0",
283 id: 2,
284 method: "ui/request-display-mode",
285 params: { mode: "fullscreen" },
286 });
287 await flush();
288 host.updateHostContext();
289 expect(sent.find((m) => m.id === 1)?.result).toEqual({ mode: "inline" });
290 expect(sent.find((m) => m.id === 2)?.result).toEqual({ mode: "fullscreen" });
291 expect(sent.find((m) => m.method === "ui/notifications/host-context-changed")?.params).toEqual({
292 displayMode: "fullscreen",
293 });
294​
295 const declined = setup();
296 initialize(declined.host, { availableDisplayModes: ["inline"] });
297 declined.host.receive({
298 jsonrpc: "2.0",
299 id: 3,
300 method: "ui/request-display-mode",
301 params: { mode: "fullscreen" },
302 });
303 await flush();
304 expect(declined.sent.find((m) => m.id === 3)?.result).toEqual({ mode: "inline" });
305 });
306​
307 it("forwards model context and download requests, and declares both", async () => {
308 const contexts: Array<unknown> = [];
309 const downloads: Array<unknown> = [];
310 const { host, sent } = setup({
311 updateModelContext: async (update) => void contexts.push(update),
312 downloadFile: async (files) => {
313 downloads.push(files);
314 if (files.length > 1) throw new McpAppHostRefusal({ message: "Declined by the user." });
315 },
316 });
317 initialize(host);
318 const capabilities = (
319 sent[0]?.result as { hostCapabilities: Record<string, unknown> } | undefined
320 )?.hostCapabilities;
321 expect(capabilities?.updateModelContext).toEqual({ text: {}, structuredContent: {} });
322 expect(capabilities?.downloadFile).toEqual({});
323​
324 host.receive({
325 jsonrpc: "2.0",
326 id: 1,
327 method: "ui/update-model-context",
328 params: { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
329 });
330 const embedded = {
331 type: "resource",
332 resource: { uri: "file:///report.csv", mimeType: "text/csv", text: "a,b" },
333 };
334 host.receive({
335 jsonrpc: "2.0",
336 id: 2,
337 method: "ui/download-file",
338 params: { contents: [embedded] },
339 });
340 host.receive({
341 jsonrpc: "2.0",
342 id: 3,
343 method: "ui/download-file",
344 params: {
345 contents: [embedded, { type: "resource_link", uri: "ui://todos/export", name: "x" }],
346 },
347 });
348 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/download-file", params: { contents: [{}] } });
349 await flush();
350 expect(contexts).toEqual([
351 { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
352 ]);
353 expect(downloads[0]).toEqual([
354 {
355 _tag: "embedded",
356 name: "report.csv",
357 mimeType: "text/csv",
358 bytes: new TextEncoder().encode("a,b"),
359 },
360 ]);
361 expect(sent.find((m) => m.id === 2)?.result).toEqual({});
362 expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
363 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
364 });
365});