@botdojo/chat-sdk 0.0.25 → 0.0.26

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.
package/lib/index.d.ts CHANGED
@@ -1,389 +1,309 @@
1
1
  import React$1 from 'react';
2
- import { BotDojoConnector as BotDojoConnector$1 } from './BotDojoConnector';
3
- export { BotDojoConnector } from './BotDojoConnector';
4
- import { Core_FlowCanvas, Core_ToolExecutionPhase, Core_TokenUpdate } from './backend-types-snapshot';
5
- import { ChatMessage as ChatMessage$1 } from 'botdojo-core/lib/src/store/session';
6
- import { FlowCanvasType } from 'botdojo-core/lib/src/store/flowRequest';
7
- export { citation, citations, imageResult, mcpResource, modelContext, textResult, tool, uiResource } from './tool-utils';
8
- export { McpUiHostContext } from './mcp-apps';
2
+ import { ModelContext, FlowResponse, FlowRequestStep, Core_TokenUpdate } from '@botdojo/sdk-types';
3
+ export { CitationData, ContentItem, MIME_TYPES, McpUiHostContext, ModelContext, ModelContextMessage, ModelContextPrompt, ModelContextResource, ResourceContent, ResourceProvider, ResourceReference, ResourceTemplate, ToolDefinition, ToolExecutionContext, ToolExecutionResult, ToolMetadata, citation, citations, imageResult, mcpResource, modelContext, textResult, tool, uiResource } from '@botdojo/sdk-types';
9
4
  import * as react_jsx_runtime from 'react/jsx-runtime';
10
5
 
