-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathapp.examples.ts
More file actions
532 lines (485 loc) · 14.8 KB
/
app.examples.ts
File metadata and controls
532 lines (485 loc) · 14.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
/**
* Type-checked examples for {@link App `App`} and constants in {@link ./app.ts `app.ts`}.
*
* These examples are included in the API documentation via `@includeCode` tags.
* Each function's region markers define the code snippet that appears in the docs.
*
* @module
*/
import type { Tool } from "@modelcontextprotocol/sdk/types.js";
import type {
McpServer,
ToolCallback,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { App, PostMessageTransport, RESOURCE_URI_META_KEY } from "./app.js";
/**
* Example: How MCP servers use RESOURCE_URI_META_KEY (server-side, not in Apps).
*/
function RESOURCE_URI_META_KEY_serverSide(
server: McpServer,
handler: ToolCallback,
) {
//#region RESOURCE_URI_META_KEY_serverSide
server.registerTool(
"weather",
{
description: "Get weather forecast",
_meta: {
[RESOURCE_URI_META_KEY]: "ui://weather/forecast",
},
},
handler,
);
//#endregion RESOURCE_URI_META_KEY_serverSide
}
/**
* Example: How hosts check for RESOURCE_URI_META_KEY metadata (host-side).
*/
function RESOURCE_URI_META_KEY_hostSide(tool: Tool) {
//#region RESOURCE_URI_META_KEY_hostSide
// Check tool definition metadata (from tools/list response):
const uiUri = tool._meta?.[RESOURCE_URI_META_KEY];
if (typeof uiUri === "string" && uiUri.startsWith("ui://")) {
// Fetch the resource and display the UI
}
//#endregion RESOURCE_URI_META_KEY_hostSide
}
/**
* Example: App constructor with appInfo, capabilities, and options.
*/
function App_constructor_basic() {
//#region App_constructor_basic
const app = new App(
{ name: "MyApp", version: "1.0.0" },
{ tools: { listChanged: true } }, // capabilities
{ autoResize: true }, // options
);
//#endregion App_constructor_basic
return app;
}
/**
* Example: Basic usage of the App class with PostMessageTransport.
*/
async function App_basicUsage() {
//#region App_basicUsage
const app = new App(
{ name: "WeatherApp", version: "1.0.0" },
{}, // capabilities
);
// Register handlers before connecting to ensure no notifications are missed
app.ontoolinput = (params) => {
console.log("Tool arguments:", params.arguments);
};
await app.connect();
//#endregion App_basicUsage
}
/**
* Example: Check host capabilities after connection.
*/
async function App_getHostCapabilities_checkAfterConnection(app: App) {
//#region App_getHostCapabilities_checkAfterConnection
await app.connect();
if (app.getHostCapabilities()?.serverTools) {
console.log("Host supports server tool calls");
}
//#endregion App_getHostCapabilities_checkAfterConnection
}
/**
* Example: Log host information after connection.
*/
async function App_getHostVersion_logAfterConnection(
app: App,
transport: PostMessageTransport,
) {
//#region App_getHostVersion_logAfterConnection
await app.connect(transport);
const { name, version } = app.getHostVersion() ?? {};
console.log(`Connected to ${name} v${version}`);
//#endregion App_getHostVersion_logAfterConnection
}
/**
* Example: Access host context after connection.
*/
async function App_getHostContext_accessAfterConnection(
app: App,
transport: PostMessageTransport,
) {
//#region App_getHostContext_accessAfterConnection
await app.connect(transport);
const context = app.getHostContext();
if (context?.theme === "dark") {
document.body.classList.add("dark-theme");
}
if (context?.toolInfo) {
console.log("Tool:", context.toolInfo.tool.name);
}
//#endregion App_getHostContext_accessAfterConnection
}
/**
* Example: Using the ontoolinput setter (simpler approach).
*/
async function App_ontoolinput_setter(app: App) {
//#region App_ontoolinput_setter
// Register before connecting to ensure no notifications are missed
app.ontoolinput = (params) => {
console.log("Tool:", params.arguments);
// Update your UI with the tool arguments
};
await app.connect();
//#endregion App_ontoolinput_setter
}
/**
* Example: Progressive rendering of tool arguments using ontoolinputpartial.
*/
function App_ontoolinputpartial_progressiveRendering(app: App) {
//#region App_ontoolinputpartial_progressiveRendering
const codePreview = document.querySelector<HTMLPreElement>("#code-preview")!;
const canvas = document.querySelector<HTMLCanvasElement>("#canvas")!;
app.ontoolinputpartial = (params) => {
codePreview.textContent = (params.arguments?.code as string) ?? "";
codePreview.style.display = "block";
canvas.style.display = "none";
};
app.ontoolinput = (params) => {
codePreview.style.display = "none";
canvas.style.display = "block";
render(params.arguments?.code as string);
};
//#endregion App_ontoolinputpartial_progressiveRendering
}
// Stub for App_ontoolinputpartial_progressiveRendering example
declare function render(code: string): void;
/**
* Example: Display tool execution results using ontoolresult.
*/
function App_ontoolresult_displayResults(app: App) {
//#region App_ontoolresult_displayResults
app.ontoolresult = (params) => {
if (params.isError) {
console.error("Tool execution failed:", params.content);
} else if (params.content) {
console.log("Tool output:", params.content);
}
};
//#endregion App_ontoolresult_displayResults
}
/**
* Example: Handle tool cancellation notifications.
*/
function App_ontoolcancelled_handleCancellation(app: App) {
//#region App_ontoolcancelled_handleCancellation
app.ontoolcancelled = (params) => {
console.log("Tool cancelled:", params.reason);
// Update your UI to show cancellation state
};
//#endregion App_ontoolcancelled_handleCancellation
}
/**
* Example: Respond to theme changes using onhostcontextchanged.
*/
function App_onhostcontextchanged_respondToTheme(app: App) {
//#region App_onhostcontextchanged_respondToTheme
app.onhostcontextchanged = (ctx) => {
if (ctx.theme === "dark") {
document.body.classList.add("dark-theme");
} else {
document.body.classList.remove("dark-theme");
}
};
//#endregion App_onhostcontextchanged_respondToTheme
}
/**
* Example: Respond to display mode changes using onhostcontextchanged.
*/
function App_onhostcontextchanged_respondToDisplayMode(app: App) {
//#region App_onhostcontextchanged_respondToDisplayMode
app.onhostcontextchanged = (ctx) => {
// Adjust to current display mode
if (ctx.displayMode) {
const container = document.getElementById("main")!;
const isFullscreen = ctx.displayMode === "fullscreen";
container.classList.toggle("fullscreen", isFullscreen);
}
// Adjust display mode controls
if (ctx.availableDisplayModes) {
const fullscreenBtn = document.getElementById("fullscreen-btn")!;
const canFullscreen = ctx.availableDisplayModes.includes("fullscreen");
fullscreenBtn.style.display = canFullscreen ? "block" : "none";
}
};
//#endregion App_onhostcontextchanged_respondToDisplayMode
}
/**
* Example: Perform cleanup before teardown.
*/
function App_onteardown_performCleanup(app: App) {
//#region App_onteardown_performCleanup
app.onteardown = async () => {
await saveState();
closeConnections();
console.log("App ready for teardown");
return {};
};
//#endregion App_onteardown_performCleanup
}
// Stubs for example
declare function saveState(): Promise<void>;
declare function closeConnections(): void;
/**
* Example: Handle tool calls from the host.
*/
function App_oncalltool_handleFromHost(app: App) {
//#region App_oncalltool_handleFromHost
app.oncalltool = async (params, extra) => {
if (params.name === "greet") {
const name = params.arguments?.name ?? "World";
return { content: [{ type: "text", text: `Hello, ${name}!` }] };
}
throw new Error(`Unknown tool: ${params.name}`);
};
//#endregion App_oncalltool_handleFromHost
}
/**
* Example: Return available tools from the onlisttools handler.
*/
function App_onlisttools_returnTools(app: App) {
//#region App_onlisttools_returnTools
app.onlisttools = async (params, extra) => {
return {
tools: ["greet", "calculate", "format"],
};
};
//#endregion App_onlisttools_returnTools
}
/**
* Example: Fetch updated weather data using callServerTool.
*/
async function App_callServerTool_fetchWeather(app: App) {
//#region App_callServerTool_fetchWeather
try {
const result = await app.callServerTool({
name: "get_weather",
arguments: { location: "Tokyo" },
});
if (result.isError) {
console.error("Tool returned error:", result.content);
} else {
console.log(result.content);
}
} catch (error) {
console.error("Tool call failed:", error);
}
//#endregion App_callServerTool_fetchWeather
}
/**
* Example: Simple LLM completion via host sampling.
*/
async function App_createSamplingMessage_simple(app: App) {
//#region App_createSamplingMessage_simple
const result = await app.createSamplingMessage({
messages: [
{
role: "user",
content: { type: "text", text: "Summarize this in one line." },
},
],
maxTokens: 100,
});
console.log(result.content);
//#endregion App_createSamplingMessage_simple
}
/**
* Example: Agentic loop with tools (requires host sampling.tools capability).
*/
async function App_createSamplingMessage_withTools(
app: App,
messages: import("@modelcontextprotocol/sdk/types.js").SamplingMessage[],
) {
//#region App_createSamplingMessage_withTools
if (!app.getHostCapabilities()?.sampling?.tools) return;
const result = await app.createSamplingMessage({
messages,
maxTokens: 1024,
tools: [
{
name: "get_weather",
description: "Get the current weather",
inputSchema: {
type: "object",
properties: { city: { type: "string" } },
},
},
],
});
if (result.stopReason === "toolUse") {
// result.content may be an array containing tool_use blocks
}
//#endregion App_createSamplingMessage_withTools
}
/**
* Example: Send a text message from user interaction.
*/
async function App_sendMessage_textFromInteraction(app: App) {
//#region App_sendMessage_textFromInteraction
try {
const result = await app.sendMessage({
role: "user",
content: [{ type: "text", text: "Show me details for item #42" }],
});
if (result.isError) {
console.error("Host rejected the message");
// Handle rejection appropriately for your app
}
} catch (error) {
console.error("Failed to send message:", error);
// Handle transport/protocol error
}
//#endregion App_sendMessage_textFromInteraction
}
/**
* Example: Send follow-up message after offloading large data to model context.
*/
async function App_sendMessage_withLargeContext(
app: App,
fullTranscript: string,
speakerNames: string[],
) {
//#region App_sendMessage_withLargeContext
const markdown = `---
word-count: ${fullTranscript.split(/\s+/).length}
speaker-names: ${speakerNames.join(", ")}
---
${fullTranscript}`;
// Offload long transcript to model context
await app.updateModelContext({ content: [{ type: "text", text: markdown }] });
// Send brief trigger message
await app.sendMessage({
role: "user",
content: [{ type: "text", text: "Summarize the key points" }],
});
//#endregion App_sendMessage_withLargeContext
}
/**
* Example: Log app state for debugging.
*/
function App_sendLog_debugState(app: App) {
//#region App_sendLog_debugState
app.sendLog({
level: "info",
data: "Weather data refreshed",
logger: "WeatherApp",
});
//#endregion App_sendLog_debugState
}
/**
* Example: Update model context with current app state.
*/
async function App_updateModelContext_appState(
app: App,
itemList: string[],
totalCost: string,
currency: string,
) {
//#region App_updateModelContext_appState
const markdown = `---
item-count: ${itemList.length}
total-cost: ${totalCost}
currency: ${currency}
---
User is viewing their shopping cart with ${itemList.length} items selected:
${itemList.map((item) => `- ${item}`).join("\n")}`;
await app.updateModelContext({
content: [{ type: "text", text: markdown }],
});
//#endregion App_updateModelContext_appState
}
/**
* Example: Report runtime error to model.
*/
async function App_updateModelContext_reportError(app: App) {
//#region App_updateModelContext_reportError
try {
const _stream = await navigator.mediaDevices.getUserMedia({ audio: true });
// ... use _stream for transcription
} catch (err) {
// Inform the model that the app is in a degraded state
await app.updateModelContext({
content: [
{
type: "text",
text: "Error: transcription unavailable",
},
],
});
}
//#endregion App_updateModelContext_reportError
}
/**
* Example: Open documentation link.
*/
async function App_openLink_documentation(app: App) {
//#region App_openLink_documentation
const { isError } = await app.openLink({ url: "https://docs.example.com" });
if (isError) {
// Host denied the request (e.g., blocked domain, user cancelled)
// Optionally show fallback: display URL for manual copy
console.warn("Link request denied");
}
//#endregion App_openLink_documentation
}
/**
* Example: Toggle between inline and fullscreen display modes.
*/
async function App_requestDisplayMode_toggle(app: App) {
//#region App_requestDisplayMode_toggle
const container = document.getElementById("main")!;
const ctx = app.getHostContext();
const newMode = ctx?.displayMode === "inline" ? "fullscreen" : "inline";
if (ctx?.availableDisplayModes?.includes(newMode)) {
const result = await app.requestDisplayMode({ mode: newMode });
container.classList.toggle("fullscreen", result.mode === "fullscreen");
}
//#endregion App_requestDisplayMode_toggle
}
/**
* Example: Manually notify host of size change.
*/
function App_sendSizeChanged_manual(app: App) {
//#region App_sendSizeChanged_manual
app.sendSizeChanged({
width: 400,
height: 600,
});
//#endregion App_sendSizeChanged_manual
}
/**
* Example: Manual setup for custom scenarios (setupSizeChangedNotifications).
*/
async function App_setupAutoResize_manual(transport: PostMessageTransport) {
//#region App_setupAutoResize_manual
const app = new App(
{ name: "MyApp", version: "1.0.0" },
{},
{ autoResize: false },
);
await app.connect(transport);
// Later, enable auto-resize manually
const cleanup = app.setupSizeChangedNotifications();
// Clean up when done
cleanup();
//#endregion App_setupAutoResize_manual
}
/**
* Example: Connect with PostMessageTransport.
*/
async function App_connect_withPostMessageTransport() {
//#region App_connect_withPostMessageTransport
const app = new App({ name: "MyApp", version: "1.0.0" }, {});
try {
await app.connect(new PostMessageTransport(window.parent, window.parent));
console.log("Connected successfully!");
} catch (error) {
console.error("Failed to connect:", error);
}
//#endregion App_connect_withPostMessageTransport
}