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

McpAppFrame.tsx

494 lines19.3 KB

1import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import {
3 makeMcpAppHost,
4 McpAppHostRefusal,
5 mcpAppStyleVariables,
6 mcpResourceBytes,
7 type McpAppCallToolResult,
8 type McpAppDisplayMode,
9 type McpAppHost,
10 type McpAppHostContext,
11} from "@t3tools/client-runtime/mcp-apps";
12import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13import {
14 clampMcpAppHeight,
15 MCP_APP_COLOR_SCHEME_PARAM,
16 MCP_APP_DEFAULT_HEIGHT,
17 MCP_APP_MAX_HEIGHT,
18 mcpAppAllowAttribute,
19 mcpAppFileName,
20 type McpAppReference,
21} from "@t3tools/shared/mcpApp";
22import { Minimize2Icon } from "lucide-react";
23import { useEffect, useRef, useState, type FocusEvent, type ToggleEvent } from "react";
24import { flushSync } from "react-dom";
25​
26import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls";
27import { APP_VERSION } from "~/branding";
28import { isConfirmDialogActive, requestConfirmDialog } from "~/confirmDialog";
29import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
30import { useStableCallback } from "~/hooks/useStableCallback";
31import { Button } from "~/components/ui/button";
32import { isElectron } from "~/env";
33import { cn } from "~/lib/utils";
34import { useEnvironmentQuery } from "~/state/query";
35import { useTurnItemDetail } from "~/state/queries";
36import { mcpAppEnvironment } from "~/state/mcpApps";
37import { useAtomCommand } from "~/state/use-atom-command";
38import { observeResize } from "~/lib/observeResize";
39​
40const commandFailure = (result: {
41 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
42}) => {
43 const error = squashAtomCommandFailure(result);
44 return new McpAppHostRefusal({
45 message:
46 error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
47 });
48};
49​
50const fullscreenSupported =
51 typeof HTMLElement !== "undefined" && "popover" in HTMLElement.prototype;
52​
53const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
54// Exclude activation left by input elsewhere in T3.
55const PAGE_ACTIVATION_MS = 5_000;
56​
57// Frame input does not bubble here. An app can refocus itself, so focus
58// alone cannot exclude activation from input elsewhere in T3.
59let lastPageInputAt = Number.NEGATIVE_INFINITY;
60if (typeof window !== "undefined") {
61 const note = () => {
62 lastPageInputAt = performance.now();
63 };
64 if (navigator.userActivation?.isActive) note();
65 for (const type of ["pointerdown", "pointerup", "touchend", "keydown"] as const) {
66 window.addEventListener(type, note, true);
67 }
69​
70function saveBlob(blob: Blob, name: string) {
71 const url = URL.createObjectURL(blob);
72 const link = document.createElement("a");
73 link.href = url;
74 link.download = name;
75 link.click();
76 // Browsers may start downloading after the click's task; defer revocation.
77 setTimeout(() => URL.revokeObjectURL(url), 60_000);
79​
80export function McpAppFrame(props: {
81 readonly environmentId: EnvironmentId;
82 readonly threadId: ThreadId;
83 readonly conversationThreadId: ThreadId;
84 readonly itemId: TurnItemId;
85 readonly revision: string;
86 readonly app: McpAppReference;
87 readonly onSendMessage: ((text: string) => Promise<void>) | undefined;
88 readonly awaitingUser?: boolean;
89 readonly onFullscreenChange?: (fullscreen: boolean) => void;
90}) {
91 const { app } = props;
92 const theme = useHtmlRenderTheme();
93 const frameRef = useRef<HTMLIFrameElement>(null);
94 const boxRef = useRef<HTMLDivElement>(null);
95 const [width, setWidth] = useState(0);
96 const [height, setHeight] = useState(MCP_APP_DEFAULT_HEIGHT);
97 const [navigatedAway, setNavigatedAway] = useState(false);
98 const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
99 const [closed, setClosed] = useState(false);
100 const [documentGeneration, setDocumentGeneration] = useState(0);
101 // Closing and reopening replaces the box, which re-attaches this.
102 const attachBox = (box: HTMLDivElement) => {
103 boxRef.current = box;
104 setWidth(box.clientWidth);
105 const stopResize = observeResize(box, ([entry]) => {
106 if (entry) setWidth(Math.round(entry.contentRect.width));
107 // Full screen reports the viewport, which can change height alone.
108 if (fullscreenSupported && box.matches(":popover-open")) {
109 hostRef.current?.updateHostContext();
110 }
111 });
112 return () => {
113 stopResize();
114 boxRef.current = null;
115 };
116 };
117​
118 const resource = {
119 _tag: "attachment" as const,
120 attachmentId: app.attachmentId,
121 fileName: mcpAppFileName(app),
122 mimeType: "text/html",
123 disposition: "inline" as const,
124 renderIntent: "mcp-app" as const,
125 };
126 // The frame keeps its first URL: a re-minted one would reload the app.
127 const [src, setSrc] = useState<string | null>(null);
128 const asset = useLongLivedAssetUrl(src === null ? props.environmentId : null, resource);
129 if (src === null && asset._tag === "Success") {
130 // The app paints before `ui/initialize`, so it reads the initial scheme from its URL.
131 const url = new URL(asset.url);
132 url.searchParams.set(MCP_APP_COLOR_SCHEME_PARAM, theme.appearance);
133 setSrc(url.toString());
134 }
135​
136 const detail = useTurnItemDetail({
137 environmentId: props.environmentId,
138 threadId: props.threadId,
139 itemId: props.itemId,
140 revision: props.revision,
141 });
142 const storedItem = detail.data?.item;
143 // Keep tool-call identity stable for the host's delivery effect.
144 const toolCall =
145 storedItem?.type === "dynamic_tool"
146 ? {
147 arguments: storedItem.input,
148 result: (storedItem.output as { readonly result?: unknown } | undefined)?.result as
149 | McpAppCallToolResult
150 | undefined,
151 }
152 : undefined;
153​
154 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
155 const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
156 const toolDefinition = useEnvironmentQuery(
157 mcpAppEnvironment.toolInfoQuery({
158 environmentId: props.environmentId,
159 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
160 }),
161 ).data?.tool;
162 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
163 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
164 reportFailure: false,
165 });
166​
167 // Read live values without rebuilding the host and losing the app session.
168 const readLive = useStableCallback(() => ({
169 theme,
170 width,
171 props,
172 callTool,
173 toolInfo,
174 readResource,
175 updateModelContext,
176 displayMode,
177 toolDefinition,
178 }));
179 const hostRef = useRef<McpAppHost | null>(null);
180​
181 const [stepAsideFor, setStepAsideFor] = useState(props.awaitingUser);
182 if (stepAsideFor !== props.awaitingUser) {
183 setStepAsideFor(props.awaitingUser);
184 if (props.awaitingUser === true) setDisplayMode("inline");
185 }
186 // The box is in the top layer exactly while its full-screen chrome is
187 // mounted, so every way out of full screen (including the step-aside above,
188 // decided during render) closes the popover and releases the timeline pin.
189 const attachFullscreenChrome = (chrome: HTMLDivElement) => {
190 const box = chrome.parentElement;
191 if (box === null) return;
192 if (!box.matches(":popover-open")) box.showPopover();
193 readLive().props.onFullscreenChange?.(true);
194 return () => {
195 if (box.matches(":popover-open")) box.hidePopover();
196 readLive().props.onFullscreenChange?.(false);
197 };
198 };
199 // Light dismiss (Escape) closes the popover without React.
200 const onBoxToggle = (event: ToggleEvent<HTMLDivElement>) => {
201 if (event.newState === "closed") setDisplayMode("inline");
202 };
203 const onBoxBlur = (event: FocusEvent<HTMLDivElement>) => {
204 const next = event.relatedTarget;
205 if (
206 displayMode === "fullscreen" &&
207 next instanceof Node &&
208 !event.currentTarget.contains(next)
209 ) {
210 setDisplayMode("inline");
211 }
212 };
213​
214 // Navigation retains the frame window; reject second loads to prevent impersonation.
215 const loads = useRef({ generation: 0, count: 0 });
216 const onFrameLoad = () => {
217 if (loads.current.generation !== documentGeneration) {
218 loads.current = { generation: documentGeneration, count: 0 };
219 }
220 loads.current.count += 1;
221 if (loads.current.count > 1) {
222 hostRef.current?.dispose();
223 setNavigatedAway(true);
224 }
225 };
226​
227 // The host belongs to this frame element, which is replaced when the document is reopened.
228 const attachFrame = (frame: HTMLIFrameElement) => {
229 frameRef.current = frame;
230 const hostContext = (): McpAppHostContext => {
231 const current = readLive();
232 return {
233 theme: current.theme.appearance,
234 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
235 displayMode: current.displayMode,
236 availableDisplayModes: fullscreenSupported ? ["inline", "fullscreen"] : ["inline"],
237 containerDimensions:
238 current.displayMode === "fullscreen"
239 ? {
240 width: frameRef.current?.clientWidth || window.innerWidth,
241 height: frameRef.current?.clientHeight || window.innerHeight,
242 }
243 : { width: current.width, maxHeight: MCP_APP_MAX_HEIGHT },
244 platform: isElectron ? "desktop" : "web",
245 locale: navigator.language,
246 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
247 userAgent: `t3-code/${APP_VERSION}`,
248 deviceCapabilities: {
249 touch: window.matchMedia("(pointer: coarse)").matches,
250 hover: window.matchMedia("(hover: hover)").matches,
251 },
252 safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
253 ...(current.toolDefinition === undefined
254 ? {}
255 : { toolInfo: { tool: current.toolDefinition } }),
256 };
257 };
258 // Return inline so approvals stay visible above the app.
259 const ask = async (message: string) => {
260 flushSync(() => setDisplayMode("inline"));
261 const approved = await requestConfirmDialog(message);
262 if (approved === undefined) {
263 throw new McpAppHostRefusal({ message: "T3 could not ask for approval here." });
264 }
265 return approved;
266 };
267 const target = () => frameRef.current?.contentWindow ?? null;
268 const scope = () => {
269 const { environmentId, threadId, itemId } = readLive().props;
270 return { environmentId, input: { threadId, itemId } };
271 };
272 const host = makeMcpAppHost({
273 app,
274 hostVersion: APP_VERSION,
275 // Opaque origins require "*"; the window reference scopes delivery to this frame.
276 post: (message) => target()?.postMessage(message, "*"),
277 hostContext,
278 callTool: async ({ name, arguments: args }) => {
279 const { environmentId, input } = scope();
280 const info = await readLive().toolInfo({ environmentId, input: { ...input, name } });
281 if (info._tag !== "Success") throw commandFailure(info);
282 if (!info.value.callable)
283 throw new McpAppHostRefusal({ message: "This app cannot call that tool." });
284 if (!info.value.readOnly) {
285 const approved = await ask(
286 `Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,
287 );
288 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
289 }
290 const result = await readLive().callTool({
291 environmentId,
292 input: { ...input, name, arguments: args },
293 });
294 if (result._tag !== "Success") throw commandFailure(result);
295 return result.value;
296 },
297 readResource: async ({ uri }) => {
298 const { environmentId, input } = scope();
299 const result = await readLive().readResource({
300 environmentId,
301 input: { ...input, uri },
302 });
303 if (result._tag !== "Success") throw commandFailure(result);
304 return result.value;
305 },
306 openLink: async (url) => {
307 if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) {
308 throw new McpAppHostRefusal({ message: "Links open only from a click in the app." });
309 }
310 window.open(url, "_blank", "noopener,noreferrer");
311 },
312 sendMessage: async (text) => {
313 const send = readLive().props.onSendMessage;
314 if (send === undefined)
315 throw new McpAppHostRefusal({ message: "Messages are not available here." });
316 const approved = await ask(`Send this message from ${app.server}?\n${text}`);
317 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
318 await send(text);
319 },
320 updateModelContext: async (context) => {
321 const { environmentId, input } = scope();
322 const result = await readLive().updateModelContext({
323 environmentId,
324 input: {
325 ...input,
326 ...context,
327 conversationThreadId: readLive().props.conversationThreadId,
328 },
329 });
330 if (result._tag !== "Success") throw commandFailure(result);
331 },
332 requestDisplayMode: async (mode) => {
333 const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");
334 if (
335 mode === "fullscreen" &&
336 (!fullscreenSupported ||
337 document.activeElement !== frameRef.current ||
338 !navigator.userActivation?.isActive ||
339 performance.now() - lastPageInputAt < PAGE_ACTIVATION_MS ||
340 readLive().props.awaitingUser === true ||
341 isConfirmDialogActive() ||
342 (otherFullscreen !== null && otherFullscreen !== boxRef.current))
343 ) {
344 return readLive().displayMode;
345 }
346 setDisplayMode(mode);
347 return mode;
348 },
349 downloadFile: async (files) => {
350 const names = files.map((file) => file.name).join(", ");
351 const approved = await ask(`Save ${names} from ${app.server}?`);
352 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
353 for (const file of files) {
354 let bytes: Uint8Array | undefined;
355 let mimeType = file.mimeType ?? "application/octet-stream";
356 if (file._tag === "embedded") {
357 bytes = file.bytes;
358 } else {
359 const { environmentId, input } = scope();
360 const read = await readLive().readResource({
361 environmentId,
362 input: { ...input, uri: file.uri },
363 });
364 if (read._tag !== "Success") throw commandFailure(read);
365 const content = read.value.contents[0];
366 bytes = mcpResourceBytes(content);
367 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
368 if (typeof declared === "string") mimeType = declared;
369 }
370 if (bytes === undefined)
371 throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
372 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
373 throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
374 }
375 saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
376 }
377 },
378 onRequestTeardown: () => {
379 if (readLive().displayMode === "fullscreen") {
380 setDisplayMode("inline");
381 return;
382 }
383 void host.teardown().then(() => setClosed(true));
384 },
385 onSizeChanged: (size) => {
386 // Ignore fullscreen height when restoring inline sizing.
387 if (readLive().displayMode === "fullscreen") return;
388 if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
389 },
390 });
391 hostRef.current = host;
392 const receive = (event: MessageEvent) => {
393 if (event.source !== null && event.source === target()) host.receive(event.data);
394 };
395 window.addEventListener("message", receive);
396 return () => {
397 window.removeEventListener("message", receive);
398 void host.teardown();
399 hostRef.current = null;
400 frameRef.current = null;
401 };
402 };
403​
404 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes theme, width, display mode and tool definition to the MCP app host in the iframe
405 useEffect(() => {
406 hostRef.current?.updateHostContext();
407 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
408 }, [theme, width, displayMode, toolDefinition]);
409​
410 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends the current tool call to the MCP app host, again for each new iframe document
411 useEffect(() => {
412 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
413 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
414 }, [toolCall, src, documentGeneration]);
415​
416 if (closed) {
417 return (
418 <div className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
419 <span>The {app.server} app was closed</span>
420 <Button
421 size="xs"
422 variant="ghost"
423 onClick={() => {
424 setSrc(null);
425 setDocumentGeneration((value) => value + 1);
426 setClosed(false);
427 }}
428 >
429 Show app
430 </Button>
431 </div>
432 );
433 }
434​
435 const fullscreen = displayMode === "fullscreen";
436 return (
437 // Preserve inline row height during fullscreen to prevent timeline jumps.
438 <div style={{ height }}>
439 <div
440 ref={attachBox}
441 // Preserve the frame's parent to avoid reloads; the top layer escapes timeline containment.
442 {...(fullscreenSupported
443 ? { popover: "auto" as const, onToggle: onBoxToggle, onBlur: onBoxBlur }
444 : {})}
445 data-mcp-app-fullscreen={fullscreen ? "" : undefined}
446 className={cn(
447 "relative size-full overflow-hidden",
448 app.prefersBorder === true && !fullscreen && "rounded-lg border border-border",
449 fullscreen
450 ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0"
451 : "block! static! m-0 border-0 bg-transparent p-0 text-inherit",
452 )}
453 >
454 {fullscreen ? (
455 <div
456 ref={attachFullscreenChrome}
457 className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm"
458 >
459 <span className="truncate">{app.server}</span>
460 <Button
461 aria-label="Exit full screen"
462 size="icon-sm"
463 variant="ghost"
464 onClick={() => setDisplayMode("inline")}
465 >
466 <Minimize2Icon className="size-4" />
467 </Button>
468 </div>
469 ) : null}
470 {navigatedAway ? (
471 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
472 The {app.server} app left its page and was stopped
473 </p>
474 ) : src !== null ? (
475 <iframe
476 ref={attachFrame}
477 src={src}
478 title={`${app.server} app`}
479 // Omitting allow-same-origin isolates the app from the session.
480 sandbox="allow-scripts allow-forms"
481 allow={mcpAppAllowAttribute(app.permissions)}
482 onLoad={onFrameLoad}
483 className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
484 style={{ colorScheme: theme.appearance }}
485 />
486 ) : asset._tag === "Failure" ? (
487 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
488 Unable to load the {app.server} app
489 </p>
490 ) : null}
491 </div>
492 </div>
493 );