11
- /**
12
- * Shared TypeScript types for BotDojo SDK and Canvas Client
13
- *
14
- * This package contains pure TypeScript type definitions with no JSX or React dependencies.
15
- * It can be safely imported by any TypeScript project without requiring JSX configuration.
16
- */
17
-
18
- /**
19
- * Resource reference for UI, ModelContext, or other resources
20
- *
21
- * MIME types determine how resource is handled:
22
- * - 'text/uri-list': External URL loaded in iframe (MCP Apps standard)
23
- * - 'text/html': Inline HTML rendered in iframe
24
- * - 'application/vnd.botdojo.ui-remote-dom': Remote DOM script
25
- * - 'application/vnd.botdojo.modelcontext': Nested ModelContext (URI points to resource)
26
- * - 'application/vnd.botdojo.citation': Single citation
27
- * - 'application/vnd.botdojo.citations': Multiple citations
28
- */
29
- interface ResourceReference$1 {
30
- /** Resource URI (e.g., 'ui://product/123', 'mcp://actions') */
31
- uri: string;
32
- /** MIME type determines how resource is processed */
33
- mimeType?: string;
34
- /** Resource content (URL for uri-list, inline HTML for text/html(+mcp), or URI for modelcontext) */
35
- text?: string;
36
- /** Inline HTML for `text/html`, `text/html+mcp`, or `text/html;profile=mcp-app` resources */
37
- html?: string;
38
- /** Optional allowlist for URL-based resources (matches SEP url-list direction) */
39
- urlList?: string[];
40
- /** Base URL to apply to inline HTML (used for relative asset resolution) */
41
- baseUrl?: string;
42
- /** Hint to prefer sandbox proxy even when a URL exists */
43
- prefersProxy?: boolean;
44
- /** Hint to allow direct external URL rendering even when inline HTML is present */
45
- allowExternal?: boolean;
46
- /** Metadata for UI resources only */
47
- meta?: {
48
- /** SEP-1865 UI metadata */
49
- ui?: {
50
- /** Preferred iframe dimensions (object or tuple) */
51
- preferredFrameSize?: {
52
- width: string;
53
- height: string;
54
- } | [string, string];
55
- /** Initial render data/state */
56
- initialRenderData?: any;
57
- /** Optional display name for the canvas */
58
- displayName?: string;
59
- /** If true, canvas should not be persisted */
60
- stateless?: boolean;
61
- /** MIME type hint for the UI resource */
62
- mimeType?: string;
63
- /** Optional CSP hints */
64
- csp?: {
65
- connectDomains?: string[];
66
- resourceDomains?: string[];
67
- domain?: string;
68
- allowPopups?: boolean;
69
- allowForms?: boolean;
70
- allowSameOrigin?: boolean;
71
- prefersBorder?: boolean;
72
- };
73
- /** Optional resource hints for inline/URL handling */
74
- urlList?: string[];
75
- baseUrl?: string;
76
- prefersProxy?: boolean;
77
- allowExternal?: boolean;
78
- };
79
- /** Additional metadata */
80
- [key: string]: any;
81
- };
6
+ declare class ConectionOptions {
7
+ timeout?: number;
8
+ maxDepth?: number;
82
9
  }
83
- /**
84
- * MCP-compliant content item for tool results
85
- *
86
- * Tools should return ContentItem[] for rich responses, or plain objects for simple results.
87
- *
88
- * @example
89
- * ```typescript
90
- * // Simple text response
91
- * return [{ type: 'text', text: 'Operation successful' }];
92
- *
93
- * // UI resource with initial data
94
- * return [
95
- * { type: 'text', text: 'Product loaded' },
96
- * {
97
- * type: 'resource',
98
- * resource: {
99
- * uri: 'ui://product/123',
100
- * mimeType: 'text/uri-list',
101
- * meta: { ui: { initialRenderData: { product } } }
102
- * }
103
- * }
104
- * ];
105
- * ```
106
- */
107
- interface ContentItem$1 {
108
- /** Content type: text, image, or resource */
109
- type: 'text' | 'image' | 'resource';
110
- /** Text content (for type: 'text') */
111
- text?: string;
112
- /** Base64-encoded image data (for type: 'image') */
113
- data?: string;
114
- /** MIME type for images (e.g., 'image/png') */
115
- mimeType?: string;
116
- /** Resource reference (for type: 'resource') */
117
- resource?: ResourceReference$1;
10
+ declare class CallbackHandlerMethods {
11
+ source: any;
12
+ func: any;
118
13
  }
14
+ declare class RPCMessage {
15
+ id: string;
16
+ source: string;
17
+ destination: string;
18
+ direction: "request" | "response";
19
+ functionName: string;
20
+ data: any;
21
+ sendOnlyIfThereIsAListener?: boolean;
22
+ host_id: string;
23
+ /** Origin of the PostMessage (for CORS validation) */
24
+ origin?: string;
25
+ static request(source: string, destination: string, functionName: string, data: any): RPCMessage;
26
+ static response(msg: RPCMessage, data: any): RPCMessage;
27
+ constructor(source: string, destination: string, direction: "request" | "response", functionName: string, data: any);
28
+ }
29
+ interface IRPC_Client {
30
+ clientId: string;
31
+ defaultDestinationId: string;
32
+ onMessage: (message: RPCMessage) => Promise<void>;
33
+ onConnectionStatusChange?: (status: 'connected' | 'disconnected' | 'reconnecting' | 'reconnect_failed', reason?: string) => void;
34
+ init(): Promise<void>;
35
+ close(): Promise<void>;
36
+ sendMessage(message: RPCMessage): Promise<any>;
37
+ }
38
+ declare class RPCConnection {
39
+ sender: IRPC_Client;
40
+ options: ConectionOptions;
41
+ callbacks: Map<string, CallbackHandlerMethods>;
42
+ onMessage: (msg: RPCMessage) => Promise<any>;
43
+ constructor(sender: IRPC_Client, options: ConectionOptions, onMessage?: (msg: RPCMessage) => Promise<any>);
44
+ log(msg: string, data?: any, data2?: any): void;
45
+ init(): Promise<void>;
46
+ close(): void;
47
+ sendRequestToHost(functionName: string, data: Array<any> | any): Promise<any>;
48
+ sendRequest(destinationId: string, functionName: string, data: Array<any> | any, timeoutMs?: number): Promise<any>;
49
+ incommingMessage(msg: RPCMessage): void;
50
+ }
51
+
119
52
  /**
120
- * Tool execution result type
121
- * Tools can return:
122
- * - ContentItem[] for rich responses (UI, citations, etc.)
123
- * - Plain object/primitive for simple results
124
- */
125
- type ToolExecutionResult$1<TResult = any> = ContentItem$1[] | TResult;
126
- /**
127
- * Context provided to tools during execution
128
- * Includes methods for updating canvas state in real-time.
129
- *
130
- * MCP App canvases receive `hostContext.toolInfo` with the tool schema.
131
- * Tool arguments/results come via ui/notifications/tool-input and tool-result.
132
- * `hostContext.state` hydrates from UI state persistence (BotDojo extension);
133
- * use `updateState` strictly for UI state (e.g., counters).
53
+ * Configuration class for handling flow request events
134
54
  */
135
- interface ToolExecutionContext$1 {
136
- /** Name of the tool being executed (helpful for logging/notifications) */
137
- toolName?: string;
55
+ declare class RequestEvents {
56
+ events?: string[];
57
+ onFlowRequestStart?: (data: any) => void;
58
+ onNewToken?: (data: any) => void;
59
+ onStepUpdate?: (data: any) => void;
60
+ onFlowRequestEnd?: (data: any) => void;
61
+ onLog?: (data: any) => void;
62
+ constructor(options?: {
63
+ events?: string[];
64
+ onFlowRequestStart?: (data: any) => void;
65
+ onNewToken?: (data: any) => void;
66
+ onStepUpdate?: (data: any) => void;
67
+ onFlowRequestEnd?: (data: any) => void;
68
+ onLog?: (data: any) => void;
69
+ });
138
70
  /**
139
- * Update canvas UI state during tool execution (if resource-template is present).
140
- * Do not mirror tool arguments/results here; the host caches that from
141
- * `ui/notifications/tool-*`. Keep this for UI persistence only.
71
+ * Get the events to listen for, with default fallback
142
72
  */
143
- updateState?: (state: any) => Promise<void>;
73
+ getEvents(): string[];
144
74
  /**
145
- * Send MCP Apps tool notifications to the UI host (SEP-1865).
146
- * Implementations should emit JSON-RPC notifications using context.toolName:
147
- * - ui/notifications/tool-input-partial (streaming args)
148
- * - ui/notifications/tool-input (final args)
149
- * - ui/notifications/tool-result (result payload)
75
+ * Check if a specific event has a callback
150
76
  */
151
- notifyToolInputPartial?: (args: Record<string, unknown>) => Promise<void>;
152
- notifyToolInput?: (args: Record<string, unknown>) => Promise<void>;
153
- notifyToolResult?: (result: any) => Promise<void>;
154
- }
155
- /**
156
- * Tool metadata following MCP Apps SDK pattern
157
- * Uses _meta with vendor-namespaced extensions (kebab-case)
158
- *
159
- * All BotDojo-specific options use 'botdojo/' prefix with kebab-case keys
160
- */
161
- interface ToolMetadata$1 {
162
- ui?: {
163
- preferredFrameSize?: {
164
- width: string;
165
- height: string;
166
- } | [string, string];
167
- initialRenderData?: any;
168
- displayName?: string;
169
- stateless?: boolean;
170
- /** Resource URI for pre-rendering during streaming */
171
- resourceUri?: string;
172
- mimeType?: 'text/html+mcp' | 'text/html;profile=mcp-app' | 'text/html' | 'text/uri-list';
173
- showInline?: boolean;
174
- agentEnabled?: boolean;
175
- /** Optional render hints for inline/URL MCP Apps */
176
- urlList?: string[];
177
- baseUrl?: string;
178
- prefersProxy?: boolean;
179
- allowExternal?: boolean;
180
- };
181
- 'botdojo/resource-template'?: {
182
- uri: string;
183
- mimeType: string;
184
- metadata?: {
185
- ui?: {
186
- preferredFrameSize?: {
187
- width: string;
188
- height: string;
189
- } | [string, string];
190
- initialRenderData?: any;
191
- displayName?: string;
192
- stateless?: boolean;
193
- mimeType?: string;
194
- };
195
- [key: string]: any;
196
- };
197
- };
198
- 'botdojo/display-name'?: string;
199
- 'botdojo/hide-step'?: boolean;
200
- 'botdojo/hide-step-details'?: boolean;
201
- }
202
- /**
203
- * Tool definition for defining tools
204
- * Can be used in two ways:
205
- * 1. In an array: tools: ToolDefinition[] (needs 'name' field)
206
- * 2. In an object: tools: Record<string, ToolDefinition> ('name' is the key, so field is optional)
207
- *
208
- * Display hints (displayName, hideStep, hideStepDetails) are in _meta with botdojo/ prefix
209
- */
210
- interface ToolDefinition$1<TParams = any, TResult = any> {
211
- name?: string;
212
- description: string;
213
- /** JSON Schema for parameters (MCP standard) */
214
- inputSchema?: any;
215
- /** Tool metadata - display hints and resource templates */
216
- _meta?: ToolMetadata$1;
217
- /** Execute function - returns ContentItem[] or plain result */
218
- /** Can accept optional ToolExecutionContext as second parameter for notifications */
219
- execute?: (params: TParams, context?: ToolExecutionContext$1) => Promise<ToolExecutionResult$1<TResult>>;
220
- }
221
- interface ModelContextMessage$1 {
222
- role: string;
223
- content: string;
224
- }
225
- interface ModelContextPrompt$1 {
226
- name: string;
227
- description: string;
228
- messages: ModelContextMessage$1[];
229
- }
230
- /**
231
- * Resource content returned by a provider
232
- */
233
- interface ResourceContent$1 {
234
- uri: string;
235
- mimeType?: string;
236
- text?: string;
237
- meta?: {
238
- title?: string;
239
- description?: string;
240
- [key: string]: any;
241
- };
242
- links?: Array<{
243
- uri: string;
244
- rel: string;
245
- description?: string;
246
- }>;
247
- /** If this resource is itself an MCP, include it here */
248
- mcp?: ModelContext$1[];
249
- }
250
- /**
251
- * Static resource with fixed URI
252
- *
253
- * @example
254
- * ```typescript
255
- * {
256
- * uri: 'myapp://help',
257
- * mimeType: 'text/markdown',
258
- * getContent: async () => '# Help...'
259
- * }
260
- * ```
261
- */
262
- interface ModelContextStaticResource$1 {
263
- /** Fixed URI for this resource */
264
- uri: string;
265
- /** Resource name (optional - can be inferred from uri) */
266
- name?: string;
267
- /** Human-readable label */
268
- label?: string;
269
- /** MIME type of the resource */
270
- mimeType?: string;
271
- /** Description of the resource */
272
- description?: string;
273
- /** Additional metadata */
274
- meta?: {
275
- title?: string;
276
- description?: string;
277
- icon?: string;
278
- [key: string]: any;
279
- };
280
- /** Get resource content (no parameters for static resources) */
281
- getContent: () => Promise<string | {
282
- url: string;
283
- } | ResourceContent$1>;
284
- }
285
- /**
286
- * Dynamic resource with parameterized URI template
287
- *
288
- * @example
289
- * ```typescript
290
- * {
291
- * uriTemplate: 'myapp://file/{filepath}',
292
- * mimeType: 'botdojo/mcp',
293
- * getContent: async (params) => {
294
- * // params.filepath is extracted from URI
295
- * return { mcp: [...] }
296
- * }
297
- * }
298
- * ```
299
- */
300
- interface ModelContextDynamicResource$1 {
301
- /** URI template with parameters - e.g., "myapp://users/{userId}" */
302
- uriTemplate: string;
303
- /** Resource name (optional - can be inferred from template) */
304
- name?: string;
305
- /** Human-readable label */
306
- label?: string;
307
- /** MIME type of the resource */
308
- mimeType?: string;
309
- /** Description of the resource */
310
- description?: string;
311
- /** Additional metadata */
312
- meta?: {
313
- title?: string;
314
- description?: string;
315
- icon?: string;
316
- [key: string]: any;
317
- };
318
- /** Get resource content with extracted parameters */
319
- getContent: (params: Record<string, any>) => Promise<string | {
320
- url: string;
321
- } | ResourceContent$1>;
77
+ hasCallback(eventType: string): boolean;
78
+ /**
79
+ * Execute the appropriate callback for an event
80
+ */
81
+ executeCallback(eventType: string, data: any): void;
82
+ /**
83
+ * Create a RequestEvents instance with only token streaming
84
+ */
85
+ static tokenStreaming(onNewToken: (data: any) => void): RequestEvents;
86
+ /**
87
+ * Create a RequestEvents instance with all events
88
+ */
89
+ static allEvents(callbacks: {
90
+ onFlowRequestStart?: (data: any) => void;
91
+ onNewToken?: (data: any) => void;
92
+ onIntermediateStepUpdate?: (data: any) => void;
93
+ onFlowRequestEnd?: (data: any) => void;
94
+ onLog?: (data: any) => void;
95
+ }): RequestEvents;
322
96
  }
323
97
  /**
324
- * Model context resource - can be either static or dynamic
325
- */
326
- type ModelContextResource$1 = ModelContextStaticResource$1 | ModelContextDynamicResource$1;
327
- /**
328
- * MCP-level CORS configuration for tool call security
329
- * Configured by developers when defining MCP backends
98
+ * Non-React client for connecting to BotDojo Flow Request API.
99
+ * Manages model context registration and tool call handling.
330
100
  *
331
- * IMPORTANT: Only validates parent/canvas → chat tool calls.
332
- * Agent → parent/canvas tool calls use origin='server' and bypass validation.
333
- */
334
- interface ModelContextCorsConfig$1 {
101
+ * Can use either PostMessage (for iframe embedding) or an external RPCConnection (for direct server communication).
102
+ */
103
+ declare class BotDojoConnector$1 {
104
+ private apiKey;
105
+ private sessionId;
106
+ private external_ui_channel_id;
107
+ private modelContext;
108
+ private nestedMcpCache;
109
+ private _hostClient;
110
+ private hasInit;
111
+ private clientId;
112
+ private hostClientId;
113
+ private canvasClientId;
114
+ private defaultCanvasId;
115
+ private registeredModelContexts;
116
+ private activeCanvasUpdates;
117
+ private transport;
118
+ private targetWindow;
119
+ private connection;
120
+ private toolCallCors?;
121
+ private botdojoChatDomain?;
122
+ constructor(props: {
123
+ apiKey: string;
124
+ accountId?: string;
125
+ projectId?: string;
126
+ flowId?: string;
127
+ modelContext?: ModelContext | ModelContext[];
128
+ sessionId?: string;
129
+ external_ui_channel_id?: string;
130
+ transport?: 'rpc' | 'postmessage';
131
+ targetWindow?: Window;
132
+ hostClient?: RPCConnection;
133
+ canvasId?: string;
134
+ });
135
+ /** Expose the current RPC connection (postMessage/RPC) for host bridges */
136
+ getConnection(): RPCConnection | null;
137
+ private generateChannelId;
138
+ /**
139
+ * Attempt to read canvas_id from the current URL.
140
+ *
141
+ * NOTE: Canvas iframes don't actually need to know their canvasId.
142
+ * The canvasId is for the chat client's internal routing (mapping messages to iframes).
143
+ * The chat client knows which iframe sent a message by which PostMessage bridge it came from.
144
+ *
145
+ * This method exists for backwards compatibility with legacy canvases that may
146
+ * expect to read canvas_id from URL params. New MCP-UI canvases should not rely on this.
147
+ */
148
+ private getCanvasIdFromUrl;
149
+ /**
150
+ * Create PostMessage RPC connection and register callbacks
151
+ */
152
+ private createPostMessageConnection;
153
+ /**
154
+ * Register all callbacks for incoming requests
155
+ */
156
+ private registerCallbacks;
157
+ /**
158
+ * Handle incoming messages not covered by registered callbacks
159
+ */
160
+ private processToolResult;
161
+ private handleIncomingMessage;
162
+ /**
163
+ * Handle getResource requests
164
+ * Supports both static and dynamic resources from the unified resources array
165
+ */
166
+ private handleGetResource;
167
+ /**
168
+ * Check if a URI matches a template (simple implementation)
169
+ */
170
+ private matchesUriTemplate;
171
+ /**
172
+ * Extract parameters from URI based on template
173
+ * Handles multi-segment parameters like {filepath} matching "Projects/test.txt"
174
+ */
175
+ private extractUriParams;
176
+ /**
177
+ * Initialize the connector
178
+ */
179
+ init(): Promise<void>;
180
+ /**
181
+ * Setup agent_host callbacks on the provided RPCConnection
182
+ */
183
+ private setupHostClientCallbacks;
184
+ /**
185
+ * Close RPC connection
186
+ */
187
+ close(): Promise<void>;
188
+ isConnected(): boolean;
189
+ /**
190
+ * Update the targetWindow for postMessage mode and initialize the RPC connection
191
+ */
192
+ updatePostMessageTarget(targetWindow: Window): Promise<void>;
193
+ getSessionId(): string | null;
194
+ getExternalUIChannelId(): string;
195
+ /**
196
+ * Get the external UI socket URL that matches the format expected by CanvasModelContextNode
197
+ */
198
+ getExternalUISocketUrl(): string;
199
+ getApiKey(): string;
200
+ setModelContext(modelContext: ModelContext | ModelContext[]): void;
201
+ /**
202
+ * Get all registered model contexts
203
+ */
204
+ getRegisteredModelContexts(): any[];
205
+ /**
206
+ * Register a new model context
207
+ */
208
+ registerModelContext(context: any): void;
209
+ /**
210
+ * Unregister a model context
211
+ */
212
+ unregisterModelContext(name: string): void;
335
213
  /**
336
- * Origins allowed to call tools on this MCP backend
337
- * Used by chat iframe router to validate tool call origins FROM parent/canvas
214
+ * Get the current model context(s)
215
+ */
216
+ getModelContext(): ModelContext | ModelContext[] | null;
217
+ /**
218
+ * Note: sendMessage, callFlow, and related flow execution methods have been removed.
219
+ * Flow execution should be handled by external callers using the BotDojo API directly.
220
+ * This connector focuses on model context management and tool call handling via postMessage or RPC.
221
+ */
222
+ /**
223
+ * Register a canvas update callback for a step
224
+ * Used to enable real-time canvas updates from parent-executed tools
338
225
  *
339
- * Default: undefined = ALL origins allowed (permissive by default)
340
- * Empty array [] = NO origins allowed (block all)
341
- * 'server' = Reserved, always allowed (agent tool calls)
226
+ * @param stepId - The step ID to associate with this canvas
227
+ * @param callback - Function to call when canvas data is updated
228
+ */
229
+ registerCanvasUpdateCallback(stepId: string, callback: (data: any) => void): void;
230
+ /**
231
+ * Unregister a canvas update callback
232
+ * Should be called when tool execution completes
342
233
  *
343
- * Protocol enforcement: Must match exactly (https:// ≠ http://)
344
- * Port enforcement: Must match exactly (:443 ≠ :80)
345
- * Wildcard support: Prefix only, follows CORS spec (*.myshop.com matches any subdomain)
234
+ * @param stepId - The step ID to unregister
235
+ */
236
+ unregisterCanvasUpdateCallback(stepId: string): void;
237
+ /**
238
+ * Send a canvas update to the agent host
239
+ * This forwards canvas data to the parent window, which will forward it to the canvas iframe
346
240
  *
347
- * Examples:
348
- * - undefined → Allow all (backward compatible)
349
- * - [] → Block all parent/canvas tool calls
350
- * - ["https://myshop.com", "https://admin.myshop.com"] → Exact matches only
351
- * - ["*.myshop.com"] → Allow any subdomain (app.myshop.com, admin.myshop.com)
352
- * - ["https://myshop.com"] → Does NOT match http://myshop.com (protocol differs)
353
- */
354
- allowedToolCallOrigins?: string[];
355
- }
356
- /**
357
- * Model context definition with tools, prompts, and resources
358
- * Tools can be defined as either:
359
- * - An array: tools: ToolDefinition[] (each tool needs 'name' field)
360
- * - An object: tools: Record<string, ToolDefinition> (key is the tool name)
361
- *
362
- * Resources support both static and dynamic patterns:
363
- * - Static: { uri: 'app://help', getContent: async () => '...' }
364
- * - Dynamic: { uriTemplate: 'app://file/{id}', getContent: async (params) => '...' }
365
- */
366
- interface ModelContext$1 {
367
- name: string;
368
- description?: string;
369
- toolPrefix?: string;
370
- /** Unique URI identifier for this model context */
371
- uri?: string;
372
- tools?: ToolDefinition$1[] | Record<string, ToolDefinition$1>;
373
- prompts?: ModelContextPrompt$1[];
374
- /** Unified resources array supporting both static and dynamic resources */
375
- resources?: ModelContextResource$1[];
376
- /**
377
- * CORS configuration for this MCP
241
+ * @param stepId - The step ID associated with the canvas (falls back to canvasId)
242
+ * @param canvasId - The canvas ID receiving updates (falls back to stepId)
243
+ * @param canvasData - The canvas data to send
244
+ * @param canvasType - The canvas type (e.g., 'mcp-app') for proper rendering
245
+ */
246
+ sendCanvasUpdate(stepId: string | undefined, canvasId: string | undefined, canvasData: any, canvasType?: string, toolInfo?: {
247
+ toolName?: string;
248
+ toolLabel?: string;
249
+ arguments?: any;
250
+ result?: any;
251
+ }): Promise<void>;
252
+ /**
253
+ * Execute a tool call if it exists
254
+ * In postMessage mode: sends request to parent via RPCConnection
255
+ * In RPC mode: sends request via Socket.IO RPCConnection
378
256
  *
379
- * **Backend Use**: Server enforces these rules before executing tools
380
- * - allowedToolCallOrigins: Which parent/canvas origins can call tools from this MCP
257
+ * @param toolName - The name of the tool to execute
258
+ * @param args - Arguments to pass to the tool
259
+ * @param stepId - Optional step ID for canvas updates (if tool has canvas template)
260
+ */
261
+ executeToolCall(toolName: string, ...args: any[]): Promise<any>;
262
+ /**
263
+ * Execute a flow run request
264
+ * In postMessage mode: sends request to parent/host who will call flow.run() API
265
+ * In RPC mode: sends request via Socket.IO to agent_host
381
266
  *
382
- * **Note**: For SDK usage (BotDojoChat/BotDojoConnector), use the
383
- * constructor-level `cors` parameter with ToolCallCorsConfig instead.
384
- * This field is primarily for backend per-MCP enforcement.
267
+ * @param body - The flow request body (e.g., { message: "Hello" })
268
+ * @returns The flow response including status, response, aiMessage, etc.
269
+ */
270
+ run(body: any): Promise<FlowResponse>;
271
+ /**
272
+ * Reset the session (will create a new session on next request)
385
273
  */
386
- cors?: ModelContextCorsConfig$1;
274
+ resetSession(): void;
275
+ /**
276
+ * Send a message to the chat iframe and wait for the flow response
277
+ * This is useful for parent pages that want to programmatically send messages to the chat
278
+ *
279
+ * @param message - The message to send to the chat
280
+ * @returns Promise that resolves with the FlowResponse from the chat
281
+ */
282
+ sendMessageToChat(message: string): Promise<FlowResponse>;
283
+ /**
284
+ * Call a remote function with timeout (needed for agent_host compatibility)
285
+ * Now unified for both transports!
286
+ */
287
+ callWithTimeout(target: string, functionName: string, timeoutMs: number, ...args: any[]): Promise<any>;
288
+ /**
289
+ * Update canvas data and persist it to the backend
290
+ * This allows canvases to maintain state across page refreshes
291
+ *
292
+ * @param state - The updated canvas state to persist
293
+ * @returns Promise that resolves when the data is saved
294
+ */
295
+ updateState(state: any): Promise<any>;
296
+ /**
297
+ * Set botdojoChatDomain from flow chat settings
298
+ * Called by canvas host after it receives config from server
299
+ *
300
+ * This is separate from the constructor's cors parameter because:
301
+ * - Constructor cors: Set by SDK user (allowedToolCallOrigins)
302
+ * - botdojoChatDomain: Set by flow settings (server-side configuration)
303
+ *
304
+ * @param domains - Allowed chat iframe domains from flow settings
305
+ */
306
+ setBotDojoChatDomain(domains: string[] | undefined): void;
387
307
  }
388
308
 
389
309
  /**
@@ -604,7 +524,7 @@ interface BotDojoChatProps {
604
524
  * Can be a single ModelContext or an array of ModelContext objects
605
525
  * Tools should include `execute` functions directly in their definitions
606
526
  */
607
- modelContext?: ModelContext$1 | ModelContext$1[];
527
+ modelContext?: ModelContext | ModelContext[];
608
528
  /**
609
529
  * Called when chat iframe loads
610
530
  */
@@ -795,7 +715,7 @@ interface HeadlessChatProps {
795
715
  * Model context with tools, prompts, and resources
796
716
  * Tools should include `execute` functions directly in their definitions
797
717
  */
798
- modelContext?: ModelContext$1 | ModelContext$1[];
718
+ modelContext?: ModelContext | ModelContext[];
799
719
  /**
800
720
  * Base URL for the headless embed iframe
801
721
  * @default 'http://localhost:3000' (development)
@@ -933,475 +853,6 @@ interface HeadlessChatHandle {
933
853
  isReady: () => boolean;
934
854
  }
935
855
 
936
- /**
937
- * Shared TypeScript types for BotDojo SDK and Canvas Client
938
- *
939
- * This package contains pure TypeScript type definitions with no JSX or React dependencies.
940
- * It can be safely imported by any TypeScript project without requiring JSX configuration.
941
- */
942
-
943
- /**
944
- * Resource reference for UI, ModelContext, or other resources
945
- *
946
- * MIME types determine how resource is handled:
947
- * - 'text/uri-list': External URL loaded in iframe (MCP Apps standard)
948
- * - 'text/html': Inline HTML rendered in iframe
949
- * - 'application/vnd.botdojo.ui-remote-dom': Remote DOM script
950
- * - 'application/vnd.botdojo.modelcontext': Nested ModelContext (URI points to resource)
951
- * - 'application/vnd.botdojo.citation': Single citation
952
- * - 'application/vnd.botdojo.citations': Multiple citations
953
- */
954
- interface ResourceReference {
955
- /** Resource URI (e.g., 'ui://product/123', 'mcp://actions') */
956
- uri: string;
957
- /** MIME type determines how resource is processed */
958
- mimeType?: string;
959
- /** Resource content (URL for uri-list, inline HTML for text/html(+mcp), or URI for modelcontext) */
960
- text?: string;
961
- /** Inline HTML for `text/html`, `text/html+mcp`, or `text/html;profile=mcp-app` resources */
962
- html?: string;
963
- /** Optional allowlist for URL-based resources (matches SEP url-list direction) */
964
- urlList?: string[];
965
- /** Base URL to apply to inline HTML (used for relative asset resolution) */
966
- baseUrl?: string;
967
- /** Hint to prefer sandbox proxy even when a URL exists */
968
- prefersProxy?: boolean;
969
- /** Hint to allow direct external URL rendering even when inline HTML is present */
970
- allowExternal?: boolean;
971
- /** Metadata for UI resources only */
972
- meta?: {
973
- /** SEP-1865 UI metadata */
974
- ui?: {
975
- /** Preferred iframe dimensions (object or tuple) */
976
- preferredFrameSize?: {
977
- width: string;
978
- height: string;
979
- } | [string, string];
980
- /** Initial render data/state */
981
- initialRenderData?: any;
982
- /** Optional display name for the canvas */
983
- displayName?: string;
984
- /** If true, canvas should not be persisted */
985
- stateless?: boolean;
986
- /** MIME type hint for the UI resource */
987
- mimeType?: string;
988
- /** Optional CSP hints */
989
- csp?: {
990
- connectDomains?: string[];
991
- resourceDomains?: string[];
992
- domain?: string;
993
- allowPopups?: boolean;
994
- allowForms?: boolean;
995
- allowSameOrigin?: boolean;
996
- prefersBorder?: boolean;
997
- };
998
- /** Optional resource hints for inline/URL handling */
999
- urlList?: string[];
1000
- baseUrl?: string;
1001
- prefersProxy?: boolean;
1002
- allowExternal?: boolean;
1003
- };
1004
- /** Additional metadata */
1005
- [key: string]: any;
1006
- };
1007
- }
1008
- /**
1009
- * MCP-compliant content item for tool results
1010
- *
1011
- * Tools should return ContentItem[] for rich responses, or plain objects for simple results.
1012
- *
1013
- * @example
1014
- * ```typescript
1015
- * // Simple text response
1016
- * return [{ type: 'text', text: 'Operation successful' }];
1017
- *
1018
- * // UI resource with initial data
1019
- * return [
1020
- * { type: 'text', text: 'Product loaded' },
1021
- * {
1022
- * type: 'resource',
1023
- * resource: {
1024
- * uri: 'ui://product/123',
1025
- * mimeType: 'text/uri-list',
1026
- * meta: { ui: { initialRenderData: { product } } }
1027
- * }
1028
- * }
1029
- * ];
1030
- * ```
1031
- */
1032
- interface ContentItem {
1033
- /** Content type: text, image, or resource */
1034
- type: 'text' | 'image' | 'resource';
1035
- /** Text content (for type: 'text') */
1036
- text?: string;
1037
- /** Base64-encoded image data (for type: 'image') */
1038
- data?: string;
1039
- /** MIME type for images (e.g., 'image/png') */
1040
- mimeType?: string;
1041
- /** Resource reference (for type: 'resource') */
1042
- resource?: ResourceReference;
1043
- }
1044
- /**
1045
- * Citation data for referencing sources
1046
- * Citations are BotDojo primitives, not UI resources
1047
- */
1048
- interface CitationData {
1049
- /** Required unique identifier */
1050
- id: string;
1051
- /** Source name/title */
1052
- source: string;
1053
- /** Optional URL */
1054
- url?: string;
1055
- /** Optional quote/excerpt */
1056
- text?: string;
1057
- /** Additional metadata */
1058
- [key: string]: any;
1059
- }
1060
- /**
1061
- * Tool execution result type
1062
- * Tools can return:
1063
- * - ContentItem[] for rich responses (UI, citations, etc.)
1064
- * - Plain object/primitive for simple results
1065
- */
1066
- type ToolExecutionResult<TResult = any> = ContentItem[] | TResult;
1067
- /**
1068
- * Standard MIME types for BotDojo resources
1069
- */
1070
- declare const MIME_TYPES: {
1071
- readonly URI_LIST: "text/uri-list";
1072
- readonly HTML: "text/html";
1073
- readonly HTML_MCP: "text/html+mcp";
1074
- readonly HTML_MCP_PROFILE: "text/html;profile=mcp-app";
1075
- readonly REMOTE_DOM: "application/vnd.mcp-ui.remote-dom";
1076
- readonly REMOTE_DOM_BOTDOJO: "application/vnd.botdojo.ui-remote-dom";
1077
- readonly MODEL_CONTEXT: "application/vnd.botdojo.modelcontext";
1078
- readonly CITATION: "application/vnd.botdojo.citation";
1079
- readonly CITATIONS: "application/vnd.botdojo.citations";
1080
- };
1081
- /**
1082
- * Context provided to tools during execution
1083
- * Includes methods for updating canvas state in real-time.
1084
- *
1085
- * MCP App canvases receive `hostContext.toolInfo` with the tool schema.
1086
- * Tool arguments/results come via ui/notifications/tool-input and tool-result.
1087
- * `hostContext.state` hydrates from UI state persistence (BotDojo extension);
1088
- * use `updateState` strictly for UI state (e.g., counters).
1089
- */
1090
- interface ToolExecutionContext {
1091
- /** Name of the tool being executed (helpful for logging/notifications) */
1092
- toolName?: string;
1093
- /**
1094
- * Update canvas UI state during tool execution (if resource-template is present).
1095
- * Do not mirror tool arguments/results here; the host caches that from
1096
- * `ui/notifications/tool-*`. Keep this for UI persistence only.
1097
- */
1098
- updateState?: (state: any) => Promise<void>;
1099
- /**
1100
- * Send MCP Apps tool notifications to the UI host (SEP-1865).
1101
- * Implementations should emit JSON-RPC notifications using context.toolName:
1102
- * - ui/notifications/tool-input-partial (streaming args)
1103
- * - ui/notifications/tool-input (final args)
1104
- * - ui/notifications/tool-result (result payload)
1105
- */
1106
- notifyToolInputPartial?: (args: Record<string, unknown>) => Promise<void>;
1107
- notifyToolInput?: (args: Record<string, unknown>) => Promise<void>;
1108
- notifyToolResult?: (result: any) => Promise<void>;
1109
- }
1110
- /**
1111
- * Tool metadata following MCP Apps SDK pattern
1112
- * Uses _meta with vendor-namespaced extensions (kebab-case)
1113
- *
1114
- * All BotDojo-specific options use 'botdojo/' prefix with kebab-case keys
1115
- */
1116
- interface ToolMetadata {
1117
- ui?: {
1118
- preferredFrameSize?: {
1119
- width: string;
1120
- height: string;
1121
- } | [string, string];
1122
- initialRenderData?: any;
1123
- displayName?: string;
1124
- stateless?: boolean;
1125
- /** Resource URI for pre-rendering during streaming */
1126
- resourceUri?: string;
1127
- mimeType?: 'text/html+mcp' | 'text/html;profile=mcp-app' | 'text/html' | 'text/uri-list';
1128
- showInline?: boolean;
1129
- agentEnabled?: boolean;
1130
- /** Optional render hints for inline/URL MCP Apps */
1131
- urlList?: string[];
1132
- baseUrl?: string;
1133
- prefersProxy?: boolean;
1134
- allowExternal?: boolean;
1135
- };
1136
- 'botdojo/resource-template'?: {
1137
- uri: string;
1138
- mimeType: string;
1139
- metadata?: {
1140
- ui?: {
1141
- preferredFrameSize?: {
1142
- width: string;
1143
- height: string;
1144
- } | [string, string];
1145
- initialRenderData?: any;
1146
- displayName?: string;
1147
- stateless?: boolean;
1148
- mimeType?: string;
1149
- };
1150
- [key: string]: any;
1151
- };
1152
- };
1153
- 'botdojo/display-name'?: string;
1154
- 'botdojo/hide-step'?: boolean;
1155
- 'botdojo/hide-step-details'?: boolean;
1156
- }
1157
- /**
1158
- * Tool definition for defining tools
1159
- * Can be used in two ways:
1160
- * 1. In an array: tools: ToolDefinition[] (needs 'name' field)
1161
- * 2. In an object: tools: Record<string, ToolDefinition> ('name' is the key, so field is optional)
1162
- *
1163
- * Display hints (displayName, hideStep, hideStepDetails) are in _meta with botdojo/ prefix
1164
- */
1165
- interface ToolDefinition<TParams = any, TResult = any> {
1166
- name?: string;
1167
- description: string;
1168
- /** JSON Schema for parameters (MCP standard) */
1169
- inputSchema?: any;
1170
- /** Tool metadata - display hints and resource templates */
1171
- _meta?: ToolMetadata;
1172
- /** Execute function - returns ContentItem[] or plain result */
1173
- /** Can accept optional ToolExecutionContext as second parameter for notifications */
1174
- execute?: (params: TParams, context?: ToolExecutionContext) => Promise<ToolExecutionResult<TResult>>;
1175
- }
1176
- interface ModelContextMessage {
1177
- role: string;
1178
- content: string;
1179
- }
1180
- interface ModelContextPrompt {
1181
- name: string;
1182
- description: string;
1183
- messages: ModelContextMessage[];
1184
- }
1185
- /**
1186
- * Resource template for dynamic resource discovery
1187
- * Compatible with IResourceProvider pattern in botdojo-core
1188
- */
1189
- interface ResourceTemplate {
1190
- /** URI template following RFC 6570 (e.g., "myapp://users/{userId}") */
1191
- uriTemplate: string;
1192
- /** Unique identifier for this template */
1193
- name: string;
1194
- /** Human-readable name */
1195
- label: string;
1196
- /** Description of this resource type */
1197
- description?: string;
1198
- /** MIME type for resources matching this template */
1199
- mimeType?: string;
1200
- /** Additional metadata */
1201
- meta?: {
1202
- title?: string;
1203
- description?: string;
1204
- icon?: string;
1205
- defaultToolPrefix?: string;
1206
- [key: string]: any;
1207
- };
1208
- }
1209
- /**
1210
- * Resource provider for dynamic resource discovery
1211
- * Compatible with Resource Manager MCP v2
1212
- */
1213
- interface ResourceProvider {
1214
- /** Unique provider ID */
1215
- id: string;
1216
- /** Resource templates this provider supports */
1217
- templates: ResourceTemplate[];
1218
- /**
1219
- * Get a resource by URI
1220
- * @param templateName The name of the template that matched
1221
- * @param uri The resource URI to fetch
1222
- * @param params Extracted template parameters
1223
- * @param onlyMetadata If true, only return metadata (no content)
1224
- */
1225
- getResource: (templateName: string, uri: string, params: any, onlyMetadata?: boolean) => Promise<ResourceContent>;
1226
- }
1227
- /**
1228
- * Resource content returned by a provider
1229
- */
1230
- interface ResourceContent {
1231
- uri: string;
1232
- mimeType?: string;
1233
- text?: string;
1234
- meta?: {
1235
- title?: string;
1236
- description?: string;
1237
- [key: string]: any;
1238
- };
1239
- links?: Array<{
1240
- uri: string;
1241
- rel: string;
1242
- description?: string;
1243
- }>;
1244
- /** If this resource is itself an MCP, include it here */
1245
- mcp?: ModelContext[];
1246
- }
1247
- /**
1248
- * Static resource with fixed URI
1249
- *
1250
- * @example
1251
- * ```typescript
1252
- * {
1253
- * uri: 'myapp://help',
1254
- * mimeType: 'text/markdown',
1255
- * getContent: async () => '# Help...'
1256
- * }
1257
- * ```
1258
- */
1259
- interface ModelContextStaticResource {
1260
- /** Fixed URI for this resource */
1261
- uri: string;
1262
- /** Resource name (optional - can be inferred from uri) */
1263
- name?: string;
1264
- /** Human-readable label */
1265
- label?: string;
1266
- /** MIME type of the resource */
1267
- mimeType?: string;
1268
- /** Description of the resource */
1269
- description?: string;
1270
- /** Additional metadata */
1271
- meta?: {
1272
- title?: string;
1273
- description?: string;
1274
- icon?: string;
1275
- [key: string]: any;
1276
- };
1277
- /** Get resource content (no parameters for static resources) */
1278
- getContent: () => Promise<string | {
1279
- url: string;
1280
- } | ResourceContent>;
1281
- }
1282
- /**
1283
- * Dynamic resource with parameterized URI template
1284
- *
1285
- * @example
1286
- * ```typescript
1287
- * {
1288
- * uriTemplate: 'myapp://file/{filepath}',
1289
- * mimeType: 'botdojo/mcp',
1290
- * getContent: async (params) => {
1291
- * // params.filepath is extracted from URI
1292
- * return { mcp: [...] }
1293
- * }
1294
- * }
1295
- * ```
1296
- */
1297
- interface ModelContextDynamicResource {
1298
- /** URI template with parameters - e.g., "myapp://users/{userId}" */
1299
- uriTemplate: string;
1300
- /** Resource name (optional - can be inferred from template) */
1301
- name?: string;
1302
- /** Human-readable label */
1303
- label?: string;
1304
- /** MIME type of the resource */
1305
- mimeType?: string;
1306
- /** Description of the resource */
1307
- description?: string;
1308
- /** Additional metadata */
1309
- meta?: {
1310
- title?: string;
1311
- description?: string;
1312
- icon?: string;
1313
- [key: string]: any;
1314
- };
1315
- /** Get resource content with extracted parameters */
1316
- getContent: (params: Record<string, any>) => Promise<string | {
1317
- url: string;
1318
- } | ResourceContent>;
1319
- }
1320
- /**
1321
- * Model context resource - can be either static or dynamic
1322
- */
1323
- type ModelContextResource = ModelContextStaticResource | ModelContextDynamicResource;
1324
- /**
1325
- * MCP-level CORS configuration for tool call security
1326
- * Configured by developers when defining MCP backends
1327
- *
1328
- * IMPORTANT: Only validates parent/canvas → chat tool calls.
1329
- * Agent → parent/canvas tool calls use origin='server' and bypass validation.
1330
- */
1331
- interface ModelContextCorsConfig {
1332
- /**
1333
- * Origins allowed to call tools on this MCP backend
1334
- * Used by chat iframe router to validate tool call origins FROM parent/canvas
1335
- *
1336
- * Default: undefined = ALL origins allowed (permissive by default)
1337
- * Empty array [] = NO origins allowed (block all)
1338
- * 'server' = Reserved, always allowed (agent tool calls)
1339
- *
1340
- * Protocol enforcement: Must match exactly (https:// ≠ http://)
1341
- * Port enforcement: Must match exactly (:443 ≠ :80)
1342
- * Wildcard support: Prefix only, follows CORS spec (*.myshop.com matches any subdomain)
1343
- *
1344
- * Examples:
1345
- * - undefined → Allow all (backward compatible)
1346
- * - [] → Block all parent/canvas tool calls
1347
- * - ["https://myshop.com", "https://admin.myshop.com"] → Exact matches only
1348
- * - ["*.myshop.com"] → Allow any subdomain (app.myshop.com, admin.myshop.com)
1349
- * - ["https://myshop.com"] → Does NOT match http://myshop.com (protocol differs)
1350
- */
1351
- allowedToolCallOrigins?: string[];
1352
- }
1353
- /**
1354
- * Model context definition with tools, prompts, and resources
1355
- * Tools can be defined as either:
1356
- * - An array: tools: ToolDefinition[] (each tool needs 'name' field)
1357
- * - An object: tools: Record<string, ToolDefinition> (key is the tool name)
1358
- *
1359
- * Resources support both static and dynamic patterns:
1360
- * - Static: { uri: 'app://help', getContent: async () => '...' }
1361
- * - Dynamic: { uriTemplate: 'app://file/{id}', getContent: async (params) => '...' }
1362
- */
1363
- interface ModelContext {
1364
- name: string;
1365
- description?: string;
1366
- toolPrefix?: string;
1367
- /** Unique URI identifier for this model context */
1368
- uri?: string;
1369
- tools?: ToolDefinition[] | Record<string, ToolDefinition>;
1370
- prompts?: ModelContextPrompt[];
1371
- /** Unified resources array supporting both static and dynamic resources */
1372
- resources?: ModelContextResource[];
1373
- /**
1374
- * CORS configuration for this MCP
1375
- *
1376
- * **Backend Use**: Server enforces these rules before executing tools
1377
- * - allowedToolCallOrigins: Which parent/canvas origins can call tools from this MCP
1378
- *
1379
- * **Note**: For SDK usage (BotDojoChat/BotDojoConnector), use the
1380
- * constructor-level `cors` parameter with ToolCallCorsConfig instead.
1381
- * This field is primarily for backend per-MCP enforcement.
1382
- */
1383
- cors?: ModelContextCorsConfig;
1384
- }
1385
- /**
1386
- * SDK version of flow request step with clean terminology
1387
- * Maps to internal FlowRequestIntermediateStep but uses cleaner field names
1388
- */
1389
- interface FlowRequestStep {
1390
- stepId: string;
1391
- stepLabel: string;
1392
- stepStatus: 'complete' | 'error' | 'processing';
1393
- error?: string;
1394
- content: string;
1395
- startTime: Date;
1396
- canvas?: Core_FlowCanvas;
1397
- parentStepId?: string;
1398
- subSteps?: FlowRequestStep[];
1399
- stepToolName?: string;
1400
- stepToolArguments?: Record<string, any>;
1401
- stepToolResult?: any;
1402
- stepToolPhase?: Core_ToolExecutionPhase;
1403
- }
1404
-
1405
856
  /**
1406
857
  * McpAppHostContext
1407
858
  *
@@ -1543,10 +994,6 @@ type HeadlessEvent = {
1543
994
  type: 'token';
1544
995
  messageId: string;
1545
996
  tokenUpdate: Core_TokenUpdate;
1546
- } | {
1547
- type: 'session_hydrated';
1548
- sessionId: string;
1549
- messages: ChatMessage$1[];
1550
997
  } | {
1551
998
  type: 'request_aborted';
1552
999
  };
@@ -1574,10 +1021,6 @@ type HeadlessAction = {
1574
1021
  type: 'TOKEN';
1575
1022
  messageId: string;
1576
1023
  tokenUpdate: Core_TokenUpdate;
1577
- } | {
1578
- type: 'SESSION_HYDRATED';
1579
- sessionId: string;
1580
- messages: ChatMessage$1[];
1581
1024
  } | {
1582
1025
  type: 'REQUEST_ABORTED';
1583
1026
  } | {
@@ -1755,19 +1198,27 @@ declare function useChatStatus(): ChatStatusHook;
1755
1198
 
1756
1199
  declare function useChatActions(): ChatActionsHook;
1757
1200
 
1201
+ /**
1202
+ * Canvas type for the chat SDK.
1203
+ * Only 'mcp-app' is supported in the open-source SDK.
1204
+ */
1205
+ type FlowCanvasType = 'mcp-app';
1758
1206
  interface BotDojoCanvasFrameProps {
1759
1207
  canvasId: string;
1760
1208
  canvasData: any;
1761
- canvasType?: FlowCanvasType;
1209
+ canvasType?: FlowCanvasType | string;
1762
1210
  width?: string | number;
1763
1211
  height?: string | number;
1764
1212
  style?: React$1.CSSProperties;
1765
1213
  }
1766
1214
  /**
1767
1215
  * Minimal headless canvas iframe renderer.
1768
- * Renders mcp-app (or legacy iframe/dojo) canvases by loading the URL or inline HTML.
1216
+ * Renders mcp-app canvases by loading the URL or inline HTML.
1217
+ *
1218
+ * Note: Only 'mcp-app' canvas type is supported in the open-source SDK.
1219
+ * Other canvas types will render nothing and emit a dev warning.
1769
1220
  */
1770
- declare function BotDojoCanvasFrame(props: BotDojoCanvasFrameProps): JSX.Element;
1221
+ declare function BotDojoCanvasFrame(props: BotDojoCanvasFrameProps): JSX.Element | null;
1771
1222
 
1772
1223
  /**
1773
1224
  * McpAppHost Component
@@ -1887,34 +1338,239 @@ declare function useMcpAppHost(): McpAppHostContextValue | null;
1887
1338
  */
1888
1339
  declare function useMcpAppHostRequired(): McpAppHostContextValue;
1889
1340
 
1890
- interface BotDojoChatConfig {
1891
- apiKey: string;
1892
- mode: BotDojoChatDisplayMode;
1893
- popupOptions?: PopupOptions;
1894
- sidePanelOptions?: SidePanelOptions;
1895
- width?: string;
1896
- height?: string;
1897
- accentColor: string;
1898
- backgroundColor: string;
1899
- theme?: 'light' | 'dark' | 'modern-light' | 'modern-dark';
1900
- fontSize?: string;
1901
- flowVersion: string;
1902
- flowHeaders?: Record<string, any>;
1903
- userImage?: string;
1904
- widgetImage?: string;
1905
- botImage?: string;
1906
- voiceIcon?: string;
1907
- newSession: boolean;
1908
- sessionId?: string;
1909
- allowMicrophone: boolean;
1910
- baseUrl?: string;
1341
+ /**
1342
+ * Shared utilities for MCP App hosting
1343
+ */
1344
+ /**
1345
+ * Default host capabilities for MCP Apps
1346
+ */
1347
+ declare const DEFAULT_MCP_HOST_CAPABILITIES: {
1348
+ openLinks: {};
1349
+ 'botdojo/persistence': boolean;
1350
+ extensions: {
1351
+ 'io.modelcontextprotocol/ui': {
1352
+ mimeTypes: string[];
1353
+ };
1354
+ };
1355
+ };
1356
+ /**
1357
+ * Generate a stable content key for iframe change detection.
1358
+ * Changes to this key indicate content has changed enough to warrant iframe reload.
1359
+ *
1360
+ * Per MCP spec (SEP-1865), we only support proxy URLs (no blob URLs).
1361
+ *
1362
+ * @param url - URL string (proxy URL)
1363
+ * @returns A stable key representing the content
1364
+ */
1365
+ declare function getContentKey(url: string | undefined): string;
1366
+ /**
1367
+ * Validate tool notification parameters.
1368
+ * Prevents sending empty/invalid notifications to MCP Apps.
1369
+ *
1370
+ * @param params - The notification params
1371
+ * @param kind - Type of notification: 'partial', 'input', or 'result'
1372
+ * @returns true if params are valid and should be sent
1373
+ */
1374
+ declare function validateToolParams(params: any, kind: 'partial' | 'input' | 'result'): boolean;
1375
+ /**
1376
+ * Process a step update into tool notifications.
1377
+ * Centralizes the logic for converting step updates to MCP App notifications.
1378
+ */
1379
+ interface StepUpdate {
1380
+ stepToolName?: string;
1381
+ toolName?: string;
1382
+ stepToolArguments?: any;
1383
+ stepToolResult?: any;
1384
+ stepToolProgress?: any;
1385
+ toolPhase?: string;
1386
+ stepId?: string;
1387
+ stepLabel?: string;
1911
1388
  }
1912
- interface BotDojoChatConfiguratorProps {
1913
- initialConfig?: Partial<BotDojoChatConfig>;
1914
- onClose?: () => void;
1915
- onApply?: (config: BotDojoChatConfig) => void;
1389
+ interface ToolNotification {
1390
+ method: string;
1391
+ params: {
1392
+ tool: {
1393
+ name: string;
1394
+ };
1395
+ arguments?: any;
1396
+ result?: any;
1397
+ };
1398
+ }
1399
+ /**
1400
+ * Process a step update and return notifications to send to the MCP App.
1401
+ *
1402
+ * @param stepUpdate - The step update from the server
1403
+ * @returns Array of notifications to send
1404
+ */
1405
+ declare function processStepUpdate(stepUpdate: StepUpdate): ToolNotification[];
1406
+
1407
+ /**
1408
+ * useMcpHostBridge - React hook for hosting MCP Apps in iframes
1409
+ *
1410
+ * Encapsulates all iframe lifecycle management, JSON-RPC communication,
1411
+ * and MCP protocol handling. This is the consolidated implementation
1412
+ * that both McpAppHost and McpAppCanvas can use.
1413
+ *
1414
+ * Per MCP spec (SEP-1865), web hosts MUST use a sandbox proxy with a different
1415
+ * origin. Blob URLs are not supported as they have null origin.
1416
+ */
1417
+
1418
+ /**
1419
+ * Iframe lifecycle states
1420
+ */
1421
+ type IframeState = 'idle' | 'loading' | 'initializing' | 'ready';
1422
+ /**
1423
+ * Tool info for hydration
1424
+ */
1425
+ interface ToolInfo {
1426
+ id?: string | number;
1427
+ tool: {
1428
+ name: string;
1429
+ description?: string;
1430
+ inputSchema?: Record<string, unknown>;
1431
+ };
1916
1432
  }
1917
- declare const BotDojoChatConfigurator: React$1.FC<BotDojoChatConfiguratorProps>;
1433
+ /**
1434
+ * Options for useMcpHostBridge hook
1435
+ */
1436
+ interface UseMcpHostBridgeOptions {
1437
+ /** Unique identifier for this MCP App instance */
1438
+ appId: string;
1439
+ /**
1440
+ * URL for the app (proxy URL for ui:// resources, or direct HTTP URL).
1441
+ * Required for rendering - if not provided, no iframe will be rendered.
1442
+ */
1443
+ url?: string;
1444
+ /**
1445
+ * HTML content - only used for sandbox-resource-ready response, not for iframe src.
1446
+ * The proxy will request this via sandbox-resource message.
1447
+ */
1448
+ html?: string;
1449
+ /** Tool info for hydration */
1450
+ toolInfo?: ToolInfo;
1451
+ /** Tool arguments for hydration */
1452
+ arguments?: any;
1453
+ /** Tool result for hydration */
1454
+ result?: any;
1455
+ /** Persisted state to restore */
1456
+ state?: any;
1457
+ /** Whether the tool is complete */
1458
+ isComplete?: boolean;
1459
+ /** Called when app requests to open a link */
1460
+ onOpenLink?: (url: string, target: string) => void;
1461
+ /** Called when app requests a tool execution */
1462
+ onToolCall?: (tool: string, params: any) => Promise<any>;
1463
+ /** Called when app sends a UI message */
1464
+ onMessage?: (message: string, params: any) => void;
1465
+ /** Called when app wants to persist state */
1466
+ onPersistState?: (state: any) => void;
1467
+ /** Called when app reports size change */
1468
+ onSizeChange?: (width: number, height: number) => void;
1469
+ /** Called when app is initialized and ready */
1470
+ onReady?: () => void;
1471
+ /** Additional host context */
1472
+ hostContext?: Record<string, any>;
1473
+ /** Enable debug logging and error display */
1474
+ debug?: boolean;
1475
+ /**
1476
+ * Called when proxy requests a sandbox resource (ui/requests/sandbox-resource).
1477
+ * Should return the resolved HTML content for the resource.
1478
+ */
1479
+ onSandboxResourceRequest?: (params: {
1480
+ resource: string;
1481
+ flowId?: string;
1482
+ }) => Promise<{
1483
+ html?: string;
1484
+ sandbox?: string;
1485
+ csp?: string;
1486
+ } | string | null>;
1487
+ }
1488
+ /**
1489
+ * Return value from useMcpHostBridge hook
1490
+ */
1491
+ interface UseMcpHostBridgeResult {
1492
+ /** Ref to attach to the iframe element */
1493
+ iframeRef: React.RefObject<HTMLIFrameElement>;
1494
+ /** Current iframe state */
1495
+ status: IframeState;
1496
+ /** Auto-detected height from app */
1497
+ autoHeight: number | null;
1498
+ /** Handle iframe onLoad event */
1499
+ handleIframeLoad: () => void;
1500
+ /** Send a tool notification to the app */
1501
+ sendToolNotification: (method: string, params: any) => void;
1502
+ /** Process and send step update notifications */
1503
+ sendStepUpdate: (stepUpdate: StepUpdate) => void;
1504
+ /** The computed src for the iframe (proxy URL) */
1505
+ iframeSrc: string | undefined;
1506
+ /** Error message if rendering is not possible (null if OK) */
1507
+ renderError: string | null;
1508
+ /** Convenience boolean - true if iframeSrc is valid and no render error */
1509
+ canRender: boolean;
1510
+ /** True if initialization timed out */
1511
+ initFailed: boolean;
1512
+ /** Detailed initialization error message */
1513
+ initError: string | null;
1514
+ /** Reset iframe state to retry rendering */
1515
+ resetIframe: () => void;
1516
+ }
1517
+ /**
1518
+ * Hook for hosting MCP Apps in iframes with full JSON-RPC communication.
1519
+ * Handles initialization, hydration, tool notifications, and lifecycle management.
1520
+ */
1521
+ declare function useMcpHostBridge(options: UseMcpHostBridgeOptions): UseMcpHostBridgeResult;
1522
+
1523
+ type UiCspMeta = {
1524
+ domain?: string;
1525
+ connectDomains?: string[];
1526
+ resourceDomains?: string[];
1527
+ allowPopups?: boolean;
1528
+ allowForms?: boolean;
1529
+ allowSameOrigin?: boolean;
1530
+ };
1531
+ type ResolvedUiCsp = {
1532
+ /** Space-delimited sandbox attribute value */
1533
+ sandbox: string;
1534
+ /** Content-Security-Policy string */
1535
+ csp: string;
1536
+ /** Normalized metadata used to build the policy */
1537
+ meta: UiCspMeta;
1538
+ };
1539
+ declare function resolveUiCsp(meta?: UiCspMeta): ResolvedUiCsp;
1540
+ declare function extractUiCspFromResource(resource: any): UiCspMeta | undefined;
1541
+
1542
+ type McpHtmlProxyOptions = {
1543
+ html: string;
1544
+ baseUrl?: string;
1545
+ urlList?: string[];
1546
+ };
1547
+ type McpProxyUrlOptions = {
1548
+ flowId: string;
1549
+ resource: string;
1550
+ origin?: string;
1551
+ };
1552
+ /**
1553
+ * Build a sandbox-friendly blob URL for MCP HTML content.
1554
+ * Injects a base URL and optional url-list hint for relative assets.
1555
+ */
1556
+ declare function createMcpHtmlProxy(options: McpHtmlProxyOptions): {
1557
+ url: string;
1558
+ revoke: () => void;
1559
+ };
1560
+ /**
1561
+ * Build the MCP HTML proxy URL served by the sdk-mcp-app-html-proxy app.
1562
+ * Format: /{flowId}/?url=<encodeURIComponent(resource)>
1563
+ */
1564
+ declare function buildMcpProxyUrl(options: McpProxyUrlOptions): string;
1565
+ /**
1566
+ * Build a stable cache key (base64url) for MCP UI HTML content.
1567
+ * Combines flowId + context resourceUri + resourceUri to avoid collisions.
1568
+ */
1569
+ declare function buildMcpCacheKey(opts: {
1570
+ flowId?: string;
1571
+ contextResourceUri?: string;
1572
+ resourceUri: string;
1573
+ }): string;
1918
1574
 
1919
1575
  /**
1920
1576
  * Canvas types for inline canvas cards in chat widgets
@@ -2161,4 +1817,4 @@ declare function useBotDojoCanvas(): UseBotDojoCanvasReturn;
2161
1817
  /** @deprecated Use AppAction instead */
2162
1818
  type CanvasAction = AppAction;
2163
1819
 
2164
- export { type AppAction, type AppContextValue, type AppEvent, BotDojoCanvasFrame, type BotDojoCanvasFrameProps, BotDojoCanvasProvider, type BotDojoCanvasProviderProps, BotDojoChat, type BotDojoChatConfig, BotDojoChatConfigurator, type BotDojoChatConfiguratorProps, type BotDojoChatControl, type BotDojoChatDisplayMode, type BotDojoChatHook, type BotDojoChatProps, BotDojoChatProvider, type BotDojoChatProviderProps, type CanvasAction, type CanvasActionOptions, type CanvasEvent, type CanvasMode, type ChatActionsHook, type ChatConfig, type ChatMessage, type ChatMessagesHook, type ChatStatus, type ChatStatusHook, type CitationData, type ContentItem, type HeadlessAction, HeadlessChat, type HeadlessChatHandle, type HeadlessChatProps, type HeadlessChatState, type HeadlessEvent, type HeadlessMessageEvent, type HeadlessStatusEvent, type HeadlessStepEvent, type HeadlessTokenEvent, MIME_TYPES, type McpAppData, McpAppHost, McpAppHostContext, type McpAppHostContextValue, type McpAppHostProps, McpAppHostProvider, type McpAppHostProviderProps, MockCanvasProvider, type MockCanvasProviderProps, type ModelContext, type ModelContextMessage, type ModelContextPrompt, type ModelContextResource, type PopupOptions, type ResourceContent, type ResourceProvider, type ResourceReference, type ResourceTemplate, type SidePanelOptions, type ToolDefinition, type ToolExecutionContext, type ToolExecutionResult, type ToolMetadata, type UiSize, type UseBotDojoCanvasReturn, extractMcpAppData, parseMaybeJson, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus, useMcpAppHost, useMcpAppHostRequired };
1820
+ export { type AppAction, type AppContextValue, type AppEvent, BotDojoCanvasFrame, type BotDojoCanvasFrameProps, BotDojoCanvasProvider, type BotDojoCanvasProviderProps, BotDojoChat, type BotDojoChatControl, type BotDojoChatDisplayMode, type BotDojoChatHook, type BotDojoChatProps, BotDojoChatProvider, type BotDojoChatProviderProps, BotDojoConnector$1 as BotDojoConnector, type CanvasAction, type CanvasActionOptions, type CanvasEvent, type CanvasMode, type ChatActionsHook, type ChatConfig, type ChatMessage, type ChatMessagesHook, type ChatStatus, type ChatStatusHook, DEFAULT_MCP_HOST_CAPABILITIES, type HeadlessAction, HeadlessChat, type HeadlessChatHandle, type HeadlessChatProps, type HeadlessChatState, type HeadlessEvent, type HeadlessMessageEvent, type HeadlessStatusEvent, type HeadlessStepEvent, type HeadlessTokenEvent, type IframeState, type McpAppData, McpAppHost, McpAppHostContext, type McpAppHostContextValue, type McpAppHostProps, McpAppHostProvider, type McpAppHostProviderProps, type McpHtmlProxyOptions, type McpProxyUrlOptions, MockCanvasProvider, type MockCanvasProviderProps, type PopupOptions, RequestEvents, type ResolvedUiCsp, type SidePanelOptions, type StepUpdate, type ToolInfo, type ToolNotification, type UiCspMeta, type UiSize, type UseBotDojoCanvasReturn, type UseMcpHostBridgeOptions, type UseMcpHostBridgeResult, buildMcpCacheKey, buildMcpProxyUrl, createMcpHtmlProxy, extractMcpAppData, extractUiCspFromResource, getContentKey, parseMaybeJson, processStepUpdate, resolveUiCsp, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus, useMcpAppHost, useMcpAppHostRequired, useMcpHostBridge, validateToolParams };