-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathpatterns.tsx
More file actions
573 lines (515 loc) · 15.8 KB
/
patterns.tsx
File metadata and controls
573 lines (515 loc) · 15.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
/**
* Type-checked code examples for the patterns documentation.
*
* These examples are included in {@link ./patterns.md} via `@includeCode` tags.
* Each function's region markers define the code snippet that appears in the docs.
*
* @module
*/
import { App } from "../src/app.js";
import {
applyDocumentTheme,
applyHostFonts,
applyHostStyleVariables,
} from "../src/styles.js";
import { randomUUID } from "node:crypto";
import type {
CallToolResult,
ReadResourceResult,
} from "@modelcontextprotocol/sdk/types.js";
import { ReadResourceResultSchema } from "@modelcontextprotocol/sdk/types.js";
import type { McpUiHostContext } from "../src/types.js";
import { useEffect, useState } from "react";
import { useApp } from "../src/react/index.js";
import { registerAppTool } from "../src/server/index.js";
import {
McpServer,
ResourceTemplate,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
/**
* Example: Polling for live data (Vanilla JS)
*/
function pollingVanillaJs(app: App, updateUI: (data: unknown) => void) {
//#region pollingVanillaJs
let intervalId: number | null = null;
async function poll() {
const result = await app.callServerTool({
name: "poll-data",
arguments: {},
});
updateUI(result.structuredContent);
}
function startPolling() {
if (intervalId !== null) return;
poll();
intervalId = window.setInterval(poll, 2000);
}
function stopPolling() {
if (intervalId === null) return;
clearInterval(intervalId);
intervalId = null;
}
// Clean up when host tears down the view
app.onteardown = async () => {
stopPolling();
return {};
};
//#endregion pollingVanillaJs
}
/**
* Example: Polling for live data (React)
*/
function pollingReact(
app: App | null, // via useApp()
) {
const [data, setData] = useState<unknown>();
//#region pollingReact
useEffect(() => {
if (!app) return;
let cancelled = false;
async function poll() {
const result = await app!.callServerTool({
name: "poll-data",
arguments: {},
});
if (!cancelled) setData(result.structuredContent);
}
poll();
const id = setInterval(poll, 2000);
return () => {
cancelled = true;
clearInterval(id);
};
}, [app]);
//#endregion pollingReact
}
/**
* Example: Server-side chunked data tool (app-only)
*/
function chunkedDataServer(server: McpServer) {
//#region chunkedDataServer
// Define the chunk response schema
const DataChunkSchema = z.object({
bytes: z.string(), // base64-encoded data
offset: z.number(),
byteCount: z.number(),
totalBytes: z.number(),
hasMore: z.boolean(),
});
const MAX_CHUNK_BYTES = 500 * 1024; // 500KB per chunk
registerAppTool(
server,
"read_data_bytes",
{
title: "Read Data Bytes",
description: "Load binary data in chunks",
inputSchema: {
id: z.string().describe("Resource identifier"),
offset: z.number().min(0).default(0).describe("Byte offset"),
byteCount: z
.number()
.default(MAX_CHUNK_BYTES)
.describe("Bytes to read"),
},
outputSchema: DataChunkSchema,
// Hidden from model - only callable by the App
_meta: { ui: { visibility: ["app"] } },
},
async ({ id, offset, byteCount }): Promise<CallToolResult> => {
const data = await loadData(id); // Your data loading logic
const chunk = data.slice(offset, offset + byteCount);
return {
content: [{ type: "text", text: `${chunk.length} bytes at ${offset}` }],
structuredContent: {
bytes: Buffer.from(chunk).toString("base64"),
offset,
byteCount: chunk.length,
totalBytes: data.length,
hasMore: offset + chunk.length < data.length,
},
};
},
);
//#endregion chunkedDataServer
}
// Stub for the example
declare function loadData(id: string): Promise<Uint8Array>;
/**
* Example: Client-side chunked data loading
*/
function chunkedDataClient(app: App, resourceId: string) {
//#region chunkedDataClient
interface DataChunk {
bytes: string; // base64
offset: number;
byteCount: number;
totalBytes: number;
hasMore: boolean;
}
async function loadDataInChunks(
id: string,
onProgress?: (loaded: number, total: number) => void,
): Promise<Uint8Array> {
const CHUNK_SIZE = 500 * 1024; // 500KB chunks
const chunks: Uint8Array[] = [];
let offset = 0;
let totalBytes = 0;
let hasMore = true;
while (hasMore) {
const result = await app.callServerTool({
name: "read_data_bytes",
arguments: { id, offset, byteCount: CHUNK_SIZE },
});
if (result.isError || !result.structuredContent) {
throw new Error("Failed to load data chunk");
}
const chunk = result.structuredContent as unknown as DataChunk;
totalBytes = chunk.totalBytes;
hasMore = chunk.hasMore;
// Decode base64 to bytes
const binaryString = atob(chunk.bytes);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
chunks.push(bytes);
offset += chunk.byteCount;
onProgress?.(offset, totalBytes);
}
// Combine all chunks into single array
const fullData = new Uint8Array(totalBytes);
let pos = 0;
for (const chunk of chunks) {
fullData.set(chunk, pos);
pos += chunk.length;
}
return fullData;
}
// Usage: load data with progress updates
loadDataInChunks(resourceId, (loaded, total) => {
console.log(`Loading: ${Math.round((loaded / total) * 100)}%`);
}).then((data) => {
console.log(`Loaded ${data.length} bytes`);
});
//#endregion chunkedDataClient
}
/**
* Example: Serving binary blobs via resources (server-side)
*/
function binaryBlobResourceServer(
server: McpServer,
getVideoData: (id: string) => Promise<ArrayBuffer>,
) {
//#region binaryBlobResourceServer
server.registerResource(
"Video",
new ResourceTemplate("video://{id}", { list: undefined }),
{
description: "Video data served as base64 blob",
mimeType: "video/mp4",
},
async (uri, { id }): Promise<ReadResourceResult> => {
// Fetch or load your binary data
const idString = Array.isArray(id) ? id[0] : id;
const buffer = await getVideoData(idString);
const blob = Buffer.from(buffer).toString("base64");
return { contents: [{ uri: uri.href, mimeType: "video/mp4", blob }] };
},
);
//#endregion binaryBlobResourceServer
}
/**
* Example: Serving binary blobs via resources (client-side)
*/
async function binaryBlobResourceClient(app: App, videoId: string) {
//#region binaryBlobResourceClient
const result = await app.request(
{ method: "resources/read", params: { uri: `video://${videoId}` } },
ReadResourceResultSchema,
);
const content = result.contents[0];
if (!content || !("blob" in content)) {
throw new Error("Resource did not contain blob data");
}
const videoEl = document.querySelector("video")!;
videoEl.src = `data:${content.mimeType!};base64,${content.blob}`;
//#endregion binaryBlobResourceClient
}
/**
* Example: Adapting to host context (theme, CSS variables, fonts, safe areas)
*/
function hostContextVanillaJs(app: App, mainEl: HTMLElement) {
//#region hostContextVanillaJs
function applyHostContext(ctx: McpUiHostContext) {
if (ctx.theme) {
applyDocumentTheme(ctx.theme);
}
if (ctx.styles?.variables) {
applyHostStyleVariables(ctx.styles.variables);
}
if (ctx.styles?.css?.fonts) {
applyHostFonts(ctx.styles.css.fonts);
}
if (ctx.safeAreaInsets) {
mainEl.style.paddingTop = `${ctx.safeAreaInsets.top}px`;
mainEl.style.paddingRight = `${ctx.safeAreaInsets.right}px`;
mainEl.style.paddingBottom = `${ctx.safeAreaInsets.bottom}px`;
mainEl.style.paddingLeft = `${ctx.safeAreaInsets.left}px`;
}
}
// Apply when host context changes
app.onhostcontextchanged = applyHostContext;
// Apply initial context after connecting
app.connect().then(() => {
const ctx = app.getHostContext();
if (ctx) {
applyHostContext(ctx);
}
});
//#endregion hostContextVanillaJs
}
/**
* Example: Adapting to host context with React (CSS variables, theme, fonts, safe areas)
*/
function hostContextReact() {
//#region hostContextReact
function MyApp() {
const [hostContext, setHostContext] = useState<McpUiHostContext>();
const { app } = useApp({
appInfo: { name: "MyApp", version: "1.0.0" },
capabilities: {},
onAppCreated: (app) => {
app.onhostcontextchanged = (ctx) => {
setHostContext((prev) => ({ ...prev, ...ctx }));
};
},
});
// Set initial host context after connection
useEffect(() => {
if (app) {
setHostContext(app.getHostContext());
}
}, [app]);
// Apply styles when host context changes
useEffect(() => {
if (hostContext?.theme) {
applyDocumentTheme(hostContext.theme);
}
if (hostContext?.styles?.variables) {
applyHostStyleVariables(hostContext.styles.variables);
}
if (hostContext?.styles?.css?.fonts) {
applyHostFonts(hostContext.styles.css.fonts);
}
}, [hostContext]);
return (
<div
style={{
background: "var(--color-background-primary)",
fontFamily: "var(--font-sans)",
paddingTop: hostContext?.safeAreaInsets?.top,
paddingRight: hostContext?.safeAreaInsets?.right,
paddingBottom: hostContext?.safeAreaInsets?.bottom,
paddingLeft: hostContext?.safeAreaInsets?.left,
}}
>
Styled with host CSS variables, fonts, and safe area insets
</div>
);
}
//#endregion hostContextReact
}
/**
* Example: Persisting view state (server-side)
*/
function persistViewStateServer(url: string, title: string, pageCount: number) {
function toolCallback(): CallToolResult {
//#region persistDataServer
// In your tool callback, include viewUUID in the result metadata.
return {
content: [{ type: "text", text: `Displaying PDF viewer for "${title}"` }],
structuredContent: { url, title, pageCount, initialPage: 1 },
_meta: {
viewUUID: randomUUID(),
},
};
//#endregion persistDataServer
}
}
/**
* Example: Persisting view state (client-side)
*/
function persistViewState(app: App) {
//#region persistData
// Store the viewUUID received from the server
let viewUUID: string | undefined;
// Helper to save state to localStorage
function saveState<T>(state: T): void {
if (!viewUUID) return;
try {
localStorage.setItem(viewUUID, JSON.stringify(state));
} catch (err) {
console.error("Failed to save view state:", err);
}
}
// Helper to load state from localStorage
function loadState<T>(): T | null {
if (!viewUUID) return null;
try {
const saved = localStorage.getItem(viewUUID);
return saved ? (JSON.parse(saved) as T) : null;
} catch (err) {
console.error("Failed to load view state:", err);
return null;
}
}
// Receive viewUUID from the tool result
app.ontoolresult = (result) => {
viewUUID = result._meta?.viewUUID
? String(result._meta.viewUUID)
: undefined;
// Restore any previously saved state
const savedState = loadState<{ currentPage: number }>();
if (savedState) {
// Apply restored state to your UI...
}
};
// Call saveState() whenever your view state changes
// e.g., saveState({ currentPage: 5 });
//#endregion persistData
}
/**
* Example: Pausing computation-heavy views when out of view
*/
function visibilityBasedPause(
app: App,
container: HTMLElement,
animation: { play: () => void; pause: () => void },
) {
//#region visibilityBasedPause
// Use IntersectionObserver to pause when view scrolls out of view
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
animation.play(); // or startPolling(), etc
} else {
animation.pause(); // or stopPolling(), etc
}
});
});
observer.observe(container);
// Clean up when the host tears down the view
app.onteardown = async () => {
observer.disconnect();
animation.pause();
return {};
};
//#endregion visibilityBasedPause
}
/**
* Example: Server-side tools for UI-driven tool responses
*/
function uiDataToolResponseServer(server: McpServer) {
//#region uiDataToolResponseServer
// Map of pending color picks waiting for user input
const pendingColorPicks = new Map<
string,
{ resolve: (color: string) => void }
>();
// 1. Model-visible tool that displays the color picker UI
registerAppTool(
server,
"pick_color",
{
title: "Pick Color",
description: "Let the user pick a color",
inputSchema: {
requestId: z.string().describe("Unique ID for this request"),
defaultColor: z.string().optional().describe("Initial color value"),
},
_meta: { ui: { resourceUri: "ui://colors/picker.html" } },
},
async ({ requestId, defaultColor }) => {
// Wait for the user to pick a color via the UI
const pickedColor = await new Promise<string>((resolve) => {
pendingColorPicks.set(requestId, { resolve });
});
return {
content: [{ type: "text", text: `User selected: ${pickedColor}` }],
structuredContent: { color: pickedColor },
};
},
);
// 2. App-only tool that the UI calls when user finishes picking
registerAppTool(
server,
"user_picked_color",
{
title: "User Picked Color",
description: "Called by the UI when user selects a color",
inputSchema: {
requestId: z.string().describe("Request ID from pick_color"),
color: z.string().describe("The color the user picked"),
},
// Hidden from model - only callable by the App
_meta: { ui: { visibility: ["app"] } },
},
async ({ requestId, color }) => {
const pending = pendingColorPicks.get(requestId);
if (pending) {
pending.resolve(color);
pendingColorPicks.delete(requestId);
return { content: [{ type: "text", text: "Color submitted" }] };
}
return {
isError: true,
content: [{ type: "text", text: "No pending request found" }],
};
},
);
//#endregion uiDataToolResponseServer
}
/**
* Example: Client-side color picker that submits user selection
*/
function uiDataToolResponseClient(app: App) {
//#region uiDataToolResponseClient
let requestId: string | undefined;
// Receive the request ID from the tool input
app.ontoolinput = (params) => {
requestId = params.arguments?.requestId as string;
const defaultColor = (params.arguments?.defaultColor as string) ?? "#000000";
initializeColorPicker(defaultColor);
};
// When user picks a color, call the app-only tool to complete the request
async function onColorSelected(color: string) {
if (!requestId) return;
await app.callServerTool({
name: "user_picked_color",
arguments: { requestId, color },
});
}
// Example: Wire up a color input
const colorInput = document.querySelector<HTMLInputElement>("#color-picker");
colorInput?.addEventListener("change", () => {
onColorSelected(colorInput.value);
});
//#endregion uiDataToolResponseClient
}
// Stubs for uiDataToolResponseClient example
declare function initializeColorPicker(defaultColor: string): void;
// Suppress unused variable warnings
void pollingVanillaJs;
void pollingReact;
void chunkedDataServer;
void chunkedDataClient;
void binaryBlobResourceServer;
void binaryBlobResourceClient;
void hostContextVanillaJs;
void hostContextReact;
void persistViewStateServer;
void persistViewState;
void visibilityBasedPause;
void uiDataToolResponseServer;
void uiDataToolResponseClient;