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

host.test.ts

338 lines11.2 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("accepts ui/message as one text block or the SDK's block array", async () => {
134 const messages: Array<string> = [];
135 const { host, sent } = setup({ sendMessage: async (text) => void messages.push(text) });
136 host.receive({
137 jsonrpc: "2.0",
138 id: 1,
139 method: "ui/message",
140 params: { role: "user", content: { type: "text", text: "one" } },
141 });
142 host.receive({
143 jsonrpc: "2.0",
144 id: 2,
145 method: "ui/message",
146 params: { role: "user", content: [{ type: "text", text: "two" }] },
147 });
148 host.receive({
149 jsonrpc: "2.0",
150 id: 3,
151 method: "ui/message",
152 params: { role: "user", content: [{ type: "image", data: "x" }] },
153 });
154 host.receive({
155 jsonrpc: "2.0",
156 id: 4,
157 method: "ui/message",
158 params: { role: "user", content: { type: "text", text: " " } },
159 });
160 await flush();
161 expect(messages).toEqual(["one", "two"]);
162 expect(sent.find((m) => m.id === 3)?.error).toMatchObject({ code: -32602 });
163 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
164 });
165​
166 it("catches the app up on context that changed while it was initializing", () => {
167 const { host, sent, setTheme } = setup();
168 host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });
169 setTheme("light");
170 host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
171 expect(sent.at(-1)).toEqual({
172 jsonrpc: "2.0",
173 method: "ui/notifications/host-context-changed",
174 params: { theme: "light", styles: context("light").styles },
175 });
176 });
177​
178 it("proxies tools/call and reports a refusal as a JSON-RPC error", async () => {
179 const { host, sent } = setup({
180 callTool: async (input) => {
181 if (input.name === "delete_everything")
182 throw new McpAppHostRefusal("Declined by the user.");
183 return { content: [], structuredContent: { ok: true } };
184 },
185 });
186 host.receive({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "refresh" } });
187 host.receive({
188 jsonrpc: "2.0",
189 id: 8,
190 method: "tools/call",
191 params: { name: "delete_everything", arguments: {} },
192 });
193 await flush();
194 expect(sent).toContainEqual({
195 jsonrpc: "2.0",
196 id: 7,
197 result: { content: [], structuredContent: { ok: true } },
198 });
199 expect(sent).toContainEqual({
200 jsonrpc: "2.0",
201 id: 8,
202 error: { code: -32000, message: "Declined by the user." },
203 });
204 });
205​
206 it("rejects malformed requests and unsupported methods", () => {
207 const { host, sent } = setup();
208 host.receive({
209 jsonrpc: "2.0",
210 id: 1,
211 method: "ui/open-link",
212 params: { url: "javascript:x" },
213 });
214 host.receive({ jsonrpc: "2.0", id: 3, method: "sampling/createMessage", params: {} });
215 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant" } });
216 expect(sent.map((message) => (message.error as { code: number }).code)).toEqual([
217 -32602, -32601, -32602,
218 ]);
219 });
220​
221 it("refuses requests past the in-flight limit and posts nothing after dispose", async () => {
222 let release: () => void = () => undefined;
223 const gate = new Promise<void>((resolve) => {
224 release = resolve;
225 });
226 const { host, sent } = setup({
227 callTool: async () => {
228 await gate;
229 return { content: [] };
230 },
231 });
232 for (let id = 0; id < 17; id++) {
233 host.receive({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "slow" } });
234 }
235 expect(sent).toEqual([
236 { jsonrpc: "2.0", id: 16, error: { code: -32000, message: "Too many requests in flight." } },
237 ]);
238 host.dispose();
239 release();
240 await flush();
241 expect(sent).toHaveLength(1);
242 });
243​
244 it("switches display mode only to one both sides offer, and tells the app", async () => {
245 const { host, sent } = setup();
246 initialize(host, { availableDisplayModes: ["inline", "fullscreen"] });
247 sent.length = 0;
248 host.receive({
249 jsonrpc: "2.0",
250 id: 1,
251 method: "ui/request-display-mode",
252 params: { mode: "pip" },
253 });
254 host.receive({
255 jsonrpc: "2.0",
256 id: 2,
257 method: "ui/request-display-mode",
258 params: { mode: "fullscreen" },
259 });
260 await flush();
261 host.updateHostContext();
262 expect(sent.find((m) => m.id === 1)?.result).toEqual({ mode: "inline" });
263 expect(sent.find((m) => m.id === 2)?.result).toEqual({ mode: "fullscreen" });
264 expect(sent.find((m) => m.method === "ui/notifications/host-context-changed")?.params).toEqual({
265 displayMode: "fullscreen",
266 });
267​
268 const declined = setup();
269 initialize(declined.host, { availableDisplayModes: ["inline"] });
270 declined.host.receive({
271 jsonrpc: "2.0",
272 id: 3,
273 method: "ui/request-display-mode",
274 params: { mode: "fullscreen" },
275 });
276 await flush();
277 expect(declined.sent.find((m) => m.id === 3)?.result).toEqual({ mode: "inline" });
278 });
279​
280 it("forwards model context and download requests, and declares both", async () => {
281 const contexts: Array<unknown> = [];
282 const downloads: Array<unknown> = [];
283 const { host, sent } = setup({
284 updateModelContext: async (update) => void contexts.push(update),
285 downloadFile: async (files) => {
286 downloads.push(files);
287 if (files.length > 1) throw new McpAppHostRefusal("Declined by the user.");
288 },
289 });
290 initialize(host);
291 const capabilities = (
292 sent[0]?.result as { hostCapabilities: Record<string, unknown> } | undefined
293 )?.hostCapabilities;
294 expect(capabilities?.updateModelContext).toEqual({ text: {}, structuredContent: {} });
295 expect(capabilities?.downloadFile).toEqual({});
296​
297 host.receive({
298 jsonrpc: "2.0",
299 id: 1,
300 method: "ui/update-model-context",
301 params: { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
302 });
303 const embedded = {
304 type: "resource",
305 resource: { uri: "file:///report.csv", mimeType: "text/csv", text: "a,b" },
306 };
307 host.receive({
308 jsonrpc: "2.0",
309 id: 2,
310 method: "ui/download-file",
311 params: { contents: [embedded] },
312 });
313 host.receive({
314 jsonrpc: "2.0",
315 id: 3,
316 method: "ui/download-file",
317 params: {
318 contents: [embedded, { type: "resource_link", uri: "ui://todos/export", name: "x" }],
319 },
320 });
321 host.receive({ jsonrpc: "2.0", id: 4, method: "ui/download-file", params: { contents: [{}] } });
322 await flush();
323 expect(contexts).toEqual([
324 { content: [{ type: "text", text: "2 overdue" }], structuredContent: { overdue: 2 } },
325 ]);
326 expect(downloads[0]).toEqual([
327 {
328 _tag: "embedded",
329 name: "report.csv",
330 mimeType: "text/csv",
331 bytes: new TextEncoder().encode("a,b"),
332 },
333 ]);
334 expect(sent.find((m) => m.id === 2)?.result).toEqual({});
335 expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
336 expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
337 });
338});