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

host.ts

534 lines18.9 KB

1// @effect-diagnostics globalTimers:off - The bridge runs in the client, outside an Effect runtime.
2import { MCP_APP_PROTOCOL_VERSION, type McpAppReference } from "@t3tools/shared/mcpApp";
3import * as Base64 from "effect/encoding/Base64";
4import * as Predicate from "effect/Predicate";
5import * as Result from "effect/Result";
6​
7const MAX_MESSAGE_BYTES = 256 * 1024;
8const MAX_PENDING_REQUESTS = 16;
9const TEARDOWN_TIMEOUT_MS = 2000;
10const encoder = new TextEncoder();
11​
12type JsonRpcId = string | number;
13​
14export type McpAppDisplayMode = "inline" | "fullscreen" | "pip";
15​
16export interface McpAppHostContext {
17 readonly theme: "light" | "dark";
18 readonly styles: { readonly variables: Readonly<Record<string, string>> };
19 readonly displayMode: McpAppDisplayMode;
20 readonly availableDisplayModes: ReadonlyArray<McpAppDisplayMode>;
21 /**
22 * `maxHeight` when the host sizes the frame to the app's reported height,
23 * `height` when the frame is a fixed box the app must fit (spec
24 * "Container Dimensions").
25 */
26 readonly containerDimensions:
27 | { readonly width: number; readonly maxHeight: number }
28 | { readonly width: number; readonly height: number };
29 readonly platform: "web" | "desktop" | "mobile";
30 readonly locale?: string;
31 readonly timeZone?: string;
32 readonly userAgent?: string;
33 readonly deviceCapabilities?: { readonly touch?: boolean; readonly hover?: boolean };
34 readonly safeAreaInsets?: {
35 readonly top: number;
36 readonly right: number;
37 readonly bottom: number;
38 readonly left: number;
39 };
40 readonly toolInfo?: { readonly tool: unknown };
42​
43export type McpAppDownload =
44 | {
45 readonly _tag: "embedded";
46 readonly name: string;
47 readonly mimeType: string;
48 readonly bytes: Uint8Array;
49 }
50 | {
51 readonly _tag: "link";
52 readonly name: string;
53 readonly uri: string;
54 readonly mimeType?: string;
55 };
56​
57export function mcpResourceBytes(content: unknown): Uint8Array | undefined {
58 if (!Predicate.isObject(content)) return undefined;
59 if (typeof content.text === "string") return encoder.encode(content.text);
60 if (typeof content.blob === "string") {
61 const decoded = Base64.decode(content.blob);
62 return Result.isSuccess(decoded) ? decoded.success : undefined;
63 }
64 return undefined;
66​
67export interface McpAppCallToolResult {
68 readonly content: ReadonlyArray<unknown>;
69 readonly structuredContent?: unknown;
70 readonly isError?: boolean | undefined;
71 readonly _meta?: unknown;
73​
74export class McpAppHostRefusal extends Error {}
75​
76export interface McpAppHostOptions {
77 readonly app: McpAppReference;
78 readonly hostVersion: string;
79 readonly post: (message: unknown) => void;
80 readonly hostContext: () => McpAppHostContext;
81​
82 readonly callTool: (input: {
83 readonly name: string;
84 readonly arguments: Record<string, unknown>;
85 }) => Promise<McpAppCallToolResult>;
86 readonly readResource: (input: { readonly uri: string }) => Promise<unknown>;
87 readonly openLink: (url: string) => Promise<void>;
88 readonly sendMessage: (text: string) => Promise<void>;
89 /** Replaces what this app tells the agent on its next turn; undefined content clears it. */
90 readonly updateModelContext: (context: {
91 readonly content?: ReadonlyArray<unknown>;
92 readonly structuredContent?: Record<string, unknown>;
93 }) => Promise<void>;
94 readonly requestDisplayMode: (mode: McpAppDisplayMode) => Promise<McpAppDisplayMode>;
95 readonly downloadFile: (files: ReadonlyArray<McpAppDownload>) => Promise<void>;
96 readonly onRequestTeardown: () => void;
97 readonly onSizeChanged: (size: { readonly width?: number; readonly height?: number }) => void;
99​
100export interface McpAppHost {
101 /** Handles one message the app posted; the caller has already checked its source. */
102 readonly receive: (data: unknown) => void;
103 readonly setToolCall: (call: {
104 readonly arguments: unknown;
105 readonly result: McpAppCallToolResult | undefined;
106 }) => void;
107 readonly updateHostContext: () => void;
108 /**
109 * Asks the app to wrap up before its document goes away (`ui/resource-teardown`),
110 * resolving once it answers or after a short timeout, then disposes the host.
111 */
112 readonly teardown: () => Promise<void>;
113 readonly dispose: () => void;
115​
116function jsonBytes(value: unknown): number {
117 try {
118 return encoder.encode(JSON.stringify(value) ?? "").byteLength;
119 } catch {
120 return Number.POSITIVE_INFINITY;
121 }
123​
124function isId(value: unknown): value is JsonRpcId {
125 return typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
127​
128/**
129 * Providers can report absent fields as null (Codex sends `_meta: null`), which
130 * the MCP Apps SDK rejects, dropping the whole notification or response.
131 */
132function normalizeMcpAppToolResult(result: McpAppCallToolResult): McpAppCallToolResult {
133 return {
134 content: Array.isArray(result.content) ? result.content : [],
135 ...(Predicate.isObject(result.structuredContent)
136 ? { structuredContent: result.structuredContent }
137 : {}),
138 ...(result.isError === true ? { isError: true } : {}),
139 ...(Predicate.isObject(result._meta) ? { _meta: result._meta } : {}),
140 };
142​
143const errorMessage = (error: unknown) =>
144 error instanceof McpAppHostRefusal
145 ? error.message
146 : error instanceof Error && error.message.trim() !== ""
147 ? error.message
148 : "Request failed.";
149​
150export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost {
151 let initialized = false;
152 let disposed = false;
153 let toolCall:
154 | { readonly arguments: unknown; readonly result: McpAppCallToolResult | undefined }
155 | undefined;
156 let toolCallSent = false;
157 let pending = 0;
158 let sentContext: McpAppHostContext | undefined;
159 let appDisplayModes: ReadonlyArray<string> | undefined;
160 let nextHostRequestId = 0;
161 const hostRequests = new Map<string, () => void>();
162​
163 const post = (message: unknown) => {
164 if (!disposed) options.post(message);
165 };
166 const notify = (method: string, params: unknown) => post({ jsonrpc: "2.0", method, params });
167 const respond = (id: JsonRpcId, result: unknown) => post({ jsonrpc: "2.0", id, result });
168 const fail = (id: JsonRpcId, code: number, message: string) =>
169 post({ jsonrpc: "2.0", id, error: { code, message } });
170​
171 const sendToolCall = () => {
172 if (!initialized || toolCall === undefined || toolCallSent) return;
173 toolCallSent = true;
174 notify("ui/notifications/tool-input", {
175 arguments: Predicate.isObject(toolCall.arguments) ? toolCall.arguments : {},
176 });
177 if (toolCall.result !== undefined) {
178 notify("ui/notifications/tool-result", normalizeMcpAppToolResult(toolCall.result));
179 }
180 };
181​
182 const answer = (id: JsonRpcId, run: () => Promise<unknown>) => {
183 if (pending >= MAX_PENDING_REQUESTS) {
184 fail(id, -32000, "Too many requests in flight.");
185 return;
186 }
187 pending += 1;
188 void run().then(
189 (result) => {
190 pending -= 1;
191 respond(id, result);
192 },
193 (error: unknown) => {
194 pending -= 1;
195 fail(id, -32000, errorMessage(error));
196 },
197 );
198 };
199​
200 const handleRequest = (id: JsonRpcId, method: string, params: Record<PropertyKey, unknown>) => {
201 switch (method) {
202 case "ui/initialize": {
203 const requested = params.protocolVersion;
204 const declared = Predicate.isObject(params.appCapabilities)
205 ? params.appCapabilities.availableDisplayModes
206 : undefined;
207 appDisplayModes = Array.isArray(declared)
208 ? declared.filter((mode): mode is string => typeof mode === "string")
209 : undefined;
210 sentContext = options.hostContext();
211 respond(id, {
212 protocolVersion:
213 requested === MCP_APP_PROTOCOL_VERSION ? requested : MCP_APP_PROTOCOL_VERSION,
214 hostInfo: { name: "t3-code", version: options.hostVersion },
215 hostCapabilities: {
216 openLinks: {},
217 serverTools: {},
218 serverResources: {},
219 logging: {},
220 message: { text: {} },
221 updateModelContext: { text: {}, structuredContent: {} },
222 downloadFile: {},
223 sandbox: {
224 ...(options.app.csp === undefined ? {} : { csp: options.app.csp }),
225 ...(options.app.permissions === undefined
226 ? {}
227 : { permissions: options.app.permissions }),
228 },
229 },
230 hostContext: sentContext,
231 });
232 return;
233 }
234 case "ping":
235 respond(id, {});
236 return;
237 case "tools/call": {
238 const name = params.name;
239 const args = params.arguments ?? {};
240 if (typeof name !== "string" || name.trim() === "" || !Predicate.isObject(args)) {
241 fail(id, -32602, "tools/call needs a tool name and object arguments.");
242 return;
243 }
244 answer(id, () =>
245 options
246 .callTool({ name, arguments: args as Record<string, unknown> })
247 .then(normalizeMcpAppToolResult),
248 );
249 return;
250 }
251 case "resources/read": {
252 const uri = params.uri;
253 if (typeof uri !== "string" || uri.trim() === "") {
254 fail(id, -32602, "resources/read needs a uri.");
255 return;
256 }
257 answer(id, () => options.readResource({ uri }));
258 return;
259 }
260 case "ui/open-link": {
261 const url = params.url;
262 if (typeof url !== "string" || !/^https?:\/\//i.test(url)) {
263 fail(id, -32602, "Only http(s) links can be opened.");
264 return;
265 }
266 answer(id, () => options.openLink(url).then(() => ({})));
267 return;
268 }
269 case "ui/message": {
270 // The SDK sends an array of content blocks; the spec text shows one block.
271 const blocks = Array.isArray(params.content) ? params.content : [params.content];
272 const texts = blocks.map((block) =>
273 Predicate.isObject(block) && block.type === "text" && typeof block.text === "string"
274 ? block.text
275 : undefined,
276 );
277 if (params.role !== "user" || texts.length === 0 || texts.includes(undefined)) {
278 fail(id, -32602, "Only text messages from the user role are supported.");
279 return;
280 }
281 const text = texts.join("\n").trim();
282 if (text === "") {
283 fail(id, -32602, "ui/message needs non-empty text.");
284 return;
285 }
286 answer(id, () => options.sendMessage(text).then(() => ({})));
287 return;
288 }
289 case "ui/request-display-mode": {
290 const current = options.hostContext().displayMode;
291 const mode = params.mode;
292 // A mode the host lacks, or the app did not declare, leaves the
293 // current one; the spec has the host answer with whichever applies.
294 const allowed =
295 typeof mode === "string" &&
296 options.hostContext().availableDisplayModes.includes(mode as McpAppDisplayMode) &&
297 (appDisplayModes === undefined || appDisplayModes.includes(mode));
298 if (!allowed || mode === current) {
299 respond(id, { mode: current });
300 return;
301 }
302 answer(id, () =>
303 options
304 .requestDisplayMode(mode as McpAppDisplayMode)
305 .then((result) => ({ mode: result })),
306 );
307 return;
308 }
309 case "ui/update-model-context": {
310 const content = params.content;
311 const structured = params.structuredContent;
312 if (
313 (content !== undefined && !Array.isArray(content)) ||
314 (structured !== undefined && !Predicate.isObject(structured))
315 ) {
316 fail(
317 id,
318 -32602,
319 "Model context needs content blocks or an object of structured content.",
320 );
321 return;
322 }
323 answer(id, () =>
324 options
325 .updateModelContext({
326 ...(content === undefined ? {} : { content }),
327 ...(structured === undefined
328 ? {}
329 : { structuredContent: structured as Record<string, unknown> }),
330 })
331 .then(() => ({})),
332 );
333 return;
334 }
335 case "ui/download-file": {
336 const files = readDownloads(params.contents);
337 if (files === undefined) {
338 fail(id, -32602, "ui/download-file needs embedded resources or resource links.");
339 return;
340 }
341 answer(id, () =>
342 options.downloadFile(files).then(
343 () => ({}),
344 (error: unknown) =>
345 error instanceof McpAppHostRefusal ? { isError: true } : Promise.reject(error),
346 ),
347 );
348 return;
349 }
350 default:
351 fail(id, -32601, `Method not found: ${method}`);
352 }
353 };
354​
355 const handleNotification = (method: string, params: Record<PropertyKey, unknown>) => {
356 switch (method) {
357 case "ui/notifications/initialized": {
358 if (initialized) return;
359 initialized = true;
360 sendToolCall();
361 hostHandle.updateHostContext();
362 return;
363 }
364 case "ui/notifications/size-changed": {
365 const width = typeof params.width === "number" ? params.width : undefined;
366 const height = typeof params.height === "number" ? params.height : undefined;
367 if (width !== undefined || height !== undefined) {
368 options.onSizeChanged({
369 ...(width === undefined ? {} : { width }),
370 ...(height === undefined ? {} : { height }),
371 });
372 }
373 return;
374 }
375 case "ui/notifications/request-teardown":
376 options.onRequestTeardown();
377 return;
378 default:
379 }
380 };
381​
382 const handleResponse = (id: JsonRpcId) => {
383 const settle = hostRequests.get(String(id));
384 if (settle === undefined) return;
385 hostRequests.delete(String(id));
386 settle();
387 };
388​
389 const hostHandle: McpAppHost = {
390 receive: (data) => {
391 if (disposed || !Predicate.isObject(data) || data.jsonrpc !== "2.0") return;
392 if (jsonBytes(data) > MAX_MESSAGE_BYTES) {
393 if (isId(data.id) && typeof data.method === "string") {
394 fail(data.id, -32600, "Message too large.");
395 }
396 return;
397 }
398 const method = data.method;
399 if (typeof method !== "string") {
400 if (isId(data.id) && ("result" in data || "error" in data)) handleResponse(data.id);
401 return;
402 }
403 const params = Predicate.isObject(data.params) ? data.params : {};
404 if (isId(data.id)) handleRequest(data.id, method, params);
405 else handleNotification(method, params);
406 },
407 setToolCall: (call) => {
408 toolCall ??= call;
409 sendToolCall();
410 },
411 updateHostContext: () => {
412 // The spec forbids messages before the app finishes initializing; it
413 // reads the then-current context from the initialize response anyway.
414 if (!initialized || sentContext === undefined) return;
415 const next = options.hostContext();
416 const changes: Record<string, unknown> = {};
417 for (const key of Object.keys(next) as Array<keyof McpAppHostContext>) {
418 if (JSON.stringify(next[key]) !== JSON.stringify(sentContext[key])) {
419 changes[key] = next[key];
420 }
421 }
422 sentContext = next;
423 if (Object.keys(changes).length > 0) {
424 notify("ui/notifications/host-context-changed", changes);
425 }
426 },
427 teardown: () =>
428 new Promise<void>((resolve) => {
429 let timer: ReturnType<typeof setTimeout> | undefined;
430 const finish = () => {
431 clearTimeout(timer);
432 disposed = true;
433 resolve();
434 };
435 // Before initialization the app has nothing to save and may not be
436 // listening; the spec only asks for teardown after it.
437 if (disposed || !initialized) {
438 finish();
439 return;
440 }
441 const id = `t3-host-${nextHostRequestId++}`;
442 hostRequests.set(id, finish);
443 timer = setTimeout(() => {
444 hostRequests.delete(id);
445 finish();
446 }, TEARDOWN_TIMEOUT_MS);
447 post({ jsonrpc: "2.0", id, method: "ui/resource-teardown", params: {} });
448 }),
449 dispose: () => {
450 disposed = true;
451 },
452 };
453 return hostHandle;
455​
456const MAX_DOWNLOAD_NAME = 200;
457​
458function downloadName(uri: unknown, name: unknown): string {
459 const raw =
460 typeof name === "string" && name.trim() !== ""
461 ? name
462 : typeof uri === "string"
463 ? (uri.split(/[/?#]/).findLast(Boolean) ?? "download")
464 : "download";
465 const safe = Array.from(raw, (char) =>
466 /[\\/:*?"<>|]/.test(char) || char.charCodeAt(0) < 32 ? "-" : char,
467 ).join("");
468 return safe.slice(0, MAX_DOWNLOAD_NAME) || "download";
470​
471function readDownloads(contents: unknown): ReadonlyArray<McpAppDownload> | undefined {
472 if (!Array.isArray(contents) || contents.length === 0) return undefined;
473 const files: Array<McpAppDownload> = [];
474 for (const entry of contents) {
475 if (!Predicate.isObject(entry)) return undefined;
476 if (entry.type === "resource" && Predicate.isObject(entry.resource)) {
477 const resource = entry.resource;
478 const bytes = mcpResourceBytes(resource);
479 if (bytes === undefined) return undefined;
480 files.push({
481 _tag: "embedded",
482 name: downloadName(resource.uri, resource.name),
483 mimeType:
484 typeof resource.mimeType === "string" ? resource.mimeType : "application/octet-stream",
485 bytes,
486 });
487 } else if (entry.type === "resource_link" && typeof entry.uri === "string") {
488 files.push({
489 _tag: "link",
490 name: downloadName(entry.uri, entry.name),
491 uri: entry.uri,
492 ...(typeof entry.mimeType === "string" ? { mimeType: entry.mimeType } : {}),
493 });
494 } else {
495 return undefined;
496 }
497 }
498 return files;
500​
501export function mcpAppStyleVariables(
502 theme: Readonly<Record<string, string>>,
503): Record<string, string> {
504 const pick = (name: string) => theme[name];
505 const pairs: ReadonlyArray<readonly [string, string | undefined]> = [
506 ["--color-background-primary", pick("--background")],
507 ["--color-background-secondary", pick("--card")],
508 ["--color-background-tertiary", pick("--muted")],
509 ["--color-background-inverse", pick("--foreground")],
510 ["--color-background-info", pick("--info")],
511 ["--color-background-danger", pick("--destructive-surface")],
512 ["--color-background-warning", pick("--warning-surface")],
513 ["--color-text-primary", pick("--foreground")],
514 ["--color-text-secondary", pick("--muted-foreground")],
515 ["--color-text-tertiary", pick("--muted-foreground")],
516 ["--color-text-inverse", pick("--background")],
517 ["--color-text-info", pick("--info-foreground")],
518 ["--color-text-danger", pick("--destructive-foreground")],
519 ["--color-text-success", pick("--success-foreground")],
520 ["--color-text-warning", pick("--warning-foreground")],
521 ["--color-border-primary", pick("--border")],
522 ["--color-border-secondary", pick("--input")],
523 ["--color-border-danger", pick("--destructive")],
524 ["--color-ring-primary", pick("--ring")],
525 ["--font-sans", pick("--font-sans")],
526 ["--font-mono", pick("--font-mono")],
527 ["--border-radius-md", pick("--radius")],
528 ];
529 const variables: Record<string, string> = {};
530 for (const [name, value] of pairs) {
531 if (value !== undefined && value !== "") variables[name] = value;
532 }
533 return variables;