@blade-hq/agent-react 2612.0.0-beta.67 → 2612.0.0-beta.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +2 -0
  2. package/dist/{chunk-MAFNMG2O.js → chunk-2DPLLZOU.js} +18 -13
  3. package/dist/{chunk-MAFNMG2O.js.map → chunk-2DPLLZOU.js.map} +1 -1
  4. package/dist/{chunk-N576N2XO.js → chunk-7MCGQH34.js} +12 -9
  5. package/dist/chunk-7MCGQH34.js.map +1 -0
  6. package/dist/{chunk-UC7SY3G5.js → chunk-HCW7SI5Q.js} +333 -269
  7. package/dist/chunk-HCW7SI5Q.js.map +1 -0
  8. package/dist/{chunk-X66C66OQ.js → chunk-J72ZLILV.js} +287 -67
  9. package/dist/chunk-J72ZLILV.js.map +1 -0
  10. package/dist/{chunk-HS5G33FO.js → chunk-QIR73CES.js} +1031 -8
  11. package/dist/chunk-QIR73CES.js.map +1 -0
  12. package/dist/{chunk-VSIUEXGV.js → chunk-WRIMPZPN.js} +12 -962
  13. package/dist/chunk-WRIMPZPN.js.map +1 -0
  14. package/dist/{chunk-XV6AO37F.js → chunk-XJ6ZA6LN.js} +9 -9
  15. package/dist/{chunk-U3RHQHI6.js → chunk-XP6T6SHZ.js} +48 -48
  16. package/dist/components/AccountConnectors.d.ts +1 -1
  17. package/dist/components/ManagedConnection.d.ts +0 -1
  18. package/dist/components/McpAppFrame.d.ts +17 -0
  19. package/dist/components/SessionPluginIcon.d.ts +1 -0
  20. package/dist/connectors.js +2 -2
  21. package/dist/index.js +7 -7
  22. package/dist/internal.d.ts +2 -0
  23. package/dist/internal.js +10 -8
  24. package/dist/internal.js.map +1 -1
  25. package/dist/questions.js +4 -5
  26. package/dist/questions.js.map +1 -1
  27. package/dist/rich-input.js +20 -20
  28. package/dist/style.full.css +1 -1
  29. package/dist/tool-details.js +4 -4
  30. package/node_modules/@modelcontextprotocol/ext-apps/LICENSE +216 -0
  31. package/node_modules/@modelcontextprotocol/ext-apps/README.md +284 -0
  32. package/node_modules/@modelcontextprotocol/ext-apps/dist/docs/patterns.d.ts +9 -0
  33. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.d.ts +1348 -0
  34. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.examples.d.ts +9 -0
  35. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js +39 -0
  36. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.test.d.ts +1 -0
  37. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-with-deps.js +82 -0
  38. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app.d.ts +1214 -0
  39. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app.examples.d.ts +9 -0
  40. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app.js +39 -0
  41. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/app.test.d.ts +1 -0
  42. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/constants.d.ts +65 -0
  43. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/events.d.ts +47 -0
  44. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/events.test.d.ts +1 -0
  45. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/generated/schema.d.ts +1047 -0
  46. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/generated/schema.json +6170 -0
  47. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/generated/schema.test.d.ts +41 -0
  48. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/interop-v1.test.d.ts +1 -0
  49. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/legacy-handlers.d.ts +66 -0
  50. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/legacy-handlers.test.d.ts +1 -0
  51. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/message-transport.d.ts +126 -0
  52. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/message-transport.examples.d.ts +9 -0
  53. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/message-transport.test.d.ts +1 -0
  54. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/index.d.ts +37 -0
  55. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/index.examples.d.ts +6 -0
  56. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/index.js +39 -0
  57. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/react-with-deps.js +82 -0
  58. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useApp.d.ts +115 -0
  59. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useApp.examples.d.ts +6 -0
  60. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useAutoResize.d.ts +54 -0
  61. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useAutoResize.examples.d.ts +6 -0
  62. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useDocumentTheme.d.ts +44 -0
  63. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useDocumentTheme.examples.d.ts +6 -0
  64. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useHostStyles.d.ts +113 -0
  65. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/react/useHostStyles.examples.d.ts +6 -0
  66. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.d.ts +381 -0
  67. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.examples.d.ts +9 -0
  68. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.js +1 -0
  69. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.test.d.ts +1 -0
  70. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/spec.types.d.ts +698 -0
  71. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/standard-schema.d.ts +23 -0
  72. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/styles.d.ts +184 -0
  73. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/styles.examples.d.ts +9 -0
  74. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/types.d.ts +33 -0
  75. package/node_modules/@modelcontextprotocol/ext-apps/dist/src/wire-compat.test.d.ts +1 -0
  76. package/node_modules/@modelcontextprotocol/ext-apps/package.json +144 -0
  77. package/node_modules/@standard-schema/spec/LICENSE +21 -0
  78. package/node_modules/@standard-schema/spec/README.md +198 -0
  79. package/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
  80. package/node_modules/@standard-schema/spec/dist/index.d.cts +119 -0
  81. package/node_modules/@standard-schema/spec/dist/index.d.ts +119 -0
  82. package/node_modules/@standard-schema/spec/dist/index.js +0 -0
  83. package/node_modules/@standard-schema/spec/package.json +52 -0
  84. package/package.json +6 -2
  85. package/dist/chunk-HS5G33FO.js.map +0 -1
  86. package/dist/chunk-N576N2XO.js.map +0 -1
  87. package/dist/chunk-UC7SY3G5.js.map +0 -1
  88. package/dist/chunk-VSIUEXGV.js.map +0 -1
  89. package/dist/chunk-X66C66OQ.js.map +0 -1
  90. /package/dist/{chunk-XV6AO37F.js.map → chunk-XJ6ZA6LN.js.map} +0 -0
  91. /package/dist/{chunk-U3RHQHI6.js.map → chunk-XP6T6SHZ.js.map} +0 -0
