@botdojo/chat-sdk 0.0.21 → 0.0.23

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
 
@@ -10271,6 +10877,8 @@ function BotDojoChatProvider(props) {
10271
10877
  onSessionHydrated,
10272
10878
  onConnectorInit,
10273
10879
  onConnectorError,
10880
+ // Debug mode for MCP App rendering
10881
+ debug = false,
10274
10882
  // MCP App handlers (SEP-1865)
10275
10883
  onOpenLink,
10276
10884
  onToolCall,
@@ -10298,6 +10906,7 @@ function BotDojoChatProvider(props) {
10298
10906
  const pendingBroadcastNotificationsRef = useRef([]);
10299
10907
  const toolArgumentsCacheRef = useRef(/* @__PURE__ */ new Map());
10300
10908
  const mcpAppDataCacheRef = useRef(/* @__PURE__ */ new Map());
10909
+ const [mcpAppDataVersion, setMcpAppDataVersion] = useState(0);
10301
10910
  const pendingStepUpdatesRef = useRef(/* @__PURE__ */ new Map());
10302
10911
  const appHandlersRef = useRef({
10303
10912
  onOpenLink,
@@ -10559,18 +11168,46 @@ function BotDojoChatProvider(props) {
10559
11168
  throw new Error(`Tool not found: ${toolName}`);
10560
11169
  }, []);
10561
11170
  const getMcpAppData = useCallback((appId) => {
11171
+ var _a, _b, _c, _d;
10562
11172
  const cached = mcpAppDataCacheRef.current.get(appId);
10563
- if (!cached)
10564
- return null;
10565
- return {
10566
- mcpAppId: appId,
10567
- mcpAppType: "mcp-app",
10568
- ...cached
10569
- };
10570
- }, []);
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]);
10571
11207
  const updateMcpAppDataCache = useCallback((appId, data) => {
10572
11208
  const existing = mcpAppDataCacheRef.current.get(appId) || {};
10573
11209
  mcpAppDataCacheRef.current.set(appId, { ...existing, ...data });
11210
+ setMcpAppDataVersion((v) => v + 1);
10574
11211
  }, []);
10575
11212
  const getResource = useCallback(async (uri, params, onlyMetadata) => {
10576
11213
  console.log("[BotDojoChatProvider] getResource called for URI:", uri);
@@ -10876,12 +11513,25 @@ ${htmlContent}`;
10876
11513
  }
10877
11514
  };
10878
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
+ }
10879
11529
  const appIdForCache = rawStep.canvas.canvasId;
10880
11530
  if (appIdForCache) {
10881
11531
  const toolNameForCache = rawStep.stepToolName || rawStep.stepLabel;
10882
11532
  updateMcpAppDataCache(appIdForCache, {
10883
11533
  html: htmlContent,
10884
- url: canvasUrl,
11534
+ url: proxyUrl || canvasUrl,
10885
11535
  toolInfo: toolNameForCache ? { tool: { name: toolNameForCache } } : void 0,
10886
11536
  height: (_e = rawStep.canvas.canvasData) == null ? void 0 : _e.height,
10887
11537
  width: (_f = rawStep.canvas.canvasData) == null ? void 0 : _f.width
@@ -11021,9 +11671,12 @@ ${htmlContent}`;
11021
11671
  registerStepUpdateCallback,
11022
11672
  sendStepUpdateToApp,
11023
11673
  getMcpAppData,
11024
- appHandlers: appHandlersRef
11674
+ mcpAppDataVersion,
11675
+ getResource,
11676
+ appHandlers: appHandlersRef,
11677
+ debug
11025
11678
  }),
11026
- [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp, getMcpAppData]
11679
+ [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp, getMcpAppData, mcpAppDataVersion, getResource, debug]
11027
11680
  );
