The best way to control Claude Code, Codex and more from any computer or phone

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