@@ -0,0 +1,1214 @@
1
+ import { Protocol, type BaseContext, type ProtocolOptions, type RequestOptions, type CallToolRequest, type CallToolResult, type CreateMessageRequest, type CreateMessageResult, type CreateMessageResultWithTools, type Implementation, type ListResourcesRequest, type ListResourcesResult, type ListToolsRequest, type ListToolsResult, type LoggingMessageNotification, type ReadResourceRequest, type ReadResourceResult, type ToolAnnotations, type ToolListChangedNotification, type Transport } from "@modelcontextprotocol/client";
2
+ export { RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY } from "./constants.js";
3
+ import { type LegacyNotificationHandlerSetter, type LegacyRequestHandlerSetter } from "./legacy-handlers.js";
4
+ export type { LegacyMethodSchema, LegacyNotificationHandler, LegacyNotificationHandlerSetter, LegacyRequestHandler, LegacyRequestHandlerExtra, LegacyRequestHandlerSetter, } from "./legacy-handlers.js";
5
+ export { EventDispatcher } from "./events.js";
6
+ import { McpUiAppCapabilities, McpUiUpdateModelContextRequest, McpUiHostCapabilities, McpUiHostContext, McpUiHostContextChangedNotification, McpUiMessageRequest, McpUiOpenLinkRequest, McpUiDownloadFileRequest, McpUiResourceTeardownRequest, McpUiResourceTeardownResult, McpUiRequestTeardownNotification, McpUiSizeChangedNotification, McpUiToolCancelledNotification, McpUiToolInputNotification, McpUiToolInputPartialNotification, McpUiToolResultNotification, McpUiRequestDisplayModeRequest } from "./types.js";
7
+ import { StandardSchemaV1 } from "./standard-schema.js";
8
+ export type { StandardSchemaV1, StandardSchemaWithJSON, } from "./standard-schema.js";
9
+ export { PostMessageTransport } from "./message-transport.js";
10
+ export * from "./types.js";
11
+ export { applyHostStyleVariables, applyHostFonts, getDocumentTheme, applyDocumentTheme, } from "./styles.js";
12
+ /**
13
+ * Options for configuring {@link App `App`} behavior.
14
+ *
15
+ * Extends `ProtocolOptions` from the base MCP SDK with `App`-specific configuration.
16
+ *
17
+ * @see `ProtocolOptions` from @modelcontextprotocol/client for inherited options
18
+ */
19
+ export type AppOptions = Omit<ProtocolOptions, "supportedProtocolVersions"> & {
20
+ /**
21
+ * Automatically report size changes to the host using `ResizeObserver`.
22
+ *
23
+ * When enabled, the {@link App `App`} monitors `document.body` and `document.documentElement`
24
+ * for size changes and automatically sends `ui/notifications/size-changed`
25
+ * notifications to the host.
26
+ *
27
+ * @default true
28
+ */
29
+ autoResize?: boolean;
30
+ /**
31
+ * Throw on detected misuse instead of logging a console warning.
32
+ *
33
+ * Currently this affects calling host-bound methods (e.g.
34
+ * {@link App.callServerTool `callServerTool`}, {@link App.sendMessage `sendMessage`})
35
+ * before {@link App.connect `connect`} has completed the `ui/initialize`
36
+ * handshake. With `strict: false` (default) a `console.warn` is emitted;
37
+ * with `strict: true` an `Error` is thrown.
38
+ *
39
+ * @remarks Throwing will become the default in a future release.
40
+ * @default false
41
+ */
42
+ strict?: boolean;
43
+ /**
44
+ * Allow code paths that require CSP `unsafe-eval` (e.g. `new Function()`).
45
+ *
46
+ * Views typically run under a strict CSP without `unsafe-eval`. Zod's JIT
47
+ * object parser uses `new Function()` and throws on the first message parse
48
+ * under such a policy. By default (`allowUnsafeEval: false`) the
49
+ * {@link App `App`} constructor sets `z.config({ jitless: true })` so the
50
+ * SDK works out of the box under the spec's default CSP. Set
51
+ * `allowUnsafeEval: true` to skip that and keep the faster JIT path when
52
+ * the host's CSP permits `unsafe-eval`.
53
+ *
54
+ * @default false
55
+ */
56
+ allowUnsafeEval?: boolean;
57
+ };
58
+ type RequestHandlerExtra = BaseContext;
59
+ /**
60
+ * Result of an app-registered tool callback. When `Out` is provided,
61
+ * `structuredContent` is required and typed (unless `isError: true`).
62
+ */
63
+ export type AppToolResult<Out extends StandardSchemaV1 | undefined = undefined> = Out extends StandardSchemaV1 ? (CallToolResult & {
64
+ structuredContent: StandardSchemaV1.InferOutput<Out>;
65
+ isError?: false;
66
+ }) | (CallToolResult & {
67
+ isError: true;
68
+ }) : CallToolResult;
69
+ /**
70
+ * Callback for an app-registered tool. When `In` is provided, `args` is the
71
+ * validated/parsed input; when `In` is `undefined`, the callback receives only
72
+ * `extra`. When `Out` is provided, the return's `structuredContent` is typed.
73
+ *
74
+ * Mirrors `ToolCallback` from `@modelcontextprotocol/server` but is
75
+ * parameterized over {@link StandardSchemaV1} instead of zod, so any
76
+ * Standard-Schema-compatible library (Zod, ArkType, Valibot, …) can be used.
77
+ */
78
+ 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>>;
79
+ /**
80
+ * Handle returned by {@link App.registerTool}. Mirrors `RegisteredTool` from
81
+ * `@modelcontextprotocol/server` but stores
82
+ * {@link StandardSchemaV1} schemas.
83
+ */
84
+ export type RegisteredAppTool = {
85
+ title?: string;
86
+ description?: string;
87
+ inputSchema?: StandardSchemaV1;
88
+ outputSchema?: StandardSchemaV1;
89
+ annotations?: ToolAnnotations;
90
+ _meta?: Record<string, unknown>;
91
+ enabled: boolean;
92
+ enable(): void;
93
+ disable(): void;
94
+ remove(): void;
95
+ update(updates: Partial<Omit<RegisteredAppTool, "update">>): void;
96
+ /** @internal */
97
+ handler: (args: unknown, extra: RequestHandlerExtra) => Promise<CallToolResult>;
98
+ };
99
+ /**
100
+ * Maps DOM-style event names to their notification `params` types.
101
+ *
102
+ * Used by {@link App `App`} and its composed {@link EventDispatcher} to
103
+ * provide type-safe `addEventListener` / `removeEventListener` and singular
104
+ * `on*` handler support.
105
+ */
106
+ export type AppEventMap = {
107
+ toolinput: McpUiToolInputNotification["params"];
108
+ toolinputpartial: McpUiToolInputPartialNotification["params"];
109
+ toolresult: McpUiToolResultNotification["params"];
110
+ toolcancelled: McpUiToolCancelledNotification["params"];
111
+ hostcontextchanged: McpUiHostContextChangedNotification["params"];
112
+ };
113
+ /**
114
+ * Main class for MCP Apps to communicate with their host.
115
+ *
116
+ * The `App` class provides a framework-agnostic way to build interactive MCP Apps
117
+ * that run inside host applications. It extends the base MCP SDK's public
118
+ * `Protocol` class, composes an {@link EventDispatcher}, and adds the Apps
119
+ * handshake, lifecycle, and high-level APIs.
120
+ *
121
+ * ## Architecture
122
+ *
123
+ * Views (Apps) act as MCP clients connecting to the host via {@link PostMessageTransport `PostMessageTransport`}.
124
+ * The host proxies requests to the actual MCP server and forwards
125
+ * responses back to the App.
126
+ *
127
+ * ## Lifecycle
128
+ *
129
+ * 1. **Create**: Instantiate App with info and capabilities
130
+ * 2. **Connect**: Call `connect()` to establish transport and perform handshake
131
+ * 3. **Interactive**: Send requests, receive notifications, call tools
132
+ * 4. **Teardown**: Host sends teardown request before unmounting
133
+ *
134
+ * ## Protocol and event methods
135
+ *
136
+ * From the base MCP SDK's `Protocol`, `App` provides:
137
+ * - `setRequestHandler()` - Register handlers for requests from host
138
+ * - `setNotificationHandler()` - Register handlers for notifications from host
139
+ *
140
+ * From its composed {@link EventDispatcher}, `App` also provides:
141
+ * - `addEventListener()` - Append a listener for a notification event (multi-listener)
142
+ * - `removeEventListener()` - Remove a previously added listener
143
+ *
144
+ * ## Notification Setters (DOM-model `on*` handlers)
145
+ *
146
+ * For common notifications, the `App` class provides getter/setter properties
147
+ * that follow DOM-model replace semantics (like `el.onclick`):
148
+ * - `ontoolinput` - Complete tool arguments from host
149
+ * - `ontoolinputpartial` - Streaming partial tool arguments
150
+ * - `ontoolresult` - Tool execution results
151
+ * - `ontoolcancelled` - Tool execution was cancelled by user or host
152
+ * - `onhostcontextchanged` - Host context changes (theme, locale, etc.)
153
+ *
154
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
155
+ * Use `addEventListener` to attach multiple listeners without replacing.
156
+ *
157
+ * @example Basic usage with PostMessageTransport
158
+ * ```ts source="./app.examples.ts#App_basicUsage"
159
+ * const app = new App(
160
+ * { name: "WeatherApp", version: "1.0.0" },
161
+ * {}, // capabilities
162
+ * );
163
+ *
164
+ * // Register handlers before connecting to ensure no notifications are missed
165
+ * app.ontoolinput = (params) => {
166
+ * console.log("Tool arguments:", params.arguments);
167
+ * };
168
+ *
169
+ * await app.connect();
170
+ * ```
171
+ */
172
+ export declare class App extends Protocol<BaseContext> {
173
+ private _appInfo;
174
+ private _appCapabilities;
175
+ private options;
176
+ private _hostCapabilities?;
177
+ private _hostInfo?;
178
+ private _hostContext?;
179
+ private _registeredTools;
180
+ private _initializedSent;
181
+ private readonly _registeredEvents;
182
+ private readonly _events;
183
+ private readonly _methods;
184
+ /**
185
+ * Registers a request handler. Throws if a handler for the same method has
186
+ * already been registered — use the `on*` setter for replace semantics.
187
+ *
188
+ * @throws {Error} if a handler for this method is already registered.
189
+ */
190
+ setRequestHandler: LegacyRequestHandlerSetter<Protocol<BaseContext>["setRequestHandler"]>;
191
+ /**
192
+ * Registers a notification handler. Throws if a handler for the same method
193
+ * has already been registered — use the `on*` setter (replace semantics) or
194
+ * `addEventListener` (multi-listener) for mapped events.
195
+ *
196
+ * @throws {Error} if a handler for this method is already registered.
197
+ */
198
+ setNotificationHandler: LegacyNotificationHandlerSetter<Protocol<BaseContext>["setNotificationHandler"]>;
199
+ removeRequestHandler: Protocol<BaseContext>["removeRequestHandler"];
200
+ removeNotificationHandler: Protocol<BaseContext>["removeNotificationHandler"];
201
+ /**
202
+ * Register a request handler with replace semantics, bypassing the
203
+ * double-set protection of {@link setRequestHandler `setRequestHandler`}.
204
+ * Used by the `on*` request-handler setters.
205
+ */
206
+ protected replaceRequestHandler: Protocol<BaseContext>["setRequestHandler"];
207
+ /**
208
+ * Warn if a host-bound method is called before {@link connect `connect`} has
209
+ * completed the `ui/initialize` → `ui/notifications/initialized` handshake.
210
+ *
211
+ * Calling these methods early can race the handshake on strict hosts and
212
+ * leave the iframe permanently hidden. See
213
+ * {@link https://github.com/anthropics/claude-ai-mcp/issues/61 claude-ai-mcp#61} /
214
+ * {@link https://github.com/anthropics/claude-ai-mcp/issues/149 #149}.
215
+ *
216
+ * @remarks This will become a thrown `Error` in a future minor release.
217
+ */
218
+ private _assertInitialized;
219
+ private readonly eventSchemas;
220
+ /**
221
+ * Events the host typically sends once, shortly after the handshake.
222
+ * Registering a handler for one of these *after* {@link connect `connect`}
223
+ * resolves risks missing the notification entirely.
224
+ */
225
+ private static readonly ONE_SHOT_EVENTS;
226
+ /**
227
+ * One-shot events that have had at least one handler registered (via `on*`
228
+ * setter or `addEventListener`) at any point. Once an event is in this set,
229
+ * subsequent late registrations are not flagged — only the *first* handler
230
+ * matters for the missed-notification race, and re-registration (e.g. React
231
+ * `useEffect` cleanup → re-add on dep change) is a legitimate pattern.
232
+ */
233
+ private readonly _everHadListener;
234
+ /**
235
+ * Warn (or throw under `strict`) when the *first* handler for a one-shot
236
+ * event is registered after the `ui/initialize` → `ui/notifications/initialized`
237
+ * handshake has completed. The host may have already fired the notification
238
+ * by then. Subsequent registrations for the same event are not flagged.
239
+ *
240
+ * Mirrors {@link _assertInitialized `_assertInitialized`} (the outbound-side guard).
241
+ */
242
+ private _assertHandlerTiming;
243
+ protected setEventHandler<K extends keyof AppEventMap>(event: K, handler: ((params: AppEventMap[K]) => void) | undefined): void;
244
+ addEventListener<K extends keyof AppEventMap>(event: K, handler: (params: AppEventMap[K]) => void): void;
245
+ removeEventListener<K extends keyof AppEventMap>(event: K, handler: (params: AppEventMap[K]) => void): void;
246
+ private _ensureEventSlot;
247
+ protected getEventHandler<K extends keyof AppEventMap>(event: K): ((params: AppEventMap[K]) => void) | undefined;
248
+ protected warnIfRequestHandlerReplaced(name: string, previous: unknown, next: unknown): void;
249
+ /**
250
+ * Create a new MCP App instance.
251
+ *
252
+ * @param _appInfo - App identification (name and version)
253
+ * @param _appCapabilities - Features and capabilities this app provides
254
+ * @param options - Configuration options including `autoResize` behavior
255
+ *
256
+ * @example
257
+ * ```ts source="./app.examples.ts#App_constructor_basic"
258
+ * const app = new App(
259
+ * { name: "MyApp", version: "1.0.0" },
260
+ * { tools: { listChanged: true } }, // capabilities
261
+ * { autoResize: true }, // options
262
+ * );
263
+ * ```
264
+ */
265
+ constructor(_appInfo: Implementation, _appCapabilities?: McpUiAppCapabilities, options?: AppOptions);
266
+ /** @internal */
267
+ protected buildContext(ctx: BaseContext): BaseContext;
268
+ private registerAppCapabilities;
269
+ registerTool<OutputArgs extends undefined | StandardSchemaV1 = undefined, InputArgs extends undefined | StandardSchemaV1 = undefined>(name: string, config: {
270
+ title?: string;
271
+ description?: string;
272
+ inputSchema?: InputArgs;
273
+ outputSchema?: OutputArgs;
274
+ annotations?: ToolAnnotations;
275
+ _meta?: Record<string, unknown>;
276
+ }, cb: AppToolCallback<InputArgs, OutputArgs>): RegisteredAppTool;
277
+ private _toolHandlersInitialized;
278
+ private ensureToolHandlersInitialized;
279
+ sendToolListChanged(params?: ToolListChangedNotification["params"]): Promise<void>;
280
+ /**
281
+ * Get the host's capabilities discovered during initialization.
282
+ *
283
+ * Returns the capabilities that the host advertised during the
284
+ * {@link connect `connect`} handshake. Returns `undefined` if called before
285
+ * connection is established.
286
+ *
287
+ * @returns Host capabilities, or `undefined` if not yet connected
288
+ *
289
+ * @example Check host capabilities after connection
290
+ * ```ts source="./app.examples.ts#App_getHostCapabilities_checkAfterConnection"
291
+ * await app.connect();
292
+ * if (app.getHostCapabilities()?.serverTools) {
293
+ * console.log("Host supports server tool calls");
294
+ * }
295
+ * ```
296
+ *
297
+ * @see {@link connect `connect`} for the initialization handshake
298
+ * @see {@link McpUiHostCapabilities `McpUiHostCapabilities`} for the capabilities structure
299
+ */
300
+ getHostCapabilities(): McpUiHostCapabilities | undefined;
301
+ /**
302
+ * Get the host's implementation info discovered during initialization.
303
+ *
304
+ * Returns the host's name and version as advertised during the
305
+ * {@link connect `connect`} handshake. Returns `undefined` if called before
306
+ * connection is established.
307
+ *
308
+ * @returns Host implementation info, or `undefined` if not yet connected
309
+ *
310
+ * @example Log host information after connection
311
+ * ```ts source="./app.examples.ts#App_getHostVersion_logAfterConnection"
312
+ * await app.connect(transport);
313
+ * const { name, version } = app.getHostVersion() ?? {};
314
+ * console.log(`Connected to ${name} v${version}`);
315
+ * ```
316
+ *
317
+ * @see {@link connect `connect`} for the initialization handshake
318
+ */
319
+ getHostVersion(): Implementation | undefined;
320
+ /**
321
+ * Get the host context discovered during initialization.
322
+ *
323
+ * Returns the host context that was provided in the initialization response,
324
+ * including tool info, theme, locale, and other environment details.
325
+ * This context is automatically updated when the host sends
326
+ * `ui/notifications/host-context-changed` notifications.
327
+ *
328
+ * Returns `undefined` if called before connection is established.
329
+ *
330
+ * @returns Host context, or `undefined` if not yet connected
331
+ *
332
+ * @example Access host context after connection
333
+ * ```ts source="./app.examples.ts#App_getHostContext_accessAfterConnection"
334
+ * await app.connect(transport);
335
+ * const context = app.getHostContext();
336
+ * if (context?.theme === "dark") {
337
+ * document.body.classList.add("dark-theme");
338
+ * }
339
+ * if (context?.toolInfo) {
340
+ * console.log("Tool:", context.toolInfo.tool.name);
341
+ * }
342
+ * ```
343
+ *
344
+ * @see {@link connect `connect`} for the initialization handshake
345
+ * @see {@link onhostcontextchanged `onhostcontextchanged`} for context change notifications
346
+ * @see {@link McpUiHostContext `McpUiHostContext`} for the context structure
347
+ */
348
+ getHostContext(): McpUiHostContext | undefined;
349
+ /**
350
+ * Convenience handler for receiving complete tool input from the host.
351
+ *
352
+ * Set this property to register a handler that will be called when the host
353
+ * sends a tool's complete arguments. This is sent after a tool call begins
354
+ * and before the tool result is available.
355
+ *
356
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
357
+ * Use {@link addEventListener `addEventListener`} to attach multiple listeners
358
+ * without replacing.
359
+ *
360
+ * Register handlers before calling {@link connect `connect`} to avoid missing notifications.
361
+ *
362
+ * @example
363
+ * ```ts source="./app.examples.ts#App_ontoolinput_setter"
364
+ * // Register before connecting to ensure no notifications are missed
365
+ * app.ontoolinput = (params) => {
366
+ * console.log("Tool:", params.arguments);
367
+ * // Update your UI with the tool arguments
368
+ * };
369
+ * await app.connect();
370
+ * ```
371
+ *
372
+ * @deprecated Use {@link addEventListener `addEventListener("toolinput", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
373
+ * @see {@link McpUiToolInputNotification `McpUiToolInputNotification`} for the notification structure
374
+ */
375
+ get ontoolinput(): ((params: McpUiToolInputNotification["params"]) => void) | undefined;
376
+ set ontoolinput(callback: ((params: McpUiToolInputNotification["params"]) => void) | undefined);
377
+ /**
378
+ * Convenience handler for receiving streaming partial tool input from the host.
379
+ *
380
+ * Set this property to register a handler that will be called as the host
381
+ * streams partial tool arguments during tool call initialization. This enables
382
+ * progressive rendering of tool arguments before they're complete.
383
+ *
384
+ * **Important:** Partial arguments are "healed" JSON — the host closes unclosed
385
+ * brackets/braces to produce valid JSON. This means objects may be incomplete
386
+ * (e.g., the last item in an array may be truncated). Use partial data only
387
+ * for preview UI, not for critical operations.
388
+ *
389
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
390
+ * Use {@link addEventListener `addEventListener`} to attach multiple listeners
391
+ * without replacing.
392
+ *
393
+ * Register handlers before calling {@link connect `connect`} to avoid missing notifications.
394
+ *
395
+ * @example Progressive rendering of tool arguments
396
+ * ```ts source="./app.examples.ts#App_ontoolinputpartial_progressiveRendering"
397
+ * const codePreview = document.querySelector<HTMLPreElement>("#code-preview")!;
398
+ * const canvas = document.querySelector<HTMLCanvasElement>("#canvas")!;
399
+ *
400
+ * app.ontoolinputpartial = (params) => {
401
+ * codePreview.textContent = (params.arguments?.code as string) ?? "";
402
+ * codePreview.style.display = "block";
403
+ * canvas.style.display = "none";
404
+ * };
405
+ *
406
+ * app.ontoolinput = (params) => {
407
+ * codePreview.style.display = "none";
408
+ * canvas.style.display = "block";
409
+ * render(params.arguments?.code as string);
410
+ * };
411
+ * ```
412
+ *
413
+ * @deprecated Use {@link addEventListener `addEventListener("toolinputpartial", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
414
+ * @see {@link McpUiToolInputPartialNotification `McpUiToolInputPartialNotification`} for the notification structure
415
+ * @see {@link ontoolinput `ontoolinput`} for the complete tool input handler
416
+ */
417
+ get ontoolinputpartial(): ((params: McpUiToolInputPartialNotification["params"]) => void) | undefined;
418
+ set ontoolinputpartial(callback: ((params: McpUiToolInputPartialNotification["params"]) => void) | undefined);
419
+ /**
420
+ * Convenience handler for receiving tool execution results from the host.
421
+ *
422
+ * Set this property to register a handler that will be called when the host
423
+ * sends the result of a tool execution. This is sent after the tool completes
424
+ * on the MCP server, allowing your app to display the results or update its state.
425
+ *
426
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
427
+ * Use {@link addEventListener `addEventListener`} to attach multiple listeners
428
+ * without replacing.
429
+ *
430
+ * Register handlers before calling {@link connect `connect`} to avoid missing notifications.
431
+ *
432
+ * @example Display tool execution results
433
+ * ```ts source="./app.examples.ts#App_ontoolresult_displayResults"
434
+ * app.ontoolresult = (params) => {
435
+ * if (params.isError) {
436
+ * console.error("Tool execution failed:", params.content);
437
+ * } else if (params.content) {
438
+ * console.log("Tool output:", params.content);
439
+ * }
440
+ * };
441
+ * ```
442
+ *
443
+ * @deprecated Use {@link addEventListener `addEventListener("toolresult", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
444
+ * @see {@link McpUiToolResultNotification `McpUiToolResultNotification`} for the notification structure
445
+ * @see {@link ontoolinput `ontoolinput`} for the initial tool input handler
446
+ */
447
+ get ontoolresult(): ((params: McpUiToolResultNotification["params"]) => void) | undefined;
448
+ set ontoolresult(callback: ((params: McpUiToolResultNotification["params"]) => void) | undefined);
449
+ /**
450
+ * Convenience handler for receiving tool cancellation notifications from the host.
451
+ *
452
+ * Set this property to register a handler that will be called when the host
453
+ * notifies that tool execution was cancelled. This can occur for various reasons
454
+ * including user action, sampling error, classifier intervention, or other
455
+ * interruptions. Apps should update their state and display appropriate feedback.
456
+ *
457
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
458
+ * Use {@link addEventListener `addEventListener`} to attach multiple listeners
459
+ * without replacing.
460
+ *
461
+ * Register handlers before calling {@link connect `connect`} to avoid missing notifications.
462
+ *
463
+ * @example Handle tool cancellation
464
+ * ```ts source="./app.examples.ts#App_ontoolcancelled_handleCancellation"
465
+ * app.ontoolcancelled = (params) => {
466
+ * console.log("Tool cancelled:", params.reason);
467
+ * // Update your UI to show cancellation state
468
+ * };
469
+ * ```
470
+ *
471
+ * @deprecated Use {@link addEventListener `addEventListener("toolcancelled", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
472
+ * @see {@link McpUiToolCancelledNotification `McpUiToolCancelledNotification`} for the notification structure
473
+ * @see {@link ontoolresult `ontoolresult`} for successful tool completion
474
+ */
475
+ get ontoolcancelled(): ((params: McpUiToolCancelledNotification["params"]) => void) | undefined;
476
+ set ontoolcancelled(callback: ((params: McpUiToolCancelledNotification["params"]) => void) | undefined);
477
+ /**
478
+ * Convenience handler for host context changes (theme, locale, etc.).
479
+ *
480
+ * Set this property to register a handler that will be called when the host's
481
+ * context changes, such as theme switching (light/dark), locale changes, or
482
+ * other environmental updates. Apps should respond by updating their UI
483
+ * accordingly.
484
+ *
485
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
486
+ * Use {@link addEventListener `addEventListener`} to attach multiple listeners
487
+ * without replacing.
488
+ *
489
+ * Notification params are automatically merged into the internal host context
490
+ * before any handler or listener fires. This means
491
+ * {@link getHostContext `getHostContext`} will return the updated values even
492
+ * before your callback runs.
493
+ *
494
+ * Register handlers before calling {@link connect `connect`} to avoid missing notifications.
495
+ *
496
+ * @example Respond to theme changes
497
+ * ```ts source="./app.examples.ts#App_onhostcontextchanged_respondToTheme"
498
+ * app.onhostcontextchanged = (ctx) => {
499
+ * if (ctx.theme === "dark") {
500
+ * document.body.classList.add("dark-theme");
501
+ * } else {
502
+ * document.body.classList.remove("dark-theme");
503
+ * }
504
+ * };
505
+ * ```
506
+ *
507
+ * @deprecated Use {@link addEventListener `addEventListener("hostcontextchanged", handler)`} instead — it composes with other listeners and supports cleanup via {@link removeEventListener `removeEventListener`}.
508
+ * @see {@link McpUiHostContextChangedNotification `McpUiHostContextChangedNotification`} for the notification structure
509
+ * @see {@link McpUiHostContext `McpUiHostContext`} for the full context structure
510
+ */
511
+ get onhostcontextchanged(): ((params: McpUiHostContextChangedNotification["params"]) => void) | undefined;
512
+ set onhostcontextchanged(callback: ((params: McpUiHostContextChangedNotification["params"]) => void) | undefined);
513
+ /**
514
+ * Convenience handler for graceful shutdown requests from the host.
515
+ *
516
+ * Set this property to register a handler that will be called when the host
517
+ * requests the app to prepare for teardown. This allows the app to perform
518
+ * cleanup operations (save state, close connections, etc.) before being unmounted.
519
+ *
520
+ * The handler can be sync or async. The host will wait for the returned promise
521
+ * to resolve before proceeding with teardown.
522
+ *
523
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
524
+ *
525
+ * Register handlers before calling {@link connect `connect`} to avoid missing requests.
526
+ *
527
+ * @param callback - Function called when teardown is requested.
528
+ * Must return `McpUiResourceTeardownResult` (can be an empty object `{}`) or a Promise resolving to it.
529
+ *
530
+ * @example Perform cleanup before teardown
531
+ * ```ts source="./app.examples.ts#App_onteardown_performCleanup"
532
+ * app.onteardown = async () => {
533
+ * await saveState();
534
+ * closeConnections();
535
+ * console.log("App ready for teardown");
536
+ * return {};
537
+ * };
538
+ * ```
539
+ *
540
+ * @see {@link McpUiResourceTeardownRequest `McpUiResourceTeardownRequest`} for the request structure
541
+ */
542
+ private _onteardown?;
543
+ get onteardown(): ((params: McpUiResourceTeardownRequest["params"], extra: RequestHandlerExtra) => McpUiResourceTeardownResult | Promise<McpUiResourceTeardownResult>) | undefined;
544
+ set onteardown(callback: ((params: McpUiResourceTeardownRequest["params"], extra: RequestHandlerExtra) => McpUiResourceTeardownResult | Promise<McpUiResourceTeardownResult>) | undefined);
545
+ /**
546
+ * Convenience handler for tool call requests from the host.
547
+ *
548
+ * Set this property to register a handler that will be called when the host
549
+ * requests this app to execute a tool. This enables apps to provide their own
550
+ * tools that can be called by the host or LLM.
551
+ *
552
+ * The app must declare tool capabilities in the constructor to use this handler.
553
+ *
554
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
555
+ *
556
+ * Register handlers before calling {@link connect `connect`} to avoid missing requests.
557
+ *
558
+ * @param callback - Async function that executes the tool and returns the result.
559
+ * The callback will only be invoked if the app declared tool capabilities
560
+ * in the constructor.
561
+ *
562
+ * @example Handle tool calls from the host
563
+ * ```ts source="./app.examples.ts#App_oncalltool_handleFromHost"
564
+ * app.oncalltool = async (params, extra) => {
565
+ * if (params.name === "greet") {
566
+ * const name = params.arguments?.name ?? "World";
567
+ * return { content: [{ type: "text", text: `Hello, ${name}!` }] };
568
+ * }
569
+ * throw new Error(`Unknown tool: ${params.name}`);
570
+ * };
571
+ * ```
572
+ */
573
+ private _oncalltool?;
574
+ get oncalltool(): ((params: CallToolRequest["params"], extra: RequestHandlerExtra) => Promise<CallToolResult>) | undefined;
575
+ set oncalltool(callback: ((params: CallToolRequest["params"], extra: RequestHandlerExtra) => Promise<CallToolResult>) | undefined);
576
+ /**
577
+ * Convenience handler for listing available tools.
578
+ *
579
+ * Set this property to register a handler that will be called when the host
580
+ * requests a list of tools this app provides. This enables dynamic tool
581
+ * discovery by the host or LLM.
582
+ *
583
+ * The app must declare tool capabilities in the constructor to use this handler.
584
+ *
585
+ * Assigning replaces the previous handler; assigning `undefined` clears it.
586
+ *
587
+ * Register handlers before calling {@link connect `connect`} to avoid missing requests.
588
+ *
589
+ * @param callback - Async function that returns a {@link ListToolsResult `ListToolsResult`}.
590
+ * Registration is always allowed; capability validation occurs when handlers
591
+ * are invoked.
592
+ *
593
+ * @example Return available tools
594
+ * ```ts source="./app.examples.ts#App_onlisttools_returnTools"
595
+ * app.onlisttools = async (params, extra) => {
596
+ * return {
597
+ * tools: [
598
+ * {
599
+ * name: "greet",
600
+ * description: "Greet the user",
601
+ * inputSchema: { type: "object" as const },
602
+ * },
603
+ * {
604
+ * name: "calculate",
605
+ * description: "Perform a calculation",
606
+ * inputSchema: { type: "object" as const },
607
+ * },
608
+ * {
609
+ * name: "format",
610
+ * description: "Format text",
611
+ * inputSchema: { type: "object" as const },
612
+ * },
613
+ * ],
614
+ * };
615
+ * };
616
+ * ```
617
+ *
618
+ * @see {@link oncalltool `oncalltool`} for handling tool execution
619
+ */
620
+ private _onlisttools?;
621
+ get onlisttools(): ((params: ListToolsRequest["params"], extra: RequestHandlerExtra) => Promise<ListToolsResult>) | undefined;
622
+ set onlisttools(callback: ((params: ListToolsRequest["params"], extra: RequestHandlerExtra) => Promise<ListToolsResult>) | undefined);
623
+ /**
624
+ * Verify that the host supports the capability required for the given request method.
625
+ * @internal
626
+ */
627
+ protected assertCapabilityForMethod(method: string): void;
628
+ /**
629
+ * Verify that the app declared the capability required for the given request method.
630
+ * @internal
631
+ */
632
+ protected assertRequestHandlerCapability(method: string): void;
633
+ /**
634
+ * Verify that the app supports the capability required for the given notification method.
635
+ * @internal
636
+ */
637
+ protected assertNotificationCapability(_method: string): void;
638
+ /**
639
+ * Call a tool on the originating MCP server (proxied through the host).
640
+ *
641
+ * Apps can call tools to fetch fresh data or trigger server-side actions.
642
+ * The host proxies the request to the actual MCP server and returns the result.
643
+ *
644
+ * @param params - Tool name and arguments
645
+ * @param options - Request options (timeout, etc.)
646
+ * @returns Tool execution result
647
+ *
648
+ * @throws {Error} If the tool does not exist on the server
649
+ * @throws {Error} If the request times out or the connection is lost
650
+ * @throws {Error} If the host rejects the request
651
+ *
652
+ * Note: Tool-level execution errors are returned in the result with `isError: true`
653
+ * rather than throwing exceptions. Always check `result.isError` to distinguish
654
+ * between transport failures (thrown) and tool execution failures (returned).
655
+ *
656
+ * @example Fetch updated weather data
657
+ * ```ts source="./app.examples.ts#App_callServerTool_fetchWeather"
658
+ * try {
659
+ * const result = await app.callServerTool({
660
+ * name: "get_weather",
661
+ * arguments: { location: "Tokyo" },
662
+ * });
663
+ * if (result.isError) {
664
+ * console.error("Tool returned error:", result.content);
665
+ * } else {
666
+ * console.log(result.content);
667
+ * }
668
+ * } catch (error) {
669
+ * console.error("Tool call failed:", error);
670
+ * }
671
+ * ```
672
+ */
673
+ callServerTool(params: CallToolRequest["params"], options?: RequestOptions): Promise<CallToolResult>;
674
+ /**
675
+ * Read a resource from the originating MCP server (proxied through the host).
676
+ *
677
+ * Apps can read resources to access files, data, or other content provided by
678
+ * the MCP server. Resources are identified by URI (e.g., `file:///path/to/file`
679
+ * or custom schemes like `videos://bunny-1mb`). The host proxies the request to
680
+ * the actual MCP server and returns the resource content.
681
+ *
682
+ * @param params - Resource URI to read
683
+ * @param options - Request options (timeout, etc.)
684
+ * @returns Resource content with URI, name, description, mimeType, and contents array
685
+ *
686
+ * @throws {Error} If the resource does not exist on the server
687
+ * @throws {Error} If the request times out or the connection is lost
688
+ * @throws {Error} If the host rejects the request
689
+ *
690
+ * @example Read a video resource and play it
691
+ * ```ts source="./app.examples.ts#App_readServerResource_playVideo"
692
+ * try {
693
+ * const result = await app.readServerResource({
694
+ * uri: "videos://bunny-1mb",
695
+ * });
696
+ * const content = result.contents[0];
697
+ * if (content && "blob" in content) {
698
+ * const binary = Uint8Array.from(atob(content.blob), (c) =>
699
+ * c.charCodeAt(0),
700
+ * );
701
+ * const url = URL.createObjectURL(
702
+ * new Blob([binary], { type: content.mimeType || "video/mp4" }),
703
+ * );
704
+ * videoElement.src = url;
705
+ * videoElement.play();
706
+ * }
707
+ * } catch (error) {
708
+ * console.error("Failed to read resource:", error);
709
+ * }
710
+ * ```
711
+ *
712
+ * @see {@link listServerResources `listServerResources`} to discover available resources
713
+ */
714
+ readServerResource(params: ReadResourceRequest["params"], options?: RequestOptions): Promise<ReadResourceResult>;
715
+ /**
716
+ * List available resources from the originating MCP server (proxied through the host).
717
+ *
718
+ * Apps can list resources to discover what content is available on the MCP server.
719
+ * This enables dynamic resource discovery and building resource browsers or pickers.
720
+ * The host proxies the request to the actual MCP server and returns the resource list.
721
+ *
722
+ * Results may be paginated using the `cursor` parameter for servers with many resources.
723
+ *
724
+ * @param params - Optional parameters (omit for all resources, or `{ cursor }` for pagination)
725
+ * @param options - Request options (timeout, etc.)
726
+ * @returns List of resources with their URIs, names, descriptions, mimeTypes, and optional pagination cursor
727
+ *
728
+ * @throws {Error} If the request times out or the connection is lost
729
+ * @throws {Error} If the host rejects the request
730
+ *
731
+ * @example Discover available videos and build a picker UI
732
+ * ```ts source="./app.examples.ts#App_listServerResources_buildPicker"
733
+ * try {
734
+ * const result = await app.listServerResources();
735
+ * const videoResources = result.resources.filter((r) =>
736
+ * r.mimeType?.startsWith("video/"),
737
+ * );
738
+ * videoResources.forEach((resource) => {
739
+ * const option = document.createElement("option");
740
+ * option.value = resource.uri;
741
+ * option.textContent = resource.description || resource.name;
742
+ * selectElement.appendChild(option);
743
+ * });
744
+ * } catch (error) {
745
+ * console.error("Failed to list resources:", error);
746
+ * }
747
+ * ```
748
+ *
749
+ * @see {@link readServerResource `readServerResource`} to read a specific resource
750
+ */
751
+ listServerResources(params?: ListResourcesRequest["params"], options?: RequestOptions): Promise<ListResourcesResult>;
752
+ /**
753
+ * Request an LLM completion from the host (standard MCP `sampling/createMessage`).
754
+ *
755
+ * Enables the app to use the host's model connection for completions. The host
756
+ * has full discretion over which model to select and MAY modify or reject the
757
+ * request (human-in-the-loop). Check {@link getHostCapabilities `getHostCapabilities`}`()?.sampling`
758
+ * before calling — hosts without this capability will reject the request.
759
+ *
760
+ * This method reuses the stock MCP `CreateMessageRequest` shape. When `params.tools`
761
+ * is provided, the result is parsed with the extended schema that permits
762
+ * `stopReason: "toolUse"` and array content containing `tool_use` blocks.
763
+ *
764
+ * @param params - Standard MCP `CreateMessageRequest` params (messages, maxTokens,
765
+ * systemPrompt, temperature, modelPreferences, tools, toolChoice, etc.)
766
+ * @param options - Request options (timeout, abort signal)
767
+ * @returns `CreateMessageResult` (single content block) or `CreateMessageResultWithTools`
768
+ * (array content, may include `tool_use` blocks) depending on whether `tools` was set
769
+ *
770
+ * @throws {Error} If the host rejects the request or does not support sampling
771
+ * @throws {Error} If the request times out or the connection is lost
772
+ *
773
+ * @example Simple completion
774
+ * ```ts source="./app.examples.ts#App_createSamplingMessage_simple"
775
+ * const result = await app.createSamplingMessage({
776
+ * messages: [
777
+ * {
778
+ * role: "user",
779
+ * content: { type: "text", text: "Summarize this in one line." },
780
+ * },
781
+ * ],
782
+ * maxTokens: 100,
783
+ * });
784
+ * console.log(result.content);
785
+ * ```
786
+ *
787
+ * @example Agentic loop with tools
788
+ * ```ts source="./app.examples.ts#App_createSamplingMessage_withTools"
789
+ * if (!app.getHostCapabilities()?.sampling?.tools) return;
790
+ *
791
+ * const result = await app.createSamplingMessage({
792
+ * messages,
793
+ * maxTokens: 1024,
794
+ * tools: [
795
+ * {
796
+ * name: "get_weather",
797
+ * description: "Get the current weather",
798
+ * inputSchema: {
799
+ * type: "object",
800
+ * properties: { city: { type: "string" } },
801
+ * },
802
+ * },
803
+ * ],
804
+ * });
805
+ * if (result.stopReason === "toolUse") {
806
+ * // result.content may be an array containing tool_use blocks
807
+ * }
808
+ * ```
809
+ *
810
+ * @see `CreateMessageRequest` from @modelcontextprotocol/client for the request type
811
+ * @see `CreateMessageResult` / `CreateMessageResultWithTools` from @modelcontextprotocol/client for result types
812
+ */
813
+ createSamplingMessage(params: CreateMessageRequest["params"] & {
814
+ tools?: undefined;
815
+ }, options?: RequestOptions): Promise<CreateMessageResult>;
816
+ createSamplingMessage(params: CreateMessageRequest["params"], options?: RequestOptions): Promise<CreateMessageResultWithTools>;
817
+ /**
818
+ * Send a message to the host's chat interface.
819
+ *
820
+ * Enables the app to add messages to the conversation thread. Useful for
821
+ * user-initiated messages or app-to-conversation communication.
822
+ *
823
+ * @param params - Message role and content
824
+ * @param options - Request options (timeout, etc.)
825
+ * @returns Result with optional `isError` flag indicating host rejection
826
+ *
827
+ * @throws {Error} If the request times out or the connection is lost
828
+ *
829
+ * @example Send a text message from user interaction
830
+ * ```ts source="./app.examples.ts#App_sendMessage_textFromInteraction"
831
+ * try {
832
+ * const result = await app.sendMessage({
833
+ * role: "user",
834
+ * content: [{ type: "text", text: "Show me details for item #42" }],
835
+ * });
836
+ * if (result.isError) {
837
+ * console.error("Host rejected the message");
838
+ * // Handle rejection appropriately for your app
839
+ * }
840
+ * } catch (error) {
841
+ * console.error("Failed to send message:", error);
842
+ * // Handle transport/protocol error
843
+ * }
844
+ * ```
845
+ *
846
+ * @example Send follow-up message after offloading large data to model context
847
+ * ```ts source="./app.examples.ts#App_sendMessage_withLargeContext"
848
+ * const markdown = `---
849
+ * word-count: ${fullTranscript.split(/\s+/).length}
850
+ * speaker-names: ${speakerNames.join(", ")}
851
+ * ---
852
+ *
853
+ * ${fullTranscript}`;
854
+ *
855
+ * // Offload long transcript to model context
856
+ * await app.updateModelContext({ content: [{ type: "text", text: markdown }] });
857
+ *
858
+ * // Send brief trigger message
859
+ * await app.sendMessage({
860
+ * role: "user",
861
+ * content: [{ type: "text", text: "Summarize the key points" }],
862
+ * });
863
+ * ```
864
+ *
865
+ * @see {@link McpUiMessageRequest `McpUiMessageRequest`} for request structure
866
+ */
867
+ sendMessage(params: McpUiMessageRequest["params"], options?: RequestOptions): Promise<{
868
+ [x: string]: unknown;
869
+ isError?: boolean | undefined;
870
+ }>;
871
+ /**
872
+ * Send log messages to the host for debugging and telemetry.
873
+ *
874
+ * Logs are not added to the conversation but may be recorded by the host
875
+ * for debugging purposes.
876
+ *
877
+ * @param params - Log level and message
878
+ *
879
+ * @example Log app state for debugging
880
+ * ```ts source="./app.examples.ts#App_sendLog_debugState"
881
+ * app.sendLog({
882
+ * level: "info",
883
+ * data: "Weather data refreshed",
884
+ * logger: "WeatherApp",
885
+ * });
886
+ * ```
887
+ *
888
+ * @returns Promise that resolves when the log notification is sent
889
+ */
890
+ sendLog(params: LoggingMessageNotification["params"]): Promise<void>;
891
+ /**
892
+ * Update the host's model context with app state.
893
+ *
894
+ * Context updates are intended to be available to the model in future
895
+ * turns, without triggering an immediate model response (unlike {@link sendMessage `sendMessage`}).
896
+ *
897
+ * The host will typically defer sending the context to the model until the
898
+ * next user message — either from the actual user or via `sendMessage`. Only
899
+ * the last update is sent; each call overwrites any previous context.
900
+ *
901
+ * @param params - Context content and/or structured content
902
+ * @param options - Request options (timeout, etc.)
903
+ *
904
+ * @throws {Error} If the host rejects the context update (e.g., unsupported content type)
905
+ * @throws {Error} If the request times out or the connection is lost
906
+ *
907
+ * @example Update model context with current app state
908
+ * ```ts source="./app.examples.ts#App_updateModelContext_appState"
909
+ * const markdown = `---
910
+ * item-count: ${itemList.length}
911
+ * total-cost: ${totalCost}
912
+ * currency: ${currency}
913
+ * ---
914
+ *
915
+ * User is viewing their shopping cart with ${itemList.length} items selected:
916
+ *
917
+ * ${itemList.map((item) => `- ${item}`).join("\n")}`;
918
+ *
919
+ * await app.updateModelContext({
920
+ * content: [{ type: "text", text: markdown }],
921
+ * });
922
+ * ```
923
+ *
924
+ * @example Report runtime error to model
925
+ * ```ts source="./app.examples.ts#App_updateModelContext_reportError"
926
+ * try {
927
+ * const _stream = await navigator.mediaDevices.getUserMedia({ audio: true });
928
+ * // ... use _stream for transcription
929
+ * } catch (err) {
930
+ * // Inform the model that the app is in a degraded state
931
+ * await app.updateModelContext({
932
+ * content: [
933
+ * {
934
+ * type: "text",
935
+ * text: "Error: transcription unavailable",
936
+ * },
937
+ * ],
938
+ * });
939
+ * }
940
+ * ```
941
+ *
942
+ * @returns Promise that resolves when the context update is acknowledged
943
+ */
944
+ updateModelContext(params: McpUiUpdateModelContextRequest["params"], options?: RequestOptions): Promise<{
945
+ _meta?: {
946
+ [x: string]: unknown;
947
+ "io.modelcontextprotocol/serverInfo"?: {
948
+ version: string;
949
+ name: string;
950
+ websiteUrl?: string | undefined;
951
+ description?: string | undefined;
952
+ icons?: {
953
+ src: string;
954
+ mimeType?: string | undefined;
955
+ sizes?: string[] | undefined;
956
+ theme?: "light" | "dark" | undefined;
957
+ }[] | undefined;
958
+ title?: string | undefined;
959
+ } | undefined;
960
+ } | undefined;
961
+ }>;
962
+ /**
963
+ * Request the host to open an external URL in the default browser.
964
+ *
965
+ * The host may deny this request based on user preferences or security policy.
966
+ * Apps should handle rejection gracefully by checking `result.isError`.
967
+ *
968
+ * @param params - URL to open
969
+ * @param options - Request options (timeout, etc.)
970
+ * @returns Result with `isError: true` if the host denied the request (e.g., blocked domain, user cancelled)
971
+ *
972
+ * @throws {Error} If the request times out or the connection is lost
973
+ *
974
+ * @example Open documentation link
975
+ * ```ts source="./app.examples.ts#App_openLink_documentation"
976
+ * const { isError } = await app.openLink({ url: "https://docs.example.com" });
977
+ * if (isError) {
978
+ * // Host denied the request (e.g., blocked domain, user cancelled)
979
+ * // Optionally show fallback: display URL for manual copy
980
+ * console.warn("Link request denied");
981
+ * }
982
+ * ```
983
+ *
984
+ * @see {@link McpUiOpenLinkRequest `McpUiOpenLinkRequest`} for request structure
985
+ * @see {@link McpUiOpenLinkResult `McpUiOpenLinkResult`} for result structure
986
+ */
987
+ openLink(params: McpUiOpenLinkRequest["params"], options?: RequestOptions): Promise<{
988
+ [x: string]: unknown;
989
+ isError?: boolean | undefined;
990
+ }>;
991
+ /** @deprecated Use {@link openLink `openLink`} instead */
992
+ sendOpenLink: App["openLink"];
993
+ /**
994
+ * Request the host to download a file.
995
+ *
996
+ * Since MCP Apps run in sandboxed iframes where direct downloads are blocked,
997
+ * this provides a host-mediated mechanism for file exports. The host will
998
+ * typically show a confirmation dialog before initiating the download.
999
+ *
1000
+ * Uses standard MCP resource types: `EmbeddedResource` for inline content
1001
+ * and `ResourceLink` for content the host can fetch directly.
1002
+ *
1003
+ * @param params - Resource contents to download
1004
+ * @param options - Request options (timeout, etc.)
1005
+ * @returns Result with `isError: true` if the host denied the request (e.g., user cancelled)
1006
+ *
1007
+ * @throws {Error} If the request times out or the connection is lost
1008
+ *
1009
+ * @example Download a JSON file (embedded text resource)
1010
+ * ```ts
1011
+ * const data = JSON.stringify({ items: selectedItems }, null, 2);
1012
+ * const { isError } = await app.downloadFile({
1013
+ * contents: [{
1014
+ * type: "resource",
1015
+ * resource: {
1016
+ * uri: "file:///export.json",
1017
+ * mimeType: "application/json",
1018
+ * text: data,
1019
+ * },
1020
+ * }],
1021
+ * });
1022
+ * if (isError) {
1023
+ * console.warn("Download denied or cancelled");
1024
+ * }
1025
+ * ```
1026
+ *
1027
+ * @example Download binary content (embedded blob resource)
1028
+ * ```ts
1029
+ * const { isError } = await app.downloadFile({
1030
+ * contents: [{
1031
+ * type: "resource",
1032
+ * resource: {
1033
+ * uri: "file:///image.png",
1034
+ * mimeType: "image/png",
1035
+ * blob: base64EncodedPng,
1036
+ * },
1037
+ * }],
1038
+ * });
1039
+ * ```
1040
+ *
1041
+ * @example Download via resource link (host fetches)
1042
+ * ```ts
1043
+ * const { isError } = await app.downloadFile({
1044
+ * contents: [{
1045
+ * type: "resource_link",
1046
+ * uri: "https://api.example.com/reports/q4.pdf",
1047
+ * name: "Q4 Report",
1048
+ * mimeType: "application/pdf",
1049
+ * }],
1050
+ * });
1051
+ * ```
1052
+ *
1053
+ * @see {@link McpUiDownloadFileRequest `McpUiDownloadFileRequest`} for request structure
1054
+ * @see {@link McpUiDownloadFileResult `McpUiDownloadFileResult`} for result structure
1055
+ */
1056
+ downloadFile(params: McpUiDownloadFileRequest["params"], options?: RequestOptions): Promise<{
1057
+ [x: string]: unknown;
1058
+ isError?: boolean | undefined;
1059
+ }>;
1060
+ /**
1061
+ * Request the host to tear down this app.
1062
+ *
1063
+ * Apps call this method to request that the host tear them down. The host
1064
+ * decides whether to proceed - if approved, the host will send
1065
+ * `ui/resource-teardown` to allow the app to perform gracefull termination before being
1066
+ * unmounted. This piggybacks on the existing teardown mechanism, ensuring
1067
+ * the app only needs a single shutdown procedure (via {@link onteardown `onteardown`})
1068
+ * regardless of whether the teardown was initiated by the app or the host.
1069
+ *
1070
+ * This is a fire-and-forget notification - no response is expected.
1071
+ * If the host approves, the app will receive a `ui/resource-teardown`
1072
+ * request via the {@link onteardown `onteardown`} handler to persist unsaved state.
1073
+ *
1074
+ * @param params - Empty params object (reserved for future use)
1075
+ * @returns Promise that resolves when the notification is sent
1076
+ *
1077
+ * @example App-initiated teardown after user action
1078
+ * ```typescript
1079
+ * // User clicks "Done" button in the app
1080
+ * async function handleDoneClick() {
1081
+ * // Request the host to tear down the app
1082
+ * await app.requestTeardown();
1083
+ * // If host approves, onteardown handler will be called for termination
1084
+ * }
1085
+ *
1086
+ * // Set up teardown handler (called for both app-initiated and host-initiated teardown)
1087
+ * app.onteardown = async () => {
1088
+ * await saveState();
1089
+ * closeConnections();
1090
+ * return {};
1091
+ * };
1092
+ * ```
1093
+ *
1094
+ * @see {@link McpUiRequestTeardownNotification `McpUiRequestTeardownNotification`} for notification structure
1095
+ * @see {@link onteardown `onteardown`} for the graceful termination handler
1096
+ */
1097
+ requestTeardown(params?: McpUiRequestTeardownNotification["params"]): Promise<void>;
1098
+ /**
1099
+ * Request a change to the display mode.
1100
+ *
1101
+ * Requests the host to change the UI container to the specified display mode
1102
+ * (e.g., "inline", "fullscreen", "pip"). The host will respond with the actual
1103
+ * display mode that was set, which may differ from the requested mode if
1104
+ * the requested mode is not available (check `availableDisplayModes` in host context).
1105
+ *
1106
+ * @param params - The display mode being requested
1107
+ * @param options - Request options (timeout, etc.)
1108
+ * @returns Result containing the actual display mode that was set
1109
+ *
1110
+ * @example Toggle display mode
1111
+ * ```ts source="./app.examples.ts#App_requestDisplayMode_toggle"
1112
+ * const container = document.getElementById("main")!;
1113
+ * const ctx = app.getHostContext();
1114
+ * const newMode = ctx?.displayMode === "inline" ? "fullscreen" : "inline";
1115
+ * if (ctx?.availableDisplayModes?.includes(newMode)) {
1116
+ * const result = await app.requestDisplayMode({ mode: newMode });
1117
+ * container.classList.toggle("fullscreen", result.mode === "fullscreen");
1118
+ * }
1119
+ * ```
1120
+ *
1121
+ * @see {@link McpUiRequestDisplayModeRequest `McpUiRequestDisplayModeRequest`} for request structure
1122
+ * @see {@link McpUiHostContext `McpUiHostContext`} for checking availableDisplayModes
1123
+ */
1124
+ requestDisplayMode(params: McpUiRequestDisplayModeRequest["params"], options?: RequestOptions): Promise<{
1125
+ [x: string]: unknown;
1126
+ mode: "inline" | "fullscreen" | "pip";
1127
+ }>;
1128
+ /**
1129
+ * Notify the host of UI size changes.
1130
+ *
1131
+ * Apps can manually report size changes to help the host adjust the container.
1132
+ * If `autoResize` is enabled (default), this is called automatically.
1133
+ *
1134
+ * @param params - New width and height in pixels
1135
+ *
1136
+ * @example Manually notify host of size change
1137
+ * ```ts source="./app.examples.ts#App_sendSizeChanged_manual"
1138
+ * app.sendSizeChanged({
1139
+ * width: 400,
1140
+ * height: 600,
1141
+ * });
1142
+ * ```
1143
+ *
1144
+ * @returns Promise that resolves when the notification is sent
1145
+ *
1146
+ * @see {@link McpUiSizeChangedNotification `McpUiSizeChangedNotification`} for notification structure
1147
+ */
1148
+ sendSizeChanged(params: McpUiSizeChangedNotification["params"]): Promise<void>;
1149
+ /**
1150
+ * Set up automatic size change notifications using ResizeObserver.
1151
+ *
1152
+ * Observes both `document.documentElement` and `document.body` for size changes
1153
+ * and automatically sends `ui/notifications/size-changed` notifications to the host.
1154
+ * The notifications are debounced using requestAnimationFrame to avoid duplicates.
1155
+ *
1156
+ * Note: This method is automatically called by `connect()` if the `autoResize`
1157
+ * option is true (default). You typically don't need to call this manually unless
1158
+ * you disabled autoResize and want to enable it later.
1159
+ *
1160
+ * @returns Cleanup function to disconnect the observer
1161
+ *
1162
+ * @example Manual setup for custom scenarios
1163
+ * ```ts source="./app.examples.ts#App_setupAutoResize_manual"
1164
+ * const app = new App(
1165
+ * { name: "MyApp", version: "1.0.0" },
1166
+ * {},
1167
+ * { autoResize: false },
1168
+ * );
1169
+ * await app.connect(transport);
1170
+ *
1171
+ * // Later, enable auto-resize manually
1172
+ * const cleanup = app.setupSizeChangedNotifications();
1173
+ *
1174
+ * // Clean up when done
1175
+ * cleanup();
1176
+ * ```
1177
+ */
1178
+ setupSizeChangedNotifications(): () => void;
1179
+ /**
1180
+ * Establish connection with the host and perform initialization handshake.
1181
+ *
1182
+ * This method performs the following steps:
1183
+ * 1. Connects the transport layer
1184
+ * 2. Sends `ui/initialize` request with app info and capabilities
1185
+ * 3. Receives host capabilities and context in response
1186
+ * 4. Sends `ui/notifications/initialized` notification
1187
+ * 5. Sets up auto-resize using {@link setupSizeChangedNotifications `setupSizeChangedNotifications`} if enabled (default)
1188
+ *
1189
+ * If initialization fails, the connection is automatically closed and an error
1190
+ * is thrown.
1191
+ *
1192
+ * @param transport - Transport layer (typically {@link PostMessageTransport `PostMessageTransport`})
1193
+ * @param options - Request options for the initialize request
1194
+ *
1195
+ * @throws {Error} If initialization fails or connection is lost
1196
+ *
1197
+ * @example Connect with PostMessageTransport
1198
+ * ```ts source="./app.examples.ts#App_connect_withPostMessageTransport"
1199
+ * const app = new App({ name: "MyApp", version: "1.0.0" }, {});
1200
+ *
1201
+ * try {
1202
+ * await app.connect(new PostMessageTransport(window.parent, window.parent));
1203
+ * console.log("Connected successfully!");
1204
+ * } catch (error) {
1205
+ * console.error("Failed to connect:", error);
1206
+ * }
1207
+ * ```
1208
+ *
1209
+ * @see {@link McpUiInitializeRequest `McpUiInitializeRequest`} for the initialization request structure
1210
+ * @see {@link McpUiInitializedNotification `McpUiInitializedNotification`} for the initialized notification
1211
+ * @see {@link PostMessageTransport `PostMessageTransport`} for the typical transport implementation
1212
+ */
1213
+ connect(transport?: Transport, options?: RequestOptions): Promise<void>;
1214
+ }