-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathapp-bridge.ts
More file actions
1424 lines (1368 loc) · 46.6 KB
/
app-bridge.ts
File metadata and controls
1424 lines (1368 loc) · 46.6 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 { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import {
CallToolRequest,
CallToolRequestSchema,
CallToolResult,
CallToolResultSchema,
EmptyResult,
Implementation,
ListPromptsRequest,
ListPromptsRequestSchema,
ListPromptsResult,
ListPromptsResultSchema,
ListResourcesRequest,
ListResourcesRequestSchema,
ListResourcesResult,
ListResourcesResultSchema,
ListResourceTemplatesRequest,
ListResourceTemplatesRequestSchema,
ListResourceTemplatesResult,
ListResourceTemplatesResultSchema,
LoggingMessageNotification,
LoggingMessageNotificationSchema,
PingRequest,
PingRequestSchema,
PromptListChangedNotification,
PromptListChangedNotificationSchema,
ReadResourceRequest,
ReadResourceRequestSchema,
ReadResourceResult,
ReadResourceResultSchema,
ResourceListChangedNotification,
ResourceListChangedNotificationSchema,
ToolListChangedNotification,
ToolListChangedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js";
import {
Protocol,
ProtocolOptions,
RequestOptions,
} from "@modelcontextprotocol/sdk/shared/protocol.js";
import {
type AppNotification,
type AppRequest,
type AppResult,
type McpUiSandboxResourceReadyNotification,
type McpUiSizeChangedNotification,
type McpUiToolCancelledNotification,
type McpUiToolInputNotification,
type McpUiToolInputPartialNotification,
type McpUiToolResultNotification,
LATEST_PROTOCOL_VERSION,
McpUiAppCapabilities,
McpUiUpdateModelContextRequest,
McpUiUpdateModelContextRequestSchema,
McpUiHostCapabilities,
McpUiHostContext,
McpUiHostContextChangedNotification,
McpUiInitializedNotification,
McpUiInitializedNotificationSchema,
McpUiInitializeRequest,
McpUiInitializeRequestSchema,
McpUiInitializeResult,
McpUiMessageRequest,
McpUiMessageRequestSchema,
McpUiMessageResult,
McpUiOpenLinkRequest,
McpUiOpenLinkRequestSchema,
McpUiOpenLinkResult,
McpUiResourceTeardownRequest,
McpUiResourceTeardownResultSchema,
McpUiSandboxProxyReadyNotification,
McpUiSandboxProxyReadyNotificationSchema,
McpUiSizeChangedNotificationSchema,
McpUiRequestDisplayModeRequest,
McpUiRequestDisplayModeRequestSchema,
McpUiRequestDisplayModeResult,
} from "./types";
export * from "./types";
export { RESOURCE_URI_META_KEY, RESOURCE_MIME_TYPE } from "./app";
import { RESOURCE_URI_META_KEY } from "./app";
export { PostMessageTransport } from "./message-transport";
/**
* Extract UI resource URI from tool metadata.
*
* Supports both the new nested format (`_meta.ui.resourceUri`) and the
* deprecated flat format (`_meta["ui/resourceUri"]`). The new nested format
* takes precedence if both are present.
*
* @param tool - A tool object with optional `_meta` property
* @returns The UI resource URI if valid, undefined if not present
* @throws Error if resourceUri is present but invalid (not starting with "ui://")
*
* @example
* ```typescript
* // New nested format (preferred)
* const uri = getToolUiResourceUri({
* _meta: { ui: { resourceUri: "ui://server/app.html" } }
* });
*
* // Deprecated flat format (still supported)
* const uri = getToolUiResourceUri({
* _meta: { "ui/resourceUri": "ui://server/app.html" }
* });
* ```
*/
export function getToolUiResourceUri(tool: {
_meta?: Record<string, unknown>;
}): string | undefined {
// Try new nested format first: _meta.ui.resourceUri
const uiMeta = tool._meta?.ui as { resourceUri?: unknown } | undefined;
let uri: unknown = uiMeta?.resourceUri;
// Fall back to deprecated flat format: _meta["ui/resourceUri"]
if (uri === undefined) {
uri = tool._meta?.[RESOURCE_URI_META_KEY];
}
if (typeof uri === "string" && uri.startsWith("ui://")) {
return uri;
} else if (uri !== undefined) {
throw new Error(`Invalid UI resource URI: ${JSON.stringify(uri)}`);
}
return undefined;
}
/**
* Options for configuring AppBridge behavior.
*
* @see ProtocolOptions from @modelcontextprotocol/sdk for available options
*/
export type HostOptions = ProtocolOptions & {
hostContext?: McpUiHostContext;
};
/**
* Protocol versions supported by this AppBridge implementation.
*
* The SDK automatically handles version negotiation during initialization.
* Hosts don't need to manage protocol versions manually.
*/
export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION];
/**
* Extra metadata passed to request handlers.
*
* This type represents the additional context provided by the Protocol class
* when handling requests, including abort signals and session information.
* It is extracted from the MCP SDK's request handler signature.
*
* @internal
*/
type RequestHandlerExtra = Parameters<
Parameters<AppBridge["setRequestHandler"]>[1]
>[1];
/**
* Host-side bridge for communicating with a single Guest UI (App).
*
* AppBridge extends the MCP SDK's Protocol class and acts as a proxy between
* the host application and a Guest UI running in an iframe. It automatically
* forwards MCP server capabilities (tools, resources, prompts) to the Guest UI
* and handles the initialization handshake.
*
* ## Architecture
*
* **Guest UI ↔ AppBridge ↔ Host ↔ MCP Server**
*
* The bridge proxies requests from the Guest UI to the MCP server and forwards
* responses back. It also sends host-initiated notifications like tool input
* and results to the Guest UI.
*
* ## Lifecycle
*
* 1. **Create**: Instantiate AppBridge with MCP client and capabilities
* 2. **Connect**: Call `connect()` with transport to establish communication
* 3. **Wait for init**: Guest UI sends initialize request, bridge responds
* 4. **Send data**: Call `sendToolInput()`, `sendToolResult()`, etc.
* 5. **Teardown**: Call `teardownResource()` before unmounting iframe
*
* @example Basic usage
* ```typescript
* import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';
* import { Client } from '@modelcontextprotocol/sdk/client/index.js';
*
* // Create MCP client for the server
* const client = new Client({
* name: "MyHost",
* version: "1.0.0",
* });
* await client.connect(serverTransport);
*
* // Create bridge for the Guest UI
* const bridge = new AppBridge(
* client,
* { name: "MyHost", version: "1.0.0" },
* { openLinks: {}, serverTools: {}, logging: {} }
* );
*
* // Set up iframe and connect
* const iframe = document.getElementById('app') as HTMLIFrameElement;
* const transport = new PostMessageTransport(
* iframe.contentWindow!,
* iframe.contentWindow!,
* );
*
* bridge.oninitialized = () => {
* console.log("Guest UI initialized");
* // Now safe to send tool input
* bridge.sendToolInput({ arguments: { location: "NYC" } });
* };
*
* await bridge.connect(transport);
* ```
*/
export class AppBridge extends Protocol<
AppRequest,
AppNotification,
AppResult
> {
private _appCapabilities?: McpUiAppCapabilities;
private _hostContext: McpUiHostContext = {};
private _appInfo?: Implementation;
/**
* Create a new AppBridge instance.
*
* @param _client - MCP client connected to the server, or `null`. When provided,
* {@link connect} will automatically set up forwarding of MCP requests/notifications
* between the Guest UI and the server. When `null`, you must register handlers
* manually using the `oncalltool`, `onlistresources`, etc. setters.
* @param _hostInfo - Host application identification (name and version)
* @param _capabilities - Features and capabilities the host supports
* @param options - Configuration options (inherited from Protocol)
*
* @example With MCP client (automatic forwarding)
* ```typescript
* const bridge = new AppBridge(
* mcpClient,
* { name: "MyHost", version: "1.0.0" },
* { openLinks: {}, serverTools: {}, logging: {} }
* );
* ```
*
* @example Without MCP client (manual handlers)
* ```typescript
* const bridge = new AppBridge(
* null,
* { name: "MyHost", version: "1.0.0" },
* { openLinks: {}, serverTools: {}, logging: {} }
* );
* bridge.oncalltool = async (params, extra) => { ... };
* ```
*/
constructor(
private _client: Client | null,
private _hostInfo: Implementation,
private _capabilities: McpUiHostCapabilities,
options?: HostOptions,
) {
super(options);
this._hostContext = options?.hostContext || {};
this.setRequestHandler(McpUiInitializeRequestSchema, (request) =>
this._oninitialize(request),
);
this.setRequestHandler(PingRequestSchema, (request, extra) => {
this.onping?.(request.params, extra);
return {};
});
// Default handler for requestDisplayMode - returns current mode from host context.
// Hosts can override this by setting bridge.onrequestdisplaymode = ...
this.setRequestHandler(McpUiRequestDisplayModeRequestSchema, (request) => {
const currentMode = this._hostContext.displayMode ?? "inline";
return { mode: currentMode };
});
}
/**
* Get the Guest UI's capabilities discovered during initialization.
*
* Returns the capabilities that the Guest UI advertised during its
* initialization request. Returns `undefined` if called before
* initialization completes.
*
* @returns Guest UI capabilities, or `undefined` if not yet initialized
*
* @example Check Guest UI capabilities after initialization
* ```typescript
* bridge.oninitialized = () => {
* const caps = bridge.getAppCapabilities();
* if (caps?.tools) {
* console.log("Guest UI provides tools");
* }
* };
* ```
*
* @see {@link McpUiAppCapabilities} for the capabilities structure
*/
getAppCapabilities(): McpUiAppCapabilities | undefined {
return this._appCapabilities;
}
/**
* Get the Guest UI's implementation info discovered during initialization.
*
* Returns the Guest UI's name and version as provided in its initialization
* request. Returns `undefined` if called before initialization completes.
*
* @returns Guest UI implementation info, or `undefined` if not yet initialized
*
* @example Log Guest UI information after initialization
* ```typescript
* bridge.oninitialized = () => {
* const appInfo = bridge.getAppVersion();
* if (appInfo) {
* console.log(`Guest UI: ${appInfo.name} v${appInfo.version}`);
* }
* };
* ```
*/
getAppVersion(): Implementation | undefined {
return this._appInfo;
}
/**
* Optional handler for ping requests from the Guest UI.
*
* The Guest UI can send standard MCP `ping` requests to verify the connection
* is alive. The AppBridge automatically responds with an empty object, but this
* handler allows the host to observe or log ping activity.
*
* Unlike the other handlers which use setters, this is a direct property
* assignment. It is optional; if not set, pings are still handled automatically.
*
* @param params - Empty params object from the ping request
* @param extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.onping = (params, extra) => {
* console.log("Received ping from Guest UI");
* };
* ```
*/
onping?: (params: PingRequest["params"], extra: RequestHandlerExtra) => void;
/**
* Register a handler for size change notifications from the Guest UI.
*
* The Guest UI sends `ui/notifications/size-changed` when its rendered content
* size changes, typically via ResizeObserver. Set this callback to dynamically
* adjust the iframe container dimensions based on the Guest UI's content.
*
* Note: This is for Guest UI → Host communication. To notify the Guest UI of
* host container dimension changes, use {@link setHostContext}.
*
* @example
* ```typescript
* bridge.onsizechange = ({ width, height }) => {
* if (width != null) {
* iframe.style.width = `${width}px`;
* }
* if (height != null) {
* iframe.style.height = `${height}px`;
* }
* };
* ```
*
* @see {@link McpUiSizeChangedNotification} for the notification type
* @see {@link app.App.sendSizeChanged} for Host → Guest UI size notifications
*/
set onsizechange(
callback: (params: McpUiSizeChangedNotification["params"]) => void,
) {
this.setNotificationHandler(McpUiSizeChangedNotificationSchema, (n) =>
callback(n.params),
);
}
/**
* Register a handler for sandbox proxy ready notifications.
*
* This is an internal callback used by web-based hosts implementing the
* double-iframe sandbox architecture. The sandbox proxy sends
* `ui/notifications/sandbox-proxy-ready` after it loads and is ready to receive
* HTML content.
*
* When this fires, the host should call {@link sendSandboxResourceReady} with
* the HTML content to load into the inner sandboxed iframe.
*
* @example
* ```typescript
* bridge.onsandboxready = async () => {
* const resource = await mcpClient.request(
* { method: "resources/read", params: { uri: "ui://my-app" } },
* ReadResourceResultSchema
* );
*
* bridge.sendSandboxResourceReady({
* html: resource.contents[0].text,
* sandbox: "allow-scripts"
* });
* };
* ```
*
* @internal
* @see {@link McpUiSandboxProxyReadyNotification} for the notification type
* @see {@link sendSandboxResourceReady} for sending content to the sandbox
*/
set onsandboxready(
callback: (params: McpUiSandboxProxyReadyNotification["params"]) => void,
) {
this.setNotificationHandler(McpUiSandboxProxyReadyNotificationSchema, (n) =>
callback(n.params),
);
}
/**
* Called when the Guest UI completes initialization.
*
* Set this callback to be notified when the Guest UI has finished its
* initialization handshake and is ready to receive tool input and other data.
*
* @example
* ```typescript
* bridge.oninitialized = () => {
* console.log("Guest UI ready");
* bridge.sendToolInput({ arguments: toolArgs });
* };
* ```
*
* @see {@link McpUiInitializedNotification} for the notification type
* @see {@link sendToolInput} for sending tool arguments to the Guest UI
*/
set oninitialized(
callback: (params: McpUiInitializedNotification["params"]) => void,
) {
this.setNotificationHandler(McpUiInitializedNotificationSchema, (n) =>
callback(n.params),
);
}
/**
* Register a handler for message requests from the Guest UI.
*
* The Guest UI sends `ui/message` requests when it wants to add a message to
* the host's chat interface. This enables interactive apps to communicate with
* the user through the conversation thread.
*
* The handler should process the message (add it to the chat) and return a
* result indicating success or failure. For security, the host should NOT
* return conversation content or follow-up results to prevent information
* leakage.
*
* @param callback - Handler that receives message params and returns a result
* - params.role - Message role (currently only "user" is supported)
* - params.content - Message content blocks (text, image, etc.)
* - extra - Request metadata (abort signal, session info)
* - Returns: Promise<McpUiMessageResult> with optional isError flag
*
* @example
* ```typescript
* bridge.onmessage = async ({ role, content }, extra) => {
* try {
* await chatManager.addMessage({ role, content, source: "app" });
* return {}; // Success
* } catch (error) {
* console.error("Failed to add message:", error);
* return { isError: true };
* }
* };
* ```
*
* @see {@link McpUiMessageRequest} for the request type
* @see {@link McpUiMessageResult} for the result type
*/
set onmessage(
callback: (
params: McpUiMessageRequest["params"],
extra: RequestHandlerExtra,
) => Promise<McpUiMessageResult>,
) {
this.setRequestHandler(
McpUiMessageRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for external link requests from the Guest UI.
*
* The Guest UI sends `ui/open-link` requests when it wants to open an external
* URL in the host's default browser. The handler should validate the URL and
* open it according to the host's security policy and user preferences.
*
* The host MAY:
* - Show a confirmation dialog before opening
* - Block URLs based on a security policy or allowlist
* - Log the request for audit purposes
* - Reject the request entirely
*
* @param callback - Handler that receives URL params and returns a result
* - params.url - URL to open in the host's browser
* - extra - Request metadata (abort signal, session info)
* - Returns: Promise<McpUiOpenLinkResult> with optional isError flag
*
* @example
* ```typescript
* bridge.onopenlink = async ({ url }, extra) => {
* if (!isAllowedDomain(url)) {
* console.warn("Blocked external link:", url);
* return { isError: true };
* }
*
* const confirmed = await showDialog({
* message: `Open external link?\n${url}`,
* buttons: ["Open", "Cancel"]
* });
*
* if (confirmed) {
* window.open(url, "_blank", "noopener,noreferrer");
* return {};
* }
*
* return { isError: true };
* };
* ```
*
* @see {@link McpUiOpenLinkRequest} for the request type
* @see {@link McpUiOpenLinkResult} for the result type
*/
set onopenlink(
callback: (
params: McpUiOpenLinkRequest["params"],
extra: RequestHandlerExtra,
) => Promise<McpUiOpenLinkResult>,
) {
this.setRequestHandler(
McpUiOpenLinkRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for display mode change requests from the Guest UI.
*
* The Guest UI sends `ui/request-display-mode` requests when it wants to change
* its display mode (e.g., from "inline" to "fullscreen"). The handler should
* check if the requested mode is in `availableDisplayModes` from the host context,
* update the display mode if supported, and return the actual mode that was set.
*
* If the requested mode is not available, the handler should return the current
* display mode instead.
*
* @param callback - Handler that receives the requested mode and returns the actual mode set
* - params.mode - The display mode being requested ("inline" | "fullscreen" | "pip")
* - extra - Request metadata (abort signal, session info)
* - Returns: Promise<McpUiRequestDisplayModeResult> with the actual mode set
*
* @example
* ```typescript
* bridge.onrequestdisplaymode = async ({ mode }, extra) => {
* const availableModes = hostContext.availableDisplayModes ?? ["inline"];
* if (availableModes.includes(mode)) {
* setDisplayMode(mode);
* return { mode };
* }
* // Return current mode if requested mode not available
* return { mode: currentDisplayMode };
* };
* ```
*
* @see {@link McpUiRequestDisplayModeRequest} for the request type
* @see {@link McpUiRequestDisplayModeResult} for the result type
*/
set onrequestdisplaymode(
callback: (
params: McpUiRequestDisplayModeRequest["params"],
extra: RequestHandlerExtra,
) => Promise<McpUiRequestDisplayModeResult>,
) {
this.setRequestHandler(
McpUiRequestDisplayModeRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for logging messages from the Guest UI.
*
* The Guest UI sends standard MCP `notifications/message` (logging) notifications
* to report debugging information, errors, warnings, and other telemetry to the
* host. The host can display these in a console, log them to a file, or send
* them to a monitoring service.
*
* This uses the standard MCP logging notification format, not a UI-specific
* message type.
*
* @param callback - Handler that receives logging params
* - params.level - Log level: "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"
* - params.logger - Optional logger name/identifier
* - params.data - Log message and optional structured data
*
* @example
* ```typescript
* bridge.onloggingmessage = ({ level, logger, data }) => {
* const prefix = logger ? `[${logger}]` : "[Guest UI]";
* console[level === "error" ? "error" : "log"](
* `${prefix} ${level.toUpperCase()}:`,
* data
* );
* };
* ```
*/
set onloggingmessage(
callback: (params: LoggingMessageNotification["params"]) => void,
) {
this.setNotificationHandler(
LoggingMessageNotificationSchema,
async (notification) => {
callback(notification.params);
},
);
}
/**
* Register a handler for model context updates from the Guest UI.
*
* The Guest UI sends `ui/update-model-context` requests to update the Host's
* model context. Each request overwrites the previous context stored by the Guest UI.
* Unlike logging messages, context updates are intended to be available to
* the model in future turns. Unlike messages, context updates do not trigger follow-ups.
*
* The host will typically defer sending the context to the model until the
* next user message (including `ui/message`), and will only send the last
* update received.
*
* @example
* ```typescript
* bridge.onupdatemodelcontext = async ({ content, structuredContent }, extra) => {
* // Update the model context with the new snapshot
* modelContext = {
* type: "app_context",
* content,
* structuredContent,
* timestamp: Date.now()
* };
* return {};
* };
* ```
*
* @see {@link McpUiUpdateModelContextRequest} for the request type
*/
set onupdatemodelcontext(
callback: (
params: McpUiUpdateModelContextRequest["params"],
extra: RequestHandlerExtra,
) => Promise<EmptyResult>,
) {
this.setRequestHandler(
McpUiUpdateModelContextRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for tool call requests from the Guest UI.
*
* The Guest UI sends `tools/call` requests to execute MCP server tools. This
* handler allows the host to intercept and process these requests, typically
* by forwarding them to the MCP server.
*
* @param callback - Handler that receives tool call params and returns a
* {@link CallToolResult}
* @param callback.params - Tool call parameters (name and arguments)
* @param callback.extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.oncalltool = async ({ name, arguments: args }, extra) => {
* return mcpClient.request(
* { method: "tools/call", params: { name, arguments: args } },
* CallToolResultSchema,
* { signal: extra.signal }
* );
* };
* ```
*
* @see {@link CallToolRequest} for the request type
* @see {@link CallToolResult} for the result type
*/
set oncalltool(
callback: (
params: CallToolRequest["params"],
extra: RequestHandlerExtra,
) => Promise<CallToolResult>,
) {
this.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
return callback(request.params, extra);
});
}
/**
* Notify the Guest UI that the MCP server's tool list has changed.
*
* The host sends `notifications/tools/list_changed` to the Guest UI when it
* receives this notification from the MCP server. This allows the Guest UI
* to refresh its tool cache or UI accordingly.
*
* @param params - Optional notification params (typically empty)
*
* @example
* ```typescript
* // In your MCP client notification handler:
* mcpClient.setNotificationHandler(ToolListChangedNotificationSchema, () => {
* bridge.sendToolListChanged();
* });
* ```
*
* @see {@link ToolListChangedNotification} for the notification type
*/
sendToolListChanged(params: ToolListChangedNotification["params"] = {}) {
return this.notification({
method: "notifications/tools/list_changed" as const,
params,
});
}
/**
* Register a handler for list resources requests from the Guest UI.
*
* The Guest UI sends `resources/list` requests to enumerate available MCP
* resources. This handler allows the host to intercept and process these
* requests, typically by forwarding them to the MCP server.
*
* @param callback - Handler that receives list params and returns a
* {@link ListResourcesResult}
* @param callback.params - Request params (may include cursor for pagination)
* @param callback.extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.onlistresources = async (params, extra) => {
* return mcpClient.request(
* { method: "resources/list", params },
* ListResourcesResultSchema,
* { signal: extra.signal }
* );
* };
* ```
*
* @see {@link ListResourcesRequest} for the request type
* @see {@link ListResourcesResult} for the result type
*/
set onlistresources(
callback: (
params: ListResourcesRequest["params"],
extra: RequestHandlerExtra,
) => Promise<ListResourcesResult>,
) {
this.setRequestHandler(
ListResourcesRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for list resource templates requests from the Guest UI.
*
* The Guest UI sends `resources/templates/list` requests to enumerate available
* MCP resource templates. This handler allows the host to intercept and process
* these requests, typically by forwarding them to the MCP server.
*
* @param callback - Handler that receives list params and returns a
* {@link ListResourceTemplatesResult}
* @param callback.params - Request params (may include cursor for pagination)
* @param callback.extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.onlistresourcetemplates = async (params, extra) => {
* return mcpClient.request(
* { method: "resources/templates/list", params },
* ListResourceTemplatesResultSchema,
* { signal: extra.signal }
* );
* };
* ```
*
* @see {@link ListResourceTemplatesRequest} for the request type
* @see {@link ListResourceTemplatesResult} for the result type
*/
set onlistresourcetemplates(
callback: (
params: ListResourceTemplatesRequest["params"],
extra: RequestHandlerExtra,
) => Promise<ListResourceTemplatesResult>,
) {
this.setRequestHandler(
ListResourceTemplatesRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Register a handler for read resource requests from the Guest UI.
*
* The Guest UI sends `resources/read` requests to retrieve the contents of an
* MCP resource. This handler allows the host to intercept and process these
* requests, typically by forwarding them to the MCP server.
*
* @param callback - Handler that receives read params and returns a
* {@link ReadResourceResult}
* @param callback.params - Read parameters including the resource URI
* @param callback.extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.onreadresource = async ({ uri }, extra) => {
* return mcpClient.request(
* { method: "resources/read", params: { uri } },
* ReadResourceResultSchema,
* { signal: extra.signal }
* );
* };
* ```
*
* @see {@link ReadResourceRequest} for the request type
* @see {@link ReadResourceResult} for the result type
*/
set onreadresource(
callback: (
params: ReadResourceRequest["params"],
extra: RequestHandlerExtra,
) => Promise<ReadResourceResult>,
) {
this.setRequestHandler(
ReadResourceRequestSchema,
async (request, extra) => {
return callback(request.params, extra);
},
);
}
/**
* Notify the Guest UI that the MCP server's resource list has changed.
*
* The host sends `notifications/resources/list_changed` to the Guest UI when it
* receives this notification from the MCP server. This allows the Guest UI
* to refresh its resource cache or UI accordingly.
*
* @param params - Optional notification params (typically empty)
*
* @example
* ```typescript
* // In your MCP client notification handler:
* mcpClient.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
* bridge.sendResourceListChanged();
* });
* ```
*
* @see {@link ResourceListChangedNotification} for the notification type
*/
sendResourceListChanged(
params: ResourceListChangedNotification["params"] = {},
) {
return this.notification({
method: "notifications/resources/list_changed" as const,
params,
});
}
/**
* Register a handler for list prompts requests from the Guest UI.
*
* The Guest UI sends `prompts/list` requests to enumerate available MCP
* prompts. This handler allows the host to intercept and process these
* requests, typically by forwarding them to the MCP server.
*
* @param callback - Handler that receives list params and returns a
* {@link ListPromptsResult}
* @param callback.params - Request params (may include cursor for pagination)
* @param callback.extra - Request metadata (abort signal, session info)
*
* @example
* ```typescript
* bridge.onlistprompts = async (params, extra) => {
* return mcpClient.request(
* { method: "prompts/list", params },
* ListPromptsResultSchema,
* { signal: extra.signal }
* );
* };
* ```
*
* @see {@link ListPromptsRequest} for the request type
* @see {@link ListPromptsResult} for the result type
*/
set onlistprompts(
callback: (
params: ListPromptsRequest["params"],
extra: RequestHandlerExtra,
) => Promise<ListPromptsResult>,
) {
this.setRequestHandler(ListPromptsRequestSchema, async (request, extra) => {
return callback(request.params, extra);
});
}
/**
* Notify the Guest UI that the MCP server's prompt list has changed.
*
* The host sends `notifications/prompts/list_changed` to the Guest UI when it
* receives this notification from the MCP server. This allows the Guest UI
* to refresh its prompt cache or UI accordingly.
*
* @param params - Optional notification params (typically empty)
*
* @example
* ```typescript
* // In your MCP client notification handler:
* mcpClient.setNotificationHandler(PromptListChangedNotificationSchema, () => {
* bridge.sendPromptListChanged();
* });
* ```
*
* @see {@link PromptListChangedNotification} for the notification type
*/
sendPromptListChanged(params: PromptListChangedNotification["params"] = {}) {
return this.notification({
method: "notifications/prompts/list_changed" as const,
params,
});
}
/**
* Verify that the guest supports the capability required for the given request method.
* @internal
*/
assertCapabilityForMethod(method: AppRequest["method"]): void {
// TODO
}
/**
* Verify that a request handler is registered and supported for the given method.
* @internal
*/
assertRequestHandlerCapability(method: AppRequest["method"]): void {
// TODO
}
/**
* Verify that the host supports the capability required for the given notification method.
* @internal
*/
assertNotificationCapability(method: AppNotification["method"]): void {
// TODO
}
/**
* Verify that task creation is supported for the given request method.
* @internal
*/
protected assertTaskCapability(_method: string): void {
throw new Error("Tasks are not supported in MCP Apps");
}
/**
* Verify that task handler is supported for the given method.
* @internal
*/
protected assertTaskHandlerCapability(_method: string): void {
throw new Error("Task handlers are not supported in MCP Apps");
}
/**
* Get the host capabilities passed to the constructor.
*
* @returns Host capabilities object
*
* @see {@link McpUiHostCapabilities} for the capabilities structure
*/