@botdojo/chat-sdk 0.0.20 → 0.0.22

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.js CHANGED
@@ -7695,6 +7695,7 @@ var require_AppBridge = __commonJS({
7695
7695
  this.pendingRequests = /* @__PURE__ */ new Map();
7696
7696
  this.nextRequestId = 0;
7697
7697
  this.sandboxResourceCache = /* @__PURE__ */ new Map();
7698
+ this.pendingSandboxRequests = /* @__PURE__ */ new Set();
7698
7699
  this.options = options;
7699
7700
  }
7700
7701
  async mount(container, appUrl) {
@@ -7749,6 +7750,7 @@ var require_AppBridge = __commonJS({
7749
7750
  this.isInitialized = false;
7750
7751
  this.pendingQueue = [];
7751
7752
  this.sandboxResourceCache.clear();
7753
+ this.pendingSandboxRequests.clear();
7752
7754
  }
7753
7755
  sendToolInputPartial(params) {
7754
7756
  console.log("[AppBridge] sendToolInputPartial:", params);
@@ -7977,27 +7979,6 @@ var require_AppBridge = __commonJS({
7977
7979
  await this.options.onAppMessage(params);
7978
7980
  }
7979
7981
  break;
7980
- case "ui/intent":
7981
- if (params && this.options.onAppIntent) {
7982
- this.options.onAppIntent(params);
7983
- }
7984
- break;
7985
- case "ui/prompt":
7986
- if (params && this.options.onAppPrompt) {
7987
- this.options.onAppPrompt(params);
7988
- }
7989
- break;
7990
- case "ui/notify":
7991
- case "ui/notifications/notify":
7992
- if (params && this.options.onAppNotify) {
7993
- this.options.onAppNotify(params);
7994
- }
7995
- break;
7996
- case "ui/update":
7997
- if (params && this.options.onAppUpdate) {
7998
- this.options.onAppUpdate(params);
7999
- }
8000
- break;
8001
7982
  case "ui/resource-teardown":
8002
7983
  result = { ok: true, teardown: true };
8003
7984
  break;
@@ -8043,14 +8024,19 @@ var require_AppBridge = __commonJS({
8043
8024
  const cacheKey = `${params.flowId || "unknown"}|${resource}`;
8044
8025
  if (this.sandboxResourceCache.has(cacheKey)) {
8045
8026
  const cached = this.sandboxResourceCache.get(cacheKey);
8046
- console.log("[AppBridge] \u{1F4E6} Using CACHED HTML for:", resource, "length:", (_a = cached.html) === null || _a === void 0 ? void 0 : _a.length);
8027
+ console.log("[AppBridge] \u{1F4E6} Using CACHED HTML for:", resource, "length:", (_a = cached.html) === null || _a === void 0 ? void 0 : _a.length, "(Safari reload?)");
8047
8028
  this.sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({ resource, flowId: params.flowId }, cached));
8048
8029
  this.sendInitializeWithRetry();
8049
8030
  return;
8050
8031
  }
8032
+ if (this.pendingSandboxRequests.has(cacheKey)) {
8033
+ console.log("[AppBridge] \u{1F4E6} Request already pending for:", resource, "skipping duplicate");
8034
+ return;
8035
+ }
8051
8036
  if (!this.options.onSandboxResourceRequest)
8052
8037
  return;
8053
8038
  try {
8039
+ this.pendingSandboxRequests.add(cacheKey);
8054
8040
  console.log("[AppBridge] \u{1F4E6} Fetching FRESH HTML for:", resource);
8055
8041
  const resolved = await this.options.onSandboxResourceRequest({ resource, flowId: params.flowId, canvasId: params.canvasId });
8056
8042
  const payload = typeof resolved === "string" ? { html: resolved } : resolved;
@@ -8068,6 +8054,8 @@ var require_AppBridge = __commonJS({
8068
8054
  }
8069
8055
  } catch (err) {
8070
8056
  console.warn("[AppBridge] Failed to resolve sandbox resource HTML", err);
8057
+ } finally {
8058
+ this.pendingSandboxRequests.delete(cacheKey);
8071
8059
  }
8072
8060
  }
8073
8061
  };
@@ -8129,13 +8117,13 @@ ${html}`;
8129
8117
  const encoded = typeof btoa === "function" ? btoa(unescape(encodeURIComponent(value2))) : typeof Buffer !== "undefined" ? Buffer.from(value2, "utf-8").toString("base64") : "";
8130
8118
  return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8131
8119
  }
8132
- function buildMcpProxyUrl(options) {
8120
+ function buildMcpProxyUrl2(options) {
8133
8121
  const origin = options.origin || "https://mcp-app-proxy.botdojo.com";
8134
8122
  const flowId = encodeURIComponent(options.flowId || "unknown");
8135
8123
  const encodedResource = encodeURIComponent(options.resource || "");
8136
8124
  return `${origin}/${flowId}/?url=${encodedResource}`;
8137
8125
  }
8138
- exports.buildMcpProxyUrl = buildMcpProxyUrl;
8126
+ exports.buildMcpProxyUrl = buildMcpProxyUrl2;
8139
8127
  function buildMcpCacheKey(opts) {
8140
8128
  const raw = `${opts.flowId || "unknown"}|${opts.contextResourceUri || ""}|${opts.resourceUri || ""}`;
8141
8129
  return toBase64Url(raw);
@@ -8144,11 +8132,609 @@ ${html}`;
8144
8132
  }
8145
8133
  });
8146
8134
 
8135
+ // ../sdk-canvas/lib/src/utils/index.js
8136
+ var require_utils = __commonJS({
8137
+ "../sdk-canvas/lib/src/utils/index.js"(exports) {
8138
+ Object.defineProperty(exports, "__esModule", { value: true });
8139
+ exports.processStepUpdate = exports.validateToolParams = exports.getContentKey = exports.parseMaybeJson = exports.DEFAULT_MCP_HOST_CAPABILITIES = void 0;
8140
+ exports.DEFAULT_MCP_HOST_CAPABILITIES = {
8141
+ openLinks: {},
8142
+ "botdojo/persistence": true,
8143
+ extensions: {
8144
+ "io.modelcontextprotocol/ui": {
8145
+ mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"]
8146
+ }
8147
+ }
8148
+ };
8149
+ function parseMaybeJson2(value2) {
8150
+ if (value2 === void 0 || value2 === null || value2 === "")
8151
+ return void 0;
8152
+ if (typeof value2 === "object")
8153
+ return value2;
8154
+ if (typeof value2 === "string" && value2.trim()) {
8155
+ try {
8156
+ return JSON.parse(value2);
8157
+ } catch (_a) {
8158
+ return value2;
8159
+ }
8160
+ }
8161
+ return value2;
8162
+ }
8163
+ exports.parseMaybeJson = parseMaybeJson2;
8164
+ function getContentKey(url2) {
8165
+ if (url2)
8166
+ return `url:${url2}`;
8167
+ return "empty";
8168
+ }
8169
+ exports.getContentKey = getContentKey;
8170
+ function validateToolParams(params, kind) {
8171
+ if (kind === "result") {
8172
+ const result = params === null || params === void 0 ? void 0 : params.result;
8173
+ return result !== void 0 && result !== "";
8174
+ }
8175
+ const args = params === null || params === void 0 ? void 0 : params.arguments;
8176
+ return args && args !== "" && typeof args === "object" && Object.keys(args).length > 0;
8177
+ }
8178
+ exports.validateToolParams = validateToolParams;
8179
+ function processStepUpdate(stepUpdate) {
8180
+ const notifications = [];
8181
+ const toolName = stepUpdate.stepToolName || stepUpdate.toolName;
8182
+ if (!toolName)
8183
+ return notifications;
8184
+ if (stepUpdate.stepToolProgress) {
8185
+ notifications.push({
8186
+ method: "ui/notifications/tool-input-partial",
8187
+ params: {
8188
+ tool: { name: toolName },
8189
+ arguments: Object.assign(Object.assign({}, stepUpdate.stepToolProgress), { _botdojoProgress: true })
8190
+ }
8191
+ });
8192
+ } else if (stepUpdate.toolPhase === "streaming_args" && (stepUpdate.stepId || stepUpdate.stepLabel)) {
8193
+ notifications.push({
8194
+ method: "ui/notifications/tool-input-partial",
8195
+ params: {
8196
+ tool: { name: toolName },
8197
+ arguments: Object.assign(Object.assign({}, stepUpdate.stepToolArguments || {}), { stepId: stepUpdate.stepId, stepLabel: stepUpdate.stepLabel })
8198
+ }
8199
+ });
8200
+ }
8201
+ if (stepUpdate.toolPhase === "executing" && stepUpdate.stepToolArguments) {
8202
+ const args = parseMaybeJson2(stepUpdate.stepToolArguments);
8203
+ if (args && typeof args === "object" && Object.keys(args).length > 0) {
8204
+ notifications.push({
8205
+ method: "ui/notifications/tool-input",
8206
+ params: {
8207
+ tool: { name: toolName },
8208
+ arguments: args
8209
+ }
8210
+ });
8211
+ }
8212
+ }
8213
+ const result = parseMaybeJson2(stepUpdate.stepToolResult);
8214
+ if (result !== void 0 && result !== "") {
8215
+ notifications.push({
8216
+ method: "ui/notifications/tool-result",
8217
+ params: {
8218
+ tool: { name: toolName },
8219
+ result
8220
+ }
8221
+ });
8222
+ }
8223
+ return notifications;
8224
+ }
8225
+ exports.processStepUpdate = processStepUpdate;
8226
+ }
8227
+ });
8228
+
8229
+ // ../sdk-canvas/lib/src/hooks/useMcpHostBridge.js
8230
+ var require_useMcpHostBridge = __commonJS({
8231
+ "../sdk-canvas/lib/src/hooks/useMcpHostBridge.js"(exports) {
8232
+ Object.defineProperty(exports, "__esModule", { value: true });
8233
+ exports.useMcpHostBridge = void 0;
8234
+ var react_1 = __require("react");
8235
+ var utils_1 = require_utils();
8236
+ function useMcpHostBridge2(options) {
8237
+ const { appId, html, url: url2, toolInfo, arguments: toolArguments, result: toolResult, state, isComplete, onOpenLink, onToolCall, onMessage, onPersistState, onSizeChange, onReady, hostContext, debug = false, onSandboxResourceRequest } = options;
8238
+ const iframeRef = (0, react_1.useRef)(null);
8239
+ const [iframeState, setIframeState] = (0, react_1.useState)("idle");
8240
+ const [autoHeight, setAutoHeight] = (0, react_1.useState)(null);
8241
+ const [renderError, setRenderError] = (0, react_1.useState)(null);
8242
+ const [initFailed, setInitFailed] = (0, react_1.useState)(false);
8243
+ const [initError, setInitError] = (0, react_1.useState)(null);
8244
+ const pendingRequestsRef = (0, react_1.useRef)(/* @__PURE__ */ new Map());
8245
+ const nextRequestIdRef = (0, react_1.useRef)(0);
8246
+ const initializeAttemptsRef = (0, react_1.useRef)(0);
8247
+ const initializeTimerRef = (0, react_1.useRef)(null);
8248
+ const pendingNotificationsRef = (0, react_1.useRef)([]);
8249
+ const sandboxResourceCacheRef = (0, react_1.useRef)(/* @__PURE__ */ new Map());
8250
+ const iframeStateRef = (0, react_1.useRef)(iframeState);
8251
+ iframeStateRef.current = iframeState;
8252
+ const contentKey = (0, react_1.useMemo)(() => url2 ? `url:${url2}` : "empty", [url2]);
8253
+ const renderedContentKeyRef = (0, react_1.useRef)("");
8254
+ const [iframeSrc, setIframeSrc] = (0, react_1.useState)(void 0);
8255
+ const canRender = !!iframeSrc && !renderError;
8256
+ const log = (0, react_1.useCallback)((...args) => {
8257
+ if (debug) {
8258
+ console.log(`[useMcpHostBridge:${appId}]`, ...args);
8259
+ }
8260
+ }, [debug, appId]);
8261
+ const sendResponse = (0, react_1.useCallback)((id, result) => {
8262
+ var _a;
8263
+ if (!((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow))
8264
+ return;
8265
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", id, result }, "*");
8266
+ }, []);
8267
+ const sendError = (0, react_1.useCallback)((id, code, message) => {
8268
+ var _a;
8269
+ if (!((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow))
8270
+ return;
8271
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", id, error: { code, message } }, "*");
8272
+ }, []);
8273
+ const sendNotification = (0, react_1.useCallback)((method, params) => {
8274
+ var _a;
8275
+ if (!((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow))
8276
+ return;
8277
+ log("Sending notification:", method);
8278
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method, params }, "*");
8279
+ }, [log]);
8280
+ const sendRequest = (0, react_1.useCallback)((method, params, timeout = 5e3) => {
8281
+ return new Promise((resolve, reject) => {
8282
+ var _a;
8283
+ if (!((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow)) {
8284
+ reject(new Error("Iframe not ready"));
8285
+ return;
8286
+ }
8287
+ const id = `host-${++nextRequestIdRef.current}`;
8288
+ const timer = setTimeout(() => {
8289
+ pendingRequestsRef.current.delete(id);
8290
+ reject(new Error(`Request timeout: ${method}`));
8291
+ }, timeout);
8292
+ pendingRequestsRef.current.set(id, { resolve, reject, timer });
8293
+ log("Sending request:", method);
8294
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
8295
+ });
8296
+ }, [log]);
8297
+ const sendToolNotification = (0, react_1.useCallback)((method, params) => {
8298
+ var _a;
8299
+ const kind = method.includes("result") ? "result" : method.includes("partial") ? "partial" : "input";
8300
+ if (!(0, utils_1.validateToolParams)(params, kind)) {
8301
+ log("Skipping invalid notification:", method);
8302
+ return;
8303
+ }
8304
+ if (iframeStateRef.current === "ready" && ((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow)) {
8305
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method, params }, "*");
8306
+ } else {
8307
+ pendingNotificationsRef.current.push({ method, params });
8308
+ }
8309
+ }, [log]);
8310
+ const sendStepUpdate = (0, react_1.useCallback)((stepUpdate) => {
8311
+ const notifications = (0, utils_1.processStepUpdate)(stepUpdate);
8312
+ notifications.forEach(({ method, params }) => {
8313
+ sendToolNotification(method, params);
8314
+ });
8315
+ }, [sendToolNotification]);
8316
+ const sendInitialize = (0, react_1.useCallback)(() => {
8317
+ var _a;
8318
+ if (iframeStateRef.current === "ready" || !((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow))
8319
+ return;
8320
+ const context = Object.assign({
8321
+ mcpAppId: appId,
8322
+ state,
8323
+ toolInfo
8324
+ }, hostContext);
8325
+ const params = {
8326
+ protocolVersion: "mcp-apps/0.1",
8327
+ appInfo: { name: "McpAppHost", version: "1.0.0" },
8328
+ hostCapabilities: utils_1.DEFAULT_MCP_HOST_CAPABILITIES,
8329
+ hostContext: context
8330
+ };
8331
+ log("Sending ui/initialize");
8332
+ sendRequest("ui/initialize", params, 2e3).catch((err) => {
8333
+ log("ui/initialize failed:", err.message);
8334
+ });
8335
+ }, [appId, state, toolInfo, hostContext, log, sendRequest]);
8336
+ const sendInitializeWithRetry = (0, react_1.useCallback)(() => {
8337
+ if (iframeStateRef.current === "ready")
8338
+ return;
8339
+ const attemptSend = () => {
8340
+ if (iframeStateRef.current === "ready")
8341
+ return;
8342
+ initializeAttemptsRef.current += 1;
8343
+ sendInitialize();
8344
+ if (initializeAttemptsRef.current < 5) {
8345
+ initializeTimerRef.current = setTimeout(attemptSend, 300);
8346
+ } else {
8347
+ initializeTimerRef.current = null;
8348
+ log("Max initialize attempts reached");
8349
+ }
8350
+ };
8351
+ if (initializeTimerRef.current !== null) {
8352
+ clearTimeout(initializeTimerRef.current);
8353
+ }
8354
+ initializeAttemptsRef.current = 0;
8355
+ attemptSend();
8356
+ }, [sendInitialize, log]);
8357
+ const sendHydrationData = (0, react_1.useCallback)(() => {
8358
+ var _a, _b;
8359
+ const toolName = (_a = toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.tool) === null || _a === void 0 ? void 0 : _a.name;
8360
+ if (!toolName || !((_b = iframeRef.current) === null || _b === void 0 ? void 0 : _b.contentWindow))
8361
+ return;
8362
+ const args = (0, utils_1.parseMaybeJson)(toolArguments);
8363
+ const result = (0, utils_1.parseMaybeJson)(toolResult);
8364
+ log("Sending hydration data:", { toolName, hasArgs: !!args, hasResult: !!result });
8365
+ if (args && typeof args === "object" && Object.keys(args).length > 0) {
8366
+ iframeRef.current.contentWindow.postMessage({
8367
+ jsonrpc: "2.0",
8368
+ method: "ui/notifications/tool-input",
8369
+ params: { tool: { name: toolName }, arguments: args }
8370
+ }, "*");
8371
+ }
8372
+ if (result !== void 0 && result !== "") {
8373
+ iframeRef.current.contentWindow.postMessage({
8374
+ jsonrpc: "2.0",
8375
+ method: "ui/notifications/tool-result",
8376
+ params: { tool: { name: toolName }, result }
8377
+ }, "*");
8378
+ } else if (isComplete) {
8379
+ iframeRef.current.contentWindow.postMessage({
8380
+ jsonrpc: "2.0",
8381
+ method: "ui/notifications/tool-result",
8382
+ params: { tool: { name: toolName }, result: { completed: true } }
8383
+ }, "*");
8384
+ }
8385
+ }, [toolInfo, toolArguments, toolResult, isComplete, log]);
8386
+ const handleMessage = (0, react_1.useCallback)((event) => {
8387
+ var _a;
8388
+ if (debug) {
8389
+ console.log(`[useMcpHostBridge:${appId}] raw message`, { origin: event.origin, data: event.data });
8390
+ }
8391
+ if (!event.data || event.data.jsonrpc !== "2.0")
8392
+ return;
8393
+ const data = event.data;
8394
+ if ("id" in data && !("method" in data)) {
8395
+ const pending = pendingRequestsRef.current.get(String(data.id));
8396
+ if (pending) {
8397
+ if (pending.timer)
8398
+ clearTimeout(pending.timer);
8399
+ pendingRequestsRef.current.delete(String(data.id));
8400
+ if ("error" in data) {
8401
+ pending.reject(data.error);
8402
+ } else {
8403
+ pending.resolve(data.result);
8404
+ }
8405
+ }
8406
+ return;
8407
+ }
8408
+ const { method, params, id } = data;
8409
+ log("Received:", method);
8410
+ switch (method) {
8411
+ case "ui/notifications/client-ready": {
8412
+ log("App reported client-ready; triggering initialize");
8413
+ sendInitializeWithRetry();
8414
+ break;
8415
+ }
8416
+ case "ui/notifications/sandbox-ready":
8417
+ case "ui/notifications/sandbox-proxy-ready": {
8418
+ log("Proxy reported sandbox-ready");
8419
+ const resource = params === null || params === void 0 ? void 0 : params.resource;
8420
+ if (resource && html) {
8421
+ log("Sending sandbox-resource-ready with inline HTML for:", resource);
8422
+ sendNotification("ui/notifications/sandbox-resource-ready", {
8423
+ resource,
8424
+ html,
8425
+ sandbox: "allow-scripts allow-same-origin"
8426
+ });
8427
+ }
8428
+ break;
8429
+ }
8430
+ case "ui/requests/sandbox-resource": {
8431
+ const resource = params === null || params === void 0 ? void 0 : params.resource;
8432
+ const flowId = params === null || params === void 0 ? void 0 : params.flowId;
8433
+ log("Proxy requesting sandbox-resource:", resource);
8434
+ if (!resource)
8435
+ break;
8436
+ const cacheKey = `${flowId || "unknown"}|${resource}`;
8437
+ if (sandboxResourceCacheRef.current.has(cacheKey)) {
8438
+ const cached = sandboxResourceCacheRef.current.get(cacheKey);
8439
+ log("Using cached sandbox resource for:", resource);
8440
+ sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({
8441
+ resource,
8442
+ flowId
8443
+ }, cached));
8444
+ break;
8445
+ }
8446
+ if (html) {
8447
+ log("Using inline HTML for sandbox-resource:", resource);
8448
+ const entry = {
8449
+ html,
8450
+ sandbox: "allow-scripts allow-same-origin"
8451
+ };
8452
+ sandboxResourceCacheRef.current.set(cacheKey, entry);
8453
+ sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({
8454
+ resource,
8455
+ flowId
8456
+ }, entry));
8457
+ break;
8458
+ }
8459
+ if (onSandboxResourceRequest) {
8460
+ (async () => {
8461
+ try {
8462
+ log("Calling onSandboxResourceRequest for:", resource);
8463
+ const resolved = await onSandboxResourceRequest({ resource, flowId });
8464
+ const payload = typeof resolved === "string" ? { html: resolved } : resolved;
8465
+ if (payload === null || payload === void 0 ? void 0 : payload.html) {
8466
+ log("Got HTML from onSandboxResourceRequest for:", resource, "length:", payload.html.length);
8467
+ const entry = {
8468
+ html: payload.html,
8469
+ sandbox: payload.sandbox || "allow-scripts allow-same-origin",
8470
+ csp: payload.csp
8471
+ };
8472
+ sandboxResourceCacheRef.current.set(cacheKey, entry);
8473
+ sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({
8474
+ resource,
8475
+ flowId
8476
+ }, entry));
8477
+ } else {
8478
+ log("onSandboxResourceRequest returned no HTML for:", resource);
8479
+ }
8480
+ } catch (err) {
8481
+ console.warn("[useMcpHostBridge] Failed to resolve sandbox resource:", err);
8482
+ }
8483
+ })();
8484
+ } else {
8485
+ log("No onSandboxResourceRequest handler and no inline HTML for:", resource);
8486
+ }
8487
+ break;
8488
+ }
8489
+ case "ui/notifications/initialized": {
8490
+ log("App confirmed initialization");
8491
+ if (initializeTimerRef.current !== null) {
8492
+ clearTimeout(initializeTimerRef.current);
8493
+ initializeTimerRef.current = null;
8494
+ }
8495
+ setIframeState("ready");
8496
+ sendHydrationData();
8497
+ if (pendingNotificationsRef.current.length > 0 && ((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow)) {
8498
+ log(`Replaying ${pendingNotificationsRef.current.length} queued notifications`);
8499
+ pendingNotificationsRef.current.forEach(({ method: method2, params: params2 }) => {
8500
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method: method2, params: params2 }, "*");
8501
+ });
8502
+ pendingNotificationsRef.current = [];
8503
+ }
8504
+ onReady === null || onReady === void 0 ? void 0 : onReady();
8505
+ break;
8506
+ }
8507
+ case "ui/initialize": {
8508
+ log("Handling ui/initialize request from app");
8509
+ sendResponse(id, {
8510
+ appInfo: { name: "McpAppHost", version: "1.0.0" },
8511
+ hostCapabilities: utils_1.DEFAULT_MCP_HOST_CAPABILITIES,
8512
+ hostContext: Object.assign({ state, toolInfo }, hostContext)
8513
+ });
8514
+ sendNotification("ui/notifications/initialized", {});
8515
+ if (initializeTimerRef.current !== null) {
8516
+ clearTimeout(initializeTimerRef.current);
8517
+ initializeTimerRef.current = null;
8518
+ }
8519
+ setIframeState("ready");
8520
+ onReady === null || onReady === void 0 ? void 0 : onReady();
8521
+ break;
8522
+ }
8523
+ case "ui/open-link": {
8524
+ if (params === null || params === void 0 ? void 0 : params.url) {
8525
+ onOpenLink === null || onOpenLink === void 0 ? void 0 : onOpenLink(params.url, params.target || "_blank");
8526
+ }
8527
+ if (id !== void 0) {
8528
+ sendResponse(id, { ok: true });
8529
+ }
8530
+ break;
8531
+ }
8532
+ case "tools/call": {
8533
+ const toolName = (params === null || params === void 0 ? void 0 : params.name) || (params === null || params === void 0 ? void 0 : params.tool);
8534
+ const toolParams = (params === null || params === void 0 ? void 0 : params.arguments) || (params === null || params === void 0 ? void 0 : params.params) || {};
8535
+ if (onToolCall && toolName) {
8536
+ Promise.resolve(onToolCall(toolName, toolParams)).then((result) => {
8537
+ if (id !== void 0) {
8538
+ sendResponse(id, result !== null && result !== void 0 ? result : { ok: true });
8539
+ }
8540
+ }).catch((err) => {
8541
+ if (id !== void 0) {
8542
+ sendError(id, -32e3, err.message || "Tool execution failed");
8543
+ }
8544
+ });
8545
+ } else {
8546
+ if (id !== void 0) {
8547
+ sendResponse(id, { ok: false, error: "No tool handler" });
8548
+ }
8549
+ }
8550
+ break;
8551
+ }
8552
+ case "ui/message": {
8553
+ const contentArray = Array.isArray(params === null || params === void 0 ? void 0 : params.content) ? params.content : [params === null || params === void 0 ? void 0 : params.content].filter(Boolean);
8554
+ const firstContent = contentArray[0];
8555
+ if ((firstContent === null || firstContent === void 0 ? void 0 : firstContent["botdojo/messageType"]) === "persist-state" && typeof firstContent.text === "string") {
8556
+ try {
8557
+ const parsed = JSON.parse(firstContent.text);
8558
+ onPersistState === null || onPersistState === void 0 ? void 0 : onPersistState(parsed);
8559
+ } catch (_b) {
8560
+ }
8561
+ if (id !== void 0)
8562
+ sendResponse(id, { ok: true });
8563
+ break;
8564
+ }
8565
+ if ((firstContent === null || firstContent === void 0 ? void 0 : firstContent.type) === "botdojo/persist" && firstContent.state) {
8566
+ onPersistState === null || onPersistState === void 0 ? void 0 : onPersistState(firstContent.state);
8567
+ if (id !== void 0)
8568
+ sendResponse(id, { ok: true });
8569
+ break;
8570
+ }
8571
+ const text = (firstContent === null || firstContent === void 0 ? void 0 : firstContent.text) || JSON.stringify(params);
8572
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(text, params);
8573
+ if (id !== void 0)
8574
+ sendResponse(id, { ok: true });
8575
+ break;
8576
+ }
8577
+ case "ui/size-change":
8578
+ case "ui/notifications/size-change": {
8579
+ if (params === null || params === void 0 ? void 0 : params.height) {
8580
+ setAutoHeight(params.height);
8581
+ }
8582
+ if ((params === null || params === void 0 ? void 0 : params.width) && (params === null || params === void 0 ? void 0 : params.height)) {
8583
+ onSizeChange === null || onSizeChange === void 0 ? void 0 : onSizeChange(params.width, params.height);
8584
+ }
8585
+ break;
8586
+ }
8587
+ default: {
8588
+ if (id !== void 0) {
8589
+ sendResponse(id, { ok: true, ignored: true });
8590
+ }
8591
+ }
8592
+ }
8593
+ }, [
8594
+ log,
8595
+ state,
8596
+ toolInfo,
8597
+ hostContext,
8598
+ html,
8599
+ onOpenLink,
8600
+ onToolCall,
8601
+ onMessage,
8602
+ onPersistState,
8603
+ onSizeChange,
8604
+ onReady,
8605
+ onSandboxResourceRequest,
8606
+ sendResponse,
8607
+ sendError,
8608
+ sendNotification,
8609
+ sendHydrationData,
8610
+ sendInitializeWithRetry
8611
+ ]);
8612
+ (0, react_1.useEffect)(() => {
8613
+ window.addEventListener("message", handleMessage);
8614
+ return () => window.removeEventListener("message", handleMessage);
8615
+ }, [handleMessage]);
8616
+ (0, react_1.useEffect)(() => {
8617
+ log("Content effect running:", { contentKey, renderedContentKey: renderedContentKeyRef.current, url: url2 });
8618
+ if (contentKey === renderedContentKeyRef.current) {
8619
+ log("Skipping - content key unchanged");
8620
+ return;
8621
+ }
8622
+ if (contentKey === "empty" && renderedContentKeyRef.current !== "" && iframeSrc) {
8623
+ log("URL became empty but iframe has content, preserving");
8624
+ return;
8625
+ }
8626
+ log("Content key changed:", { old: renderedContentKeyRef.current, new: contentKey });
8627
+ renderedContentKeyRef.current = contentKey;
8628
+ setIframeState("idle");
8629
+ setAutoHeight(null);
8630
+ setInitFailed(false);
8631
+ setInitError(null);
8632
+ initializeAttemptsRef.current = 0;
8633
+ pendingNotificationsRef.current = [];
8634
+ if (initializeTimerRef.current !== null) {
8635
+ clearTimeout(initializeTimerRef.current);
8636
+ initializeTimerRef.current = null;
8637
+ }
8638
+ if (url2) {
8639
+ log("Using proxy URL:", url2);
8640
+ setIframeSrc(url2);
8641
+ setRenderError(null);
8642
+ } else {
8643
+ log("No URL provided - parent must build proxy URL for ui:// resources");
8644
+ setIframeSrc(void 0);
8645
+ setRenderError("No proxy URL available for MCP App");
8646
+ }
8647
+ }, [contentKey, url2, log, iframeSrc]);
8648
+ (0, react_1.useEffect)(() => {
8649
+ if (iframeState === "loading") {
8650
+ log("Iframe loaded, sending ui/initialize");
8651
+ setIframeState("initializing");
8652
+ sendInitializeWithRetry();
8653
+ }
8654
+ }, [iframeState, sendInitializeWithRetry, log]);
8655
+ (0, react_1.useEffect)(() => {
8656
+ if (iframeState === "initializing") {
8657
+ const timeout = setTimeout(() => {
8658
+ if (iframeStateRef.current === "initializing") {
8659
+ log("Initialization timeout after 5 seconds");
8660
+ setIframeState("idle");
8661
+ setInitFailed(true);
8662
+ setInitError("MCP App initialization timed out after 5 seconds");
8663
+ }
8664
+ }, 5e3);
8665
+ return () => clearTimeout(timeout);
8666
+ } else if (iframeState === "ready") {
8667
+ setInitFailed(false);
8668
+ setInitError(null);
8669
+ }
8670
+ }, [iframeState, log]);
8671
+ const resetIframe = (0, react_1.useCallback)(() => {
8672
+ log("Resetting iframe for retry");
8673
+ setInitFailed(false);
8674
+ setInitError(null);
8675
+ setRenderError(null);
8676
+ renderedContentKeyRef.current = "";
8677
+ setIframeState("idle");
8678
+ setIframeSrc(void 0);
8679
+ setTimeout(() => {
8680
+ if (url2) {
8681
+ setIframeSrc(url2);
8682
+ }
8683
+ }, 0);
8684
+ }, [log, url2]);
8685
+ (0, react_1.useEffect)(() => {
8686
+ return () => {
8687
+ if (initializeTimerRef.current !== null) {
8688
+ clearTimeout(initializeTimerRef.current);
8689
+ }
8690
+ pendingRequestsRef.current.forEach(({ timer, reject }) => {
8691
+ if (timer)
8692
+ clearTimeout(timer);
8693
+ reject(new Error("Component unmounted"));
8694
+ });
8695
+ pendingRequestsRef.current.clear();
8696
+ };
8697
+ }, []);
8698
+ const handleIframeLoad = (0, react_1.useCallback)(() => {
8699
+ log("Iframe onLoad fired");
8700
+ setIframeState((prev2) => prev2 === "idle" ? "loading" : prev2);
8701
+ }, [log]);
8702
+ return {
8703
+ iframeRef,
8704
+ status: iframeState,
8705
+ autoHeight,
8706
+ handleIframeLoad,
8707
+ sendToolNotification,
8708
+ sendStepUpdate,
8709
+ iframeSrc,
8710
+ renderError,
8711
+ canRender,
8712
+ initFailed,
8713
+ initError,
8714
+ resetIframe
8715
+ };
8716
+ }
8717
+ exports.useMcpHostBridge = useMcpHostBridge2;
8718
+ }
8719
+ });
8720
+
8721
+ // ../sdk-canvas/lib/src/hooks/index.js
8722
+ var require_hooks = __commonJS({
8723
+ "../sdk-canvas/lib/src/hooks/index.js"(exports) {
8724
+ Object.defineProperty(exports, "__esModule", { value: true });
8725
+ exports.useMcpHostBridge = void 0;
8726
+ var useMcpHostBridge_1 = require_useMcpHostBridge();
8727
+ Object.defineProperty(exports, "useMcpHostBridge", { enumerable: true, get: function() {
8728
+ return useMcpHostBridge_1.useMcpHostBridge;
8729
+ } });
8730
+ }
8731
+ });
8732
+
8147
8733
  // ../sdk-canvas/lib/src/index.js