11028
11681
  return /* @__PURE__ */ jsxs(BotDojoChatContext.Provider, { value: contextValue, children: [
11029
11682
  children,
@@ -11192,6 +11845,9 @@ function BotDojoCanvasFrame(props) {
11192
11845
  }
11193
11846
  );
11194
11847
  }
11848
+
11849
+ // src/headless/components/McpAppHost.tsx
11850
+ var import_sdk_canvas4 = __toESM(require_src3());
11195
11851
  var McpAppHostContext = createContext(null);
11196
11852
  function McpAppHostProvider(props) {
11197
11853
  const { children, onOpenLink, onToolCall, onUiMessage, onPersistState, debug = false } = props;
@@ -11323,20 +11979,11 @@ function useMcpAppHostRequired() {
11323
11979
  }
11324
11980
  return context;
11325
11981
  }
11326
- function getContentKey(appHtml, appUrl) {
11327
- if (appUrl)
11328
- return `url:${appUrl}`;
11329
- if (appHtml) {
11330
- const prefix = appHtml.slice(0, 100);
11331
- const suffix = appHtml.slice(-100);
11332
- return `html:${appHtml.length}:${prefix}:${suffix}`;
11333
- }
11334
- return "empty";
11335
- }
11336
11982
  function McpAppHost(props) {
11337
- var _a;
11983
+ var _a, _b, _c;
11338
11984
  const {
11339
11985
  mcpAppId,
11986
+ resourceUri,
11340
11987
  onOpenLink,
11341
11988
  onToolCall,
11342
11989
  onUiMessage,
@@ -11347,583 +11994,191 @@ function McpAppHost(props) {
11347
11994
  height = "100%",
11348
11995
  style,
11349
11996
  initialHostContext,
11350
- debug = false
11997
+ debug: debugProp
11351
11998
  } = props;
11352
- const iframeRef = useRef(null);
11353
- const [iframeState, setIframeState] = useState("idle");
11354
- const [autoHeight, setAutoHeight] = useState(null);
11355
- const pendingRequestsRef = useRef(/* @__PURE__ */ new Map());
11356
- const nextRequestIdRef = useRef(0);
11357
- const initializeAttemptsRef = useRef(0);
11358
- const initializeTimerRef = useRef(null);
11359
11999
  const mcpAppHostContext = useMcpAppHost();
11360
12000
  const chatContext = useContext(BotDojoChatContext);
11361
- const pendingNotificationsRef = useRef([]);
11362
- const mcpAppData = (_a = chatContext == null ? void 0 : chatContext.getMcpAppData) == null ? void 0 : _a.call(chatContext, mcpAppId);
11363
- const appUrl = mcpAppData == null ? void 0 : mcpAppData.url;
11364
- const appHtml = mcpAppData == null ? void 0 : mcpAppData.html;
11365
- const contentKey = useMemo(() => getContentKey(appHtml, appUrl), [appHtml, appUrl]);
11366
- const renderedContentKeyRef = useRef("");
11367
- const currentBlobUrlRef = useRef(null);
11368
- const log = useCallback((...args) => {
11369
- if (debug) {
11370
- console.log(`[McpAppHost:${mcpAppId}]`, ...args);
11371
- }
11372
- }, [debug, mcpAppId]);
11373
- const sendResponse = useCallback((id, result) => {
11374
- var _a2;
11375
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11376
- return;
11377
- iframeRef.current.contentWindow.postMessage(
11378
- { jsonrpc: "2.0", id, result },
11379
- "*"
11380
- );
11381
- }, []);
11382
- const sendError = useCallback((id, code, message) => {
11383
- var _a2;
11384
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11385
- return;
11386
- iframeRef.current.contentWindow.postMessage(
11387
- { jsonrpc: "2.0", id, error: { code, message } },
11388
- "*"
11389
- );
11390
- }, []);
11391
- const sendNotification = useCallback((method, params) => {
11392
- var _a2;
11393
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11394
- return;
11395
- log("Sending notification:", method, params);
11396
- iframeRef.current.contentWindow.postMessage(
11397
- { jsonrpc: "2.0", method, params },
11398
- "*"
11399
- );
11400
- }, [log]);
11401
- const sendRequest = useCallback((method, params, timeout = 5e3) => {
11402
- return new Promise((resolve, reject) => {
11403
- var _a2;
11404
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11405
- reject(new Error("Iframe not ready"));
11406
- return;
11407
- }
11408
- const id = `host-${++nextRequestIdRef.current}`;
11409
- const timer = setTimeout(() => {
11410
- pendingRequestsRef.current.delete(id);
11411
- reject(new Error(`Request timeout: ${method}`));
11412
- }, timeout);
11413
- pendingRequestsRef.current.set(id, { resolve, reject, timer });
11414
- log("Sending request:", method, params);
11415
- iframeRef.current.contentWindow.postMessage(
11416
- { jsonrpc: "2.0", id, method, params },
11417
- "*"
11418
- );
11419
- });
11420
- }, [log]);
11421
- const sendInitialize = useCallback(() => {
11422
- var _a2;
11423
- if (iframeStateRef.current === "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11424
- return;
11425
- const hostContext = {
11426
- mcpAppId,
11427
- state: mcpAppData == null ? void 0 : mcpAppData.state,
11428
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11429
- ...initialHostContext
11430
- };
11431
- const params = {
11432
- protocolVersion: "mcp-apps/0.1",
11433
- appInfo: { name: "McpAppHost", version: "1.0.0" },
11434
- hostCapabilities: {
11435
- openLinks: {},
11436
- "botdojo/persistence": true,
11437
- extensions: {
11438
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11439
- }
11440
- },
11441
- hostContext
11442
- };
11443
- log("Sending ui/initialize to app", params);
11444
- sendRequest("ui/initialize", params, 2e3).then((result) => {
11445
- log("App responded to ui/initialize:", result);
11446
- }).catch((err) => {
11447
- log("ui/initialize failed:", err.message);
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
11448
12011
  });
11449
- }, [mcpAppId, mcpAppData, initialHostContext, log, sendRequest]);
11450
- const iframeStateRef = useRef(iframeState);
11451
- iframeStateRef.current = iframeState;
11452
- const sendInitializeWithRetry = useCallback(() => {
11453
- if (iframeStateRef.current === "ready")
11454
- return;
11455
- const attemptSend = () => {
11456
- if (iframeStateRef.current === "ready")
11457
- return;
11458
- initializeAttemptsRef.current += 1;
11459
- sendInitialize();
11460
- if (initializeAttemptsRef.current < 5) {
11461
- initializeTimerRef.current = setTimeout(attemptSend, 300);
11462
- } else {
11463
- initializeTimerRef.current = null;
11464
- 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);
11465
12047
  }
11466
- };
11467
- if (initializeTimerRef.current !== null) {
11468
- clearTimeout(initializeTimerRef.current);
11469
- }
11470
- initializeAttemptsRef.current = 0;
11471
- attemptSend();
11472
- }, [sendInitialize, log]);
11473
- const sendHydrationData = useCallback(() => {
11474
- var _a2, _b, _c;
11475
- const toolName = (_b = (_a2 = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a2.tool) == null ? void 0 : _b.name;
11476
- if (!toolName || !((_c = iframeRef.current) == null ? void 0 : _c.contentWindow))
11477
- return;
11478
- const parseMaybeJson2 = (value2) => {
11479
- if (value2 === void 0 || value2 === null || value2 === "")
11480
- return void 0;
11481
- if (typeof value2 === "object")
11482
- return value2;
11483
- 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);
11484
12074
  try {
11485
- return JSON.parse(value2);
11486
- } catch {
11487
- return value2;
11488
- }
11489
- }
11490
- return value2;
11491
- };
11492
- const args = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.arguments);
11493
- const result = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.result);
11494
- const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
11495
- const hasValidArgs = args !== void 0 && typeof args === "object" && Object.keys(args).length > 0;
11496
- const hasValidResult = result !== void 0 && result !== "";
11497
- log("Sending hydration data:", { toolName, hasArgs: hasValidArgs, hasResult: hasValidResult });
11498
- if (hasValidArgs) {
11499
- iframeRef.current.contentWindow.postMessage({
11500
- jsonrpc: "2.0",
11501
- method: "ui/notifications/tool-input",
11502
- params: { tool: { name: toolName }, arguments: args }
11503
- }, "*");
11504
- }
11505
- if (hasValidResult) {
11506
- iframeRef.current.contentWindow.postMessage({
11507
- jsonrpc: "2.0",
11508
- method: "ui/notifications/tool-result",
11509
- params: { tool: { name: toolName }, result }
11510
- }, "*");
11511
- } else if (toolIsComplete) {
11512
- log("Sending synthetic tool-result for completed tool without stored result");
11513
- iframeRef.current.contentWindow.postMessage({
11514
- jsonrpc: "2.0",
11515
- method: "ui/notifications/tool-result",
11516
- params: { tool: { name: toolName }, result: { completed: true } }
11517
- }, "*");
11518
- }
11519
- }, [mcpAppData, log]);
11520
- const handleMessage = useCallback((event) => {
11521
- var _a2;
11522
- if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) {
11523
- return;
11524
- }
11525
- if (mcpAppHostContext == null ? void 0 : mcpAppHostContext.findAppIdBySource) {
11526
- const sourceAppId = mcpAppHostContext.findAppIdBySource(event.source);
11527
- if (sourceAppId && sourceAppId !== mcpAppId) {
11528
- log("Message from different app, ignoring:", sourceAppId);
11529
- return;
11530
- }
11531
- }
11532
- const data = event.data;
11533
- if (!data || data.jsonrpc !== "2.0")
11534
- return;
11535
- if ("id" in data && !("method" in data)) {
11536
- const pending = pendingRequestsRef.current.get(String(data.id));
11537
- if (pending) {
11538
- if (pending.timer)
11539
- clearTimeout(pending.timer);
11540
- pendingRequestsRef.current.delete(String(data.id));
11541
- if ("error" in data) {
11542
- pending.reject(data.error);
11543
- } else {
11544
- pending.resolve(data.result);
11545
- }
11546
- }
11547
- return;
11548
- }
11549
- const { method, params, id } = data;
11550
- log("Received:", method, params);
11551
- switch (method) {
11552
- case "ui/notifications/initialized": {
11553
- log("App confirmed initialization");
11554
- if (initializeTimerRef.current !== null) {
11555
- clearTimeout(initializeTimerRef.current);
11556
- initializeTimerRef.current = null;
11557
- }
11558
- setIframeState("ready");
11559
- sendHydrationData();
11560
- if (pendingNotificationsRef.current.length > 0 && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11561
- log(`Replaying ${pendingNotificationsRef.current.length} queued notifications`);
11562
- pendingNotificationsRef.current.forEach(({ method: method2, params: params2 }) => {
11563
- log("Replaying notification:", method2, params2);
11564
- iframeRef.current.contentWindow.postMessage(
11565
- { jsonrpc: "2.0", method: method2, params: params2 },
11566
- "*"
11567
- );
11568
- });
11569
- pendingNotificationsRef.current = [];
11570
- }
11571
- onReady == null ? void 0 : onReady(mcpAppId);
11572
- break;
11573
- }
11574
- case "ui/initialize": {
11575
- log("Handling ui/initialize request from app");
11576
- const hostContext = {
11577
- state: mcpAppData == null ? void 0 : mcpAppData.state,
11578
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11579
- ...initialHostContext
11580
- };
11581
- sendResponse(id, {
11582
- appInfo: { name: "McpAppHost", version: "1.0.0" },
11583
- hostCapabilities: {
11584
- openLinks: {},
11585
- "botdojo/persistence": true,
11586
- extensions: {
11587
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11588
- }
11589
- },
11590
- hostContext
11591
- });
11592
- sendNotification("ui/notifications/initialized", {});
11593
- if (initializeTimerRef.current !== null) {
11594
- clearTimeout(initializeTimerRef.current);
11595
- initializeTimerRef.current = null;
11596
- }
11597
- setIframeState("ready");
11598
- onReady == null ? void 0 : onReady(mcpAppId);
11599
- break;
11600
- }
11601
- case "ui/open-link": {
11602
- if (params == null ? void 0 : params.url) {
11603
- const handler = onOpenLink || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onOpenLink);
11604
- handler == null ? void 0 : handler(params.url, params.target || "_blank", mcpAppId);
11605
- }
11606
- if (id !== void 0) {
11607
- sendResponse(id, { ok: true });
11608
- }
11609
- break;
11610
- }
11611
- case "tools/call": {
11612
- const toolName = (params == null ? void 0 : params.name) || (params == null ? void 0 : params.tool);
11613
- const toolParams = (params == null ? void 0 : params.arguments) || (params == null ? void 0 : params.params) || {};
11614
- const handler = onToolCall || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onToolCall);
11615
- if (handler && toolName) {
11616
- Promise.resolve(handler(toolName, toolParams, mcpAppId)).then((result) => {
11617
- log("Tool call result:", result);
11618
- if (id !== void 0) {
11619
- sendResponse(id, result != null ? result : { ok: true });
11620
- }
11621
- }).catch((err) => {
11622
- log("Tool call error:", err);
11623
- if (id !== void 0) {
11624
- sendError(id, -32e3, err.message || "Tool execution failed");
11625
- }
11626
- });
11627
- } else {
11628
- if (id !== void 0) {
11629
- sendResponse(id, { ok: false, error: "No tool handler" });
11630
- }
11631
- }
11632
- break;
11633
- }
11634
- case "ui/message": {
11635
- const contentArray = Array.isArray(params == null ? void 0 : params.content) ? params.content : [params == null ? void 0 : params.content].filter(Boolean);
11636
- const firstContent = contentArray[0];
11637
- if ((firstContent == null ? void 0 : firstContent["botdojo/messageType"]) === "persist-state" && typeof firstContent.text === "string") {
11638
- log("Persist state message received (format 1)");
11639
- try {
11640
- const parsed = JSON.parse(firstContent.text);
11641
- const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11642
- if (persistHandler) {
11643
- persistHandler(parsed, mcpAppId);
11644
- }
11645
- } catch (err) {
11646
- 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 };
11647
12080
  }
11648
- if (id !== void 0) {
11649
- sendResponse(id, { ok: true });
11650
- }
11651
- break;
11652
- }
11653
- if ((firstContent == null ? void 0 : firstContent.type) === "botdojo/persist" && firstContent.state) {
11654
- log("Persist state message received (format 2/3)");
11655
- const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11656
- if (persistHandler) {
11657
- persistHandler(firstContent.state, mcpAppId);
11658
- }
11659
- if (id !== void 0) {
11660
- sendResponse(id, { ok: true });
11661
- }
11662
- break;
11663
- }
11664
- const handler = onUiMessage || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onUiMessage);
11665
- if (handler) {
11666
- const text = (firstContent == null ? void 0 : firstContent.text) || JSON.stringify(params);
11667
- handler(text, params, mcpAppId);
11668
- }
11669
- if (id !== void 0) {
11670
- sendResponse(id, { ok: true });
11671
- }
11672
- break;
11673
- }
11674
- case "ui/size-change":
11675
- case "ui/notifications/size-change": {
11676
- if (params == null ? void 0 : params.height) {
11677
- setAutoHeight(params.height);
11678
- }
11679
- if ((params == null ? void 0 : params.width) && (params == null ? void 0 : params.height)) {
11680
- onSizeChange == null ? void 0 : onSizeChange(params.width, params.height, mcpAppId);
11681
- }
11682
- break;
11683
- }
11684
- default: {
11685
- log("Unhandled method:", method);
11686
- if (id !== void 0) {
11687
- sendResponse(id, { ok: true, ignored: true });
12081
+ } catch (err) {
12082
+ console.error(`[McpAppHost:${mcpAppId}] Failed to resolve resource:`, err);
11688
12083
  }
11689
12084
  }
