-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathindex.tsx
More file actions
610 lines (533 loc) · 19.8 KB
/
index.tsx
File metadata and controls
610 lines (533 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
import { getToolUiResourceUri, McpUiToolMetaSchema } from "@modelcontextprotocol/ext-apps/app-bridge";
import type { Tool } from "@modelcontextprotocol/server";
import { Component, type ErrorInfo, type ReactNode, StrictMode, Suspense, use, useEffect, useMemo, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { callTool, connectToServer, hasAppHtml, initializeApp, loadSandboxProxy, log, newAppBridge, type ServerInfo, type ToolCallInfo, type ModelContext, type AppMessage } from "./implementation";
import { getTheme, toggleTheme, onThemeChange, type Theme } from "./theme";
import styles from "./index.module.css";
/**
* Check if a tool is visible to the model (not app-only).
* Tools with `visibility: ["app"]` should not be shown in tool lists.
*/
function isToolVisibleToModel(tool: { _meta?: Record<string, unknown> }): boolean {
const result = McpUiToolMetaSchema.safeParse(tool._meta?.ui);
if (!result.success) return true; // default: visible to model
const visibility = result.data.visibility;
if (!visibility) return true; // default: visible to model
return visibility.includes("model");
}
/** Compare tools: UI-enabled first, then alphabetically by name. */
function compareTools(a: Tool, b: Tool): number {
const aHasUi = !!getToolUiResourceUri(a);
const bHasUi = !!getToolUiResourceUri(b);
if (aHasUi && !bHasUi) return -1;
if (!aHasUi && bHasUi) return 1;
return a.name.localeCompare(b.name);
}
/**
* Extract default values from a tool's JSON Schema inputSchema.
* Returns a formatted JSON string with defaults, or "{}" if none found.
*/
function getToolDefaults(tool: Tool | undefined): string {
if (!tool?.inputSchema?.properties) return "{}";
const defaults: Record<string, unknown> = {};
for (const [key, prop] of Object.entries(tool.inputSchema.properties)) {
if (prop && typeof prop === "object" && "default" in prop) {
defaults[key] = prop.default;
}
}
return Object.keys(defaults).length > 0
? JSON.stringify(defaults, null, 2)
: "{}";
}
// Host passes serversPromise to CallToolPanel
interface HostProps {
serversPromise: Promise<ServerInfo[]>;
}
type ToolCallEntry = ToolCallInfo & { id: number };
let nextToolCallId = 0;
// Parse URL query params for debugging: ?server=name&tool=name&call=true&theme=hide
function getQueryParams() {
const params = new URLSearchParams(window.location.search);
return {
server: params.get("server"),
tool: params.get("tool"),
call: params.get("call") === "true",
hideThemeToggle: params.get("theme") === "hide",
};
}
/**
* Theme toggle button with light/dark icons.
*/
function ThemeToggle() {
const [theme, setTheme] = useState<Theme>(getTheme);
useEffect(() => {
return onThemeChange(setTheme);
}, []);
return (
<button
className={styles.themeToggle}
onClick={() => toggleTheme()}
title={`Switch to ${theme === "dark" ? "light" : "dark"} mode`}
>
{theme === "dark" ? "☀️" : "🌙"}
</button>
);
}
function Host({ serversPromise }: HostProps) {
const [toolCalls, setToolCalls] = useState<ToolCallEntry[]>([]);
const [destroyingIds, setDestroyingIds] = useState<Set<number>>(new Set());
const queryParams = useMemo(() => getQueryParams(), []);
const requestClose = (id: number) => {
setDestroyingIds((s) => new Set(s).add(id));
};
const completeClose = (id: number) => {
setDestroyingIds((s) => {
const next = new Set(s);
next.delete(id);
return next;
});
setToolCalls((calls) => calls.filter((c) => c.id !== id));
};
return (
<>
{!queryParams.hideThemeToggle && <ThemeToggle />}
{toolCalls.map((info) => (
<ToolCallInfoPanel
key={info.id}
toolCallInfo={info}
isDestroying={destroyingIds.has(info.id)}
onRequestClose={() => requestClose(info.id)}
onCloseComplete={() => completeClose(info.id)}
/>
))}
<CallToolPanel
serversPromise={serversPromise}
addToolCall={(info) => setToolCalls([...toolCalls, { ...info, id: nextToolCallId++ }])}
initialServer={queryParams.server}
initialTool={queryParams.tool}
autoCall={queryParams.call}
/>
</>
);
}
// CallToolPanel renders the unified form with Suspense around ServerSelect
interface CallToolPanelProps {
serversPromise: Promise<ServerInfo[]>;
addToolCall: (info: ToolCallInfo) => void;
initialServer?: string | null;
initialTool?: string | null;
autoCall?: boolean;
}
function CallToolPanel({ serversPromise, addToolCall, initialServer, initialTool, autoCall }: CallToolPanelProps) {
const [selectedServer, setSelectedServer] = useState<ServerInfo | null>(null);
const [selectedTool, setSelectedTool] = useState("");
const [inputJson, setInputJson] = useState("{}");
const [hasAutoCalledRef] = useState({ called: false });
// Filter out app-only tools, prioritize tools with UIs
const toolNames = selectedServer
? Array.from(selectedServer.tools.values())
.filter((tool) => isToolVisibleToModel(tool))
.sort(compareTools)
.map((tool) => tool.name)
: [];
const isValidJson = useMemo(() => {
try {
JSON.parse(inputJson);
return true;
} catch {
return false;
}
}, [inputJson]);
const handleServerSelect = (server: ServerInfo, preferredTool?: string) => {
setSelectedServer(server);
// Filter out app-only tools, prioritize tools with UIs
const visibleTools = Array.from(server.tools.values())
.filter((tool) => isToolVisibleToModel(tool))
.sort(compareTools);
// Use preferred tool if it exists and is visible, otherwise first visible tool
const targetTool = preferredTool && visibleTools.some(t => t.name === preferredTool)
? preferredTool
: visibleTools[0]?.name ?? "";
setSelectedTool(targetTool);
// Set input JSON to tool defaults (if any)
setInputJson(getToolDefaults(server.tools.get(targetTool)));
};
const handleToolSelect = (toolName: string) => {
setSelectedTool(toolName);
// Set input JSON to tool defaults (if any)
setInputJson(getToolDefaults(selectedServer?.tools.get(toolName)));
};
// Submit with optional override for server/tool (used by auto-call)
const handleSubmit = (overrideServer?: ServerInfo, overrideTool?: string) => {
const server = overrideServer ?? selectedServer;
const tool = overrideTool ?? selectedTool;
if (!server) return;
const toolCallInfo = callTool(server, tool, JSON.parse(inputJson));
addToolCall(toolCallInfo);
// Update URL for easy refresh/sharing (without triggering navigation)
const url = new URL(window.location.href);
url.searchParams.set("server", server.name);
url.searchParams.set("tool", tool);
url.searchParams.set("call", "true"); // Auto-call on refresh
history.replaceState(null, "", url.toString());
};
return (
<div className={styles.callToolPanel}>
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
<label>
Server
<Suspense fallback={<select disabled><option>Loading...</option></select>}>
<ServerSelect
serversPromise={serversPromise}
onSelect={handleServerSelect}
initialServer={initialServer}
initialTool={initialTool}
autoCall={autoCall && !hasAutoCalledRef.called}
onAutoCall={(server, tool) => {
hasAutoCalledRef.called = true;
handleSubmit(server, tool);
}}
/>
</Suspense>
</label>
<label>
Tool
<select
className={styles.toolSelect}
value={selectedTool}
onChange={(e) => handleToolSelect(e.target.value)}
>
{selectedServer && toolNames.map((name) => (
<option key={name} value={name}>{name}</option>
))}
</select>
</label>
<label>
Input
<textarea
className={styles.toolInput}
aria-invalid={!isValidJson}
value={inputJson}
onChange={(e) => setInputJson(e.target.value)}
/>
</label>
<button type="submit" disabled={!selectedTool || !isValidJson}>
Call Tool
</button>
</form>
</div>
);
}
// ServerSelect calls use() and renders the server <select>
interface ServerSelectProps {
serversPromise: Promise<ServerInfo[]>;
onSelect: (server: ServerInfo, toolName?: string) => void;
initialServer?: string | null;
initialTool?: string | null;
autoCall?: boolean;
onAutoCall?: (server: ServerInfo, tool: string) => void;
}
function ServerSelect({ serversPromise, onSelect, initialServer, initialTool, autoCall, onAutoCall }: ServerSelectProps) {
const servers = use(serversPromise);
const [hasInitialized, setHasInitialized] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(0);
// Initialize with the correct server/tool when servers are loaded
useEffect(() => {
if (hasInitialized || servers.length === 0) return;
// Find initial server index if specified
let idx = 0;
if (initialServer) {
const foundIdx = servers.findIndex(s => s.name === initialServer);
if (foundIdx >= 0) idx = foundIdx;
}
const server = servers[idx];
setSelectedIndex(idx);
// Find the tool to use
const visibleTools = Array.from(server.tools.values())
.filter((tool) => isToolVisibleToModel(tool))
.sort(compareTools);
const targetTool = initialTool && visibleTools.some(t => t.name === initialTool)
? initialTool
: visibleTools[0]?.name ?? "";
onSelect(server, targetTool);
setHasInitialized(true);
// Auto-call after initial selection if requested
if (autoCall && targetTool) {
onAutoCall?.(server, targetTool);
}
}, [servers, hasInitialized, initialServer, initialTool, autoCall, onSelect, onAutoCall]);
if (servers.length === 0) {
return <select disabled><option>No servers configured</option></select>;
}
return (
<select
value={selectedIndex}
onChange={(e) => {
const newIndex = Number(e.target.value);
setSelectedIndex(newIndex);
onSelect(servers[newIndex]);
}}
>
{servers.map((server, i) => (
<option key={i} value={i}>{server.name}</option>
))}
</select>
);
}
interface ToolCallInfoPanelProps {
toolCallInfo: ToolCallInfo;
isDestroying?: boolean;
onRequestClose?: () => void;
onCloseComplete?: () => void;
}
function ToolCallInfoPanel({ toolCallInfo, isDestroying, onRequestClose, onCloseComplete }: ToolCallInfoPanelProps) {
const isApp = hasAppHtml(toolCallInfo);
// For non-app tool calls, close immediately when isDestroying becomes true
useEffect(() => {
if (isDestroying && !isApp) {
onCloseComplete?.();
}
}, [isDestroying, isApp, onCloseComplete]);
const inputJson = JSON.stringify(toolCallInfo.input, null, 2);
return (
<div
className={styles.toolCallInfoPanel}
style={isDestroying ? { opacity: 0.5, pointerEvents: "none" } : undefined}
>
{/* Row 1: Header with server:tool name and close button */}
<div className={styles.appHeader}>
<span>{toolCallInfo.serverInfo.name}:<span className={styles.toolName}>{toolCallInfo.tool.name}</span></span>
{onRequestClose && !isDestroying && (
<button
className={styles.closeButton}
onClick={onRequestClose}
title="Close"
>
×
</button>
)}
</div>
{/* Row 2: Tool Input */}
<CollapsiblePanel icon="📥" label="Tool Input" content={inputJson} />
{/* Row 3: App iframe (if app) */}
{isApp && (
<ErrorBoundary>
<Suspense fallback="Loading...">
<AppIFramePanel
toolCallInfo={toolCallInfo}
isDestroying={isDestroying}
onTeardownComplete={onCloseComplete}
/>
</Suspense>
</ErrorBoundary>
)}
{/* Row 4: Tool Result */}
<ErrorBoundary>
<Suspense fallback="Loading result...">
<ToolResultPanel toolCallInfo={toolCallInfo} />
</Suspense>
</ErrorBoundary>
</div>
);
}
interface CollapsiblePanelProps {
icon: string;
label: string;
content: string;
badge?: string;
defaultExpanded?: boolean;
}
function CollapsiblePanel({ icon, label, content, badge, defaultExpanded = false }: CollapsiblePanelProps) {
const [expanded, setExpanded] = useState(defaultExpanded);
return (
<div
className={styles.collapsiblePanel}
onClick={() => setExpanded(!expanded)}
title={expanded ? "Click to collapse" : "Click to expand"}
>
<div className={styles.collapsibleHeader}>
<span className={styles.collapsibleLabel}>{icon} {label}</span>
<span className={styles.collapsibleSize}>
{badge ?? `${content.length} chars`}
</span>
<span className={styles.collapsibleToggle}>
{expanded ? "▼" : "▶"}
</span>
</div>
{expanded ? (
<pre className={styles.collapsibleFull}>{content}</pre>
) : (
<div className={styles.collapsiblePreview}>
{content.slice(0, 100)}{content.length > 100 ? "…" : ""}
</div>
)}
</div>
);
}
interface AppIFramePanelProps {
toolCallInfo: Required<ToolCallInfo>;
isDestroying?: boolean;
onTeardownComplete?: () => void;
}
function AppIFramePanel({ toolCallInfo, isDestroying, onTeardownComplete }: AppIFramePanelProps) {
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const appBridgeRef = useRef<ReturnType<typeof newAppBridge> | null>(null);
const [modelContext, setModelContext] = useState<ModelContext | null>(null);
const [messages, setMessages] = useState<AppMessage[]>([]);
const [displayMode, setDisplayMode] = useState<"inline" | "fullscreen">("inline");
useEffect(() => {
const iframe = iframeRef.current!;
// First get CSP and permissions from resource, then load sandbox
// CSP is set via HTTP headers (tamper-proof), permissions via iframe allow attribute
toolCallInfo.appResourcePromise.then(({ csp, permissions }) => {
loadSandboxProxy(iframe, csp, permissions).then((firstTime) => {
// The `firstTime` check guards against React Strict Mode's double
// invocation (mount → unmount → remount simulation in development).
// Outside of Strict Mode, this `useEffect` runs only once per
// `toolCallInfo`.
if (firstTime) {
const appBridge = newAppBridge(toolCallInfo.serverInfo, iframe, {
onContextUpdate: setModelContext,
onMessage: (msg) => setMessages((prev) => [...prev, msg]),
onDisplayModeChange: setDisplayMode,
}, {
// Provide container dimensions - maxHeight for flexible sizing
containerDimensions: { maxHeight: 6000 },
displayMode: "inline",
});
appBridgeRef.current = appBridge;
initializeApp(iframe, appBridge, toolCallInfo);
}
});
});
}, [toolCallInfo]);
// Graceful teardown: wait for guest to respond before unmounting
// This follows the spec: "Host SHOULD wait for a response before tearing
// down the resource (to prevent data loss)."
useEffect(() => {
if (!isDestroying) return;
if (!appBridgeRef.current) {
// Bridge not ready yet (e.g., user closed before iframe loaded)
onTeardownComplete?.();
return;
}
log.info("Sending teardown notification to MCP App");
appBridgeRef.current.teardownResource({})
.catch((err) => {
log.warn("Teardown request failed (app may have already closed):", err);
})
.finally(() => {
onTeardownComplete?.();
});
}, [isDestroying, onTeardownComplete]);
// Format content blocks - handle text, images, resources, etc.
const formatContentBlock = (c: { type: string; [key: string]: unknown }) => {
switch (c.type) {
case "text":
return (c as { type: "text"; text: string }).text;
case "image":
return `<image: ${(c as { mimeType?: string }).mimeType ?? "unknown"}>`;
case "audio":
return `<audio: ${(c as { mimeType?: string }).mimeType ?? "unknown"}>`;
case "resource":
return `<resource: ${(c as { resource?: { uri?: string } }).resource?.uri ?? "unknown"}>`;
default:
return `<${c.type}>`;
}
};
// Format context for display
const contextText = modelContext?.content?.map(formatContentBlock).join("\n") ?? "";
const contextJson = modelContext?.structuredContent
? JSON.stringify(modelContext.structuredContent, null, 2)
: "";
const fullContext = [contextText, contextJson].filter(Boolean).join("\n\n");
// Format messages
const formatMessage = (m: AppMessage) => {
const content = m.content.map(formatContentBlock).join("\n");
return `[${m.role}] ${content}`;
};
const messagesText = messages.map(formatMessage).join("\n\n");
const panelClassName = displayMode === "fullscreen"
? `${styles.appIframePanel} ${styles.fullscreen}`
: styles.appIframePanel;
return (
<div className={panelClassName}>
<iframe ref={iframeRef} />
{messages.length > 0 && (
<CollapsiblePanel
icon="💬"
label="Messages"
content={messagesText}
badge={`${messages.length} message${messages.length > 1 ? "s" : ""}`}
/>
)}
{modelContext && (
<CollapsiblePanel icon="📋" label="Model Context" content={fullContext} />
)}
</div>
);
}
interface ToolResultPanelProps {
toolCallInfo: ToolCallInfo;
}
function ToolResultPanel({ toolCallInfo }: ToolResultPanelProps) {
const result = use(toolCallInfo.resultPromise);
const resultJson = JSON.stringify(result, null, 2);
return <CollapsiblePanel icon="📤" label="Tool Result" content={resultJson} />;
}
interface ErrorBoundaryProps {
children: ReactNode;
}
interface ErrorBoundaryState {
hasError: boolean;
error: unknown;
}
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { hasError: false, error: undefined };
// Called during render phase - must be pure (no side effects)
// Note: error is `unknown` because JS allows throwing any value
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
return { hasError: true, error };
}
// Called during commit phase - can have side effects (logging, etc.)
componentDidCatch(error: unknown, errorInfo: ErrorInfo): void {
log.error("Caught:", error, errorInfo.componentStack);
}
render(): ReactNode {
if (this.state.hasError) {
const { error } = this.state;
const message = error instanceof Error ? error.message : String(error);
return <div className={styles.error}><strong>ERROR:</strong> {message}</div>;
}
return this.props.children;
}
}
async function connectToAllServers(): Promise<ServerInfo[]> {
const serverUrlsResponse = await fetch("/api/servers");
const serverUrls = (await serverUrlsResponse.json()) as string[];
// Use allSettled to be resilient to individual server failures
const results = await Promise.allSettled(
serverUrls.map((url) => connectToServer(new URL(url)))
);
const servers: ServerInfo[] = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.status === "fulfilled") {
servers.push(result.value);
} else {
console.warn(`[HOST] Failed to connect to ${serverUrls[i]}:`, result.reason);
}
}
if (servers.length === 0 && serverUrls.length > 0) {
throw new Error(`Failed to connect to any servers (${serverUrls.length} attempted)`);
}
return servers;
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ErrorBoundary>
<Host serversPromise={connectToAllServers()} />
</ErrorBoundary>
</StrictMode>,
);