8148
8734
  var require_src3 = __commonJS({
8149
8735
  "../sdk-canvas/lib/src/index.js"(exports) {
8150
8736
  Object.defineProperty(exports, "__esModule", { value: true });
8151
- exports.extractUiCspFromResource = exports.resolveUiCsp = exports.buildMcpCacheKey = exports.buildMcpProxyUrl = exports.createMcpHtmlProxy = exports.PostMessageTransport = exports.AppBridge = exports.unregisterModelContext = exports.registerModelContext = exports.useCanvas = exports.BotDojoCanvasProvider = exports.BotDojoCanvasClient = exports.RequestEvents = exports.BotDojoConnector = exports.MIME_TYPES = exports.citations = exports.citation = exports.mcpResource = exports.uiResource = exports.imageResult = exports.textResult = void 0;
8737
+ exports.useMcpHostBridge = exports.processStepUpdate = exports.validateToolParams = exports.getContentKey = exports.parseMaybeJson = exports.DEFAULT_MCP_HOST_CAPABILITIES = exports.extractUiCspFromResource = exports.resolveUiCsp = exports.buildMcpCacheKey = exports.buildMcpProxyUrl = exports.createMcpHtmlProxy = exports.PostMessageTransport = exports.AppBridge = exports.unregisterModelContext = exports.registerModelContext = exports.useCanvas = exports.BotDojoCanvasProvider = exports.BotDojoCanvasClient = exports.RequestEvents = exports.BotDojoConnector = exports.MIME_TYPES = exports.citations = exports.citation = exports.mcpResource = exports.uiResource = exports.imageResult = exports.textResult = void 0;
8152
8738
  var sdk_types_1 = require_lib();
8153
8739
  Object.defineProperty(exports, "textResult", { enumerable: true, get: function() {
8154
8740
  return sdk_types_1.textResult;
@@ -8220,6 +8806,26 @@ var require_src3 = __commonJS({
8220
8806
  Object.defineProperty(exports, "extractUiCspFromResource", { enumerable: true, get: function() {
8221
8807
  return uiCsp_1.extractUiCspFromResource;
8222
8808
  } });
8809
+ var utils_1 = require_utils();
8810
+ Object.defineProperty(exports, "DEFAULT_MCP_HOST_CAPABILITIES", { enumerable: true, get: function() {
8811
+ return utils_1.DEFAULT_MCP_HOST_CAPABILITIES;
8812
+ } });
8813
+ Object.defineProperty(exports, "parseMaybeJson", { enumerable: true, get: function() {
8814
+ return utils_1.parseMaybeJson;
8815
+ } });
8816
+ Object.defineProperty(exports, "getContentKey", { enumerable: true, get: function() {
8817
+ return utils_1.getContentKey;
8818
+ } });
8819
+ Object.defineProperty(exports, "validateToolParams", { enumerable: true, get: function() {
8820
+ return utils_1.validateToolParams;
8821
+ } });
8822
+ Object.defineProperty(exports, "processStepUpdate", { enumerable: true, get: function() {
8823
+ return utils_1.processStepUpdate;
8824
+ } });
8825
+ var hooks_1 = require_hooks();
8826
+ Object.defineProperty(exports, "useMcpHostBridge", { enumerable: true, get: function() {
8827
+ return hooks_1.useMcpHostBridge;
8828
+ } });
8223
8829
  }
8224
8830
  });
8225
8831
 
@@ -8305,7 +8911,13 @@ var BotDojoChat = ({
8305
8911
  const connectorRef = useRef(null);
8306
8912
  const iframeLoadedRef = useRef(false);
8307
8913
  const chatReadyRef = useRef(false);
8914
+ const chatReadyFiredRef = useRef(false);
8308
8915
  const resizeStartPos = useRef({ x: 0, y: 0, width: 0, height: 0 });
8916
+ const modelContextCapturedRef = useRef(false);
8917
+ const modelContextRef = useRef(modelContext2);
8918
+ useEffect(() => {
8919
+ modelContextRef.current = modelContext2;
8920
+ }, [modelContext2]);
8309
8921
  const eventHandlersRef = useRef({
8310
8922
  onReady,
8311
8923
  onError,
@@ -8350,6 +8962,28 @@ var BotDojoChat = ({
8350
8962
  onToolCall,
8351
8963
  onUiMessage
8352
8964
  ]);
8965
+ const rpcReadyRef = useRef(false);
8966
+ const [rpcTrigger, setRpcTrigger] = useState(0);
8967
+ useEffect(() => {
8968
+ const handleEarlyMessages = (event) => {
8969
+ const data = event.data;
8970
+ if ((data == null ? void 0 : data.type) !== "botdojo-rpc")
8971
+ return;
8972
+ const payload = data.payload;
8973
+ if ((payload == null ? void 0 : payload.functionName) === "chat_ready") {
8974
+ console.log("[BotDojoChat] Early listener captured chat_ready");
8975
+ chatReadyRef.current = true;
8976
+ if (!iframeLoadedRef.current) {
8977
+ console.log("[BotDojoChat] Setting iframeLoaded=true (inferred from chat_ready)");
8978
+ iframeLoadedRef.current = true;
8979
+ setIframeLoaded(true);
8980
+ setRpcTrigger((t) => t + 1);
8981
+ }
8982
+ }
8983
+ };
8984
+ window.addEventListener("message", handleEarlyMessages);
8985
+ return () => window.removeEventListener("message", handleEarlyMessages);
8986
+ }, []);
8353
8987
  const hasModelContextContent = useMemo(() => {
8354
8988
  if (!modelContext2)
8355
8989
  return false;
@@ -8868,7 +9502,10 @@ var BotDojoChat = ({
8868
9502
  }, [getBaseUrl]);
8869
9503
  useEffect(() => {
8870
9504
  var _a;
8871
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || !iframeLoaded) {
9505
+ if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
9506
+ return;
9507
+ }
9508
+ if (!iframeLoaded && !iframeLoadedRef.current) {
8872
9509
  return;
8873
9510
  }
8874
9511
  const initializeConnection = async () => {
@@ -8912,12 +9549,15 @@ var BotDojoChat = ({
8912
9549
  if (msg.functionName === "chat_ready") {
8913
9550
  console.log("[BotDojoChat] Chat is ready for flow requests");
8914
9551
  chatReadyRef.current = true;
8915
- const handlers2 = eventHandlersRef.current;
8916
- if (handlers2.onReady) {
8917
- try {
8918
- handlers2.onReady();
8919
- } catch (e) {
8920
- console.error("[BotDojoChat] Error in onReady:", e);
9552
+ if (!chatReadyFiredRef.current) {
9553
+ chatReadyFiredRef.current = true;
9554
+ const handlers2 = eventHandlersRef.current;
9555
+ if (handlers2.onReady) {
9556
+ try {
9557
+ handlers2.onReady();
9558
+ } catch (e) {
9559
+ console.error("[BotDojoChat] Error in onReady:", e);
9560
+ }
8921
9561
  }
8922
9562
  }
8923
9563
  return;
@@ -9091,9 +9731,28 @@ var BotDojoChat = ({
9091
9731
  }
9092
9732
  };
9093
9733
  const tryModelContext = async () => {
9094
- if (!uri || !modelContext2)
9734
+ let waited = 0;
9735
+ const maxWait = 3e3;
9736
+ while (waited < maxWait) {
9737
+ const currentContext = modelContextRef.current;
9738
+ if (currentContext) {
9739
+ const contexts2 = Array.isArray(currentContext) ? currentContext : [currentContext];
9740
+ const allResources2 = contexts2.flatMap((ctx) => ctx.resources || []);
9741
+ const hasMatchingResource = allResources2.some((r) => {
9742
+ return (r == null ? void 0 : r.uri) === uri || (r == null ? void 0 : r.uriTemplate) && matchesTemplate(r.uriTemplate, uri);
9743
+ });
9744
+ if (hasMatchingResource) {
9745
+ console.log("[BotDojoChat] tryModelContext: Found matching resource after", waited, "ms");
9746
+ break;
9747
+ }
9748
+ }
9749
+ await new Promise((r) => setTimeout(r, 50));
9750
+ waited += 50;
9751
+ }
9752
+ const currentModelContext = modelContextRef.current;
9753
+ if (!uri || !currentModelContext)
9095
9754
  return { error: "no modelContext" };
9096
- const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
9755
+ const contexts = Array.isArray(currentModelContext) ? currentModelContext : [currentModelContext];
9097
9756
  const allResources = contexts.flatMap((ctx) => ctx.resources || []);
9098
9757
  console.log("[BotDojoChat] tryModelContext: Searching", allResources.length, "resources for URI:", uri);
9099
9758
  allResources.forEach((r, i2) => {
@@ -9107,7 +9766,7 @@ var BotDojoChat = ({
9107
9766
  return uriMatch || templateMatch;
9108
9767
  });
9109
9768
  if (!match) {
9110
- console.log("[BotDojoChat] tryModelContext: No match found");
9769
+ console.log("[BotDojoChat] tryModelContext: No match found after waiting", waited, "ms");
9111
9770
  return { error: "resource not found in modelContext" };
9112
9771
  }
9113
9772
  console.log("[BotDojoChat] tryModelContext: MATCH FOUND:", match.uri);
@@ -9314,19 +9973,35 @@ var BotDojoChat = ({
9314
9973
  }
9315
9974
  });
9316
9975
  connectionRef.current = connection;
9976
+ modelContextCapturedRef.current = !!modelContext2;
9317
9977
  console.log("[BotDojoChat] RPC connection initialized");
9978
+ if (!chatReadyFiredRef.current) {
9979
+ console.log("[BotDojoChat] RPC ready, firing onReady");
9980
+ chatReadyRef.current = true;
9981
+ chatReadyFiredRef.current = true;
9982
+ rpcReadyRef.current = true;
9983
+ const handlers = eventHandlersRef.current;
9984
+ if (handlers.onReady) {
9985
+ try {
9986
+ handlers.onReady();
9987
+ } catch (e) {
9988
+ console.error("[BotDojoChat] Error in onReady:", e);
9989
+ }
9990
+ }
9991
+ }
9318
9992
  } catch (error) {
9319
9993
  console.error("[BotDojoChat] Failed to initialize RPC connection:", error);
9320
9994
  }
9321
9995
  };
9322
9996
  initializeConnection();
9323
9997
  return () => {
9998
+ modelContextCapturedRef.current = false;
9324
9999
  if (connectionRef.current) {
9325
10000
  connectionRef.current.close();
9326
10001
  connectionRef.current = null;
9327
10002
  }
9328
10003
  };
9329
- }, [connector, iframeLoaded, modelContext2, apiKey]);
10004
+ }, [connector, iframeLoaded, modelContext2, apiKey, rpcTrigger]);
9330
10005
  const parseSize = useCallback((value2, defaultVal) => {
9331
10006
  if (!value2 || value2 === "auto")
9332
10007
  return defaultVal;
@@ -9429,6 +10104,7 @@ var BotDojoChat = ({
9429
10104
  setIframeLoaded(true);
9430
10105
  iframeLoadedRef.current = true;
9431
10106
  chatReadyRef.current = false;
10107
+ chatReadyFiredRef.current = false;
9432
10108
  setIsLoading(false);
9433
10109
  onLoad == null ? void 0 : onLoad();
9434
10110
  }, [onLoad]);
@@ -10201,6 +10877,8 @@ function BotDojoChatProvider(props) {
10201
10877
  onSessionHydrated,
10202
10878
  onConnectorInit,
10203
10879
  onConnectorError,
10880
+ // Debug mode for MCP App rendering
10881
+ debug = false,
10204
10882
  // MCP App handlers (SEP-1865)
10205
10883
  onOpenLink,
10206
10884
  onToolCall,
@@ -10228,6 +10906,7 @@ function BotDojoChatProvider(props) {
10228
10906
  const pendingBroadcastNotificationsRef = useRef([]);
10229
10907
  const toolArgumentsCacheRef = useRef(/* @__PURE__ */ new Map());
10230
10908
  const mcpAppDataCacheRef = useRef(/* @__PURE__ */ new Map());
10909
+ const [mcpAppDataVersion, setMcpAppDataVersion] = useState(0);
10231
10910
  const pendingStepUpdatesRef = useRef(/* @__PURE__ */ new Map());
10232
10911
  const appHandlersRef = useRef({
10233
10912
  onOpenLink,
@@ -10489,18 +11168,46 @@ function BotDojoChatProvider(props) {
10489
11168
  throw new Error(`Tool not found: ${toolName}`);
10490
11169
  }, []);
10491
11170
  const getMcpAppData = useCallback((appId) => {
11171
+ var _a, _b, _c, _d;
10492
11172
  const cached = mcpAppDataCacheRef.current.get(appId);
10493
- if (!cached)
10494
- return null;
10495
- return {
10496
- mcpAppId: appId,
10497
- mcpAppType: "mcp-app",
10498
- ...cached
10499
- };
10500
- }, []);
11173
+ if (cached == null ? void 0 : cached.url) {
11174
+ return { mcpAppId: appId, mcpAppType: "mcp-app", ...cached };
11175
+ }
11176
+ for (const msg of state.messages) {
11177
+ for (const step of msg.steps || []) {
11178
+ if (((_a = step.canvas) == null ? void 0 : _a.canvasId) === appId) {
11179
+ const canvasUrl = (_b = step.canvas.canvasData) == null ? void 0 : _b.url;
11180
+ let proxyUrl;
11181
+ if (canvasUrl == null ? void 0 : canvasUrl.startsWith("ui://")) {
11182
+ const flowId = step.flowId || step.flow_id || msg.messageId || "unknown";
11183
+ try {
11184
+ proxyUrl = (0, import_sdk_canvas3.buildMcpProxyUrl)({ flowId: String(flowId), resource: canvasUrl });
11185
+ } catch (err) {
11186
+ console.warn("[BotDojoChatProvider] Failed to build proxy URL for hydration:", err);
11187
+ }
11188
+ }
11189
+ return {
11190
+ mcpAppId: appId,
11191
+ mcpAppType: "mcp-app",
11192
+ url: proxyUrl || canvasUrl,
11193
+ // Proxy URL for ui://, direct URL otherwise
11194
+ toolInfo: step.stepToolName ? { tool: { name: step.stepToolName } } : void 0,
11195
+ arguments: step.stepToolArguments,
11196
+ result: step.stepToolResult,
11197
+ height: (_c = step.canvas.canvasData) == null ? void 0 : _c.height,
11198
+ width: (_d = step.canvas.canvasData) == null ? void 0 : _d.width,
11199
+ ...cached
11200
+ // Merge any partial cached data
11201
+ };
11202
+ }
11203
+ }
11204
+ }
11205
+ return cached ? { mcpAppId: appId, mcpAppType: "mcp-app", ...cached } : null;
11206
+ }, [state.messages]);
10501
11207
  const updateMcpAppDataCache = useCallback((appId, data) => {
10502
11208
  const existing = mcpAppDataCacheRef.current.get(appId) || {};
10503
11209
  mcpAppDataCacheRef.current.set(appId, { ...existing, ...data });
11210
+ setMcpAppDataVersion((v) => v + 1);
10504
11211
  }, []);
10505
11212
  const getResource = useCallback(async (uri, params, onlyMetadata) => {
10506
11213
  console.log("[BotDojoChatProvider] getResource called for URI:", uri);
@@ -10806,12 +11513,25 @@ ${htmlContent}`;
10806
11513
  }
10807
11514
  };
10808
11515
  console.log("[BotDojoChatProvider] \u2705 Resolved ui:// resource to HTML (" + htmlContent.length + " chars)");
11516
+ let proxyUrl;
11517
+ const proxyOrigin = process.env.NEXT_PUBLIC_MCP_HTML_PROXY_ORIGIN || void 0;
11518
+ const flowIdForProxy = (rawStep == null ? void 0 : rawStep.flowId) || (rawStep == null ? void 0 : rawStep.flow_id) || (rawStep == null ? void 0 : rawStep.messageId) || "unknown";
11519
+ try {
11520
+ proxyUrl = (0, import_sdk_canvas3.buildMcpProxyUrl)({
11521
+ flowId: String(flowIdForProxy),
11522
+ resource: canvasUrl,
11523
+ ...proxyOrigin ? { origin: proxyOrigin } : {}
11524
+ });
11525
+ console.log("[BotDojoChatProvider] Using MCP proxy URL:", proxyUrl);
11526
+ } catch (err) {
11527
+ console.warn("[BotDojoChatProvider] Failed to build MCP proxy URL", err);
11528
+ }
10809
11529
  const appIdForCache = rawStep.canvas.canvasId;
10810
11530
  if (appIdForCache) {
10811
11531
  const toolNameForCache = rawStep.stepToolName || rawStep.stepLabel;
10812
11532
  updateMcpAppDataCache(appIdForCache, {
10813
11533
  html: htmlContent,
10814
- url: canvasUrl,
11534
+ url: proxyUrl || canvasUrl,
10815
11535
  toolInfo: toolNameForCache ? { tool: { name: toolNameForCache } } : void 0,
10816
11536
  height: (_e = rawStep.canvas.canvasData) == null ? void 0 : _e.height,
10817
11537
  width: (_f = rawStep.canvas.canvasData) == null ? void 0 : _f.width
@@ -10951,9 +11671,12 @@ ${htmlContent}`;
10951
11671
  registerStepUpdateCallback,
10952
11672
  sendStepUpdateToApp,
10953
11673
  getMcpAppData,
10954
- appHandlers: appHandlersRef
11674
+ mcpAppDataVersion,
11675
+ getResource,
11676
+ appHandlers: appHandlersRef,
11677
+ debug
10955
11678
  }),
10956
- [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp, getMcpAppData]
11679
+ [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp, getMcpAppData, mcpAppDataVersion, getResource, debug]
10957
11680
  );
10958
11681
  return /* @__PURE__ */ jsxs(BotDojoChatContext.Provider, { value: contextValue, children: [
10959
11682
  children,
@@ -11122,6 +11845,9 @@ function BotDojoCanvasFrame(props) {
11122
11845
  }
11123
11846
  );
11124
11847
  }
11848
+
11849
+ // src/headless/components/McpAppHost.tsx
11850
+ var import_sdk_canvas4 = __toESM(require_src3());
11125
11851
  var McpAppHostContext = createContext(null);
11126
11852
  function McpAppHostProvider(props) {
11127
11853
  const { children, onOpenLink, onToolCall, onUiMessage, onPersistState, debug = false } = props;
@@ -11253,20 +11979,11 @@ function useMcpAppHostRequired() {
11253
11979
  }
11254
11980
  return context;
11255
11981
  }
11256
- function getContentKey(appHtml, appUrl) {
11257
- if (appUrl)
11258
- return `url:${appUrl}`;
11259
- if (appHtml) {
11260
- const prefix = appHtml.slice(0, 100);
11261
- const suffix = appHtml.slice(-100);
11262
- return `html:${appHtml.length}:${prefix}:${suffix}`;
11263
- }
11264
- return "empty";
11265
- }
11266
11982
  function McpAppHost(props) {
11267
- var _a;
11983
+ var _a, _b, _c;
11268
11984
  const {
11269
11985
  mcpAppId,
11986
+ resourceUri,
11270
11987
  onOpenLink,
11271
11988
  onToolCall,
11272
11989
  onUiMessage,
@@ -11277,583 +11994,191 @@ function McpAppHost(props) {
11277
11994
  height = "100%",
11278
11995
  style,
11279
11996
  initialHostContext,
11280
- debug = false
11997
+ debug: debugProp
11281
11998
  } = props;
11282
- const iframeRef = useRef(null);
11283
- const [iframeState, setIframeState] = useState("idle");
11284
- const [autoHeight, setAutoHeight] = useState(null);
11285
- const pendingRequestsRef = useRef(/* @__PURE__ */ new Map());
11286
- const nextRequestIdRef = useRef(0);
11287
- const initializeAttemptsRef = useRef(0);
11288
- const initializeTimerRef = useRef(null);
11289
11999
  const mcpAppHostContext = useMcpAppHost();
11290
12000
  const chatContext = useContext(BotDojoChatContext);
11291
- const pendingNotificationsRef = useRef([]);
11292
- const mcpAppData = (_a = chatContext == null ? void 0 : chatContext.getMcpAppData) == null ? void 0 : _a.call(chatContext, mcpAppId);
11293
- const appUrl = mcpAppData == null ? void 0 : mcpAppData.url;
11294
- const appHtml = mcpAppData == null ? void 0 : mcpAppData.html;
11295
- const contentKey = useMemo(() => getContentKey(appHtml, appUrl), [appHtml, appUrl]);
11296
- const renderedContentKeyRef = useRef("");
11297
- const currentBlobUrlRef = useRef(null);
11298
- const log = useCallback((...args) => {
11299
- if (debug) {
11300
- console.log(`[McpAppHost:${mcpAppId}]`, ...args);
11301
- }
11302
- }, [debug, mcpAppId]);
11303
- const sendResponse = useCallback((id, result) => {
11304
- var _a2;
11305
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11306
- return;
11307
- iframeRef.current.contentWindow.postMessage(
11308
- { jsonrpc: "2.0", id, result },
11309
- "*"
11310
- );
11311
- }, []);
11312
- const sendError = useCallback((id, code, message) => {
11313
- var _a2;
11314
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11315
- return;
11316
- iframeRef.current.contentWindow.postMessage(
11317
- { jsonrpc: "2.0", id, error: { code, message } },
11318
- "*"
11319
- );
11320
- }, []);
11321
- const sendNotification = useCallback((method, params) => {
11322
- var _a2;
11323
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11324
- return;
11325
- log("Sending notification:", method, params);
11326
- iframeRef.current.contentWindow.postMessage(
11327
- { jsonrpc: "2.0", method, params },
11328
- "*"
11329
- );
11330
- }, [log]);
11331
- const sendRequest = useCallback((method, params, timeout = 5e3) => {
11332
- return new Promise((resolve, reject) => {
11333
- var _a2;
11334
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11335
- reject(new Error("Iframe not ready"));
11336
- return;
11337
- }
11338
- const id = `host-${++nextRequestIdRef.current}`;
11339
- const timer = setTimeout(() => {
11340
- pendingRequestsRef.current.delete(id);
11341
- reject(new Error(`Request timeout: ${method}`));
11342
- }, timeout);
11343
- pendingRequestsRef.current.set(id, { resolve, reject, timer });
11344
- log("Sending request:", method, params);
11345
- iframeRef.current.contentWindow.postMessage(
11346
- { jsonrpc: "2.0", id, method, params },
11347
- "*"
11348
- );
12001
+ const getResource = chatContext == null ? void 0 : chatContext.getResource;
12002
+ const debug = (_a = debugProp != null ? debugProp : chatContext == null ? void 0 : chatContext.debug) != null ? _a : false;
12003
+ const _version = chatContext == null ? void 0 : chatContext.mcpAppDataVersion;
12004
+ const mcpAppData = (_b = chatContext == null ? void 0 : chatContext.getMcpAppData) == null ? void 0 : _b.call(chatContext, mcpAppId);
12005
+ if (debug) {
12006
+ console.log(`[McpAppHost:${mcpAppId}] Render - mcpAppData:`, {
12007
+ version: _version,
12008
+ hasHtml: !!(mcpAppData == null ? void 0 : mcpAppData.html),
12009
+ hasUrl: !!(mcpAppData == null ? void 0 : mcpAppData.url),
12010
+ hasChatContext: !!chatContext
11349
12011
  });
11350
- }, [log]);
11351
- const sendInitialize = useCallback(() => {
11352
- var _a2;
11353
- if (iframeStateRef.current === "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11354
- return;
11355
- const hostContext = {
11356
- mcpAppId,
11357
- state: mcpAppData == null ? void 0 : mcpAppData.state,
11358
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11359
- ...initialHostContext
11360
- };
11361
- const params = {
11362
- protocolVersion: "mcp-apps/0.1",
11363
- appInfo: { name: "McpAppHost", version: "1.0.0" },
11364
- hostCapabilities: {
11365
- openLinks: {},
11366
- "botdojo/persistence": true,
11367
- extensions: {
11368
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11369
- }
11370
- },
11371
- hostContext
11372
- };
11373
- log("Sending ui/initialize to app", params);
11374
- sendRequest("ui/initialize", params, 2e3).then((result) => {
11375
- log("App responded to ui/initialize:", result);
11376
- }).catch((err) => {
11377
- log("ui/initialize failed:", err.message);
11378
- });
11379
- }, [mcpAppId, mcpAppData, initialHostContext, log, sendRequest]);
11380
- const iframeStateRef = useRef(iframeState);
11381
- iframeStateRef.current = iframeState;
11382
- const sendInitializeWithRetry = useCallback(() => {
11383
- if (iframeStateRef.current === "ready")
11384
- return;
11385
- const attemptSend = () => {
11386
- if (iframeStateRef.current === "ready")
11387
- return;
11388
- initializeAttemptsRef.current += 1;
11389
- sendInitialize();
11390
- if (initializeAttemptsRef.current < 5) {
11391
- initializeTimerRef.current = setTimeout(attemptSend, 300);
11392
- } else {
11393
- initializeTimerRef.current = null;
11394
- log("Max initialize attempts reached");
12012
+ }
12013
+ const effectiveUrl = ((_c = mcpAppData == null ? void 0 : mcpAppData.url) == null ? void 0 : _c.startsWith("http")) ? mcpAppData.url : void 0;
12014
+ const {
12015
+ iframeRef,
12016
+ status,
12017
+ autoHeight,
12018
+ handleIframeLoad,
12019
+ sendToolNotification,
12020
+ sendStepUpdate,
12021
+ iframeSrc,
12022
+ renderError,
12023
+ canRender,
12024
+ initFailed,
12025
+ initError,
12026
+ resetIframe
12027
+ } = (0, import_sdk_canvas4.useMcpHostBridge)({
12028
+ appId: mcpAppId,
12029
+ html: mcpAppData == null ? void 0 : mcpAppData.html,
12030
+ url: effectiveUrl,
12031
+ toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
12032
+ arguments: mcpAppData == null ? void 0 : mcpAppData.arguments,
12033
+ result: mcpAppData == null ? void 0 : mcpAppData.result,
12034
+ state: mcpAppData == null ? void 0 : mcpAppData.state,
12035
+ isComplete: mcpAppData == null ? void 0 : mcpAppData.isComplete,
12036
+ hostContext: initialHostContext,
12037
+ debug,
12038
+ // Wrap callbacks to include mcpAppId
12039
+ onOpenLink: (url2, target) => {
12040
+ const handler = onOpenLink || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onOpenLink);
12041
+ handler == null ? void 0 : handler(url2, target, mcpAppId);
12042
+ },
12043
+ onToolCall: async (tool2, params) => {
12044
+ const handler = onToolCall || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onToolCall);
12045
+ if (handler) {
12046
+ return handler(tool2, params, mcpAppId);
11395
12047
  }
11396
- };
11397
- if (initializeTimerRef.current !== null) {
11398
- clearTimeout(initializeTimerRef.current);
11399
- }
11400
- initializeAttemptsRef.current = 0;
11401
- attemptSend();
11402
- }, [sendInitialize, log]);
11403
- const sendHydrationData = useCallback(() => {
11404
- var _a2, _b, _c;
11405
- const toolName = (_b = (_a2 = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a2.tool) == null ? void 0 : _b.name;
11406
- if (!toolName || !((_c = iframeRef.current) == null ? void 0 : _c.contentWindow))
11407
- return;
11408
- const parseMaybeJson2 = (value2) => {
11409
- if (value2 === void 0 || value2 === null || value2 === "")
11410
- return void 0;
11411
- if (typeof value2 === "object")
11412
- return value2;
11413
- if (typeof value2 === "string" && value2.trim()) {
12048
+ return { ok: false, error: "No tool handler" };
12049
+ },
12050
+ onMessage: (message, params) => {
12051
+ const handler = onUiMessage || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onUiMessage);
12052
+ handler == null ? void 0 : handler(message, params, mcpAppId);
12053
+ },
12054
+ onPersistState: (state) => {
12055
+ const handler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
12056
+ handler == null ? void 0 : handler(state, mcpAppId);
12057
+ },
12058
+ onSizeChange: (w, h) => {
12059
+ onSizeChange == null ? void 0 : onSizeChange(w, h, mcpAppId);
12060
+ },
12061
+ onReady: () => {
12062
+ onReady == null ? void 0 : onReady(mcpAppId);
12063
+ },
12064
+ // Handle sandbox-resource requests from proxy
12065
+ onSandboxResourceRequest: async ({ resource }) => {
12066
+ console.log(`[McpAppHost:${mcpAppId}] onSandboxResourceRequest for:`, resource);
12067
+ if (mcpAppData == null ? void 0 : mcpAppData.html) {
12068
+ console.log(`[McpAppHost:${mcpAppId}] Returning cached HTML, length:`, mcpAppData.html.length);
12069
+ return { html: mcpAppData.html };
12070
+ }
12071
+ const uriToResolve = resourceUri || resource;
12072
+ if (uriToResolve && getResource) {
12073
+ console.log(`[McpAppHost:${mcpAppId}] Resolving resource on demand:`, uriToResolve);
11414
12074
  try {
11415
- return JSON.parse(value2);
11416
- } catch {
11417
- return value2;
11418
- }
11419
- }
11420
- return value2;
11421
- };
11422
- const args = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.arguments);
11423
- const result = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.result);
11424
- const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
11425
- const hasValidArgs = args !== void 0 && typeof args === "object" && Object.keys(args).length > 0;
11426
- const hasValidResult = result !== void 0 && result !== "";
11427
- log("Sending hydration data:", { toolName, hasArgs: hasValidArgs, hasResult: hasValidResult });
11428
- if (hasValidArgs) {
11429
- iframeRef.current.contentWindow.postMessage({
11430
- jsonrpc: "2.0",
11431
- method: "ui/notifications/tool-input",
11432
- params: { tool: { name: toolName }, arguments: args }
11433
- }, "*");
11434
- }
11435
- if (hasValidResult) {
11436
- iframeRef.current.contentWindow.postMessage({
11437
- jsonrpc: "2.0",
11438
- method: "ui/notifications/tool-result",
11439
- params: { tool: { name: toolName }, result }
11440
- }, "*");
11441
- } else if (toolIsComplete) {
11442
- log("Sending synthetic tool-result for completed tool without stored result");
11443
- iframeRef.current.contentWindow.postMessage({
11444
- jsonrpc: "2.0",
11445
- method: "ui/notifications/tool-result",
11446
- params: { tool: { name: toolName }, result: { completed: true } }
11447
- }, "*");
11448
- }
11449
- }, [mcpAppData, log]);
11450
- const handleMessage = useCallback((event) => {
11451
- var _a2;
11452
- if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) {
11453
- return;
11454
- }
11455
- if (mcpAppHostContext == null ? void 0 : mcpAppHostContext.findAppIdBySource) {
11456
- const sourceAppId = mcpAppHostContext.findAppIdBySource(event.source);
11457
- if (sourceAppId && sourceAppId !== mcpAppId) {
11458
- log("Message from different app, ignoring:", sourceAppId);
11459
- return;
11460
- }
11461
- }
11462
- const data = event.data;
11463
- if (!data || data.jsonrpc !== "2.0")
11464
- return;
11465
- if ("id" in data && !("method" in data)) {
11466
- const pending = pendingRequestsRef.current.get(String(data.id));
11467
- if (pending) {
11468
- if (pending.timer)
11469
- clearTimeout(pending.timer);
11470
- pendingRequestsRef.current.delete(String(data.id));
11471
- if ("error" in data) {
11472
- pending.reject(data.error);
11473
- } else {
11474
- pending.resolve(data.result);
11475
- }
11476
- }
11477
- return;
11478
- }
11479
- const { method, params, id } = data;
11480
- log("Received:", method, params);
11481
- switch (method) {
11482
- case "ui/notifications/initialized": {
11483
- log("App confirmed initialization");
11484
- if (initializeTimerRef.current !== null) {
11485
- clearTimeout(initializeTimerRef.current);
11486
- initializeTimerRef.current = null;
11487
- }
11488
- setIframeState("ready");
11489
- sendHydrationData();
11490
- if (pendingNotificationsRef.current.length > 0 && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11491
- log(`Replaying ${pendingNotificationsRef.current.length} queued notifications`);
11492
- pendingNotificationsRef.current.forEach(({ method: method2, params: params2 }) => {
11493
- log("Replaying notification:", method2, params2);
11494
- iframeRef.current.contentWindow.postMessage(
11495
- { jsonrpc: "2.0", method: method2, params: params2 },
11496
- "*"
11497
- );
11498
- });
11499
- pendingNotificationsRef.current = [];
11500
- }
11501
- onReady == null ? void 0 : onReady(mcpAppId);
11502
- break;
11503
- }
11504
- case "ui/initialize": {
11505
- log("Handling ui/initialize request from app");
11506
- const hostContext = {
11507
- state: mcpAppData == null ? void 0 : mcpAppData.state,
11508
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11509
- ...initialHostContext
11510
- };
11511
- sendResponse(id, {
11512
- appInfo: { name: "McpAppHost", version: "1.0.0" },
11513
- hostCapabilities: {
11514
- openLinks: {},
11515
- "botdojo/persistence": true,
11516
- extensions: {
11517
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11518
- }
11519
- },
11520
- hostContext
11521
- });
11522
- sendNotification("ui/notifications/initialized", {});
11523
- if (initializeTimerRef.current !== null) {
11524
- clearTimeout(initializeTimerRef.current);
11525
- initializeTimerRef.current = null;
11526
- }
11527
- setIframeState("ready");
11528
- onReady == null ? void 0 : onReady(mcpAppId);
11529
- break;
11530
- }
11531
- case "ui/open-link": {
11532
- if (params == null ? void 0 : params.url) {
11533
- const handler = onOpenLink || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onOpenLink);
11534
- handler == null ? void 0 : handler(params.url, params.target || "_blank", mcpAppId);
11535
- }
11536
- if (id !== void 0) {
11537
- sendResponse(id, { ok: true });
11538
- }
11539
- break;
11540
- }
11541
- case "tools/call": {
11542
- const toolName = (params == null ? void 0 : params.name) || (params == null ? void 0 : params.tool);
11543
- const toolParams = (params == null ? void 0 : params.arguments) || (params == null ? void 0 : params.params) || {};
11544
- const handler = onToolCall || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onToolCall);
11545
- if (handler && toolName) {
11546
- Promise.resolve(handler(toolName, toolParams, mcpAppId)).then((result) => {
11547
- log("Tool call result:", result);
11548
- if (id !== void 0) {
11549
- sendResponse(id, result != null ? result : { ok: true });
11550
- }
11551
- }).catch((err) => {
11552
- log("Tool call error:", err);
11553
- if (id !== void 0) {
11554
- sendError(id, -32e3, err.message || "Tool execution failed");
11555
- }
11556
- });
11557
- } else {
11558
- if (id !== void 0) {
11559
- sendResponse(id, { ok: false, error: "No tool handler" });
11560
- }
11561
- }
11562
- break;
11563
- }
11564
- case "ui/message": {
11565
- const contentArray = Array.isArray(params == null ? void 0 : params.content) ? params.content : [params == null ? void 0 : params.content].filter(Boolean);
11566
- const firstContent = contentArray[0];
11567
- if ((firstContent == null ? void 0 : firstContent["botdojo/messageType"]) === "persist-state" && typeof firstContent.text === "string") {
11568
- log("Persist state message received (format 1)");
11569
- try {
11570
- const parsed = JSON.parse(firstContent.text);
11571
- const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11572
- if (persistHandler) {
11573
- persistHandler(parsed, mcpAppId);
11574
- }
11575
- } catch (err) {
11576
- log("Failed to parse persist-state content:", err);
12075
+ const resolved = await getResource(uriToResolve);
12076
+ const html = (resolved == null ? void 0 : resolved.text) || (resolved == null ? void 0 : resolved.content) || (resolved == null ? void 0 : resolved.html);
12077
+ if (html) {
12078
+ console.log(`[McpAppHost:${mcpAppId}] Resolved resource to HTML, length:`, html.length);
12079
+ return { html };
11577
12080
  }
11578
- if (id !== void 0) {
11579
- sendResponse(id, { ok: true });
11580
- }
11581
- break;
11582
- }
11583
- if ((firstContent == null ? void 0 : firstContent.type) === "botdojo/persist" && firstContent.state) {
11584
- log("Persist state message received (format 2/3)");
11585
- const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11586
- if (persistHandler) {
11587
- persistHandler(firstContent.state, mcpAppId);
11588
- }
11589
- if (id !== void 0) {
11590
- sendResponse(id, { ok: true });
11591
- }
11592
- break;
11593
- }
11594
- const handler = onUiMessage || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onUiMessage);
11595
- if (handler) {
11596
- const text = (firstContent == null ? void 0 : firstContent.text) || JSON.stringify(params);
11597
- handler(text, params, mcpAppId);
11598
- }
11599
- if (id !== void 0) {
11600
- sendResponse(id, { ok: true });
11601
- }
11602
- break;
11603
- }
11604
- case "ui/size-change":
11605
- case "ui/notifications/size-change": {
11606
- if (params == null ? void 0 : params.height) {
11607
- setAutoHeight(params.height);
11608
- }
11609
- if ((params == null ? void 0 : params.width) && (params == null ? void 0 : params.height)) {
11610
- onSizeChange == null ? void 0 : onSizeChange(params.width, params.height, mcpAppId);
11611
- }
11612
- break;
11613
- }
11614
- default: {
11615
- log("Unhandled method:", method);
11616
- if (id !== void 0) {
11617
- sendResponse(id, { ok: true, ignored: true });
12081
+ } catch (err) {
12082
+ console.error(`[McpAppHost:${mcpAppId}] Failed to resolve resource:`, err);
11618
12083
  }
11619
12084
  }
12085
+ console.log(`[McpAppHost:${mcpAppId}] No HTML available for resource`);
12086
+ return null;
11620
12087
  }
11621
- }, [
11622
- mcpAppId,
11623
- mcpAppData,
11624
- onOpenLink,
11625
- onToolCall,
11626
- onUiMessage,
11627
- onPersistState,
11628
- onSizeChange,
11629
- onReady,
11630
- mcpAppHostContext,
11631
- initialHostContext,
11632
- log,
11633
- sendResponse,
11634
- sendError,
11635
- sendNotification,
11636
- sendHydrationData
11637
- ]);
11638
- useEffect(() => {
11639
- window.addEventListener("message", handleMessage);
11640
- return () => window.removeEventListener("message", handleMessage);
11641
- }, [handleMessage]);
11642
- useEffect(() => {
11643
- if (!iframeRef.current)
11644
- return;
11645
- if (contentKey === renderedContentKeyRef.current && iframeState !== "idle") {
11646
- log("Content key unchanged, keeping existing iframe");
11647
- return;
11648
- }
11649
- if (contentKey === "empty") {
11650
- if (iframeState === "ready" && iframeRef.current.src) {
11651
- log("Content became empty but iframe is ready, preserving");
11652
- renderedContentKeyRef.current = contentKey;
11653
- return;
11654
- }
11655
- if (iframeState !== "idle" && iframeRef.current.src) {
11656
- log("Content became empty but iframe is loading/initializing, preserving");
11657
- renderedContentKeyRef.current = contentKey;
11658
- return;
11659
- }
11660
- if (iframeState === "idle" && !iframeRef.current.src) {
11661
- log("Content is empty and iframe is idle with no src, skipping");
11662
- renderedContentKeyRef.current = contentKey;
11663
- return;
11664
- }
11665
- }
11666
- log("Content key changed:", { old: renderedContentKeyRef.current, new: contentKey });
11667
- renderedContentKeyRef.current = contentKey;
11668
- setIframeState("idle");
11669
- setAutoHeight(null);
11670
- initializeAttemptsRef.current = 0;
11671
- pendingNotificationsRef.current = [];
11672
- if (initializeTimerRef.current !== null) {
11673
- clearTimeout(initializeTimerRef.current);
11674
- initializeTimerRef.current = null;
11675
- }
11676
- if (currentBlobUrlRef.current) {
11677
- URL.revokeObjectURL(currentBlobUrlRef.current);
11678
- currentBlobUrlRef.current = null;
11679
- }
11680
- if (appHtml) {
11681
- const blob = new Blob([appHtml], { type: "text/html" });
11682
- const url2 = URL.createObjectURL(blob);
11683
- currentBlobUrlRef.current = url2;
11684
- iframeRef.current.src = url2;
11685
- log("Set iframe src to blob URL");
11686
- } else if (appUrl) {
11687
- iframeRef.current.src = appUrl;
11688
- log("Set iframe src to URL:", appUrl);
11689
- }
11690
- }, [contentKey, appHtml, appUrl, iframeState, log]);
11691
- useEffect(() => {
11692
- if (iframeState === "loading") {
11693
- log("Iframe loaded, sending ui/initialize");
11694
- setIframeState("initializing");
11695
- sendInitializeWithRetry();
11696
- }
11697
- }, [iframeState, sendInitializeWithRetry, log]);
11698
- const prevStateRef = useRef(void 0);
11699
- useEffect(() => {
11700
- if (iframeState !== "ready") {
11701
- prevStateRef.current = mcpAppData == null ? void 0 : mcpAppData.state;
11702
- return;
11703
- }
11704
- const currentState = mcpAppData == null ? void 0 : mcpAppData.state;
11705
- const prevState = prevStateRef.current;
11706
- const stateChanged = JSON.stringify(currentState) !== JSON.stringify(prevState);
11707
- if (stateChanged && currentState !== void 0) {
11708
- log("State changed after initialization, sending host-context-changed");
11709
- sendNotification("ui/notifications/host-context-changed", {
11710
- state: currentState,
11711
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11712
- ...initialHostContext
11713
- });
11714
- prevStateRef.current = currentState;
11715
- }
11716
- }, [iframeState, mcpAppData == null ? void 0 : mcpAppData.state, mcpAppData == null ? void 0 : mcpAppData.toolInfo, initialHostContext, sendNotification, log]);
11717
- const handleIframeLoad = useCallback(() => {
11718
- log("Iframe onLoad fired");
11719
- setIframeState((prev2) => prev2 === "idle" ? "loading" : prev2);
11720
- }, [log]);
12088
+ });
11721
12089
  useEffect(() => {
11722
12090
  var _a2;
11723
12091
  if (mcpAppHostContext && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11724
12092
  mcpAppHostContext.registerApp(mcpAppId, iframeRef.current.contentWindow);
11725
12093
  return () => mcpAppHostContext.unregisterApp(mcpAppId);
11726
12094
  }
11727
- }, [mcpAppId, mcpAppHostContext]);
12095
+ }, [mcpAppId, mcpAppHostContext, iframeRef]);
11728
12096
  const chatContextRef = useRef(chatContext);
11729
12097
  chatContextRef.current = chatContext;
11730
12098
  useEffect(() => {
11731
12099
  const ctx = chatContextRef.current;
11732
- if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender)) {
12100
+ if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender))
11733
12101
  return;
11734
- }
11735
- const sender = (method, params) => {
11736
- var _a2;
11737
- if (iframeStateRef.current !== "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11738
- pendingNotificationsRef.current.push({ method, params });
11739
- return;
11740
- }
11741
- if (method === "ui/notifications/tool-input" || method === "ui/notifications/tool-input-partial") {
11742
- const args = params == null ? void 0 : params.arguments;
11743
- if (!args || args === "" || typeof args !== "object" || Object.keys(args).length === 0) {
11744
- return;
11745
- }
11746
- }
11747
- if (method === "ui/notifications/tool-result") {
11748
- const result = params == null ? void 0 : params.result;
11749
- if (result === "" || result === void 0) {
11750
- return;
11751
- }
11752
- }
11753
- iframeRef.current.contentWindow.postMessage(
11754
- { jsonrpc: "2.0", method, params },
11755
- "*"
11756
- );
11757
- };
11758
- const unregister = ctx.registerToolNotificationSender(mcpAppId, sender);
12102
+ const unregister = ctx.registerToolNotificationSender(mcpAppId, sendToolNotification);
11759
12103
  return unregister;
11760
- }, [mcpAppId]);
12104
+ }, [mcpAppId, sendToolNotification]);
11761
12105
  useEffect(() => {
11762
12106
  const ctx = chatContextRef.current;
11763
- if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback)) {
12107
+ if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback))
11764
12108
  return;
11765
- }
11766
- const callback = (stepUpdate) => {
11767
- var _a2;
11768
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11769
- return;
11770
- const toolName = (stepUpdate == null ? void 0 : stepUpdate.stepToolName) || (stepUpdate == null ? void 0 : stepUpdate.toolName);
11771
- const toolPhase = stepUpdate == null ? void 0 : stepUpdate.toolPhase;
11772
- const toolArguments = stepUpdate == null ? void 0 : stepUpdate.stepToolArguments;
11773
- const toolProgress = stepUpdate == null ? void 0 : stepUpdate.stepToolProgress;
11774
- const rawToolResult = stepUpdate == null ? void 0 : stepUpdate.stepToolResult;
11775
- if (!toolName)
11776
- return;
11777
- const parseIfJson = (value2) => {
11778
- if (value2 === void 0 || value2 === null || value2 === "")
11779
- return void 0;
11780
- if (typeof value2 === "object")
11781
- return value2;
11782
- if (typeof value2 === "string" && value2.trim()) {
11783
- try {
11784
- return JSON.parse(value2);
11785
- } catch {
11786
- return value2;
11787
- }
11788
- }
11789
- return value2;
11790
- };
11791
- const toolResult = parseIfJson(rawToolResult);
11792
- const sendOrQueue = (method, params) => {
11793
- var _a3;
11794
- if (iframeStateRef.current === "ready" && ((_a3 = iframeRef.current) == null ? void 0 : _a3.contentWindow)) {
11795
- iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method, params }, "*");
11796
- } else {
11797
- pendingNotificationsRef.current.push({ method, params });
11798
- }
11799
- };
11800
- if (toolPhase === "executing" && toolArguments) {
11801
- sendOrQueue("ui/notifications/tool-input", {
11802
- tool: { name: toolName },
11803
- arguments: toolArguments
11804
- });
11805
- }
11806
- if (toolProgress) {
11807
- sendOrQueue("ui/notifications/tool-input-partial", {
11808
- tool: { name: toolName },
11809
- arguments: { ...toolProgress, _botdojoProgress: true }
11810
- });
11811
- } else if (toolPhase === "streaming_args" && (stepUpdate.stepId || stepUpdate.stepLabel)) {
11812
- sendOrQueue("ui/notifications/tool-input-partial", {
11813
- tool: { name: toolName },
11814
- arguments: {
11815
- ...toolArguments || {},
11816
- stepId: stepUpdate.stepId,
11817
- stepLabel: stepUpdate.stepLabel
11818
- }
11819
- });
11820
- }
11821
- if (toolResult !== void 0 && toolResult !== "") {
11822
- sendOrQueue("ui/notifications/tool-result", {
11823
- tool: { name: toolName },
11824
- result: toolResult
11825
- });
11826
- }
11827
- };
11828
- const unregister = ctx.registerStepUpdateCallback(mcpAppId, callback);
12109
+ const unregister = ctx.registerStepUpdateCallback(mcpAppId, sendStepUpdate);
11829
12110
  return unregister;
11830
- }, [mcpAppId]);
11831
- useEffect(() => {
11832
- return () => {
11833
- if (currentBlobUrlRef.current) {
11834
- URL.revokeObjectURL(currentBlobUrlRef.current);
11835
- currentBlobUrlRef.current = null;
11836
- }
11837
- };
11838
- }, []);
11839
- useEffect(() => {
11840
- return () => {
11841
- if (initializeTimerRef.current !== null) {
11842
- clearTimeout(initializeTimerRef.current);
11843
- }
11844
- pendingRequestsRef.current.forEach(({ timer, reject }) => {
11845
- if (timer)
11846
- clearTimeout(timer);
11847
- reject(new Error("Component unmounted"));
11848
- });
11849
- pendingRequestsRef.current.clear();
11850
- };
11851
- }, []);
12111
+ }, [mcpAppId, sendStepUpdate]);
11852
12112
  const effectiveHeight = autoHeight ? `${autoHeight}px` : (mcpAppData == null ? void 0 : mcpAppData.height) || height;
12113
+ if (!canRender && !debug) {
12114
+ return null;
12115
+ }
12116
+ if (!canRender && debug) {
12117
+ return /* @__PURE__ */ jsxs("div", { style: {
12118
+ padding: "16px",
12119
+ border: "2px solid #ff6b6b",
12120
+ borderRadius: "8px",
12121
+ backgroundColor: "#fff5f5",
12122
+ fontFamily: "monospace",
12123
+ fontSize: "12px",
12124
+ ...style
12125
+ }, children: [
12126
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: "bold", color: "#c92a2a", marginBottom: "8px" }, children: "MCP App Render Error" }),
12127
+ /* @__PURE__ */ jsxs("div", { style: { color: "#666" }, children: [
12128
+ /* @__PURE__ */ jsx("strong", { children: "App ID:" }),
12129
+ " ",
12130
+ mcpAppId,
12131
+ /* @__PURE__ */ jsx("br", {}),
12132
+ /* @__PURE__ */ jsx("strong", { children: "Error:" }),
12133
+ " ",
12134
+ renderError || "Unknown error",
12135
+ /* @__PURE__ */ jsx("br", {}),
12136
+ /* @__PURE__ */ jsx("strong", { children: "URL:" }),
12137
+ " ",
12138
+ iframeSrc || effectiveUrl || (mcpAppData == null ? void 0 : mcpAppData.url) || "none",
12139
+ /* @__PURE__ */ jsx("br", {}),
12140
+ /* @__PURE__ */ jsx("strong", { children: "Status:" }),
12141
+ " ",
12142
+ status,
12143
+ /* @__PURE__ */ jsx("br", {}),
12144
+ /* @__PURE__ */ jsx("strong", { children: "Has HTML:" }),
12145
+ " ",
12146
+ (mcpAppData == null ? void 0 : mcpAppData.html) ? "yes" : "no"
12147
+ ] })
12148
+ ] });
12149
+ }
12150
+ if (initFailed) {
12151
+ return /* @__PURE__ */ jsxs("div", { style: {
12152
+ padding: "16px",
12153
+ textAlign: "center",
12154
+ border: "1px solid #e0e0e0",
12155
+ borderRadius: "8px",
12156
+ backgroundColor: "#fafafa",
12157
+ ...style
12158
+ }, children: [
12159
+ /* @__PURE__ */ jsx("p", { style: { margin: "0 0 8px 0", color: "#666" }, children: "Unable to load interactive content" }),
12160
+ debug && initError && /* @__PURE__ */ jsx("p", { style: { margin: "0 0 8px 0", color: "#999", fontSize: "12px", fontFamily: "monospace" }, children: initError }),
12161
+ /* @__PURE__ */ jsx(
12162
+ "button",
12163
+ {
12164
+ onClick: resetIframe,
12165
+ style: {
12166
+ padding: "8px 16px",
12167
+ cursor: "pointer",
12168
+ borderRadius: "4px",
12169
+ border: "1px solid #ccc",
12170
+ backgroundColor: "#fff"
12171
+ },
12172
+ children: "Retry"
12173
+ }
12174
+ )
12175
+ ] });
12176
+ }
11853
12177
  return /* @__PURE__ */ jsx(
11854
12178
  "iframe",
11855
12179
  {
11856
12180
  ref: iframeRef,
12181
+ src: iframeSrc,
11857
12182
  title: `mcp-app-${mcpAppId}`,
11858
12183
  onLoad: handleIframeLoad,
11859
12184
  style: {
@@ -12738,12 +13063,12 @@ var BotDojoChatConfigurator = ({
12738
13063
  };
12739
13064
 
12740
13065
  // src/index.tsx
12741
- var import_sdk_canvas5 = __toESM(require_src3());
13066
+ var import_sdk_canvas6 = __toESM(require_src3());
12742
13067
  var import_sdk_types2 = __toESM(require_lib());
12743
13068
  var CanvasContext = createContext(null);
12744
13069
 
12745
13070
  // src/canvas/BotDojoCanvasProvider.tsx
12746
- var import_sdk_canvas4 = __toESM(require_src3());
13071
+ var import_sdk_canvas5 = __toESM(require_src3());
12747
13072
  var DEFAULT_ACK_TTL_MS = 3 * 60 * 1e3;
12748
13073
  var DEFAULT_RESPONSE_TIMEOUT_MS = 2e4;
12749
13074
  var MCP_FUNCTION_NAME_MAP = {
@@ -12941,7 +13266,7 @@ function BotDojoCanvasProvider({
12941
13266
  const apiKey = window.BOTDOJO_API_KEY || "embedded-canvas";
12942
13267
  let createdConnector = null;
12943
13268
  try {
12944
- const conn = new import_sdk_canvas4.BotDojoConnector({
13269
+ const conn = new import_sdk_canvas5.BotDojoConnector({
12945
13270
  apiKey,
12946
13271
  accountId: "embedded",
12947
13272
  projectId: "embedded",
@@ -13630,7 +13955,7 @@ function useBotDojoCanvas() {
13630
13955
  }
13631
13956
  return context;
13632
13957
  }
13633
- var export_BotDojoConnector = import_sdk_canvas5.BotDojoConnector;
13958
+ var export_BotDojoConnector = import_sdk_canvas6.BotDojoConnector;
13634
13959
  var export_MIME_TYPES = import_sdk_types2.MIME_TYPES;
13635
13960
  var export_citation = import_sdk_types2.citation;
13636
13961
  var export_citations = import_sdk_types2.citations;