12085
+ console.log(`[McpAppHost:${mcpAppId}] No HTML available for resource`);
12086
+ return null;
11690
12087
  }
11691
- }, [
11692
- mcpAppId,
11693
- mcpAppData,
11694
- onOpenLink,
11695
- onToolCall,
11696
- onUiMessage,
11697
- onPersistState,
11698
- onSizeChange,
11699
- onReady,
11700
- mcpAppHostContext,
11701
- initialHostContext,
11702
- log,
11703
- sendResponse,
11704
- sendError,
11705
- sendNotification,
11706
- sendHydrationData
11707
- ]);
11708
- useEffect(() => {
11709
- window.addEventListener("message", handleMessage);
11710
- return () => window.removeEventListener("message", handleMessage);
11711
- }, [handleMessage]);
11712
- useEffect(() => {
11713
- if (!iframeRef.current)
11714
- return;
11715
- if (contentKey === renderedContentKeyRef.current && iframeState !== "idle") {
11716
- log("Content key unchanged, keeping existing iframe");
11717
- return;
11718
- }
11719
- if (contentKey === "empty") {
11720
- if (iframeState === "ready" && iframeRef.current.src) {
11721
- log("Content became empty but iframe is ready, preserving");
11722
- renderedContentKeyRef.current = contentKey;
11723
- return;
11724
- }
11725
- if (iframeState !== "idle" && iframeRef.current.src) {
11726
- log("Content became empty but iframe is loading/initializing, preserving");
11727
- renderedContentKeyRef.current = contentKey;
11728
- return;
11729
- }
11730
- if (iframeState === "idle" && !iframeRef.current.src) {
11731
- log("Content is empty and iframe is idle with no src, skipping");
11732
- renderedContentKeyRef.current = contentKey;
11733
- return;
11734
- }
11735
- }
11736
- log("Content key changed:", { old: renderedContentKeyRef.current, new: contentKey });
11737
- renderedContentKeyRef.current = contentKey;
11738
- setIframeState("idle");
11739
- setAutoHeight(null);
11740
- initializeAttemptsRef.current = 0;
11741
- pendingNotificationsRef.current = [];
11742
- if (initializeTimerRef.current !== null) {
11743
- clearTimeout(initializeTimerRef.current);
11744
- initializeTimerRef.current = null;
11745
- }
11746
- if (currentBlobUrlRef.current) {
11747
- URL.revokeObjectURL(currentBlobUrlRef.current);
11748
- currentBlobUrlRef.current = null;
11749
- }
11750
- if (appHtml) {
11751
- const blob = new Blob([appHtml], { type: "text/html" });
11752
- const url2 = URL.createObjectURL(blob);
11753
- currentBlobUrlRef.current = url2;
11754
- iframeRef.current.src = url2;
11755
- log("Set iframe src to blob URL");
11756
- } else if (appUrl) {
11757
- iframeRef.current.src = appUrl;
11758
- log("Set iframe src to URL:", appUrl);
11759
- }
11760
- }, [contentKey, appHtml, appUrl, iframeState, log]);
11761
- useEffect(() => {
11762
- if (iframeState === "loading") {
11763
- log("Iframe loaded, sending ui/initialize");
11764
- setIframeState("initializing");
11765
- sendInitializeWithRetry();
11766
- }
11767
- }, [iframeState, sendInitializeWithRetry, log]);
11768
- const prevStateRef = useRef(void 0);
11769
- useEffect(() => {
11770
- if (iframeState !== "ready") {
11771
- prevStateRef.current = mcpAppData == null ? void 0 : mcpAppData.state;
11772
- return;
11773
- }
11774
- const currentState = mcpAppData == null ? void 0 : mcpAppData.state;
11775
- const prevState = prevStateRef.current;
11776
- const stateChanged = JSON.stringify(currentState) !== JSON.stringify(prevState);
11777
- if (stateChanged && currentState !== void 0) {
11778
- log("State changed after initialization, sending host-context-changed");
11779
- sendNotification("ui/notifications/host-context-changed", {
11780
- state: currentState,
11781
- toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
11782
- ...initialHostContext
11783
- });
11784
- prevStateRef.current = currentState;
11785
- }
11786
- }, [iframeState, mcpAppData == null ? void 0 : mcpAppData.state, mcpAppData == null ? void 0 : mcpAppData.toolInfo, initialHostContext, sendNotification, log]);
11787
- const handleIframeLoad = useCallback(() => {
11788
- log("Iframe onLoad fired");
11789
- setIframeState((prev2) => prev2 === "idle" ? "loading" : prev2);
11790
- }, [log]);
12088
+ });
11791
12089
  useEffect(() => {
11792
12090
  var _a2;
11793
12091
  if (mcpAppHostContext && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11794
12092
  mcpAppHostContext.registerApp(mcpAppId, iframeRef.current.contentWindow);
11795
12093
  return () => mcpAppHostContext.unregisterApp(mcpAppId);
11796
12094
  }
11797
- }, [mcpAppId, mcpAppHostContext]);
12095
+ }, [mcpAppId, mcpAppHostContext, iframeRef]);
11798
12096
  const chatContextRef = useRef(chatContext);
