-
Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathapp.ts
More file actions
2021 lines (1943 loc) · 71.4 KB
/
Copy pathapp.ts
File metadata and controls
2021 lines (1943 loc) · 71.4 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type RequestOptions,
mergeCapabilities,
ProtocolOptions,
DEFAULT_REQUEST_TIMEOUT_MSEC,
} from "@modelcontextprotocol/sdk/shared/protocol.js";
import {
CallToolRequest,
CallToolRequestSchema,
CallToolResult,
CallToolResultSchema,
CreateMessageRequest,
CreateMessageResult,
CreateMessageResultSchema,
CreateMessageResultWithTools,
CreateMessageResultWithToolsSchema,
EmptyResultSchema,
Implementation,
ListResourcesRequest,
ListResourcesResult,
ListResourcesResultSchema,
ListToolsRequest,
ListToolsRequestSchema,
ListToolsResult,
LoggingMessageNotification,
PingRequestSchema,
ReadResourceRequest,
ReadResourceResult,
ReadResourceResultSchema,
Tool,
ToolAnnotations,
ToolListChangedNotification,
} from "@modelcontextprotocol/sdk/types.js";
import { AppNotification, AppRequest, AppResult } from "./types";
import { ProtocolWithEvents } from "./events";
export { ProtocolWithEvents };
import { PostMessageTransport } from "./message-transport";
import {
LATEST_PROTOCOL_VERSION,
McpUiAppCapabilities,
McpUiUpdateModelContextRequest,
McpUiHostCapabilities,
McpUiHostContext,
McpUiHostContextChangedNotification,
McpUiHostContextChangedNotificationSchema,
McpUiInitializedNotification,
McpUiInitializeRequest,
McpUiInitializeResultSchema,
McpUiMessageRequest,
McpUiMessageResultSchema,
McpUiOpenLinkRequest,
McpUiOpenLinkResultSchema,
McpUiDownloadFileRequest,
McpUiDownloadFileResultSchema,
McpUiResourceTeardownRequest,
McpUiResourceTeardownRequestSchema,
McpUiResourceTeardownResult,
McpUiRequestTeardownNotification,
McpUiSizeChangedNotification,
McpUiToolCancelledNotification,
McpUiToolCancelledNotificationSchema,
McpUiToolInputNotification,
McpUiToolInputNotificationSchema,
McpUiToolInputPartialNotification,
McpUiToolInputPartialNotificationSchema,
McpUiToolResultNotification,
McpUiToolResultNotificationSchema,
McpUiRequestDisplayModeRequest,
McpUiRequestDisplayModeResultSchema,
} from "./types";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import {
StandardSchemaV1,
standardSchemaToJsonSchema,
validateStandardSchema,
} from "./standard-schema";
import { z } from "zod/v4";
export type {
StandardSchemaV1,
StandardSchemaWithJSON,
} from "./standard-schema";
export { PostMessageTransport } from "./message-transport";
export * from "./types";
export {
applyHostStyleVariables,
applyHostFonts,
getDocumentTheme,
applyDocumentTheme,
} from "./styles";
/**
* Metadata key for associating a UI resource URI with a tool.
*
* MCP servers include this key in tool definition metadata (via `tools/list`)
* to indicate which UI resource should be displayed when the tool is called.
* When hosts see a tool with this metadata, they fetch and render the
* corresponding {@link App `App`}.
*
* **Note**: This constant is provided for reference and backwards compatibility.
* Server developers should use {@link server-helpers!registerAppTool `registerAppTool`}
* with the `_meta.ui.resourceUri` format instead. Host developers must check both
* formats for compatibility.
*
* @example Modern format (server-side, not in Apps)
* ```ts source="./app.examples.ts#RESOURCE_URI_META_KEY_modernFormat"
* // Preferred: Use registerAppTool with nested ui.resourceUri
* registerAppTool(
* server,
* "weather",
* {
* description: "Get weather forecast",
* _meta: {
* ui: { resourceUri: "ui://weather/forecast" },
* },
* },
* handler,
* );
* ```
*
* @example Legacy format (deprecated, for backwards compatibility)
* ```ts source="./app.examples.ts#RESOURCE_URI_META_KEY_legacyFormat"
* // Deprecated: Direct use of RESOURCE_URI_META_KEY
* server.registerTool(
* "weather",
* {
* description: "Get weather forecast",
* _meta: {
* [RESOURCE_URI_META_KEY]: "ui://weather/forecast",
* },
* },
* handler,
* );
* ```
*
* @example How hosts check for this metadata (must support both formats)
* ```ts source="./app.examples.ts#RESOURCE_URI_META_KEY_hostSide"
* // Hosts should check both modern and legacy formats
* const meta = tool._meta;
* const uiMeta = meta?.ui as McpUiToolMeta | undefined;
* const legacyUri = meta?.[RESOURCE_URI_META_KEY] as string | undefined;
* const uiUri = uiMeta?.resourceUri ?? legacyUri;
* if (typeof uiUri === "string" && uiUri.startsWith("ui://")) {
* // Fetch the resource and display the UI
* }
* ```
*/
export const RESOURCE_URI_META_KEY = "ui/resourceUri";
/**
* MIME type for MCP UI resources.
*
* Identifies HTML content as an MCP App UI resource.
*
* Used by {@link server-helpers!registerAppResource `registerAppResource`} as the default MIME type for app resources.
*/
export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
/**
* Options for configuring {@link App `App`} behavior.
*
* Extends `ProtocolOptions` from the MCP SDK with `App`-specific configuration.
*
* @see `ProtocolOptions` from @modelcontextprotocol/sdk for inherited options
*/
export type AppOptions = ProtocolOptions & {
/**
* Automatically report size changes to the host using `ResizeObserver`.
*
* When enabled, the {@link App `App`} monitors `document.body` and `document.documentElement`
* for size changes and automatically sends `ui/notifications/size-changed`
* notifications to the host.
*
* @default true
*/
autoResize?: boolean;
/**
* Throw on detected misuse instead of logging a console warning.
*
* Currently this affects calling host-bound methods (e.g.
* {@link App.callServerTool `callServerTool`}, {@link App.sendMessage `sendMessage`})
* before {@link App.connect `connect`} has completed the `ui/initialize`
* handshake. With `strict: false` (default) a `console.warn` is emitted;
* with `strict: true` an `Error` is thrown.
*
* @remarks Throwing will become the default in a future release.
* @default false
*/
strict?: boolean;
/**
* Allow code paths that require CSP `unsafe-eval` (e.g. `new Function()`).
*
* Views typically run under a strict CSP without `unsafe-eval`. Zod's JIT
* object parser uses `new Function()` and throws on the first message parse
* under such a policy. By default (`allowUnsafeEval: false`) the
* {@link App `App`} constructor sets `z.config({ jitless: true })` so the
* SDK works out of the box under the spec's default CSP. Set
* `allowUnsafeEval: true` to skip that and keep the faster JIT path when
* the host's CSP permits `unsafe-eval`.
*
* @default false
*/
allowUnsafeEval?: boolean;
};
type RequestHandlerExtra = Parameters<
Parameters<App["setRequestHandler"]>[1]
>[1];
/**
* Result of an app-registered tool callback. When `Out` is provided,
* `structuredContent` is required and typed (unless `isError: true`).
*/
export type AppToolResult<
Out extends StandardSchemaV1 | undefined = undefined,
> = Out extends StandardSchemaV1
?
| (CallToolResult & {
structuredContent: StandardSchemaV1.InferOutput<Out>;
isError?: false;
})
| (CallToolResult & { isError: true })
: CallToolResult;
/**
* Callback for an app-registered tool. When `In` is provided, `args` is the
* validated/parsed input; when `In` is `undefined`, the callback receives only
* `extra`. When `Out` is provided, the return's `structuredContent` is typed.
*
* Mirrors `ToolCallback` from `@modelcontextprotocol/sdk/server/mcp.js` but is
* parameterized over {@link StandardSchemaV1} instead of zod, so any
* Standard-Schema-compatible library (Zod, ArkType, Valibot, …) can be used.
*/
export type AppToolCallback<
In extends StandardSchemaV1 | undefined = undefined,
Out extends StandardSchemaV1 | undefined = undefined,
> = In extends StandardSchemaV1
? (
args: StandardSchemaV1.InferOutput<In>,
extra: RequestHandlerExtra,
) => AppToolResult<Out> | Promise<AppToolResult<Out>>
: (
extra: RequestHandlerExtra,
) => AppToolResult<Out> | Promise<AppToolResult<Out>>;
/**
* Handle returned by {@link App.registerTool}. Mirrors `RegisteredTool` from
* `@modelcontextprotocol/sdk/server/mcp.js` but stores
* {@link StandardSchemaV1} schemas.
*/
export type RegisteredAppTool = {
title?: string;
description?: string;
inputSchema?: StandardSchemaV1;
outputSchema?: StandardSchemaV1;
annotations?: ToolAnnotations;
_meta?: Record<string, unknown>;
enabled: boolean;
enable(): void;
disable(): void;
remove(): void;
update(updates: Partial<Omit<RegisteredAppTool, "update">>): void;
/** @internal */
handler: (
args: unknown,
extra: RequestHandlerExtra,
) => Promise<CallToolResult>;
};
/**
* Maps DOM-style event names to their notification `params` types.
*
* Used by {@link App `App`} (which extends {@link ProtocolWithEvents `ProtocolWithEvents`})
* to provide type-safe `addEventListener` / `removeEventListener` and
* singular `on*` handler support.
*/
export type AppEventMap = {
toolinput: McpUiToolInputNotification["params"];
toolinputpartial: McpUiToolInputPartialNotification["params"];
toolresult: McpUiToolResultNotification["params"];
toolcancelled: McpUiToolCancelledNotification["params"];
hostcontextchanged: McpUiHostContextChangedNotification["params"];
};
/**
* Main class for MCP Apps to communicate with their host.
*
* The `App` class provides a framework-agnostic way to build interactive MCP Apps
* that run inside host applications. It extends the MCP SDK's `Protocol` class and
* handles the connection lifecycle, initialization handshake, and bidirectional
* communication with the host.
*
* ## Architecture
*
* Views (Apps) act as MCP clients connecting to the host via {@link PostMessageTransport `PostMessageTransport`}.
* The host proxies requests to the actual MCP server and forwards
* responses back to the App.
*
* ## Lifecycle
*
* 1. **Create**: Instantiate App with info and capabilities
* 2. **Connect**: Call `connect()` to establish transport and perform handshake
* 3. **Interactive**: Send requests, receive notifications, call tools
* 4. **Teardown**: Host sends teardown request before unmounting
*
* ## Inherited Methods
*
* As a subclass of {@link ProtocolWithEvents `ProtocolWithEvents`}, `App` inherits:
* - `setRequestHandler()` - Register handlers for requests from host
* - `setNotificationHandler()` - Register handlers for notifications from host
* - `addEventListener()` - Append a listener for a notification event (multi-listener)
* - `removeEventListener()` - Remove a previously added listener
*
* @see {@link ProtocolWithEvents `ProtocolWithEvents`} for the DOM-model event system
*
* ## Notification Setters (DOM-model `on*` handlers)
*
* For common notifications, the `App` class provides getter/setter properties
* that follow DOM-model replace semantics (like `el.onclick`):
* - `ontoolinput` - Complete tool arguments from host
* - `ontoolinputpartial` - Streaming partial tool arguments
* - `ontoolresult` - Tool execution results
* - `ontoolcancelled` - Tool execution was cancelled by user or host
* - `onhostcontextchanged` - Host context changes (theme, locale, etc.)
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use `addEventListener` to attach multiple listeners without replacing.
*
* @example Basic usage with PostMessageTransport
* ```ts source="./app.examples.ts#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();
* ```
*/
export class App extends ProtocolWithEvents<
AppRequest,
AppNotification,
AppResult,
AppEventMap
> {
private _hostCapabilities?: McpUiHostCapabilities;
private _hostInfo?: Implementation;
private _hostContext?: McpUiHostContext;
private _registeredTools: { [name: string]: RegisteredAppTool } = {};
private _initializedSent = false;
/**
* Warn if a host-bound method is called before {@link connect `connect`} has
* completed the `ui/initialize` → `ui/notifications/initialized` handshake.
*
* Calling these methods early can race the handshake on strict hosts and
* leave the iframe permanently hidden. See
* {@link https://github.com/anthropics/claude-ai-mcp/issues/61 claude-ai-mcp#61} /
* {@link https://github.com/anthropics/claude-ai-mcp/issues/149 #149}.
*
* @remarks This will become a thrown `Error` in a future minor release.
*/
private _assertInitialized(method: string): void {
if (this._initializedSent) return;
const msg =
`[ext-apps] App.${method}() called before connect() completed the ` +
`ui/initialize handshake. Await app.connect() before calling this ` +
`method, or move data loading to an ontoolresult handler.`;
if (this.options?.strict) {
throw new Error(msg);
}
// TODO(next-minor): make `strict: true` the default.
console.warn(`${msg}. This will throw in a future release.`);
}
protected readonly eventSchemas = {
toolinput: McpUiToolInputNotificationSchema,
toolinputpartial: McpUiToolInputPartialNotificationSchema,
toolresult: McpUiToolResultNotificationSchema,
toolcancelled: McpUiToolCancelledNotificationSchema,
hostcontextchanged: McpUiHostContextChangedNotificationSchema,
};
/**
* Events the host typically sends once, shortly after the handshake.
* Registering a handler for one of these *after* {@link connect `connect`}
* resolves risks missing the notification entirely.
*/
private static readonly ONE_SHOT_EVENTS: ReadonlySet<keyof AppEventMap> =
new Set(["toolinput", "toolinputpartial", "toolresult", "toolcancelled"]);
/**
* One-shot events that have had at least one handler registered (via `on*`
* setter or `addEventListener`) at any point. Once an event is in this set,
* subsequent late registrations are not flagged — only the *first* handler
* matters for the missed-notification race, and re-registration (e.g. React
* `useEffect` cleanup → re-add on dep change) is a legitimate pattern.
*/
private readonly _everHadListener = new Set<keyof AppEventMap>();
/**
* Warn (or throw under `strict`) when the *first* handler for a one-shot
* event is registered after the `ui/initialize` → `ui/notifications/initialized`
* handshake has completed. The host may have already fired the notification
* by then. Subsequent registrations for the same event are not flagged.
*
* Mirrors {@link _assertInitialized `_assertInitialized`} (the outbound-side guard).
*/
private _assertHandlerTiming(event: keyof AppEventMap): void {
if (!App.ONE_SHOT_EVENTS.has(event) || this._everHadListener.has(event)) {
return;
}
this._everHadListener.add(event);
if (!this._initializedSent) return;
const msg =
`[ext-apps] "${String(event)}" handler registered after connect() ` +
`completed the ui/initialize handshake. The host may have already sent ` +
`this notification. Register handlers before calling app.connect().`;
if (this.options?.strict) {
throw new Error(msg);
}
console.warn(msg);
}
protected override setEventHandler<K extends keyof AppEventMap>(
event: K,
handler: ((params: AppEventMap[K]) => void) | undefined,
): void {
if (handler) this._assertHandlerTiming(event);
super.setEventHandler(event, handler);
}
override addEventListener<K extends keyof AppEventMap>(
event: K,
handler: (params: AppEventMap[K]) => void,
): void {
this._assertHandlerTiming(event);
super.addEventListener(event, handler);
}
protected override onEventDispatch<K extends keyof AppEventMap>(
event: K,
params: AppEventMap[K],
): void {
if (event === "hostcontextchanged") {
this._hostContext = { ...this._hostContext, ...params };
}
}
/**
* Create a new MCP App instance.
*
* @param _appInfo - App identification (name and version)
* @param _capabilities - Features and capabilities this app provides
* @param options - Configuration options including `autoResize` behavior
*
* @example
* ```ts source="./app.examples.ts#App_constructor_basic"
* const app = new App(
* { name: "MyApp", version: "1.0.0" },
* { tools: { listChanged: true } }, // capabilities
* { autoResize: true }, // options
* );
* ```
*/
constructor(
private _appInfo: Implementation,
private _capabilities: McpUiAppCapabilities = {},
private options: AppOptions = { autoResize: true },
) {
super(options);
if (!options.allowUnsafeEval) {
z.config({ jitless: true });
}
this.setRequestHandler(PingRequestSchema, (request) => {
console.log("Received ping:", request.params);
return {};
});
// Eagerly register the hostcontextchanged event slot so that
// onEventDispatch (which merges into _hostContext) fires even if the
// user never assigns onhostcontextchanged or calls addEventListener.
this.setEventHandler("hostcontextchanged", undefined);
}
private registerCapabilities(capabilities: McpUiAppCapabilities): void {
if (this.transport) {
throw new Error(
"Cannot register capabilities after transport is established",
);
}
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
}
registerTool<
OutputArgs extends undefined | StandardSchemaV1 = undefined,
InputArgs extends undefined | StandardSchemaV1 = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
_meta?: Record<string, unknown>;
},
cb: AppToolCallback<InputArgs, OutputArgs>,
): RegisteredAppTool {
if (this._registeredTools[name]) {
throw new Error(`Tool ${name} is already registered`);
}
const app = this;
const notify = () => {
if (app._initializedSent && app._capabilities.tools?.listChanged) {
void app.sendToolListChanged();
}
};
// Arity is fixed at registration time even if inputSchema is later
// update()d, since cb's signature can't change.
const cbTakesArgs = config.inputSchema !== undefined;
const registeredTool: RegisteredAppTool = {
title: config.title,
description: config.description,
inputSchema: config.inputSchema,
outputSchema: config.outputSchema,
annotations: config.annotations,
_meta: config._meta,
enabled: true,
enable(): void {
this.enabled = true;
notify();
},
disable(): void {
this.enabled = false;
notify();
},
update(updates) {
Object.assign(this, updates);
notify();
},
remove() {
if (app._registeredTools[name] !== registeredTool) return;
delete app._registeredTools[name];
notify();
},
handler: async (rawArgs, extra) => {
if (!registeredTool.enabled) {
throw new Error(`Tool ${name} is disabled`);
}
let result: CallToolResult;
if (cbTakesArgs) {
const schema = registeredTool.inputSchema;
const parsedArgs = schema
? await validateStandardSchema(
schema,
rawArgs ?? {},
`Invalid input for tool ${name}: `,
)
: (rawArgs ?? {});
result = await (
cb as AppToolCallback<StandardSchemaV1, StandardSchemaV1>
)(parsedArgs, extra);
} else {
result = await (cb as AppToolCallback<undefined, StandardSchemaV1>)(
extra,
);
}
if (registeredTool.outputSchema && !result.isError) {
result.structuredContent = (await validateStandardSchema(
registeredTool.outputSchema,
result.structuredContent,
`Invalid output for tool ${name}: `,
)) as CallToolResult["structuredContent"];
}
return result;
},
};
this._registeredTools[name] = registeredTool;
// Auto-register tools capability so setRequestHandler's capability check
// passes. Mirrors McpServer.registerTool behavior — callers shouldn't need
// to declare { tools: {} } in the constructor just to use registerTool.
// Only do this pre-connect; post-connect the capability was already
// advertised (or wasn't) and can't change.
if (!this._capabilities.tools && !this.transport) {
this.registerCapabilities({ tools: { listChanged: true } });
}
this.ensureToolHandlersInitialized();
notify();
return registeredTool;
}
private _toolHandlersInitialized = false;
private ensureToolHandlersInitialized(): void {
if (this._toolHandlersInitialized) {
return;
}
this._toolHandlersInitialized = true;
this.oncalltool = async (params, extra) => {
const tool = this._registeredTools[params.name];
if (!tool) {
throw new Error(`Tool ${params.name} not found`);
}
return tool.handler(params.arguments, extra);
};
this.onlisttools = async (_params, _extra) => {
const tools: Tool[] = await Promise.all(
Object.entries(this._registeredTools)
.filter(([_, tool]) => tool.enabled)
.map(async ([name, tool]) => {
const result: Tool = {
name,
title: tool.title,
description: tool.description,
inputSchema: (tool.inputSchema
? await standardSchemaToJsonSchema(tool.inputSchema, "input")
: {
type: "object" as const,
properties: {},
}) as Tool["inputSchema"],
};
// outputSchema is optional in core MCP — only emit when the app
// provided one, otherwise hosts would assume structuredContent.
if (tool.outputSchema) {
result.outputSchema = (await standardSchemaToJsonSchema(
tool.outputSchema,
"output",
)) as Tool["outputSchema"];
}
if (tool.annotations) {
result.annotations = tool.annotations;
}
if (tool._meta) {
result._meta = tool._meta;
}
return result;
}),
);
return { tools };
};
}
async sendToolListChanged(
params: ToolListChangedNotification["params"] = {},
): Promise<void> {
this._assertInitialized("sendToolListChanged");
await this.notification(<ToolListChangedNotification>{
method: "notifications/tools/list_changed",
params,
});
}
/**
* Get the host's capabilities discovered during initialization.
*
* Returns the capabilities that the host advertised during the
* {@link connect `connect`} handshake. Returns `undefined` if called before
* connection is established.
*
* @returns Host capabilities, or `undefined` if not yet connected
*
* @example Check host capabilities after connection
* ```ts source="./app.examples.ts#App_getHostCapabilities_checkAfterConnection"
* await app.connect();
* if (app.getHostCapabilities()?.serverTools) {
* console.log("Host supports server tool calls");
* }
* ```
*
* @see {@link connect `connect`} for the initialization handshake
* @see {@link McpUiHostCapabilities `McpUiHostCapabilities`} for the capabilities structure
*/
getHostCapabilities(): McpUiHostCapabilities | undefined {
return this._hostCapabilities;
}
/**
* Get the host's implementation info discovered during initialization.
*
* Returns the host's name and version as advertised during the
* {@link connect `connect`} handshake. Returns `undefined` if called before
* connection is established.
*
* @returns Host implementation info, or `undefined` if not yet connected
*
* @example Log host information after connection
* ```ts source="./app.examples.ts#App_getHostVersion_logAfterConnection"
* await app.connect(transport);
* const { name, version } = app.getHostVersion() ?? {};
* console.log(`Connected to ${name} v${version}`);
* ```
*
* @see {@link connect `connect`} for the initialization handshake
*/
getHostVersion(): Implementation | undefined {
return this._hostInfo;
}
/**
* Get the host context discovered during initialization.
*
* Returns the host context that was provided in the initialization response,
* including tool info, theme, locale, and other environment details.
* This context is automatically updated when the host sends
* `ui/notifications/host-context-changed` notifications.
*
* Returns `undefined` if called before connection is established.
*
* @returns Host context, or `undefined` if not yet connected
*
* @example Access host context after connection
* ```ts source="./app.examples.ts#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);
* }
* ```
*
* @see {@link connect `connect`} for the initialization handshake
* @see {@link onhostcontextchanged `onhostcontextchanged`} for context change notifications
* @see {@link McpUiHostContext `McpUiHostContext`} for the context structure
*/
getHostContext(): McpUiHostContext | undefined {
return this._hostContext;
}
/**
* Convenience handler for receiving complete tool input from the host.
*
* Set this property to register a handler that will be called when the host
* sends a tool's complete arguments. This is sent after a tool call begins
* and before the tool result is available.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use {@link addEventListener `addEventListener`} to attach multiple listeners
* without replacing.
*
* Register handlers before calling {@link connect `connect`} to avoid missing notifications.
*
* @example
* ```ts source="./app.examples.ts#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();
* ```
*
* @deprecated Use {@link addEventListener `addEventListener("toolinput", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
* @see {@link McpUiToolInputNotification `McpUiToolInputNotification`} for the notification structure
*/
get ontoolinput():
| ((params: McpUiToolInputNotification["params"]) => void)
| undefined {
return this.getEventHandler("toolinput");
}
set ontoolinput(
callback:
| ((params: McpUiToolInputNotification["params"]) => void)
| undefined,
) {
this.setEventHandler("toolinput", callback);
}
/**
* Convenience handler for receiving streaming partial tool input from the host.
*
* Set this property to register a handler that will be called as the host
* streams partial tool arguments during tool call initialization. This enables
* progressive rendering of tool arguments before they're complete.
*
* **Important:** Partial arguments are "healed" JSON — the host closes unclosed
* brackets/braces to produce valid JSON. This means objects may be incomplete
* (e.g., the last item in an array may be truncated). Use partial data only
* for preview UI, not for critical operations.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use {@link addEventListener `addEventListener`} to attach multiple listeners
* without replacing.
*
* Register handlers before calling {@link connect `connect`} to avoid missing notifications.
*
* @example Progressive rendering of tool arguments
* ```ts source="./app.examples.ts#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);
* };
* ```
*
* @deprecated Use {@link addEventListener `addEventListener("toolinputpartial", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
* @see {@link McpUiToolInputPartialNotification `McpUiToolInputPartialNotification`} for the notification structure
* @see {@link ontoolinput `ontoolinput`} for the complete tool input handler
*/
get ontoolinputpartial():
| ((params: McpUiToolInputPartialNotification["params"]) => void)
| undefined {
return this.getEventHandler("toolinputpartial");
}
set ontoolinputpartial(
callback:
| ((params: McpUiToolInputPartialNotification["params"]) => void)
| undefined,
) {
this.setEventHandler("toolinputpartial", callback);
}
/**
* Convenience handler for receiving tool execution results from the host.
*
* Set this property to register a handler that will be called when the host
* sends the result of a tool execution. This is sent after the tool completes
* on the MCP server, allowing your app to display the results or update its state.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use {@link addEventListener `addEventListener`} to attach multiple listeners
* without replacing.
*
* Register handlers before calling {@link connect `connect`} to avoid missing notifications.
*
* @example Display tool execution results
* ```ts source="./app.examples.ts#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);
* }
* };
* ```
*
* @deprecated Use {@link addEventListener `addEventListener("toolresult", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
* @see {@link McpUiToolResultNotification `McpUiToolResultNotification`} for the notification structure
* @see {@link ontoolinput `ontoolinput`} for the initial tool input handler
*/
get ontoolresult():
| ((params: McpUiToolResultNotification["params"]) => void)
| undefined {
return this.getEventHandler("toolresult");
}
set ontoolresult(
callback:
| ((params: McpUiToolResultNotification["params"]) => void)
| undefined,
) {
this.setEventHandler("toolresult", callback);
}
/**
* Convenience handler for receiving tool cancellation notifications from the host.
*
* Set this property to register a handler that will be called when the host
* notifies that tool execution was cancelled. This can occur for various reasons
* including user action, sampling error, classifier intervention, or other
* interruptions. Apps should update their state and display appropriate feedback.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use {@link addEventListener `addEventListener`} to attach multiple listeners
* without replacing.
*
* Register handlers before calling {@link connect `connect`} to avoid missing notifications.
*
* @example Handle tool cancellation
* ```ts source="./app.examples.ts#App_ontoolcancelled_handleCancellation"
* app.ontoolcancelled = (params) => {
* console.log("Tool cancelled:", params.reason);
* // Update your UI to show cancellation state
* };
* ```
*
* @deprecated Use {@link addEventListener `addEventListener("toolcancelled", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
* @see {@link McpUiToolCancelledNotification `McpUiToolCancelledNotification`} for the notification structure
* @see {@link ontoolresult `ontoolresult`} for successful tool completion
*/
get ontoolcancelled():
| ((params: McpUiToolCancelledNotification["params"]) => void)
| undefined {
return this.getEventHandler("toolcancelled");
}
set ontoolcancelled(
callback:
| ((params: McpUiToolCancelledNotification["params"]) => void)
| undefined,
) {
this.setEventHandler("toolcancelled", callback);
}
/**
* Convenience handler for host context changes (theme, locale, etc.).
*
* Set this property to register a handler that will be called when the host's
* context changes, such as theme switching (light/dark), locale changes, or
* other environmental updates. Apps should respond by updating their UI
* accordingly.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
* Use {@link addEventListener `addEventListener`} to attach multiple listeners
* without replacing.
*
* Notification params are automatically merged into the internal host context
* via {@link onEventDispatch `onEventDispatch`} before any handler or listener
* fires. This means {@link getHostContext `getHostContext`} will return the
* updated values even before your callback runs.
*
* Register handlers before calling {@link connect `connect`} to avoid missing notifications.
*
* @example Respond to theme changes
* ```ts source="./app.examples.ts#App_onhostcontextchanged_respondToTheme"
* app.onhostcontextchanged = (ctx) => {
* if (ctx.theme === "dark") {
* document.body.classList.add("dark-theme");
* } else {
* document.body.classList.remove("dark-theme");
* }
* };
* ```
*
* @deprecated Use {@link addEventListener `addEventListener("hostcontextchanged", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
* @see {@link McpUiHostContextChangedNotification `McpUiHostContextChangedNotification`} for the notification structure
* @see {@link McpUiHostContext `McpUiHostContext`} for the full context structure
*/
get onhostcontextchanged():
| ((params: McpUiHostContextChangedNotification["params"]) => void)
| undefined {
return this.getEventHandler("hostcontextchanged");
}
set onhostcontextchanged(
callback:
| ((params: McpUiHostContextChangedNotification["params"]) => void)
| undefined,
) {
this.setEventHandler("hostcontextchanged", callback);
}
/**
* Convenience handler for graceful shutdown requests from the host.
*
* Set this property to register a handler that will be called when the host
* requests the app to prepare for teardown. This allows the app to perform
* cleanup operations (save state, close connections, etc.) before being unmounted.
*
* The handler can be sync or async. The host will wait for the returned promise
* to resolve before proceeding with teardown.
*
* Assigning replaces the previous handler; assigning `undefined` clears it.
*
* Register handlers before calling {@link connect `connect`} to avoid missing requests.
*
* @param callback - Function called when teardown is requested.
* Must return `McpUiResourceTeardownResult` (can be an empty object `{}`) or a Promise resolving to it.
*
* @example Perform cleanup before teardown
* ```ts source="./app.examples.ts#App_onteardown_performCleanup"
* app.onteardown = async () => {
* await saveState();
* closeConnections();
* console.log("App ready for teardown");
* return {};
* };
* ```
*
* @see {@link McpUiResourceTeardownRequest `McpUiResourceTeardownRequest`} for the request structure
*/
private _onteardown?: (
params: McpUiResourceTeardownRequest["params"],
extra: RequestHandlerExtra,
) => McpUiResourceTeardownResult | Promise<McpUiResourceTeardownResult>;
get onteardown() {
return this._onteardown;
}
set onteardown(
callback:
| ((