@botdojo/chat-sdk 0.0.10 → 0.0.12

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
@@ -70,7 +70,7 @@ var require_tool_utils = __commonJS({
70
70
  function uiResource2(uri, options) {
71
71
  const resource = {
72
72
  uri,
73
- mimeType: (options == null ? void 0 : options.mimeType) || (uri.startsWith("ui://") ? "text/html+mcp" : index_1.MIME_TYPES.URI_LIST)
73
+ mimeType: (options == null ? void 0 : options.mimeType) || (uri.startsWith("ui://") ? index_1.MIME_TYPES.HTML_MCP_PROFILE : index_1.MIME_TYPES.URI_LIST)
74
74
  };
75
75
  if (options == null ? void 0 : options.html) {
76
76
  resource.html = options.html;
@@ -232,7 +232,7 @@ var require_toolResponseMapper = __commonJS({
232
232
  function toCanvasFromResource(resource) {
233
233
  var _a;
234
234
  const mime = resource.mimeType || "text/uri-list";
235
- const isMcp = mime === "text/uri-list" || mime === "text/html" || mime === "text/html+mcp";
235
+ const isMcp = mime === "text/uri-list" || mime === "text/html" || mime === "text/html+mcp" || mime === "text/html;profile=mcp-app";
236
236
  if (!isMcp)
237
237
  return void 0;
238
238
  const meta = resource.meta || {};
@@ -465,7 +465,7 @@ var require_modelContextTranslation_snapshot = __commonJS({
465
465
  if (!canvasTemplate && ((_d = (_c = tool2._meta) == null ? void 0 : _c.ui) == null ? void 0 : _d.resourceUri)) {
466
466
  canvasTemplate = convertUiResourceTemplateToCanvasTemplate({
467
467
  uri: tool2._meta.ui.resourceUri,
468
- mimeType: tool2._meta.ui.mimeType || "text/html+mcp",
468
+ mimeType: tool2._meta.ui.mimeType || "text/html;profile=mcp-app",
469
469
  metadata: { ui: tool2._meta.ui }
470
470
  });
471
471
  }
@@ -552,6 +552,30 @@ var require_converters = __commonJS({
552
552
  subSteps: (_a = internalStep.subIntermediateSteps) == null ? void 0 : _a.map(toSDKStep)
553
553
  };
554
554
  delete sdkStep.subIntermediateSteps;
555
+ if (!sdkStep.stepToolArguments && internalStep.arguments) {
556
+ const argsString = internalStep.arguments;
557
+ if (typeof argsString === "string" && argsString.trim()) {
558
+ try {
559
+ sdkStep.stepToolArguments = JSON.parse(argsString);
560
+ } catch {
561
+ }
562
+ }
563
+ }
564
+ if (!sdkStep.stepToolResult && internalStep.toolPhase === "complete" && internalStep.content) {
565
+ const content = internalStep.content;
566
+ if (content.trim().startsWith("{") || content.trim().startsWith("[")) {
567
+ try {
568
+ sdkStep.stepToolResult = JSON.parse(content);
569
+ } catch {
570
+ sdkStep.stepToolResult = content;
571
+ }
572
+ } else {
573
+ sdkStep.stepToolResult = content;
574
+ }
575
+ }
576
+ if (internalStep.toolPhase) {
577
+ sdkStep.stepToolPhase = internalStep.toolPhase;
578
+ }
555
579
  return sdkStep;
556
580
  }
557
581
  exports.toSDKStep = toSDKStep;
@@ -646,12 +670,13 @@ var require_lib = __commonJS({
646
670
  __createBinding(exports2, m, p);
647
671
  };
648
672
  Object.defineProperty(exports, "__esModule", { value: true });
649
- exports.toInternalRunOptions = exports.toInternalCallbacks = exports.toInternalStep = exports.toSDKStep = exports.translateResourcesToBackend = exports.translatePromptsToBackend = exports.translateToolsToBackend = exports.translateModelContextToBackend = exports.extractUriParams = exports.matchesUriTemplate = exports.isDynamicResource = exports.buildResourceProvider = exports.mapToolResponseToBackend = exports.citations = exports.citation = exports.mcpResource = exports.uiResource = exports.imageResult = exports.textResult = exports.extractToolHandlers = exports.toolsToModelContext = exports.modelContext = exports.tool = exports.MIME_TYPES = void 0;
673
+ exports.toInternalRunOptions = exports.toInternalCallbacks = exports.toInternalStep = exports.toSDKStep = exports.translateResourcesToBackend = exports.translatePromptsToBackend = exports.translateToolsToBackend = exports.translateModelContextToBackend = exports.extractUriParams = exports.matchesUriTemplate = exports.isDynamicResource = exports.buildResourceProvider = exports.mapToolResponseToBackend = exports.citations = exports.citation = exports.mcpResource = exports.uiResource = exports.imageResult = exports.textResult = exports.extractToolHandlers = exports.toolsToModelContext = exports.modelContext = exports.tool = exports.MCP_HTML_MIME_TYPES = exports.MIME_TYPES = void 0;
650
674
  exports.MIME_TYPES = {
651
675
  // UI Canvas types (MCP Apps standard)
652
676
  URI_LIST: "text/uri-list",
653
677
  HTML: "text/html",
654
678
  HTML_MCP: "text/html+mcp",
679
+ HTML_MCP_PROFILE: "text/html;profile=mcp-app",
655
680
  // Remote DOM (both MCP Apps standard and BotDojo alias)
656
681
  REMOTE_DOM: "application/vnd.mcp-ui.remote-dom",
657
682
  REMOTE_DOM_BOTDOJO: "application/vnd.botdojo.ui-remote-dom",
@@ -660,6 +685,10 @@ var require_lib = __commonJS({
660
685
  CITATION: "application/vnd.botdojo.citation",
661
686
  CITATIONS: "application/vnd.botdojo.citations"
662
687
  };
688
+ exports.MCP_HTML_MIME_TYPES = [
689
+ exports.MIME_TYPES.HTML_MCP,
690
+ exports.MIME_TYPES.HTML_MCP_PROFILE
691
+ ];
663
692
  var tool_utils_1 = require_tool_utils();
664
693
  Object.defineProperty(exports, "tool", { enumerable: true, get: function() {
665
694
  return tool_utils_1.tool;
@@ -2412,7 +2441,7 @@ var require_BotDojoConnector = __commonJS({
2412
2441
  * Register all callbacks for incoming requests
2413
2442
  */
2414
2443
  registerCallbacks() {
2415
- var _a, _b;
2444
+ var _a, _b, _c;
2416
2445
  if (!this.connection)
2417
2446
  return;
2418
2447
  this.connection.callbacks.set("getModelContexts", {
@@ -2484,9 +2513,9 @@ var require_BotDojoConnector = __commonJS({
2484
2513
  for (const tool2 of toolsArray) {
2485
2514
  if (tool2.execute && tool2.name) {
2486
2515
  const toolName = tool2.name;
2487
- const resourceTemplate = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a["botdojo/resource-template"];
2488
- const hasResourceTemplate = !!resourceTemplate;
2489
- const displayName = ((_b = tool2._meta) === null || _b === void 0 ? void 0 : _b["botdojo/display-name"]) || toolName;
2516
+ const uiResourceUri = (_b = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a.ui) === null || _b === void 0 ? void 0 : _b.resourceUri;
2517
+ const hasResourceTemplate = !!uiResourceUri;
2518
+ const displayName = ((_c = tool2._meta) === null || _c === void 0 ? void 0 : _c["botdojo/display-name"]) || toolName;
2490
2519
  this.connection.callbacks.set(toolName, {
2491
2520
  source: this.connection.sender,
2492
2521
  func: async (...args) => {
@@ -2532,6 +2561,7 @@ var require_BotDojoConnector = __commonJS({
2532
2561
  }
2533
2562
  };
2534
2563
  const rawresult = await tool2.execute(...args, context2);
2564
+ await context2.notifyToolResult(rawresult);
2535
2565
  return await (0, sdk_types_1.mapToolResponseToBackend)(rawresult);
2536
2566
  }
2537
2567
  const defaultCanvasId = argCanvasId || fallbackCanvasId;
@@ -2558,6 +2588,7 @@ var require_BotDojoConnector = __commonJS({
2558
2588
  }
2559
2589
  };
2560
2590
  const rawResult = await tool2.execute(...args, context);
2591
+ await context.notifyToolResult(rawResult);
2561
2592
  return await (0, sdk_types_1.mapToolResponseToBackend)(rawResult);
2562
2593
  }
2563
2594
  });
@@ -2803,7 +2834,7 @@ var require_BotDojoConnector = __commonJS({
2803
2834
  * Setup agent_host callbacks on the provided RPCConnection
2804
2835
  */
2805
2836
  setupHostClientCallbacks() {
2806
- var _a, _b;
2837
+ var _a, _b, _c;
2807
2838
  if (!this._hostClient)
2808
2839
  return;
2809
2840
  this._hostClient.callbacks.set("getModelContexts", {
@@ -2873,9 +2904,9 @@ var require_BotDojoConnector = __commonJS({
2873
2904
  for (const tool2 of toolsArray) {
2874
2905
  if (tool2.execute && tool2.name) {
2875
2906
  const toolName = tool2.name;
2876
- const resourceTemplate = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a["botdojo/resource-template"];
2877
- const hasResourceTemplate = !!resourceTemplate;
2878
- const displayName = ((_b = tool2._meta) === null || _b === void 0 ? void 0 : _b["botdojo/display-name"]) || toolName;
2907
+ const uiResourceUri = (_b = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a.ui) === null || _b === void 0 ? void 0 : _b.resourceUri;
2908
+ const hasResourceTemplate = !!uiResourceUri;
2909
+ const displayName = ((_c = tool2._meta) === null || _c === void 0 ? void 0 : _c["botdojo/display-name"]) || toolName;
2879
2910
  console.log(`\u{1F527} Registering modelContext tool on host client: ${toolName}, hasResource: ${hasResourceTemplate}`);
2880
2911
  this._hostClient.callbacks.set(toolName, {
2881
2912
  source: this._hostClient.sender,
@@ -2926,6 +2957,7 @@ var require_BotDojoConnector = __commonJS({
2926
2957
  }
2927
2958
  };
2928
2959
  const rawresult2 = await tool2.execute(...args, context2);
2960
+ await context2.notifyToolResult(rawresult2);
2929
2961
  const result2 = await (0, sdk_types_1.mapToolResponseToBackend)(rawresult2);
2930
2962
  console.log(`\u2705 Tool executed successfully: ${toolName}`);
2931
2963
  return result2;
@@ -2954,6 +2986,7 @@ var require_BotDojoConnector = __commonJS({
2954
2986
  }
2955
2987
  };
2956
2988
  const rawresult = await tool2.execute(...args, context);
2989
+ await context.notifyToolResult(rawresult);
2957
2990
  const result = await (0, sdk_types_1.mapToolResponseToBackend)(rawresult);
2958
2991
  console.log(`\u2705 Tool executed successfully: ${toolName}`);
2959
2992
  return result;
@@ -3105,12 +3138,17 @@ var require_BotDojoConnector = __commonJS({
3105
3138
  });
3106
3139
  return;
3107
3140
  }
3108
- const stepUpdate = Object.assign(Object.assign(Object.assign(Object.assign({ stepId: resolvedStepId, toolPhase: "executing", stepStatus: "processing", canvas: {
3109
- canvasId: resolvedCanvasId,
3110
- canvasType: canvasType || "mcp-app",
3111
- // Default to mcp-app for MCP Apps canvases
3112
- canvasData
3113
- } }, (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.toolName) ? { toolName: toolInfo.toolName } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.toolLabel) ? { toolLabel: toolInfo.toolLabel } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.arguments) !== void 0 ? { arguments: toolInfo.arguments } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.result) !== void 0 ? { result: toolInfo.result } : {});
3141
+ const stepUpdate = Object.assign(Object.assign(Object.assign(Object.assign({ stepId: resolvedStepId, toolPhase: "executing", stepStatus: "processing" }, (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.toolName) ? { toolName: toolInfo.toolName } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.toolLabel) ? { toolLabel: toolInfo.toolLabel } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.arguments) !== void 0 ? { arguments: toolInfo.arguments } : {}), (toolInfo === null || toolInfo === void 0 ? void 0 : toolInfo.result) !== void 0 ? { result: toolInfo.result } : {});
3142
+ if (canvasData !== void 0) {
3143
+ stepUpdate.canvas = {
3144
+ canvasId: resolvedCanvasId,
3145
+ canvasType: canvasType || "mcp-app",
3146
+ canvasData
3147
+ };
3148
+ }
3149
+ if (resolvedCanvasId && canvasData === void 0) {
3150
+ stepUpdate.canvasId = resolvedCanvasId;
3151
+ }
3114
3152
  if (this.transport === "postmessage" && this.connection) {
3115
3153
  await this.connection.sendRequest("agent_host", "onIntermediateStepUpdate", [stepUpdate], 5e3);
3116
3154
  return;
@@ -7074,11 +7112,11 @@ var require_BotDojoCanvasClient = __commonJS({
7074
7112
  });
7075
7113
  const { getConnectionToFunctionCall } = await Promise.resolve().then(() => __importStar(require_src2()));
7076
7114
  this._client = await getConnectionToFunctionCall(this.config.url, this.config.channel, this.config.senderId, this.config.receiverId, async (msg) => {
7077
- console.log(`log_canvas_client:${this.clientId} - Received message:`, {
7115
+ console.log(`log_canvas_client:${this.clientId} - Received message:`, JSON.stringify({
7078
7116
  functionName: msg.functionName,
7079
7117
  destination: msg.destination,
7080
7118
  data: msg.data
7081
- });
7119
+ }, null, 2));
7082
7120
  try {
7083
7121
  let callbackOnMessage = this.callbacks.get("message");
7084
7122
  if (callbackOnMessage) {
@@ -7302,7 +7340,7 @@ var require_BotDojoCanvas = __commonJS({
7302
7340
  }
7303
7341
  }, [chatModelContext, externalUISocketUrl, registerStatus]);
7304
7342
  const connectToHost = (0, react_1.useCallback)(async () => {
7305
- var _a, _b;
7343
+ var _a, _b, _c;
7306
7344
  try {
7307
7345
  setRegisterStatus("connecting");
7308
7346
  setRegisterStatusMessage("Connecting to canvas");
@@ -7321,8 +7359,8 @@ var require_BotDojoCanvas = __commonJS({
7321
7359
  for (const tool2 of toolsArray) {
7322
7360
  if (tool2.execute && tool2.name) {
7323
7361
  const toolName = tool2.name;
7324
- const resourceTemplate = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a["botdojo/resource-template"];
7325
- const displayName = ((_b = tool2._meta) === null || _b === void 0 ? void 0 : _b["botdojo/display-name"]) || toolName;
7362
+ const uiResourceUri = (_b = (_a = tool2._meta) === null || _a === void 0 ? void 0 : _a.ui) === null || _b === void 0 ? void 0 : _b.resourceUri;
7363
+ const displayName = ((_c = tool2._meta) === null || _c === void 0 ? void 0 : _c["botdojo/display-name"]) || toolName;
7326
7364
  console.log(`[BotDojoCanvas] Registering tool from MCP: ${toolName}`);
7327
7365
  const wrappedExecutor = async (params) => {
7328
7366
  const result = await tool2.execute(params);
@@ -7732,6 +7770,7 @@ var require_AppBridge = __commonJS({
7732
7770
  this.sandboxResourceCache.clear();
7733
7771
  }
7734
7772
  sendToolInputPartial(params) {
7773
+ console.log("[AppBridge] sendToolInputPartial:", params);
7735
7774
  this.sendNotification("ui/notifications/tool-input-partial", params);
7736
7775
  }
7737
7776
  sendToolInput(params) {
@@ -7755,9 +7794,9 @@ var require_AppBridge = __commonJS({
7755
7794
  sendInitialize() {
7756
7795
  const hostCapabilities = Object.assign({}, this.options.hostCapabilities || {});
7757
7796
  if (!hostCapabilities.extensions) {
7758
- hostCapabilities.extensions = { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] } };
7797
+ hostCapabilities.extensions = { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] } };
7759
7798
  } else if (!hostCapabilities.extensions["io.modelcontextprotocol/ui"]) {
7760
- hostCapabilities.extensions = Object.assign(Object.assign({}, hostCapabilities.extensions), { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] } });
7799
+ hostCapabilities.extensions = Object.assign(Object.assign({}, hostCapabilities.extensions), { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] } });
7761
7800
  }
7762
7801
  const params = {
7763
7802
  protocolVersion: "mcp-apps/0.1",
@@ -7805,8 +7844,10 @@ var require_AppBridge = __commonJS({
7805
7844
  }
7806
7845
  enqueue(msg) {
7807
7846
  if (this.transport) {
7847
+ console.log("[AppBridge] Sending immediately:", msg.method || "response");
7808
7848
  this.transport.send(msg);
7809
7849
  } else {
7850
+ console.log("[AppBridge] Queuing (no transport yet):", msg.method || "response");
7810
7851
  this.pendingQueue.push(msg);
7811
7852
  }
7812
7853
  }
@@ -8013,12 +8054,15 @@ var require_AppBridge = __commonJS({
8013
8054
  }
8014
8055
  }
8015
8056
  async handleSandboxResourceRequest(params) {
8057
+ var _a, _b, _c;
8016
8058
  const resource = params === null || params === void 0 ? void 0 : params.resource;
8059
+ console.log("[AppBridge] \u{1F4E6} handleSandboxResourceRequest called for resource:", resource);
8017
8060
  if (!resource)
8018
8061
  return;
8019
8062
  const cacheKey = `${params.flowId || "unknown"}|${resource}`;
8020
8063
  if (this.sandboxResourceCache.has(cacheKey)) {
8021
8064
  const cached = this.sandboxResourceCache.get(cacheKey);
8065
+ console.log("[AppBridge] \u{1F4E6} Using CACHED HTML for:", resource, "length:", (_a = cached.html) === null || _a === void 0 ? void 0 : _a.length);
8022
8066
  this.sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({ resource, flowId: params.flowId }, cached));
8023
8067
  this.sendInitializeWithRetry();
8024
8068
  return;
@@ -8026,15 +8070,18 @@ var require_AppBridge = __commonJS({
8026
8070
  if (!this.options.onSandboxResourceRequest)
8027
8071
  return;
8028
8072
  try {
8073
+ console.log("[AppBridge] \u{1F4E6} Fetching FRESH HTML for:", resource);
8029
8074
  const resolved = await this.options.onSandboxResourceRequest({ resource, flowId: params.flowId, canvasId: params.canvasId });
8030
8075
  const payload = typeof resolved === "string" ? { html: resolved } : resolved;
8031
8076
  if (payload === null || payload === void 0 ? void 0 : payload.html) {
8077
+ console.log("[AppBridge] \u{1F4E6} Got HTML for:", resource, "length:", (_b = payload.html) === null || _b === void 0 ? void 0 : _b.length, "first 100 chars:", (_c = payload.html) === null || _c === void 0 ? void 0 : _c.substring(0, 100));
8032
8078
  const entry = {
8033
8079
  html: payload.html,
8034
8080
  sandbox: payload.sandbox || DEFAULT_UI_CSP.sandbox,
8035
8081
  csp: payload.csp || DEFAULT_UI_CSP.csp
8036
8082
  };
8037
8083
  this.sandboxResourceCache.set(cacheKey, entry);
8084
+ console.log("[AppBridge] \u{1F4E6} Sending sandbox-resource-ready for:", resource);
8038
8085
  this.sendNotification("ui/notifications/sandbox-resource-ready", Object.assign({ resource, flowId: params.flowId }, entry));
8039
8086
  this.sendInitializeWithRetry();
8040
8087
  }
@@ -8507,7 +8554,19 @@ var BotDojoChat = ({
8507
8554
  console.log("[BotDojoChat] Waiting for iframe to load...");
8508
8555
  let iframeRetries = 0;
8509
8556
  const maxIframeRetries = 100;
8510
- while (!iframeLoadedRef.current && iframeRetries < maxIframeRetries) {
8557
+ const isIframeReady = () => {
8558
+ var _a;
8559
+ if (iframeLoadedRef.current)
8560
+ return true;
8561
+ if ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) {
8562
+ console.log("[BotDojoChat] Iframe already loaded (contentWindow available)");
8563
+ iframeLoadedRef.current = true;
8564
+ setIframeLoaded(true);
8565
+ return true;
8566
+ }
8567
+ return false;
8568
+ };
8569
+ while (!isIframeReady() && iframeRetries < maxIframeRetries) {
8511
8570
  await new Promise((resolve) => setTimeout(resolve, 100));
8512
8571
  iframeRetries++;
8513
8572
  }
@@ -8518,7 +8577,17 @@ var BotDojoChat = ({
8518
8577
  console.log("[BotDojoChat] Waiting for chat_ready signal...");
8519
8578
  let readyRetries = 0;
8520
8579
  const maxReadyRetries = 150;
8521
- while (!chatReadyRef.current && readyRetries < maxReadyRetries) {
8580
+ const isChatReady = () => {
8581
+ if (chatReadyRef.current)
8582
+ return true;
8583
+ if (connectionRef.current) {
8584
+ console.log("[BotDojoChat] Chat ready (RPC connection established)");
8585
+ chatReadyRef.current = true;
8586
+ return true;
8587
+ }
8588
+ return false;
8589
+ };
8590
+ while (!isChatReady() && readyRetries < maxReadyRetries) {
8522
8591
  await new Promise((resolve) => setTimeout(resolve, 100));
8523
8592
  readyRetries++;
8524
8593
  }
@@ -8588,7 +8657,7 @@ var BotDojoChat = ({
8588
8657
  case "ui/initialize": {
8589
8658
  const result = {
8590
8659
  hostInfo: { name: "BotDojo Chat Host", version: "1.0.0" },
8591
- capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] } } },
8660
+ capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] } } },
8592
8661
  hostContext: {}
8593
8662
  };
8594
8663
  reply({ result });
@@ -8983,6 +9052,8 @@ var BotDojoChat = ({
8983
9052
  const uri = canvasEvent.resource;
8984
9053
  const mimeType = canvasEvent.mimeType;
8985
9054
  const connection2 = (_c = (_b = connectorRef.current) == null ? void 0 : _b.getConnection) == null ? void 0 : _c.call(_b);
9055
+ console.log("[BotDojoChat] sandbox-resource request for URI:", uri);
9056
+ console.log("[BotDojoChat] sandbox-resource: connection available?", !!(connection2 == null ? void 0 : connection2.sendRequest));
8986
9057
  const matchesTemplate = (template, value2) => {
8987
9058
  if (!template || !value2)
8988
9059
  return false;
@@ -9046,14 +9117,23 @@ var BotDojoChat = ({
9046
9117
  if (!uri || !modelContext2)
9047
9118
  return { error: "no modelContext" };
9048
9119
  const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
9049
- const match = contexts.flatMap((ctx) => ctx.resources || []).find((r) => {
9120
+ const allResources = contexts.flatMap((ctx) => ctx.resources || []);
9121
+ console.log("[BotDojoChat] tryModelContext: Searching", allResources.length, "resources for URI:", uri);
9122
+ allResources.forEach((r, i2) => {
9123
+ console.log(`[BotDojoChat] tryModelContext: Resource[${i2}].uri =`, r.uri);
9124
+ });
9125
+ const match = allResources.find((r) => {
9050
9126
  const candidate = r;
9051
9127
  const uriMatch = typeof (candidate == null ? void 0 : candidate.uri) === "string" && candidate.uri === uri;
9052
9128
  const templateMatch = "uriTemplate" in candidate && candidate.uriTemplate && matchesTemplate(candidate.uriTemplate, uri);
9129
+ console.log("[BotDojoChat] tryModelContext: Checking", candidate == null ? void 0 : candidate.uri, "=== ", uri, "?", uriMatch);
9053
9130
  return uriMatch || templateMatch;
9054
9131
  });
9055
- if (!match)
9132
+ if (!match) {
9133
+ console.log("[BotDojoChat] tryModelContext: No match found");
9056
9134
  return { error: "resource not found in modelContext" };
9135
+ }
9136
+ console.log("[BotDojoChat] tryModelContext: MATCH FOUND:", match.uri);
9057
9137
  try {
9058
9138
  const content = typeof match.getContent === "function" ? await match.getContent(
9059
9139
  "uriTemplate" in match && match.uriTemplate ? extractTemplateParams(match.uriTemplate, uri) : void 0
@@ -9073,16 +9153,22 @@ var BotDojoChat = ({
9073
9153
  return { error: (e == null ? void 0 : e.message) || "modelContext getContent error" };
9074
9154
  }
9075
9155
  };
9156
+ console.log("[BotDojoChat] sandbox-resource: Trying connector first...");
9076
9157
  const connectorResult = await tryConnector();
9158
+ console.log("[BotDojoChat] sandbox-resource: tryConnector result:", connectorResult.html ? `got HTML (${connectorResult.html.length} chars)` : connectorResult.error);
9077
9159
  if (connectorResult.html) {
9160
+ console.log("[BotDojoChat] sandbox-resource: Using connector result");
9078
9161
  return {
9079
9162
  html: connectorResult.html,
9080
9163
  sandbox: connectorResult.sandbox || canvasEvent.sandbox,
9081
9164
  csp: connectorResult.csp
9082
9165
  };
9083
9166
  }
9167
+ console.log("[BotDojoChat] sandbox-resource: Connector failed, trying modelContext...");
9084
9168
  const mcResult = await tryModelContext();
9169
+ console.log("[BotDojoChat] sandbox-resource: tryModelContext result:", mcResult.html ? `got HTML (${mcResult.html.length} chars)` : mcResult.error);
9085
9170
  if (mcResult.html) {
9171
+ console.log("[BotDojoChat] sandbox-resource: Using modelContext result");
9086
9172
  return {
9087
9173
  html: mcResult.html,
9088
9174
  sandbox: mcResult.sandbox || canvasEvent.sandbox,
@@ -9928,13 +10014,17 @@ function findOrCreateStep(steps, stepId, parentStepId) {
9928
10014
  return newStep;
9929
10015
  }
9930
10016
  function mergeStep(existing, update) {
10017
+ var _a;
9931
10018
  return {
9932
10019
  ...existing,
9933
10020
  ...update,
9934
10021
  // Preserve fields that shouldn't be overwritten by partial updates
9935
10022
  stepId: existing.stepId,
9936
10023
  startTime: existing.startTime,
9937
- subSteps: update.subSteps || existing.subSteps
10024
+ subSteps: update.subSteps || existing.subSteps,
10025
+ // CRITICAL: Preserve canvas from original step if update doesn't have one
10026
+ // This allows notifyToolInputPartial to send progress updates without destroying the canvas
10027
+ canvas: (_a = update.canvas) != null ? _a : existing.canvas
9938
10028
  };
9939
10029
  }
9940
10030
  function convertCoreMessage(msg) {
@@ -10007,17 +10097,6 @@ function chatReducer(state, action) {
10007
10097
  content: msg.content + tokenUpdate.token
10008
10098
  };
10009
10099
  }
10010
- if (tokenUpdate.updateType === "function" && tokenUpdate.stepId) {
10011
- const steps = msg.steps.map((step) => {
10012
- if (step.stepId !== tokenUpdate.stepId)
10013
- return step;
10014
- return {
10015
- ...step,
10016
- argumentStream: (step.argumentStream || "") + tokenUpdate.token
10017
- };
10018
- });
10019
- return { ...msg, steps };
10020
- }
10021
10100
  return msg;
10022
10101
  });
10023
10102
  return { ...state, messages };
@@ -10136,12 +10215,10 @@ function BotDojoChatProvider(props) {
10136
10215
  onSessionHydrated,
10137
10216
  onConnectorInit,
10138
10217
  onConnectorError,
10139
- // MCP-UI canvas handlers
10140
- onCanvasIntent,
10141
- onCanvasNotify,
10142
- onCanvasPrompt,
10143
- onCanvasLink,
10144
- onCanvasAction
10218
+ // MCP App handlers (SEP-1865)
10219
+ onOpenLink,
10220
+ onToolCall,
10221
+ onUiMessage
10145
10222
  } = props;
10146
10223
  const [state, dispatch] = useReducer(chatReducer, initialState);
10147
10224
  const iframeRef = useRef(null);
@@ -10153,21 +10230,22 @@ function BotDojoChatProvider(props) {
10153
10230
  const [connector, setConnector] = useState(null);
10154
10231
  const [isConnectorReady, setIsConnectorReady] = useState(false);
10155
10232
  const [isModelContextRegistered, setIsModelContextRegistered] = useState(false);
10156
- const canvasBridgesRef = useRef(/* @__PURE__ */ new Map());
10157
- const canvasIframeRefsRef = useRef(/* @__PURE__ */ new Map());
10158
- const pendingCanvasEventsRef = useRef(/* @__PURE__ */ new Map());
10159
- const [registeredCanvases, setRegisteredCanvases] = useState(/* @__PURE__ */ new Set());
10233
+ const appBridgesRef = useRef(/* @__PURE__ */ new Map());
10234
+ const appIframeRefsRef = useRef(/* @__PURE__ */ new Map());
10235
+ const pendingAppEventsRef = useRef(/* @__PURE__ */ new Map());
10236
+ const [registeredMcpApps, setRegisteredMcpApps] = useState(/* @__PURE__ */ new Set());
10160
10237
  const toolNotificationSendersRef = useRef(/* @__PURE__ */ new Map());
10161
10238
  const stepUpdateCallbacksRef = useRef(/* @__PURE__ */ new Map());
10162
- const activeCanvasByToolRef = useRef(/* @__PURE__ */ new Map());
10239
+ const activeAppByToolRef = useRef(/* @__PURE__ */ new Map());
10240
+ const stepIdToAppIdRef = useRef(/* @__PURE__ */ new Map());
10163
10241
  const pendingToolNotificationsRef = useRef(/* @__PURE__ */ new Map());
10164
10242
  const pendingBroadcastNotificationsRef = useRef([]);
10165
- const canvasHandlersRef = useRef({
10166
- onCanvasIntent,
10167
- onCanvasNotify,
10168
- onCanvasPrompt,
10169
- onCanvasLink,
10170
- onCanvasAction
10243
+ const toolArgumentsCacheRef = useRef(/* @__PURE__ */ new Map());
10244
+ const pendingStepUpdatesRef = useRef(/* @__PURE__ */ new Map());
10245
+ const appHandlersRef = useRef({
10246
+ onOpenLink,
10247
+ onToolCall,
10248
+ onUiMessage
10171
10249
  });
10172
10250
  const modelContextRef = useRef(modelContext2);
10173
10251
  useEffect(() => {
@@ -10184,14 +10262,12 @@ function BotDojoChatProvider(props) {
10184
10262
  return url2.toString();
10185
10263
  }, [apiKey, baseUrl, sessionId, newSession]);
10186
10264
  useEffect(() => {
10187
- canvasHandlersRef.current = {
10188
- onCanvasIntent,
10189
- onCanvasNotify,
10190
- onCanvasPrompt,
10191
- onCanvasLink,
10192
- onCanvasAction
10265
+ appHandlersRef.current = {
10266
+ onOpenLink,
10267
+ onToolCall,
10268
+ onUiMessage
10193
10269
  };
10194
- }, [onCanvasIntent, onCanvasNotify, onCanvasPrompt, onCanvasLink, onCanvasAction]);
10270
+ }, [onOpenLink, onToolCall, onUiMessage]);
10195
10271
  useEffect(() => {
10196
10272
  if (isSocketConnected && modelContext2) {
10197
10273
  setIsConnectorReady(true);
@@ -10228,91 +10304,104 @@ function BotDojoChatProvider(props) {
10228
10304
  }, baseUrl);
10229
10305
  }
10230
10306
  }, [baseUrl, serializeModelContext]);
10231
- const sendToolNotificationToCanvas = useCallback((canvasId, method, params) => {
10232
- console.log(`[BotDojoChatProvider] Sending tool notification to canvas ${canvasId}: ${method}`, params);
10233
- const sender = toolNotificationSendersRef.current.get(canvasId);
10307
+ const sendToolNotificationToApp = useCallback((appId, method, params) => {
10308
+ console.log(`[BotDojoChatProvider] Sending tool notification to app ${appId}: ${method}`, params);
10309
+ const sender = toolNotificationSendersRef.current.get(appId);
10234
10310
  if (sender) {
10235
10311
  try {
10236
10312
  sender(method, params);
10237
10313
  } catch (err) {
10238
- console.warn(`[BotDojoChatProvider] Failed to send notification to ${canvasId}:`, err);
10314
+ console.warn(`[BotDojoChatProvider] Failed to send notification to ${appId}:`, err);
10239
10315
  }
10240
10316
  } else {
10241
- console.log(`[BotDojoChatProvider] Canvas ${canvasId} not registered yet, queueing notification: ${method}`);
10242
- if (!pendingToolNotificationsRef.current.has(canvasId)) {
10243
- pendingToolNotificationsRef.current.set(canvasId, []);
10317
+ console.log(`[BotDojoChatProvider] App ${appId} not registered yet, queueing notification: ${method}`);
10318
+ if (!pendingToolNotificationsRef.current.has(appId)) {
10319
+ pendingToolNotificationsRef.current.set(appId, []);
10244
10320
  }
10245
- pendingToolNotificationsRef.current.get(canvasId).push({ method, params });
10321
+ pendingToolNotificationsRef.current.get(appId).push({ method, params });
10246
10322
  }
10247
10323
  }, []);
10248
- const broadcastToolNotification = useCallback((method, params, toolName) => {
10324
+ useCallback((method, params, toolName) => {
10249
10325
  var _a;
10250
10326
  console.log(`[BotDojoChatProvider] Broadcasting tool notification: ${method}`, params);
10251
10327
  if (toolNotificationSendersRef.current.size === 0) {
10252
- console.log(`[BotDojoChatProvider] No canvases registered, queueing broadcast notification: ${method}`);
10328
+ console.log(`[BotDojoChatProvider] No apps registered, queueing broadcast notification: ${method}`);
10253
10329
  pendingBroadcastNotificationsRef.current.push({ method, params, toolName: toolName || ((_a = params == null ? void 0 : params.tool) == null ? void 0 : _a.name) || "" });
10254
10330
  } else {
10255
- toolNotificationSendersRef.current.forEach((sender, mcpAppId) => {
10331
+ toolNotificationSendersRef.current.forEach((sender, appId) => {
10256
10332
  try {
10257
10333
  sender(method, params);
10258
10334
  } catch (err) {
10259
- console.warn(`[BotDojoChatProvider] Failed to send notification to ${mcpAppId}:`, err);
10335
+ console.warn(`[BotDojoChatProvider] Failed to send notification to ${appId}:`, err);
10260
10336
  }
10261
10337
  });
10262
10338
  }
10263
10339
  }, []);
10264
- const registerToolNotificationSender = useCallback((mcpAppId, sender) => {
10265
- console.log(`[BotDojoChatProvider] Registering tool notification sender for: ${mcpAppId}`);
10266
- toolNotificationSendersRef.current.set(mcpAppId, sender);
10267
- const pendingForCanvas = pendingToolNotificationsRef.current.get(mcpAppId);
10268
- if (pendingForCanvas && pendingForCanvas.length > 0) {
10269
- console.log(`[BotDojoChatProvider] Replaying ${pendingForCanvas.length} queued notifications for canvas: ${mcpAppId}`);
10270
- pendingForCanvas.forEach(({ method, params }) => {
10340
+ const registerToolNotificationSender = useCallback((appId, sender) => {
10341
+ console.log(`[BotDojoChatProvider] Registering tool notification sender for: ${appId}`);
10342
+ toolNotificationSendersRef.current.set(appId, sender);
10343
+ const pendingForApp = pendingToolNotificationsRef.current.get(appId);
10344
+ if (pendingForApp && pendingForApp.length > 0) {
10345
+ console.log(`[BotDojoChatProvider] Replaying ${pendingForApp.length} queued notifications for app: ${appId}`);
10346
+ pendingForApp.forEach(({ method, params }) => {
10271
10347
  try {
10272
10348
  console.log(`[BotDojoChatProvider] Replaying: ${method}`, params);
10273
10349
  sender(method, params);
10274
10350
  } catch (err) {
10275
- console.warn(`[BotDojoChatProvider] Failed to replay notification to ${mcpAppId}:`, err);
10351
+ console.warn(`[BotDojoChatProvider] Failed to replay notification to ${appId}:`, err);
10276
10352
  }
10277
10353
  });
10278
- pendingToolNotificationsRef.current.delete(mcpAppId);
10354
+ pendingToolNotificationsRef.current.delete(appId);
10279
10355
  }
10280
10356
  const pendingBroadcasts = pendingBroadcastNotificationsRef.current;
10281
10357
  if (pendingBroadcasts.length > 0) {
10282
- console.log(`[BotDojoChatProvider] Replaying ${pendingBroadcasts.length} queued broadcast notifications to: ${mcpAppId}`);
10358
+ console.log(`[BotDojoChatProvider] Replaying ${pendingBroadcasts.length} queued broadcast notifications to: ${appId}`);
10283
10359
  pendingBroadcasts.forEach(({ method, params }) => {
10284
10360
  try {
10285
10361
  console.log(`[BotDojoChatProvider] Replaying broadcast: ${method}`, params);
10286
10362
  sender(method, params);
10287
10363
  } catch (err) {
10288
- console.warn(`[BotDojoChatProvider] Failed to replay broadcast notification to ${mcpAppId}:`, err);
10364
+ console.warn(`[BotDojoChatProvider] Failed to replay broadcast notification to ${appId}:`, err);
10289
10365
  }
10290
10366
  });
10291
10367
  pendingBroadcastNotificationsRef.current = [];
10292
10368
  }
10293
10369
  return () => {
10294
- console.log(`[BotDojoChatProvider] Unregistering tool notification sender for: ${mcpAppId}`);
10295
- toolNotificationSendersRef.current.delete(mcpAppId);
10370
+ console.log(`[BotDojoChatProvider] Unregistering tool notification sender for: ${appId}`);
10371
+ toolNotificationSendersRef.current.delete(appId);
10296
10372
  };
10297
10373
  }, []);
10298
- const registerStepUpdateCallback = useCallback((canvasId, callback) => {
10299
- console.log(`[BotDojoChatProvider] Registering step update callback for canvas: ${canvasId}`);
10300
- stepUpdateCallbacksRef.current.set(canvasId, callback);
10374
+ const registerStepUpdateCallback = useCallback((appId, callback) => {
10375
+ console.log(`[BotDojoChatProvider] Registering step update callback for app: ${appId}`);
10376
+ stepUpdateCallbacksRef.current.set(appId, callback);
10377
+ const pendingUpdates = pendingStepUpdatesRef.current.get(appId);
10378
+ if (pendingUpdates && pendingUpdates.length > 0) {
10379
+ console.log(`[BotDojoChatProvider] Replaying ${pendingUpdates.length} queued step updates for app: ${appId}`);
10380
+ pendingUpdates.forEach((stepUpdate) => {
10381
+ try {
10382
+ console.log(`[BotDojoChatProvider] Replaying step update:`, stepUpdate.stepId);
10383
+ callback(stepUpdate);
10384
+ } catch (err) {
10385
+ console.warn(`[BotDojoChatProvider] Failed to replay step update to ${appId}:`, err);
10386
+ }
10387
+ });
10388
+ pendingStepUpdatesRef.current.delete(appId);
10389
+ }
10301
10390
  return () => {
10302
- console.log(`[BotDojoChatProvider] Unregistering step update callback for canvas: ${canvasId}`);
10303
- stepUpdateCallbacksRef.current.delete(canvasId);
10391
+ console.log(`[BotDojoChatProvider] Unregistering step update callback for app: ${appId}`);
10392
+ stepUpdateCallbacksRef.current.delete(appId);
10304
10393
  };
10305
10394
  }, []);
10306
- const sendStepUpdateToCanvas = useCallback((canvasId, stepUpdate) => {
10307
- const callback = stepUpdateCallbacksRef.current.get(canvasId);
10395
+ const sendStepUpdateToApp = useCallback((appId, stepUpdate) => {
10396
+ const callback = stepUpdateCallbacksRef.current.get(appId);
10308
10397
  if (callback) {
10309
- console.log(`[BotDojoChatProvider] Sending step update to canvas: ${canvasId}`, stepUpdate);
10398
+ console.log(`[BotDojoChatProvider] Sending step update to app: ${appId}`, stepUpdate);
10310
10399
  callback(stepUpdate);
10311
10400
  } else {
10312
- console.warn(`[BotDojoChatProvider] No step update callback registered for canvas: ${canvasId}`);
10401
+ console.warn(`[BotDojoChatProvider] No step update callback registered for app: ${appId}`);
10313
10402
  }
10314
10403
  }, []);
10315
- const executeToolCall = useCallback(async (toolName, args, targetCanvasId) => {
10404
+ const executeToolCall = useCallback(async (toolName, args, targetAppId) => {
10316
10405
  const ctx = modelContextRef.current;
10317
10406
  if (!ctx) {
10318
10407
  throw new Error("No model context available");
@@ -10323,40 +10412,82 @@ function BotDojoChatProvider(props) {
10323
10412
  const toolsArray = Array.isArray(context.tools) ? context.tools : Object.values(context.tools);
10324
10413
  const tool2 = toolsArray.find((t) => t.name === toolName);
10325
10414
  if (tool2 && typeof tool2.execute === "function") {
10326
- let resolvedCanvasId = targetCanvasId;
10327
- if (!resolvedCanvasId) {
10328
- resolvedCanvasId = activeCanvasByToolRef.current.get(toolName);
10329
- if (!resolvedCanvasId && context.name) {
10415
+ let resolvedAppId = targetAppId;
10416
+ if (!resolvedAppId) {
10417
+ resolvedAppId = activeAppByToolRef.current.get(toolName);
10418
+ if (!resolvedAppId && context.name) {
10330
10419
  const prefixedToolName = `${context.name}_${toolName}`;
10331
- resolvedCanvasId = activeCanvasByToolRef.current.get(prefixedToolName);
10420
+ resolvedAppId = activeAppByToolRef.current.get(prefixedToolName);
10332
10421
  }
10333
10422
  }
10334
- console.log(`[BotDojoChatProvider] Executing tool "${toolName}" for canvas: ${resolvedCanvasId || "ALL (broadcast)"}`);
10423
+ console.log(`[BotDojoChatProvider] Executing tool "${toolName}" for app: ${resolvedAppId || "ALL (broadcast)"}`);
10424
+ toolArgumentsCacheRef.current.set(toolName, args);
10425
+ if (resolvedAppId) {
10426
+ toolArgumentsCacheRef.current.set(resolvedAppId, args);
10427
+ }
10335
10428
  const executionContext = {
10336
10429
  toolName,
10337
10430
  notifyToolInputPartial: async (data) => {
10338
10431
  console.log(`[BotDojoChatProvider] Tool "${toolName}" notifyToolInputPartial:`, data);
10339
- const notification = {
10340
- tool: { name: toolName },
10341
- arguments: data
10432
+ const isProgressUpdate = (data == null ? void 0 : data.kind) === "botdojo-tool-progress";
10433
+ const stepUpdate = {
10434
+ stepToolName: toolName,
10435
+ toolName,
10436
+ // Only set stepToolArguments if NOT a progress update
10437
+ stepToolArguments: isProgressUpdate ? void 0 : data,
10438
+ arguments: isProgressUpdate ? void 0 : data,
10439
+ // Set stepToolProgress for progress updates
10440
+ stepToolProgress: isProgressUpdate ? data : void 0,
10441
+ stepStatus: "processing"
10342
10442
  };
10343
- if (resolvedCanvasId) {
10344
- sendToolNotificationToCanvas(resolvedCanvasId, "ui/notifications/tool-input-partial", notification);
10443
+ if (resolvedAppId) {
10444
+ const callback = stepUpdateCallbacksRef.current.get(resolvedAppId);
10445
+ if (callback) {
10446
+ console.log(`[BotDojoChatProvider] Sending partial update via step callback to: ${resolvedAppId}`);
10447
+ callback(stepUpdate);
10448
+ } else {
10449
+ console.log(`[BotDojoChatProvider] Callback not registered for ${resolvedAppId}, queueing`);
10450
+ if (!pendingStepUpdatesRef.current.has(resolvedAppId)) {
10451
+ pendingStepUpdatesRef.current.set(resolvedAppId, []);
10452
+ }
10453
+ pendingStepUpdatesRef.current.get(resolvedAppId).push(stepUpdate);
10454
+ }
10345
10455
  } else {
10346
- broadcastToolNotification("ui/notifications/tool-input-partial", notification, toolName);
10456
+ console.log(`[BotDojoChatProvider] Broadcasting partial update to all apps`);
10457
+ stepUpdateCallbacksRef.current.forEach((callback, appId) => {
10458
+ console.log(`[BotDojoChatProvider] Sending to: ${appId}`);
10459
+ callback(stepUpdate);
10460
+ });
10347
10461
  }
10348
10462
  },
10349
10463
  notifyToolResult: async (data) => {
10350
- var _a;
10464
+ var _a, _b;
10351
10465
  console.log(`[BotDojoChatProvider] Tool "${toolName}" notifyToolResult:`, data);
10352
- const notification = {
10353
- tool: { name: toolName },
10354
- result: (_a = data == null ? void 0 : data.result) != null ? _a : data
10466
+ const stepUpdate = {
10467
+ stepToolName: toolName,
10468
+ toolName,
10469
+ stepToolResult: (_a = data == null ? void 0 : data.result) != null ? _a : data,
10470
+ result: (_b = data == null ? void 0 : data.result) != null ? _b : data,
10471
+ stepStatus: "complete"
10355
10472
  };
10356
- if (resolvedCanvasId) {
10357
- sendToolNotificationToCanvas(resolvedCanvasId, "ui/notifications/tool-result", notification);
10473
+ if (resolvedAppId) {
10474
+ const callback = stepUpdateCallbacksRef.current.get(resolvedAppId);
10475
+ if (callback) {
10476
+ console.log(`[BotDojoChatProvider] Sending result via step callback to: ${resolvedAppId}`);
10477
+ callback(stepUpdate);
10478
+ } else {
10479
+ console.log(`[BotDojoChatProvider] Callback not registered for ${resolvedAppId}, queueing result`);
10480
+ if (!pendingStepUpdatesRef.current.has(resolvedAppId)) {
10481
+ pendingStepUpdatesRef.current.set(resolvedAppId, []);
10482
+ }
10483
+ pendingStepUpdatesRef.current.get(resolvedAppId).push(stepUpdate);
10484
+ }
10358
10485
  } else {
10359
- broadcastToolNotification("ui/notifications/tool-result", notification, toolName);
10486
+ console.log(`[BotDojoChatProvider] Broadcasting result to all apps`);
10487
+ stepUpdateCallbacksRef.current.forEach((callback, appId) => {
10488
+ console.log(`[BotDojoChatProvider] Sending result to: ${appId}`);
10489
+ callback(stepUpdate);
10490
+ });
10360
10491
  }
10361
10492
  }
10362
10493
  };
@@ -10365,18 +10496,26 @@ function BotDojoChatProvider(props) {
10365
10496
  }
10366
10497
  }
10367
10498
  throw new Error(`Tool not found: ${toolName}`);
10368
- }, [broadcastToolNotification, sendToolNotificationToCanvas]);
10499
+ }, []);
10369
10500
  const getResource = useCallback(async (uri, params, onlyMetadata) => {
10501
+ console.log("[BotDojoChatProvider] getResource called for URI:", uri);
10370
10502
  const ctx = modelContextRef.current;
10371
10503
  if (!ctx) {
10504
+ console.error("[BotDojoChatProvider] getResource: No model context available");
10372
10505
  throw new Error("No model context available");
10373
10506
  }
10374
10507
  const contexts = Array.isArray(ctx) ? ctx : [ctx];
10508
+ console.log("[BotDojoChatProvider] getResource: Searching", contexts.length, "context(s)");
10375
10509
  for (const context of contexts) {
10376
10510
  if (context.resources) {
10511
+ console.log("[BotDojoChatProvider] getResource: Context has", context.resources.length, "resources");
10377
10512
  for (const resource of context.resources) {
10513
+ const resourceUri = "uri" in resource ? resource.uri : "no-uri";
10514
+ console.log("[BotDojoChatProvider] getResource: Checking resource URI:", resourceUri, "=== requested URI:", uri, "?", resourceUri === uri);
10378
10515
  if ("uri" in resource && resource.uri === uri && resource.getContent) {
10516
+ console.log("[BotDojoChatProvider] getResource: MATCH FOUND! Calling getContent()");
10379
10517
  const content = await resource.getContent();
10518
+ console.log("[BotDojoChatProvider] getResource: getContent returned:", typeof content, typeof content === "object" && content && "uri" in content ? content.uri : "(no uri)");
10380
10519
  return {
10381
10520
  uri,
10382
10521
  mimeType: resource.mimeType,
@@ -10386,35 +10525,38 @@ function BotDojoChatProvider(props) {
10386
10525
  }
10387
10526
  }
10388
10527
  }
10528
+ console.error("[BotDojoChatProvider] getResource: Resource not found:", uri);
10389
10529
  throw new Error(`Resource not found: ${uri}`);
10390
10530
  }, []);
10391
- const registerCanvasIframe = useCallback((canvasId, iframeWindow) => {
10392
- console.log("[BotDojoChatProvider] Registering canvas iframe:", canvasId);
10393
- if (canvasBridgesRef.current.has(canvasId)) {
10394
- console.log("[BotDojoChatProvider] Canvas already registered:", canvasId);
10395
- return;
10396
- }
10397
- canvasIframeRefsRef.current.set(canvasId, iframeWindow);
10531
+ const registerMcpApp = useCallback((appId, iframeWindow) => {
10532
+ console.log("[BotDojoChatProvider] Registering MCP App iframe:", appId);
10533
+ if (appBridgesRef.current.has(appId)) {
10534
+ console.log("[BotDojoChatProvider] MCP App already registered, refreshing bridge:", appId);
10535
+ const existingBridge = appBridgesRef.current.get(appId);
10536
+ existingBridge == null ? void 0 : existingBridge.stop();
10537
+ appBridgesRef.current.delete(appId);
10538
+ }
10539
+ appIframeRefsRef.current.set(appId, iframeWindow);
10398
10540
  const bridge = new import_botdojo_rpc2.PostMessageBridge({
10399
10541
  targetWindow: iframeWindow,
10400
10542
  targetOrigin: baseUrl,
10401
- clientId: `parent-to-canvas-${canvasId}`,
10543
+ clientId: `parent-to-app-${appId}`,
10402
10544
  debug: true,
10403
10545
  role: "parent",
10404
10546
  onMessage: async (msg) => {
10405
10547
  var _a;
10406
- console.log("[BotDojoChatProvider] Message from canvas:", canvasId, msg.functionName);
10548
+ console.log("[BotDojoChatProvider] Message from MCP App:", appId, msg.functionName);
10407
10549
  if (msg.functionName.startsWith("tool_")) {
10408
10550
  const toolName = msg.functionName.substring(5);
10409
10551
  if (connectorRef.current) {
10410
- console.log("[BotDojoChatProvider] Tool call from canvas:", toolName, msg.data);
10552
+ console.log("[BotDojoChatProvider] Tool call from app:", toolName, msg.data);
10411
10553
  } else {
10412
10554
  console.log("[BotDojoChatProvider] Forwarding tool call to server:", toolName);
10413
10555
  if ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) {
10414
10556
  iframeRef.current.contentWindow.postMessage(
10415
10557
  {
10416
10558
  type: "tool_call",
10417
- canvasId,
10559
+ appId,
10418
10560
  toolName,
10419
10561
  data: msg.data
10420
10562
  },
@@ -10425,62 +10567,62 @@ function BotDojoChatProvider(props) {
10425
10567
  }
10426
10568
  },
10427
10569
  onError: (error) => {
10428
- console.error("[BotDojoChatProvider] Canvas bridge error:", canvasId, error);
10570
+ console.error("[BotDojoChatProvider] MCP App bridge error:", appId, error);
10429
10571
  }
10430
10572
  });
10431
10573
  bridge.start();
10432
- canvasBridgesRef.current.set(canvasId, bridge);
10433
- setRegisteredCanvases((prev2) => new Set(prev2).add(canvasId));
10434
- const pending = pendingCanvasEventsRef.current.get(canvasId);
10574
+ appBridgesRef.current.set(appId, bridge);
10575
+ setRegisteredMcpApps((prev2) => new Set(prev2).add(appId));
10576
+ const pending = pendingAppEventsRef.current.get(appId);
10435
10577
  if (pending && pending.length > 0) {
10436
- console.log("[BotDojoChatProvider] Sending pending events to canvas:", canvasId, pending.length);
10578
+ console.log("[BotDojoChatProvider] Sending pending events to app:", appId, pending.length);
10437
10579
  pending.forEach((event) => {
10438
10580
  bridge.sendMessage(import_botdojo_rpc2.RPCMessage.request(
10439
- `parent-to-canvas-${canvasId}`,
10440
- "canvas",
10581
+ `parent-to-app-${appId}`,
10582
+ "app",
10441
10583
  event.eventName,
10442
10584
  event.data
10443
10585
  ));
10444
10586
  });
10445
- pendingCanvasEventsRef.current.delete(canvasId);
10587
+ pendingAppEventsRef.current.delete(appId);
10446
10588
  }
10447
- console.log("[BotDojoChatProvider] Canvas registered successfully:", canvasId);
10589
+ console.log("[BotDojoChatProvider] MCP App registered successfully:", appId);
10448
10590
  }, [baseUrl]);
10449
- const unregisterCanvasIframe = useCallback((canvasId) => {
10450
- console.log("[BotDojoChatProvider] Unregistering canvas iframe:", canvasId);
10451
- const bridge = canvasBridgesRef.current.get(canvasId);
10591
+ const unregisterMcpApp = useCallback((appId) => {
10592
+ console.log("[BotDojoChatProvider] Unregistering MCP App iframe:", appId);
10593
+ const bridge = appBridgesRef.current.get(appId);
10452
10594
  if (bridge) {
10453
10595
  bridge.stop();
10454
- canvasBridgesRef.current.delete(canvasId);
10596
+ appBridgesRef.current.delete(appId);
10455
10597
  }
10456
- canvasIframeRefsRef.current.delete(canvasId);
10457
- pendingCanvasEventsRef.current.delete(canvasId);
10458
- setRegisteredCanvases((prev2) => {
10598
+ appIframeRefsRef.current.delete(appId);
10599
+ pendingAppEventsRef.current.delete(appId);
10600
+ setRegisteredMcpApps((prev2) => {
10459
10601
  const next = new Set(prev2);
10460
- next.delete(canvasId);
10602
+ next.delete(appId);
10461
10603
  return next;
10462
10604
  });
10463
10605
  }, []);
10464
- const forwardEventToCanvas = useCallback((canvasId, eventName, data) => {
10465
- const bridge = canvasBridgesRef.current.get(canvasId);
10606
+ const forwardEventToApp = useCallback((appId, eventName, data) => {
10607
+ const bridge = appBridgesRef.current.get(appId);
10466
10608
  if (bridge) {
10467
- console.log("[BotDojoChatProvider] Forwarding event to canvas:", canvasId, eventName);
10609
+ console.log("[BotDojoChatProvider] Forwarding event to app:", appId, eventName);
10468
10610
  bridge.sendMessage(import_botdojo_rpc2.RPCMessage.request(
10469
- `parent-to-canvas-${canvasId}`,
10470
- "canvas",
10611
+ `parent-to-app-${appId}`,
10612
+ "app",
10471
10613
  eventName,
10472
10614
  data
10473
10615
  ));
10474
10616
  } else {
10475
- console.log("[BotDojoChatProvider] Queueing event for canvas (not ready):", canvasId, eventName);
10476
- if (!pendingCanvasEventsRef.current.has(canvasId)) {
10477
- pendingCanvasEventsRef.current.set(canvasId, []);
10617
+ console.log("[BotDojoChatProvider] Queueing event for app (not ready):", appId, eventName);
10618
+ if (!pendingAppEventsRef.current.has(appId)) {
10619
+ pendingAppEventsRef.current.set(appId, []);
10478
10620
  }
10479
- pendingCanvasEventsRef.current.get(canvasId).push({ eventName, data });
10621
+ pendingAppEventsRef.current.get(appId).push({ eventName, data });
10480
10622
  }
10481
10623
  }, []);
10482
10624
  const handleMessage = useCallback((event) => {
10483
- var _a, _b, _c;
10625
+ var _a;
10484
10626
  try {
10485
10627
  const eventOrigin = new URL(event.origin).origin;
10486
10628
  const expectedOrigin = new URL(baseUrl).origin;
@@ -10513,20 +10655,20 @@ function BotDojoChatProvider(props) {
10513
10655
  sendModelContextToHeadless();
10514
10656
  break;
10515
10657
  case "tool_call":
10516
- console.log("[BotDojoChatProvider] Tool call from HeadlessEmbed:", data.toolName, "canvasId:", data.canvasId || "none");
10658
+ console.log("[BotDojoChatProvider] Tool call from HeadlessEmbed:", data.toolName, "appId:", data.appId || data.canvasId || "none");
10517
10659
  (async () => {
10518
- var _a2, _b2, _c2, _d;
10660
+ var _a2, _b, _c, _d;
10519
10661
  try {
10520
- const result = await executeToolCall(data.toolName, data.arguments, data.canvasId);
10662
+ const result = await executeToolCall(data.toolName, data.arguments, data.appId || data.canvasId);
10521
10663
  console.log(`[BotDojoChatProvider] \u2705 Tool "${data.toolName}" executed successfully`);
10522
- (_b2 = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b2.postMessage({
10664
+ (_b = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b.postMessage({
10523
10665
  type: "tool_response",
10524
10666
  requestId: data.requestId,
10525
10667
  result
10526
10668
  }, baseUrl);
10527
10669
  } catch (error2) {
10528
10670
  console.error(`[BotDojoChatProvider] \u274C Tool "${data.toolName}" failed:`, error2);
10529
- (_d = (_c2 = iframeRef.current) == null ? void 0 : _c2.contentWindow) == null ? void 0 : _d.postMessage({
10671
+ (_d = (_c = iframeRef.current) == null ? void 0 : _c.contentWindow) == null ? void 0 : _d.postMessage({
10530
10672
  type: "tool_response",
10531
10673
  requestId: data.requestId,
10532
10674
  error: error2.message
@@ -10537,17 +10679,17 @@ function BotDojoChatProvider(props) {
10537
10679
  case "get_resource":
10538
10680
  console.log("[BotDojoChatProvider] Resource request from HeadlessEmbed:", data.uri);
10539
10681
  (async () => {
10540
- var _a2, _b2, _c2, _d;
10682
+ var _a2, _b, _c, _d;
10541
10683
  try {
10542
10684
  const resource = await getResource(data.uri, data.params, data.onlyMetadata);
10543
- (_b2 = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b2.postMessage({
10685
+ (_b = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b.postMessage({
10544
10686
  type: "get_resource_response",
10545
10687
  requestId: data.requestId,
10546
10688
  resource
10547
10689
  }, baseUrl);
10548
10690
  } catch (error2) {
10549
10691
  console.error(`[BotDojoChatProvider] \u274C Resource fetch failed:`, error2);
10550
- (_d = (_c2 = iframeRef.current) == null ? void 0 : _c2.contentWindow) == null ? void 0 : _d.postMessage({
10692
+ (_d = (_c = iframeRef.current) == null ? void 0 : _c.contentWindow) == null ? void 0 : _d.postMessage({
10551
10693
  type: "get_resource_response",
10552
10694
  requestId: data.requestId,
10553
10695
  error: error2.message
@@ -10603,20 +10745,24 @@ function BotDojoChatProvider(props) {
10603
10745
  });
10604
10746
  break;
10605
10747
  case "step_update":
10606
- if ((_b = data.step) == null ? void 0 : _b.canvas) {
10607
- console.log("[BotDojoChatProvider] Step has canvas:", data.step.canvas.canvasId, data.step.canvas.canvasType, JSON.stringify(data.step.canvas.canvasData, null, 2));
10608
- const toolName = (_c = data.step.canvas.canvasData) == null ? void 0 : _c.toolName;
10609
- const canvasId = data.step.canvas.canvasId;
10610
- if (toolName && canvasId) {
10611
- console.log(`[BotDojoChatProvider] Registering canvas ${canvasId} for tool: ${toolName}`);
10612
- activeCanvasByToolRef.current.set(toolName, canvasId);
10748
+ const rawStep = data.step;
10749
+ if (rawStep == null ? void 0 : rawStep.canvas) {
10750
+ console.log("[BotDojoChatProvider] Step has MCP App:", rawStep.canvas.canvasId, rawStep.canvas.canvasType, JSON.stringify(rawStep.canvas.canvasData, null, 2));
10751
+ const toolName = rawStep.stepToolName || rawStep.stepLabel;
10752
+ const appId = rawStep.canvas.canvasId;
10753
+ if (toolName && appId) {
10754
+ console.log(`[BotDojoChatProvider] Registering app ${appId} for tool: ${toolName}`);
10755
+ activeAppByToolRef.current.set(toolName, appId);
10756
+ }
10757
+ if (rawStep.stepId && appId) {
10758
+ stepIdToAppIdRef.current.set(rawStep.stepId, appId);
10613
10759
  }
10614
10760
  }
10615
10761
  (async () => {
10616
- var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
10617
- let stepToDispatch = data.step;
10618
- const canvasUrl = (_c2 = (_b2 = (_a2 = data.step) == null ? void 0 : _a2.canvas) == null ? void 0 : _b2.canvasData) == null ? void 0 : _c2.url;
10619
- if (canvasUrl && canvasUrl.startsWith("ui://") && !((_f = (_e = (_d = data.step) == null ? void 0 : _d.canvas) == null ? void 0 : _e.canvasData) == null ? void 0 : _f.html)) {
10762
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
10763
+ let stepToDispatch = rawStep;
10764
+ const canvasUrl = (_b = (_a2 = rawStep == null ? void 0 : rawStep.canvas) == null ? void 0 : _a2.canvasData) == null ? void 0 : _b.url;
10765
+ if (canvasUrl && canvasUrl.startsWith("ui://") && !((_d = (_c = rawStep == null ? void 0 : rawStep.canvas) == null ? void 0 : _c.canvasData) == null ? void 0 : _d.html)) {
10620
10766
  console.log("[BotDojoChatProvider] Resolving ui:// resource:", canvasUrl);
10621
10767
  try {
10622
10768
  const resource = await getResource(canvasUrl);
@@ -10624,11 +10770,11 @@ function BotDojoChatProvider(props) {
10624
10770
  const htmlContent = (resource == null ? void 0 : resource.text) || (resource == null ? void 0 : resource.content);
10625
10771
  if (htmlContent) {
10626
10772
  stepToDispatch = {
10627
- ...data.step,
10773
+ ...rawStep,
10628
10774
  canvas: {
10629
- ...data.step.canvas,
10775
+ ...rawStep.canvas,
10630
10776
  canvasData: {
10631
- ...data.step.canvas.canvasData,
10777
+ ...rawStep.canvas.canvasData,
10632
10778
  html: htmlContent
10633
10779
  }
10634
10780
  }
@@ -10638,7 +10784,8 @@ function BotDojoChatProvider(props) {
10638
10784
  console.warn("[BotDojoChatProvider] \u26A0\uFE0F Resource resolved but no text/content found:", Object.keys(resource || {}));
10639
10785
  }
10640
10786
  } catch (err) {
10641
- console.error("[BotDojoChatProvider] \u274C Failed to resolve ui:// resource:", err.message);
10787
+ const errorMessage = err instanceof Error ? err.message : String(err);
10788
+ console.error("[BotDojoChatProvider] \u274C Failed to resolve ui:// resource:", errorMessage);
10642
10789
  }
10643
10790
  }
10644
10791
  dispatch({
@@ -10646,24 +10793,67 @@ function BotDojoChatProvider(props) {
10646
10793
  messageId: data.messageId,
10647
10794
  step: stepToDispatch
10648
10795
  });
10649
- if ((_g = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _g.canvasId) {
10650
- const canvasId = stepToDispatch.canvas.canvasId;
10651
- const callback = stepUpdateCallbacksRef.current.get(canvasId);
10796
+ const appIdFromCanvas = (_e = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _e.canvasId;
10797
+ const appIdFromStepId = (stepToDispatch == null ? void 0 : stepToDispatch.stepId) ? stepIdToAppIdRef.current.get(stepToDispatch.stepId) : void 0;
10798
+ const toolNameForLookup = (stepToDispatch == null ? void 0 : stepToDispatch.stepToolName) || (stepToDispatch == null ? void 0 : stepToDispatch.stepLabel);
10799
+ const appIdFromToolName = toolNameForLookup ? activeAppByToolRef.current.get(toolNameForLookup) : void 0;
10800
+ const appId = appIdFromCanvas || appIdFromStepId || appIdFromToolName;
10801
+ if (appId) {
10802
+ const toolName = stepToDispatch.stepToolName || stepToDispatch.stepLabel;
10803
+ const canvasResult = (_g = (_f = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _f.canvasData) == null ? void 0 : _g.result;
10804
+ const rawStepResult = stepToDispatch.stepToolResult;
10805
+ const stepResult = rawStepResult !== void 0 && rawStepResult !== "" && typeof rawStepResult !== "string" ? rawStepResult : rawStepResult && rawStepResult !== "" ? rawStepResult : canvasResult !== void 0 && canvasResult !== "" ? canvasResult : stepToDispatch.content || void 0;
10806
+ const rawStepArgs = stepToDispatch.stepToolArguments;
10807
+ const rawArgsString = stepToDispatch.arguments;
10808
+ const canvasArgs = (_i = (_h = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.arguments;
10809
+ let stepArguments = rawStepArgs && typeof rawStepArgs === "object" ? rawStepArgs : null;
10810
+ if (!stepArguments && rawArgsString && rawArgsString.trim()) {
10811
+ try {
10812
+ stepArguments = JSON.parse(rawArgsString);
10813
+ } catch {
10814
+ }
10815
+ }
10816
+ if (!stepArguments && canvasArgs !== void 0) {
10817
+ if (typeof canvasArgs === "object") {
10818
+ stepArguments = canvasArgs;
10819
+ } else if (typeof canvasArgs === "string" && canvasArgs.trim()) {
10820
+ try {
10821
+ stepArguments = JSON.parse(canvasArgs);
10822
+ } catch {
10823
+ }
10824
+ }
10825
+ }
10826
+ if (!stepArguments) {
10827
+ stepArguments = toolArgumentsCacheRef.current.get(appId) || (toolName ? toolArgumentsCacheRef.current.get(toolName) : null) || null;
10828
+ }
10829
+ const enrichedStepUpdate = {
10830
+ ...stepToDispatch,
10831
+ stepToolName: toolName,
10832
+ stepToolArguments: stepArguments != null ? stepArguments : void 0,
10833
+ stepToolResult: stepResult
10834
+ };
10835
+ const callback = stepUpdateCallbacksRef.current.get(appId);
10652
10836
  if (callback) {
10653
- const stepResult = (_j = stepToDispatch.content) != null ? _j : (_i = (_h = stepToDispatch.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.result;
10654
- console.log(`[BotDojoChatProvider] Sending step update via callback to canvas: ${canvasId}`, {
10837
+ console.log(`[BotDojoChatProvider] Sending step update via callback to app: ${appId}`, {
10838
+ hasStepToolResult: stepResult !== void 0,
10655
10839
  hasStepContent: stepToDispatch.content !== void 0,
10656
- hasCanvasResult: ((_l = (_k = stepToDispatch.canvas) == null ? void 0 : _k.canvasData) == null ? void 0 : _l.result) !== void 0
10657
- });
10658
- callback({
10659
- ...stepToDispatch,
10660
- toolName: (_n = (_m = stepToDispatch.canvas) == null ? void 0 : _m.canvasData) == null ? void 0 : _n.toolName,
10661
- arguments: (_p = (_o = stepToDispatch.canvas) == null ? void 0 : _o.canvasData) == null ? void 0 : _p.arguments,
10662
- result: stepResult
10840
+ hasCachedArgs: !!stepArguments,
10841
+ hasCanvasArgs: canvasArgs !== void 0,
10842
+ hasCanvasResult: canvasResult !== void 0 && canvasResult !== "",
10843
+ toolName,
10844
+ rawStepResult,
10845
+ rawStepArgs,
10846
+ canvasResult
10663
10847
  });
10848
+ callback(enrichedStepUpdate);
10664
10849
  } else {
10665
- forwardEventToCanvas(
10666
- canvasId,
10850
+ console.log(`[BotDojoChatProvider] Callback not registered for ${appId}, queueing step update`);
10851
+ if (!pendingStepUpdatesRef.current.has(appId)) {
10852
+ pendingStepUpdatesRef.current.set(appId, []);
10853
+ }
10854
+ pendingStepUpdatesRef.current.get(appId).push(enrichedStepUpdate);
10855
+ forwardEventToApp(
10856
+ appId,
10667
10857
  "onIntermediateStepUpdate",
10668
10858
  stepToDispatch
10669
10859
  );
@@ -10682,7 +10872,7 @@ function BotDojoChatProvider(props) {
10682
10872
  dispatch({ type: "REQUEST_ABORTED" });
10683
10873
  break;
10684
10874
  }
10685
- }, [baseUrl, onReady, onError, onConnectorInit, onConnectorError, onSessionCreated, onSessionHydrated, forwardEventToCanvas, sendModelContextToHeadless, executeToolCall, getResource]);
10875
+ }, [baseUrl, onReady, onError, onConnectorInit, onConnectorError, onSessionCreated, onSessionHydrated, forwardEventToApp, sendModelContextToHeadless, executeToolCall, getResource]);
10686
10876
  useEffect(() => {
10687
10877
  if (typeof window === "undefined")
10688
10878
  return;
@@ -10696,16 +10886,16 @@ function BotDojoChatProvider(props) {
10696
10886
  iframeRef,
10697
10887
  connector,
10698
10888
  connection: connectionRef.current,
10699
- registerCanvasIframe,
10700
- unregisterCanvasIframe,
10701
- registeredCanvases,
10889
+ registerMcpApp,
10890
+ unregisterMcpApp,
10891
+ registeredMcpApps,
10702
10892
  registerToolNotificationSender,
10703
- sendToolNotificationToCanvas,
10893
+ sendToolNotificationToApp,
10704
10894
  registerStepUpdateCallback,
10705
- sendStepUpdateToCanvas,
10706
- canvasHandlers: canvasHandlersRef
10895
+ sendStepUpdateToApp,
10896
+ appHandlers: appHandlersRef
10707
10897
  }),
10708
- [state, connector, registerCanvasIframe, unregisterCanvasIframe, registeredCanvases, registerToolNotificationSender, sendToolNotificationToCanvas, registerStepUpdateCallback, sendStepUpdateToCanvas]
10898
+ [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp]
10709
10899
  );
10710
10900
  return /* @__PURE__ */ jsxs(BotDojoChatContext.Provider, { value: contextValue, children: [
10711
10901
  children,
@@ -10780,15 +10970,15 @@ function useChatActions() {
10780
10970
  }
10781
10971
  iframeRef.current.src = iframeRef.current.src;
10782
10972
  }, [iframeRef]);
10783
- const persistCanvasState = useCallback((canvasId, state) => {
10973
+ const persistAppState = useCallback((appId, state) => {
10784
10974
  var _a;
10785
10975
  if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
10786
10976
  console.error("[useChatActions] Iframe not ready");
10787
10977
  return;
10788
10978
  }
10789
- console.log("[useChatActions] Persisting canvas state:", canvasId, state);
10979
+ console.log("[useChatActions] Persisting MCP App state:", appId, state);
10790
10980
  iframeRef.current.contentWindow.postMessage(
10791
- { type: "persist_canvas_state", canvasId, state },
10981
+ { type: "persist_app_state", appId, state },
10792
10982
  "*"
10793
10983
  );
10794
10984
  }, [iframeRef]);
@@ -10798,7 +10988,7 @@ function useChatActions() {
10798
10988
  bargeInRequest,
10799
10989
  setSessionId,
10800
10990
  reload,
10801
- persistCanvasState
10991
+ persistAppState
10802
10992
  };
10803
10993
  }
10804
10994
 
@@ -11106,7 +11296,7 @@ function McpAppHost(props) {
11106
11296
  openLinks: {},
11107
11297
  "botdojo/persistence": true,
11108
11298
  extensions: {
11109
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] }
11299
+ "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11110
11300
  }
11111
11301
  },
11112
11302
  hostContext
@@ -11181,14 +11371,18 @@ function McpAppHost(props) {
11181
11371
  isInitializedRef.current = true;
11182
11372
  const toolName = (_b = (_a = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a.tool) == null ? void 0 : _b.name;
11183
11373
  if (toolName && ((_c = iframeRef.current) == null ? void 0 : _c.contentWindow)) {
11184
- const args = mcpAppData == null ? void 0 : mcpAppData.arguments;
11185
- const result = mcpAppData == null ? void 0 : mcpAppData.result;
11374
+ const rawArgs = mcpAppData == null ? void 0 : mcpAppData.arguments;
11375
+ const rawResult = mcpAppData == null ? void 0 : mcpAppData.result;
11376
+ const args = rawArgs && rawArgs !== "" && typeof rawArgs === "object" ? rawArgs : void 0;
11377
+ const result = rawResult !== void 0 && rawResult !== "" ? rawResult : void 0;
11186
11378
  const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
11187
11379
  log("Sending hydration data after initialized:", {
11188
11380
  toolName,
11189
11381
  hasArgs: args !== void 0,
11190
11382
  hasResult: result !== void 0,
11191
- isComplete: toolIsComplete
11383
+ isComplete: toolIsComplete,
11384
+ rawArgs,
11385
+ rawResult
11192
11386
  });
11193
11387
  if (args !== void 0) {
11194
11388
  iframeRef.current.contentWindow.postMessage({
@@ -11248,7 +11442,7 @@ function McpAppHost(props) {
11248
11442
  openLinks: {},
11249
11443
  "botdojo/persistence": true,
11250
11444
  extensions: {
11251
- "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] }
11445
+ "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp", "text/html;profile=mcp-app"] }
11252
11446
  }
11253
11447
  },
11254
11448
  hostContext
@@ -11430,6 +11624,24 @@ function McpAppHost(props) {
11430
11624
  pendingNotificationsRef.current.push({ method, params });
11431
11625
  return;
11432
11626
  }
11627
+ if (method === "ui/notifications/tool-input" || method === "ui/notifications/tool-input-partial") {
11628
+ const args = params == null ? void 0 : params.arguments;
11629
+ if (!args || args === "" || typeof args !== "object" || Object.keys(args).length === 0) {
11630
+ if (debug) {
11631
+ console.log(`[McpAppHost:${mcpAppId}] Skipping ${method} - empty arguments:`, args);
11632
+ }
11633
+ return;
11634
+ }
11635
+ }
11636
+ if (method === "ui/notifications/tool-result") {
11637
+ const result = params == null ? void 0 : params.result;
11638
+ if (result === "" || result === void 0) {
11639
+ if (debug) {
11640
+ console.log(`[McpAppHost:${mcpAppId}] Skipping ${method} - empty result:`, result);
11641
+ }
11642
+ return;
11643
+ }
11644
+ }
11433
11645
  if (debug) {
11434
11646
  console.log(`[McpAppHost:${mcpAppId}] Forwarding tool notification:`, method, params);
11435
11647
  }
@@ -11449,48 +11661,73 @@ function McpAppHost(props) {
11449
11661
  }
11450
11662
  console.log(`[McpAppHost:${mcpAppId}] Registering step update callback`);
11451
11663
  const callback = (stepUpdate) => {
11452
- var _a, _b, _c, _d, _e;
11664
+ var _a;
11453
11665
  if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11454
11666
  return;
11455
11667
  if (debug) {
11456
11668
  console.log(`[McpAppHost:${mcpAppId}] Received step update via callback:`, stepUpdate);
11457
11669
  }
11458
- const toolName = (stepUpdate == null ? void 0 : stepUpdate.toolName) || (stepUpdate == null ? void 0 : stepUpdate.tool) || ((_c = (_b = stepUpdate == null ? void 0 : stepUpdate.canvas) == null ? void 0 : _b.canvasData) == null ? void 0 : _c.toolName);
11459
- const hasResult = (stepUpdate == null ? void 0 : stepUpdate.result) !== void 0;
11460
- const argsStepId = (_d = stepUpdate == null ? void 0 : stepUpdate.arguments) == null ? void 0 : _d.stepId;
11461
- const argsStepLabel = (_e = stepUpdate == null ? void 0 : stepUpdate.arguments) == null ? void 0 : _e.stepLabel;
11462
- const hasStepInfo = argsStepId !== void 0 || argsStepLabel !== void 0 || (stepUpdate == null ? void 0 : stepUpdate.stepId) !== void 0 || (stepUpdate == null ? void 0 : stepUpdate.stepLabel) !== void 0;
11463
- if (toolName && (hasStepInfo || hasResult)) {
11464
- if (hasStepInfo) {
11465
- if (debug) {
11466
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial to iframe (has step info)`);
11467
- }
11468
- iframeRef.current.contentWindow.postMessage({
11469
- jsonrpc: "2.0",
11470
- method: "ui/notifications/tool-input-partial",
11471
- params: {
11472
- tool: { name: toolName },
11473
- arguments: {
11474
- ...stepUpdate.arguments || {},
11475
- stepId: argsStepId != null ? argsStepId : stepUpdate.stepId,
11476
- stepLabel: argsStepLabel != null ? argsStepLabel : stepUpdate.stepLabel
11477
- }
11478
- }
11479
- }, "*");
11670
+ const toolName = (stepUpdate == null ? void 0 : stepUpdate.stepToolName) || (stepUpdate == null ? void 0 : stepUpdate.toolName);
11671
+ const toolPhase = stepUpdate == null ? void 0 : stepUpdate.toolPhase;
11672
+ const toolArguments = stepUpdate == null ? void 0 : stepUpdate.stepToolArguments;
11673
+ const toolProgress = stepUpdate == null ? void 0 : stepUpdate.stepToolProgress;
11674
+ const toolResult = stepUpdate == null ? void 0 : stepUpdate.stepToolResult;
11675
+ if (!toolName)
11676
+ return;
11677
+ if (toolPhase === "executing" && toolArguments) {
11678
+ if (debug) {
11679
+ console.log(`[McpAppHost:${mcpAppId}] Sending tool-input (toolPhase=executing):`, toolArguments);
11480
11680
  }
11481
- if (hasResult) {
11482
- if (debug) {
11483
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-result to iframe`);
11484
- }
11485
- iframeRef.current.contentWindow.postMessage({
11486
- jsonrpc: "2.0",
11487
- method: "ui/notifications/tool-result",
11488
- params: {
11489
- tool: { name: toolName },
11490
- result: stepUpdate.result
11681
+ iframeRef.current.contentWindow.postMessage({
11682
+ jsonrpc: "2.0",
11683
+ method: "ui/notifications/tool-input",
11684
+ params: {
11685
+ tool: { name: toolName },
11686
+ arguments: toolArguments
11687
+ }
11688
+ }, "*");
11689
+ }
11690
+ if (toolProgress) {
11691
+ if (debug) {
11692
+ console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial (progress update):`, toolProgress);
11693
+ }
11694
+ iframeRef.current.contentWindow.postMessage({
11695
+ jsonrpc: "2.0",
11696
+ method: "ui/notifications/tool-input-partial",
11697
+ params: {
11698
+ tool: { name: toolName },
11699
+ arguments: { ...toolProgress, _botdojoProgress: true }
11700
+ }
11701
+ }, "*");
11702
+ } else if (toolPhase === "streaming_args" && (stepUpdate.stepId || stepUpdate.stepLabel)) {
11703
+ if (debug) {
11704
+ console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial (streaming_args):`, { stepId: stepUpdate.stepId, stepLabel: stepUpdate.stepLabel });
11705
+ }
11706
+ iframeRef.current.contentWindow.postMessage({
11707
+ jsonrpc: "2.0",
11708
+ method: "ui/notifications/tool-input-partial",
11709
+ params: {
11710
+ tool: { name: toolName },
11711
+ arguments: {
11712
+ ...toolArguments || {},
11713
+ stepId: stepUpdate.stepId,
11714
+ stepLabel: stepUpdate.stepLabel
11491
11715
  }
11492
- }, "*");
11716
+ }
11717
+ }, "*");
11718
+ }
11719
+ if (toolResult !== void 0 && toolResult !== "") {
11720
+ if (debug) {
11721
+ console.log(`[McpAppHost:${mcpAppId}] Sending tool-result:`, toolResult);
11493
11722
  }
11723
+ iframeRef.current.contentWindow.postMessage({
11724
+ jsonrpc: "2.0",
11725
+ method: "ui/notifications/tool-result",
11726
+ params: {
11727
+ tool: { name: toolName },
11728
+ result: toolResult
11729
+ }
11730
+ }, "*");
11494
11731
  }
11495
11732
  };
11496
11733
  const unregister = ctx.registerStepUpdateCallback(mcpAppId, callback);
@@ -12889,8 +13126,11 @@ function BotDojoCanvasProvider({
12889
13126
  if (method === "ui/initialize") {
12890
13127
  log("Received ui/initialize", params);
12891
13128
  const capabilities = ((_e = (_d = params == null ? void 0 : params.hostCapabilities) == null ? void 0 : _d.extensions) == null ? void 0 : _e["io.modelcontextprotocol/ui"]) || ((_g = (_f = params == null ? void 0 : params.capabilities) == null ? void 0 : _f.extensions) == null ? void 0 : _g["io.modelcontextprotocol/ui"]);
12892
- if (!capabilities || !((_h = capabilities.mimeTypes) == null ? void 0 : _h.includes("text/html+mcp"))) {
12893
- const err = new Error("Host does not advertise io.modelcontextprotocol/ui with text/html+mcp");
13129
+ const supportsMcpHtml = (_h = capabilities == null ? void 0 : capabilities.mimeTypes) == null ? void 0 : _h.some(
13130
+ (mime) => mime === "text/html+mcp" || mime === "text/html;profile=mcp-app"
13131
+ );
13132
+ if (!capabilities || !supportsMcpHtml) {
13133
+ const err = new Error("Host does not advertise io.modelcontextprotocol/ui with text/html+mcp or text/html;profile=mcp-app");
12894
13134
  setError(err);
12895
13135
  if ((_i = event.data) == null ? void 0 : _i.id) {
12896
13136
  (window.parent || window).postMessage(