11799
12097
  chatContextRef.current = chatContext;
11800
12098
  useEffect(() => {
11801
12099
  const ctx = chatContextRef.current;
11802
- if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender)) {
12100
+ if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender))
11803
12101
  return;
11804
- }
11805
- const sender = (method, params) => {
11806
- var _a2;
11807
- if (iframeStateRef.current !== "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11808
- pendingNotificationsRef.current.push({ method, params });
11809
- return;
11810
- }
11811
- if (method === "ui/notifications/tool-input" || method === "ui/notifications/tool-input-partial") {
11812
- const args = params == null ? void 0 : params.arguments;
11813
- if (!args || args === "" || typeof args !== "object" || Object.keys(args).length === 0) {
11814
- return;
11815
- }
11816
- }
11817
- if (method === "ui/notifications/tool-result") {
11818
- const result = params == null ? void 0 : params.result;
11819
- if (result === "" || result === void 0) {
11820
- return;
11821
- }
11822
- }
11823
- iframeRef.current.contentWindow.postMessage(
11824
- { jsonrpc: "2.0", method, params },
11825
- "*"
11826
- );
11827
- };
11828
- const unregister = ctx.registerToolNotificationSender(mcpAppId, sender);
12102
+ const unregister = ctx.registerToolNotificationSender(mcpAppId, sendToolNotification);
11829
12103
  return unregister;
11830
- }, [mcpAppId]);
12104
+ }, [mcpAppId, sendToolNotification]);
11831
12105
  useEffect(() => {
11832
12106
  const ctx = chatContextRef.current;
11833
- if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback)) {
12107
+ if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback))
11834
12108
  return;
11835
- }
11836
- const callback = (stepUpdate) => {
11837
- var _a2;
11838
- if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11839
- return;
11840
- const toolName = (stepUpdate == null ? void 0 : stepUpdate.stepToolName) || (stepUpdate == null ? void 0 : stepUpdate.toolName);
11841
- const toolPhase = stepUpdate == null ? void 0 : stepUpdate.toolPhase;
11842
- const toolArguments = stepUpdate == null ? void 0 : stepUpdate.stepToolArguments;
11843
- const toolProgress = stepUpdate == null ? void 0 : stepUpdate.stepToolProgress;
11844
- const rawToolResult = stepUpdate == null ? void 0 : stepUpdate.stepToolResult;
11845
- if (!toolName)
11846
- return;
11847
- const parseIfJson = (value2) => {
11848
- if (value2 === void 0 || value2 === null || value2 === "")
11849
- return void 0;
11850
- if (typeof value2 === "object")
11851
- return value2;
11852
- if (typeof value2 === "string" && value2.trim()) {
11853
- try {
11854
- return JSON.parse(value2);
11855
- } catch {
11856
- return value2;
11857
- }
11858
- }
11859
- return value2;
11860
- };
11861
- const toolResult = parseIfJson(rawToolResult);
11862
- const sendOrQueue = (method, params) => {
11863
- var _a3;
11864
- if (iframeStateRef.current === "ready" && ((_a3 = iframeRef.current) == null ? void 0 : _a3.contentWindow)) {
11865
- iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method, params }, "*");
11866
- } else {
11867
- pendingNotificationsRef.current.push({ method, params });
11868
- }
11869
- };
11870
- if (toolPhase === "executing" && toolArguments) {
11871
- sendOrQueue("ui/notifications/tool-input", {
11872
- tool: { name: toolName },
11873
- arguments: toolArguments
11874
- });
11875
- }
11876
- if (toolProgress) {
11877
- sendOrQueue("ui/notifications/tool-input-partial", {
11878
- tool: { name: toolName },
11879
- arguments: { ...toolProgress, _botdojoProgress: true }
11880
- });
11881
- } else if (toolPhase === "streaming_args" && (stepUpdate.stepId || stepUpdate.stepLabel)) {
11882
- sendOrQueue("ui/notifications/tool-input-partial", {
11883
- tool: { name: toolName },
11884
- arguments: {
11885
- ...toolArguments || {},
11886
- stepId: stepUpdate.stepId,
11887
- stepLabel: stepUpdate.stepLabel
11888
- }
11889
- });
11890
- }
11891
- if (toolResult !== void 0 && toolResult !== "") {
11892
- sendOrQueue("ui/notifications/tool-result", {
11893
- tool: { name: toolName },
11894
- result: toolResult
11895
- });
11896
- }
11897
- };
11898
- const unregister = ctx.registerStepUpdateCallback(mcpAppId, callback);
12109
+ const unregister = ctx.registerStepUpdateCallback(mcpAppId, sendStepUpdate);
11899
12110
  return unregister;
11900
- }, [mcpAppId]);
11901
- useEffect(() => {
11902
- return () => {
11903
- if (currentBlobUrlRef.current) {
11904
- URL.revokeObjectURL(currentBlobUrlRef.current);
11905
- currentBlobUrlRef.current = null;
11906
- }
11907
- };
11908
- }, []);
11909
- useEffect(() => {
11910
- return () => {
11911
- if (initializeTimerRef.current !== null) {
11912
- clearTimeout(initializeTimerRef.current);
11913
- }
11914
- pendingRequestsRef.current.forEach(({ timer, reject }) => {
11915
- if (timer)
11916
- clearTimeout(timer);
11917
- reject(new Error("Component unmounted"));
11918
- });
11919
- pendingRequestsRef.current.clear();
11920
- };
11921
- }, []);
12111
+ }, [mcpAppId, sendStepUpdate]);
11922
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
+ }
11923
12177
  return /* @__PURE__ */ jsx(
11924
12178
  "iframe",
11925
12179
  {
11926
12180
  ref: iframeRef,
12181
+ src: iframeSrc,
11927
12182
  title: `mcp-app-${mcpAppId}`,
11928
12183
  onLoad: handleIframeLoad,
11929
12184
  style: {
@@ -12808,12 +13063,12 @@ var BotDojoChatConfigurator = ({
12808
13063
  };
12809
13064
 
12810
13065
  // src/index.tsx
12811
- var import_sdk_canvas5 = __toESM(require_src3());
13066
+ var import_sdk_canvas6 = __toESM(require_src3());
12812
13067
  var import_sdk_types2 = __toESM(require_lib());
12813
13068
  var CanvasContext = createContext(null);
12814
13069
 
12815
13070
  // src/canvas/BotDojoCanvasProvider.tsx
12816
- var import_sdk_canvas4 = __toESM(require_src3());
13071
+ var import_sdk_canvas5 = __toESM(require_src3());
12817
13072
  var DEFAULT_ACK_TTL_MS = 3 * 60 * 1e3;
12818
13073
  var DEFAULT_RESPONSE_TIMEOUT_MS = 2e4;
12819
13074
  var MCP_FUNCTION_NAME_MAP = {
@@ -13011,7 +13266,7 @@ function BotDojoCanvasProvider({
13011
13266
  const apiKey = window.BOTDOJO_API_KEY || "embedded-canvas";
13012
13267
  let createdConnector = null;
13013
13268
  try {
13014
- const conn = new import_sdk_canvas4.BotDojoConnector({
13269
+ const conn = new import_sdk_canvas5.BotDojoConnector({
13015
13270
  apiKey,
13016
13271
  accountId: "embedded",
13017
13272
  projectId: "embedded",
@@ -13700,7 +13955,7 @@ function useBotDojoCanvas() {
13700
13955
  }
13701
13956
  return context;
13702
13957
  }
13703
- var export_BotDojoConnector = import_sdk_canvas5.BotDojoConnector;
13958
+ var export_BotDojoConnector = import_sdk_canvas6.BotDojoConnector;
13704
13959
  var export_MIME_TYPES = import_sdk_types2.MIME_TYPES;
13705
13960
  var export_citation = import_sdk_types2.citation;
13706
13961
  var export_citations = import_sdk_types2.citations;