@vivix-labs/studio-chat-mcp 0.1.15 → 0.1.17

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/dist/server.js CHANGED
@@ -29429,7 +29429,7 @@ data:
29429
29429
  // package.json
29430
29430
  var package_default = {
29431
29431
  name: "@vivix-labs/studio-chat-mcp",
29432
- version: "0.1.15",
29432
+ version: "0.1.17",
29433
29433
  type: "module",
29434
29434
  engines: {
29435
29435
  node: ">=22.12.0"
@@ -29457,7 +29457,8 @@ var package_default = {
29457
29457
  files: [
29458
29458
  "dist",
29459
29459
  "studio-plugin.json",
29460
- "skills",
29460
+ "README.md",
29461
+ "docs",
29461
29462
  "LICENSE"
29462
29463
  ],
29463
29464
  exports: {
@@ -37768,6 +37769,10 @@ var EMPTY_COMPLETION_RESULT = {
37768
37769
  }
37769
37770
  };
37770
37771
 
37772
+ // src/chat.ts
37773
+ import { randomBytes } from "node:crypto";
37774
+ import { performance } from "node:perf_hooks";
37775
+
37771
37776
  // src/message.ts
37772
37777
  var chatMessageSchema = external_exports.object({
37773
37778
  intent: external_exports.string().min(1).refine((value) => Boolean(value.trim())),
@@ -37777,6 +37782,79 @@ var chatMessageSchema = external_exports.object({
37777
37782
  // src/chat.ts
37778
37783
  import { PluginError } from "vivix-studio/sdk/shared";
37779
37784
  var inputError = (code, message, hint) => new PluginError(code, message, hint);
37785
+ function uuidv72(time3 = Date.now()) {
37786
+ const bytes = randomBytes(16);
37787
+ bytes.writeUIntBE(time3, 0, 6);
37788
+ bytes[6] = bytes[6] & 15 | 112;
37789
+ bytes[8] = bytes[8] & 63 | 128;
37790
+ const hex3 = bytes.toString("hex");
37791
+ return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
37792
+ }
37793
+ function safeRecordChatTelemetry(host, event) {
37794
+ try {
37795
+ host.recordChatTelemetry?.(event);
37796
+ } catch {
37797
+ }
37798
+ }
37799
+ async function withHostInteractionContext(host, context, fn) {
37800
+ if (typeof host.withInteractionContext === "function")
37801
+ return host.withInteractionContext(context, fn);
37802
+ return fn();
37803
+ }
37804
+ function isPlainRecord(value) {
37805
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
37806
+ }
37807
+ var cardBindingMeta = /* @__PURE__ */ new Map();
37808
+ function rememberCardBindings(bindings, meta3) {
37809
+ for (const token of Object.values(bindings)) {
37810
+ if (!token) continue;
37811
+ if (cardBindingMeta.size >= 2048 && !cardBindingMeta.has(token)) {
37812
+ const oldest = cardBindingMeta.keys().next().value;
37813
+ if (oldest !== void 0) cardBindingMeta.delete(oldest);
37814
+ }
37815
+ cardBindingMeta.set(token, meta3);
37816
+ }
37817
+ }
37818
+ function extractExposedActionsFromRender(rawActions) {
37819
+ if (!Array.isArray(rawActions)) return [];
37820
+ const items = rawActions.filter(isPlainRecord);
37821
+ const footerItems = items.filter((item) => item.placement !== "header");
37822
+ const firstFooter = footerItems[0];
37823
+ const primaryFooter = footerItems.find((item) => item.emphasis === "primary") ?? (firstFooter && firstFooter.emphasis === void 0 ? firstFooter : void 0);
37824
+ return items.flatMap((item) => {
37825
+ const actionId = typeof item.id === "string" && item.id ? item.id : void 0;
37826
+ if (!actionId) return [];
37827
+ const placement = item.placement === "header" ? "header" : "footer";
37828
+ const emphasis = typeof item.emphasis === "string" && item.emphasis ? item.emphasis : placement === "footer" ? item === primaryFooter ? "primary" : "secondary" : "secondary";
37829
+ const targetObj = isPlainRecord(item.target) ? item.target : void 0;
37830
+ const dispatchMode = typeof item.prompt === "string" ? "prompt" : targetObj?.mode === "native" ? "native" : "deliver";
37831
+ return [{ action_id: actionId, placement, emphasis, dispatch_mode: dispatchMode }];
37832
+ });
37833
+ }
37834
+ function extractRenderedCardMeta(sourceChat, sourceTarget, projected, bindingContext) {
37835
+ const viewProps = isPlainRecord(projected.view?.props) ? projected.view.props : void 0;
37836
+ const render = isPlainRecord(viewProps?.render) ? viewProps.render : isPlainRecord(bindingContext) && typeof bindingContext.componentId === "string" ? bindingContext : void 0;
37837
+ const componentId = typeof render?.componentId === "string" && render.componentId || typeof projected.structuredContent.componentId === "string" && projected.structuredContent.componentId || sourceChat.component;
37838
+ const renderProps = isPlainRecord(render?.props) ? render.props : void 0;
37839
+ const viewMode = typeof renderProps?.view === "string" && renderProps.view || typeof viewProps?.view === "string" && viewProps.view || (projected.view ? null : "headless");
37840
+ if (render && Array.isArray(render.actions)) {
37841
+ return {
37842
+ componentId,
37843
+ viewMode,
37844
+ exposedActions: extractExposedActionsFromRender(render.actions)
37845
+ };
37846
+ }
37847
+ const declared = actionsFor(sourceChat, sourceTarget, bindingContext);
37848
+ const exposedActions = Object.entries(declared).filter(
37849
+ ([name]) => !(sourceChat.component === "chat-components/renderer@1" && (name === "upload" || name === "readMedia"))
37850
+ ).map(([name, binding]) => ({
37851
+ action_id: name,
37852
+ placement: "footer",
37853
+ emphasis: "primary",
37854
+ dispatch_mode: "prepareMessage" in binding && typeof binding.prepareMessage === "function" ? "prompt" : name.startsWith("deliver.") ? "deliver" : "native"
37855
+ }));
37856
+ return { componentId, viewMode, exposedActions };
37857
+ }
37780
37858
  var readOperation = (catalog, target2) => {
37781
37859
  const value = catalog.get(target2);
37782
37860
  if (!value) return;
@@ -37792,7 +37870,8 @@ var operationId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
37792
37870
  var targetSchema = external_exports.object({ instanceId: external_exports.string().regex(/^[a-z][a-z0-9-]*$/), operationId }).strict();
37793
37871
  var options = {
37794
37872
  requestKey: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional(),
37795
- approval: external_exports.string().min(1).optional()
37873
+ approval: external_exports.string().min(1).optional(),
37874
+ fromInteractionId: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional()
37796
37875
  };
37797
37876
  var jsonObjectInput = external_exports.preprocess(
37798
37877
  (value) => {
@@ -37812,6 +37891,7 @@ var chatActionSchema = external_exports.object({
37812
37891
  binding: external_exports.string().min(1).max(65536),
37813
37892
  action: operationId,
37814
37893
  input: jsonObjectInput.optional(),
37894
+ cardInstanceId: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional(),
37815
37895
  ...options
37816
37896
  }).strict();
37817
37897
  var projectionSchema = external_exports.object({
@@ -37956,8 +38036,8 @@ async function project(runtime, source, chat, result, projector, ui, action, bin
37956
38036
  );
37957
38037
  }
37958
38038
  const bindings = await actionBindings(runtime, source, chat, value.bindingContext);
37959
- const { bindingContext: _private, ...publicValue } = value;
37960
- return {
38039
+ const { bindingContext: projectedBindingContext, ...publicValue } = value;
38040
+ const projected = {
37961
38041
  ...publicValue,
37962
38042
  structuredContent: {
37963
38043
  ...value.structuredContent,
@@ -37980,6 +38060,12 @@ async function project(runtime, source, chat, result, projector, ui, action, bin
37980
38060
  ui
37981
38061
  } : void 0
37982
38062
  };
38063
+ Object.defineProperty(projected, "_bindingContext", {
38064
+ value: projectedBindingContext,
38065
+ enumerable: false,
38066
+ configurable: true
38067
+ });
38068
+ return projected;
37983
38069
  }
37984
38070
  function chatTargets(catalog, source, context) {
37985
38071
  const chat = readOperation(catalog, source)?.chat;
@@ -38007,17 +38093,31 @@ function readChatBundle(host, scope, target2, expected) {
38007
38093
  }
38008
38094
  async function runChat(host, projectId, raw) {
38009
38095
  const request = chatRunSchema.parse(raw);
38010
- return host.withOperations(
38011
- typeof projectId === "string" ? { kind: "project", id: projectId } : projectId,
38096
+ const scope = typeof projectId === "string" ? { kind: "project", id: projectId } : projectId;
38097
+ const telemetryProjectId = scope.kind === "project" ? scope.id : null;
38098
+ const cardInstanceId = uuidv72();
38099
+ const startedAt = performance.now();
38100
+ const requestedComponentId = isPlainRecord(request.input) && typeof request.input.componentId === "string" ? request.input.componentId : void 0;
38101
+ let resolvedComponentId = requestedComponentId ?? `${request.target.instanceId}/${request.target.operationId}`;
38102
+ const execute = () => host.withOperations(
38103
+ scope,
38012
38104
  (catalog) => chatTargets(catalog, request.target, request.input),
38013
38105
  async (runtime) => {
38014
38106
  const source = sourceOperation(runtime, request.target);
38107
+ resolvedComponentId = requestedComponentId ?? source.chat.component;
38015
38108
  const ui = await runtime.component(request.target, source.chat.component);
38016
- const result = await runtime.invoke(request.target, request.input, {
38109
+ const invokeOptions = request.fromInteractionId ? {
38110
+ requestKey: request.requestKey,
38111
+ approval: request.approval,
38112
+ fromInteractionId: request.fromInteractionId,
38113
+ triggerSource: "chat_component_explicit",
38114
+ callerSurface: "mcp"
38115
+ } : {
38017
38116
  requestKey: request.requestKey,
38018
38117
  approval: request.approval
38019
- });
38020
- return await project(
38118
+ };
38119
+ const result = await runtime.invoke(request.target, request.input, invokeOptions);
38120
+ const projected = await project(
38021
38121
  runtime,
38022
38122
  request.target,
38023
38123
  source.chat,
@@ -38025,126 +38125,301 @@ async function runChat(host, projectId, raw) {
38025
38125
  source.chat.projectResult,
38026
38126
  ui
38027
38127
  );
38128
+ const meta3 = extractRenderedCardMeta(
38129
+ source.chat,
38130
+ request.target,
38131
+ projected,
38132
+ projected._bindingContext
38133
+ );
38134
+ resolvedComponentId = meta3.componentId;
38135
+ if (projected.view) {
38136
+ projected.view = {
38137
+ ...projected.view,
38138
+ cardInstanceId,
38139
+ componentId: meta3.componentId
38140
+ };
38141
+ }
38142
+ const bindings = isPlainRecord(projected.structuredContent.bindings) ? projected.structuredContent.bindings : {};
38143
+ rememberCardBindings(bindings, {
38144
+ cardInstanceId,
38145
+ componentId: meta3.componentId,
38146
+ actions: new Map(meta3.exposedActions.map((item) => [item.action_id, item]))
38147
+ });
38148
+ safeRecordChatTelemetry(host, {
38149
+ event_name: "chat.card.rendered",
38150
+ project_id: telemetryProjectId,
38151
+ card_instance_id: cardInstanceId,
38152
+ component_id: meta3.componentId,
38153
+ view_mode: meta3.viewMode,
38154
+ exposed_actions: meta3.exposedActions,
38155
+ status: "ok",
38156
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38157
+ });
38158
+ return projected;
38028
38159
  }
38029
38160
  );
38161
+ try {
38162
+ return request.fromInteractionId ? await withHostInteractionContext(
38163
+ host,
38164
+ {
38165
+ fromInteractionId: request.fromInteractionId,
38166
+ triggerSource: "chat_component_explicit",
38167
+ callerSurface: "mcp"
38168
+ },
38169
+ execute
38170
+ ) : await execute();
38171
+ } catch (error62) {
38172
+ safeRecordChatTelemetry(host, {
38173
+ event_name: "chat.card.rendered",
38174
+ project_id: telemetryProjectId,
38175
+ card_instance_id: cardInstanceId,
38176
+ component_id: resolvedComponentId,
38177
+ status: "error",
38178
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
38179
+ error: error62
38180
+ });
38181
+ throw error62;
38182
+ }
38183
+ }
38184
+ function resolveActionClickMeta(request, sourceChat, bindingContext, isPrompt) {
38185
+ const isChatComponentsRenderer = sourceChat?.component === "chat-components/renderer@1";
38186
+ if (isChatComponentsRenderer && (request.action === "upload" || request.action === "readMedia")) {
38187
+ return {
38188
+ skipTelemetry: true,
38189
+ cardInstanceId: "",
38190
+ componentId: sourceChat.component,
38191
+ actionId: request.action,
38192
+ placement: "footer",
38193
+ emphasis: "secondary",
38194
+ dispatchMode: "native"
38195
+ };
38196
+ }
38197
+ const cached2 = cardBindingMeta.get(request.binding);
38198
+ const cardInstanceId = request.cardInstanceId ?? cached2?.cardInstanceId ?? uuidv72();
38199
+ const renderCtx = isPlainRecord(bindingContext) && typeof bindingContext.componentId === "string" ? bindingContext : void 0;
38200
+ const inputActionId = isPlainRecord(request.input) && typeof request.input.actionId === "string" && request.input.actionId ? request.input.actionId : void 0;
38201
+ const inputComponentId = isPlainRecord(request.input) && typeof request.input.componentId === "string" && request.input.componentId ? request.input.componentId : void 0;
38202
+ const componentId = typeof renderCtx?.componentId === "string" && renderCtx.componentId || inputComponentId || cached2?.componentId || sourceChat?.component || `${request.target.instanceId}/${request.target.operationId}`;
38203
+ const actionId = renderCtx || isChatComponentsRenderer ? inputActionId ?? request.action : request.action;
38204
+ const fromRender = renderCtx ? extractExposedActionsFromRender(renderCtx.actions).find((item) => item.action_id === actionId) : void 0;
38205
+ const fromCache = cached2?.actions.get(actionId);
38206
+ const dispatchMode = isPrompt ? "prompt" : fromRender?.dispatch_mode && fromRender.dispatch_mode !== "download" ? fromRender.dispatch_mode : fromCache?.dispatch_mode && fromCache.dispatch_mode !== "download" ? fromCache.dispatch_mode : request.action.startsWith("deliver.") ? "deliver" : "native";
38207
+ const placement = fromRender?.placement ?? fromCache?.placement ?? "footer";
38208
+ const emphasis = fromRender?.emphasis ?? fromCache?.emphasis ?? "primary";
38209
+ return {
38210
+ skipTelemetry: false,
38211
+ cardInstanceId,
38212
+ componentId,
38213
+ actionId,
38214
+ placement,
38215
+ emphasis,
38216
+ dispatchMode
38217
+ };
38030
38218
  }
38031
38219
  async function actionChat(host, projectId, raw) {
38032
38220
  const request = chatActionSchema.parse(raw);
38221
+ const scope = typeof projectId === "string" ? { kind: "project", id: projectId } : projectId;
38222
+ const telemetryProjectId = scope.kind === "project" ? scope.id : null;
38223
+ const cardInteractionId = uuidv72();
38224
+ const startedAt = performance.now();
38033
38225
  let destinationTarget;
38034
- return host.withOperations(
38035
- typeof projectId === "string" ? { kind: "project", id: projectId } : projectId,
38036
- (catalog) => {
38037
- const targets = catalog.bindingTargets(request.binding);
38038
- destinationTarget = targets[0];
38039
- try {
38040
- return [
38041
- ...targets,
38042
- ...chatTargets(catalog, request.target, catalog.bindingContext(request.binding))
38043
- ];
38044
- } catch {
38045
- return [...targets, request.target];
38046
- }
38047
- },
38048
- async (runtime) => {
38049
- const bindingContext = runtime.bindingContext(request.binding);
38050
- const current = readOperation(runtime, request.target);
38051
- const prepared = current?.chat && Object.hasOwn(current.chat.actions, request.action) ? current.chat.actions[request.action] : void 0;
38052
- if (prepared?.prepareMessage) {
38053
- if (destinationTarget.instanceId !== request.target.instanceId || destinationTarget.operationId !== request.target.operationId || await runtime.bind(request.target, [request.target], bindingContext) !== request.binding)
38054
- throw inputError(
38055
- "CHAT_ACTION_DENIED",
38056
- "The message binding does not belong to this card.",
38057
- "Use the original card and its source binding."
38058
- );
38059
- const context = {
38060
- projectId: runtime.scope.id,
38061
- target: { ...request.target },
38062
- action: request.action,
38063
- bindingContext
38064
- };
38065
- const message = chatMessageSchema.parse(await prepared.prepareMessage(request, context));
38066
- return {
38067
- text: "Message prepared. Awaiting chat client confirmation.",
38068
- structuredContent: {
38069
- protocolVersion: 1,
38070
- projectId: runtime.scope.id,
38071
- target: { ...request.target },
38072
- action: request.action
38073
- },
38074
- message
38075
- };
38076
- }
38077
- const invocation = await runtime.invokeBound(
38078
- request.binding,
38079
- { target: request.target, action: request.action, input: request.input },
38080
- { requestKey: request.requestKey, approval: request.approval },
38081
- async () => {
38082
- const source2 = sourceOperation(runtime, request.target);
38083
- const binding2 = declaredAction(
38084
- source2.chat,
38085
- request.target,
38086
- request.action,
38087
- bindingContext
38088
- );
38089
- const target2 = binding2.target;
38090
- if (target2.instanceId !== destinationTarget.instanceId || target2.operationId !== destinationTarget.operationId)
38091
- throw inputError(
38092
- "CHAT_ACTION_DENIED",
38093
- "The binding does not belong to this action.",
38094
- "Use the binding published for this card action."
38095
- );
38096
- if (await runtime.bind(target2, [request.target], bindingContext) !== request.binding)
38226
+ let telemetryMeta;
38227
+ try {
38228
+ return await host.withOperations(
38229
+ scope,
38230
+ (catalog) => {
38231
+ const targets = catalog.bindingTargets(request.binding);
38232
+ destinationTarget = targets[0];
38233
+ try {
38234
+ return [
38235
+ ...targets,
38236
+ ...chatTargets(catalog, request.target, catalog.bindingContext(request.binding))
38237
+ ];
38238
+ } catch {
38239
+ return [...targets, request.target];
38240
+ }
38241
+ },
38242
+ async (runtime) => {
38243
+ let bindingContext;
38244
+ try {
38245
+ bindingContext = runtime.bindingContext(request.binding);
38246
+ } catch (error62) {
38247
+ const currentOnFail = readOperation(runtime, request.target);
38248
+ telemetryMeta = resolveActionClickMeta(request, currentOnFail?.chat, void 0, false);
38249
+ throw error62;
38250
+ }
38251
+ const current = readOperation(runtime, request.target);
38252
+ const prepared = current?.chat && Object.hasOwn(current.chat.actions, request.action) ? current.chat.actions[request.action] : void 0;
38253
+ telemetryMeta = resolveActionClickMeta(
38254
+ request,
38255
+ current?.chat,
38256
+ bindingContext,
38257
+ Boolean(prepared?.prepareMessage)
38258
+ );
38259
+ if (prepared?.prepareMessage) {
38260
+ if (destinationTarget.instanceId !== request.target.instanceId || destinationTarget.operationId !== request.target.operationId || await runtime.bind(request.target, [request.target], bindingContext) !== request.binding)
38097
38261
  throw inputError(
38098
38262
  "CHAT_ACTION_DENIED",
38099
- "The binding does not belong to this source.",
38100
- "Use the original card and its published action binding."
38263
+ "The message binding does not belong to this card.",
38264
+ "Use the original card and its source binding."
38101
38265
  );
38102
38266
  const context = {
38103
38267
  projectId: runtime.scope.id,
38104
38268
  target: { ...request.target },
38105
38269
  action: request.action,
38106
- destination: { ...target2 },
38107
- bindingContext
38270
+ bindingContext,
38271
+ interactionId: cardInteractionId
38108
38272
  };
38109
- const input2 = binding2.mapInput ? await binding2.mapInput(request, context) : request.input ?? {};
38110
- await binding2.validate?.(input2, context);
38111
- return input2;
38112
- }
38113
- );
38114
- const source = readOperation(runtime, request.target);
38115
- let currentBinding;
38116
- try {
38117
- currentBinding = await runtime.bind(invocation.target, [request.target], bindingContext);
38118
- } catch {
38119
- }
38120
- if (!source?.chat || currentBinding !== request.binding) {
38121
- return {
38122
- text: "The original action completed. Reopen the operation to view the current card.",
38123
- structuredContent: {
38124
- protocolVersion: 1,
38125
- projectId: runtime.scope.id,
38126
- target: request.target,
38127
- action: request.action,
38128
- outcome: "succeeded",
38129
- result: invocation.result
38273
+ const message = chatMessageSchema.parse(await prepared.prepareMessage(request, context));
38274
+ if (!telemetryMeta.skipTelemetry) {
38275
+ safeRecordChatTelemetry(host, {
38276
+ event_name: "chat.card.action_clicked",
38277
+ project_id: telemetryProjectId,
38278
+ card_interaction_id: cardInteractionId,
38279
+ card_instance_id: telemetryMeta.cardInstanceId,
38280
+ component_id: telemetryMeta.componentId,
38281
+ action_id: telemetryMeta.actionId,
38282
+ placement: telemetryMeta.placement,
38283
+ emphasis: telemetryMeta.emphasis,
38284
+ dispatch_mode: "prompt",
38285
+ status: "ok",
38286
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38287
+ });
38130
38288
  }
38289
+ return {
38290
+ text: "Message prepared. Awaiting chat client confirmation.",
38291
+ structuredContent: {
38292
+ protocolVersion: 1,
38293
+ projectId: runtime.scope.id,
38294
+ target: { ...request.target },
38295
+ action: request.action
38296
+ },
38297
+ message
38298
+ };
38299
+ }
38300
+ const invokeOptions = telemetryMeta.skipTelemetry ? { requestKey: request.requestKey, approval: request.approval } : {
38301
+ requestKey: request.requestKey,
38302
+ approval: request.approval,
38303
+ fromInteractionId: cardInteractionId,
38304
+ triggerSource: "chat_component_direct",
38305
+ callerSurface: "chat_component"
38131
38306
  };
38307
+ const invokeAction = () => runtime.invokeBound(
38308
+ request.binding,
38309
+ { target: request.target, action: request.action, input: request.input },
38310
+ invokeOptions,
38311
+ async () => {
38312
+ const source2 = sourceOperation(runtime, request.target);
38313
+ const binding2 = declaredAction(
38314
+ source2.chat,
38315
+ request.target,
38316
+ request.action,
38317
+ bindingContext
38318
+ );
38319
+ const target2 = binding2.target;
38320
+ if (target2.instanceId !== destinationTarget.instanceId || target2.operationId !== destinationTarget.operationId)
38321
+ throw inputError(
38322
+ "CHAT_ACTION_DENIED",
38323
+ "The binding does not belong to this action.",
38324
+ "Use the binding published for this card action."
38325
+ );
38326
+ if (await runtime.bind(target2, [request.target], bindingContext) !== request.binding)
38327
+ throw inputError(
38328
+ "CHAT_ACTION_DENIED",
38329
+ "The binding does not belong to this source.",
38330
+ "Use the original card and its published action binding."
38331
+ );
38332
+ const context = {
38333
+ projectId: runtime.scope.id,
38334
+ target: { ...request.target },
38335
+ action: request.action,
38336
+ destination: { ...target2 },
38337
+ bindingContext
38338
+ };
38339
+ const input2 = binding2.mapInput ? await binding2.mapInput(request, context) : request.input ?? {};
38340
+ await binding2.validate?.(input2, context);
38341
+ return input2;
38342
+ }
38343
+ );
38344
+ const invocation = telemetryMeta.skipTelemetry ? await invokeAction() : await withHostInteractionContext(
38345
+ host,
38346
+ {
38347
+ cardInteractionId,
38348
+ fromInteractionId: cardInteractionId,
38349
+ triggerSource: "chat_component_direct",
38350
+ callerSurface: "chat_component"
38351
+ },
38352
+ invokeAction
38353
+ );
38354
+ if (!telemetryMeta.skipTelemetry) {
38355
+ safeRecordChatTelemetry(host, {
38356
+ event_name: "chat.card.action_clicked",
38357
+ project_id: telemetryProjectId,
38358
+ card_interaction_id: cardInteractionId,
38359
+ card_instance_id: telemetryMeta.cardInstanceId,
38360
+ component_id: telemetryMeta.componentId,
38361
+ action_id: telemetryMeta.actionId,
38362
+ placement: telemetryMeta.placement,
38363
+ emphasis: telemetryMeta.emphasis,
38364
+ dispatch_mode: telemetryMeta.dispatchMode,
38365
+ status: "ok",
38366
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38367
+ });
38368
+ }
38369
+ const source = readOperation(runtime, request.target);
38370
+ let currentBinding;
38371
+ try {
38372
+ currentBinding = await runtime.bind(invocation.target, [request.target], bindingContext);
38373
+ } catch {
38374
+ }
38375
+ if (!source?.chat || currentBinding !== request.binding) {
38376
+ return {
38377
+ text: "The original action completed. Reopen the operation to view the current card.",
38378
+ structuredContent: {
38379
+ protocolVersion: 1,
38380
+ projectId: runtime.scope.id,
38381
+ target: request.target,
38382
+ action: request.action,
38383
+ outcome: "succeeded",
38384
+ result: invocation.result
38385
+ }
38386
+ };
38387
+ }
38388
+ const binding = declaredAction(source.chat, request.target, request.action, bindingContext);
38389
+ const operation = readyDestination(runtime, invocation.target);
38390
+ const ui = await runtime.component(request.target, source.chat.component);
38391
+ return project(
38392
+ runtime,
38393
+ request.target,
38394
+ source.chat,
38395
+ invocation.result,
38396
+ binding.projectResult ?? operation.chat?.projectResult ?? source.chat.projectResult,
38397
+ ui,
38398
+ request.action,
38399
+ bindingContext
38400
+ );
38132
38401
  }
38133
- const binding = declaredAction(source.chat, request.target, request.action, bindingContext);
38134
- const operation = readyDestination(runtime, invocation.target);
38135
- const ui = await runtime.component(request.target, source.chat.component);
38136
- return project(
38137
- runtime,
38138
- request.target,
38139
- source.chat,
38140
- invocation.result,
38141
- binding.projectResult ?? operation.chat?.projectResult ?? source.chat.projectResult,
38142
- ui,
38143
- request.action,
38144
- bindingContext
38145
- );
38402
+ );
38403
+ } catch (error62) {
38404
+ const fallbackMeta = telemetryMeta ?? resolveActionClickMeta(request, void 0, void 0, false);
38405
+ if (!fallbackMeta.skipTelemetry) {
38406
+ safeRecordChatTelemetry(host, {
38407
+ event_name: "chat.card.action_clicked",
38408
+ project_id: telemetryProjectId,
38409
+ card_interaction_id: cardInteractionId,
38410
+ card_instance_id: fallbackMeta.cardInstanceId,
38411
+ component_id: fallbackMeta.componentId,
38412
+ action_id: fallbackMeta.actionId,
38413
+ placement: fallbackMeta.placement,
38414
+ emphasis: fallbackMeta.emphasis,
38415
+ dispatch_mode: fallbackMeta.dispatchMode,
38416
+ status: "error",
38417
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
38418
+ error: error62
38419
+ });
38146
38420
  }
38147
- );
38421
+ throw error62;
38422
+ }
38148
38423
  }
38149
38424
  function declaredAction(chat, source, action, context) {
38150
38425
  const actions = actionsFor(chat, source, context);
@@ -38509,7 +38784,8 @@ var common = {
38509
38784
  scope: scopeSchema.optional(),
38510
38785
  target,
38511
38786
  requestKey: external_exports.string().min(1).max(200).optional(),
38512
- approval: identifier.optional()
38787
+ approval: identifier.optional(),
38788
+ fromInteractionId: external_exports.string().min(1).max(200).optional()
38513
38789
  };
38514
38790
  var routing = (value, context) => {
38515
38791
  if (value.projectId !== void 0 && value.scope !== void 0)
@@ -38523,8 +38799,30 @@ var actionInput = external_exports.object({
38523
38799
  ...common,
38524
38800
  binding: external_exports.string().min(1).max(65536),
38525
38801
  action: identifier,
38526
- input: jsonObjectInput.optional()
38802
+ input: jsonObjectInput.optional(),
38803
+ cardInstanceId: external_exports.string().min(1).max(200).optional()
38527
38804
  }).strict().superRefine(routing);
38805
+ var cardTelemetryInput = external_exports.discriminatedUnion("event", [
38806
+ external_exports.object({
38807
+ event: external_exports.literal("mounted"),
38808
+ cardInstanceId: external_exports.string().min(1).max(200),
38809
+ componentId: external_exports.string().min(1).max(200),
38810
+ projectId: external_exports.string().min(1).max(512).nullable().optional()
38811
+ }).strict(),
38812
+ external_exports.object({
38813
+ event: external_exports.literal("download_clicked"),
38814
+ cardInteractionId: external_exports.string().min(1).max(200).optional(),
38815
+ cardInstanceId: external_exports.string().min(1).max(200),
38816
+ componentId: external_exports.string().min(1).max(200),
38817
+ projectId: external_exports.string().min(1).max(512).nullable().optional(),
38818
+ actionId: external_exports.string().min(1).max(200).optional(),
38819
+ placement: external_exports.string().min(1).max(64).optional(),
38820
+ emphasis: external_exports.string().min(1).max(64).optional(),
38821
+ status: external_exports.enum(["ok", "error"]),
38822
+ durationMs: external_exports.number().int().nonnegative().optional(),
38823
+ errorMessage: external_exports.string().max(1e3).optional()
38824
+ }).strict()
38825
+ ]);
38528
38826
  function mapChatResult(result) {
38529
38827
  const { bindings: _bindings, ...structuredContent } = result.structuredContent;
38530
38828
  return {
@@ -38545,10 +38843,54 @@ function mapChatResult(result) {
38545
38843
  }
38546
38844
  function createChatServer(options2) {
38547
38845
  const host = options2.host;
38846
+ const mountedInstances = options2.mountedInstances ?? /* @__PURE__ */ new Set();
38548
38847
  const server = new McpServer(
38549
38848
  { name: "vivix-studio-chat", version: package_default.version },
38550
38849
  {
38551
- instructions: "Use this server for Vivix Studio interactive cards. When a request involves reviewing, choosing, editing, comparing, previewing, or presenting Studio content, call list_chat_capabilities in user scope first, even when the work belongs to a project. If discovery returns a relevant component, immediately call describe_chat_capability for that route and then run_studio_action with the returned scope and target. A discovery call alone is not a completed card flow. Use project scope separately for project media queries or declared project cards. If a project-scope discovery includes a fallback user-scope card, use the scope and target returned on that card. For existing media or project progress, prefer a matching storyboard, media-result, story-progress, or media-query route when its returned inputs can be filled from the current project state. Use Studio CLI plugin operations for multi-step workflow and generation execution unless invoked via a card action. For a full Studio project, project open --no-open only returns the workbenchUrl. If the Host provides a native browser or side-panel handoff, open that exact URL there. In Codex, use the host open_in_codex handoff with a browser target and right placement when available. Do not use CUA to create or open the workbench tab. run_studio_action renders a chat card and does not open the workbench. A successful tool result confirms that the Host accepted the request, but does not confirm that the client displayed a card or opened a sidebar. Recommend a new conversation only when this conversation has just installed Studio or changed the MCP configuration and the tools are absent from the active and deferred host registries. On a later conversation with the tools still absent, report that the host has not exposed interactive cards and continue with the CLI and Workbench. Do not recommend another conversation after list_chat_capabilities or another card tool has succeeded. Terminal-only hosts should continue with the CLI and Workbench. General interactions default to user scope; saved project operations use explicit project scope. Preserve requestKey and original arguments for recovery; never automatically resubmit an uncertain action."
38850
+ instructions: "Use this server for Vivix Studio interactive cards. Whenever a turn involves creative choices, drafts, storyboards, character concepts, comparisons, media previews, or project progress, proactively use a matching native card alongside any project workflow rather than replying in plain text alone. Follow the unified vivix-studio Skill and its references/chat-interactions.md, references/habits-and-proposals.md, and references/project-and-workbench.md references for presentation choice, user collaboration preferences, session handling, media routing, custom visualization, and host handoff. Match card titles, descriptions, and button labels to the user\u2019s conversation language unless asked otherwise. Call list_chat_capabilities before selecting a card, then describe_chat_capability and run_studio_action with the returned scope, target, schemas, and input. On the immediate continuation turn after receiving a chat-component-action callback with interactionId, pass that exact value as optional fromInteractionId on run_studio_action (or --from-interaction on CLI calls). General cards use user scope. Use explicit project scope for project operations and queries. Preserve requestKey and original arguments for recovery and never automatically resubmit an uncertain write. A successful tool result means the Host accepted the request, not that the client rendered the card or opened a Workbench panel."
38851
+ }
38852
+ );
38853
+ server.registerTool(
38854
+ "report_card_telemetry",
38855
+ {
38856
+ title: "Report card telemetry",
38857
+ description: "Record MCP App card mount exposure and built-in media download interactions. App-only telemetry callback; does not mutate business state.",
38858
+ inputSchema: cardTelemetryInput,
38859
+ annotations: { readOnlyHint: true, openWorldHint: false },
38860
+ _meta: { ui: { visibility: ["app"] } }
38861
+ },
38862
+ async (input2) => {
38863
+ if (input2.event === "mounted") {
38864
+ if (!mountedInstances.has(input2.cardInstanceId)) {
38865
+ if (mountedInstances.size >= 4096) {
38866
+ const oldest = mountedInstances.values().next().value;
38867
+ if (oldest !== void 0) mountedInstances.delete(oldest);
38868
+ }
38869
+ mountedInstances.add(input2.cardInstanceId);
38870
+ safeRecordChatTelemetry(host, {
38871
+ event_name: "chat.card.mounted",
38872
+ project_id: input2.projectId ?? null,
38873
+ card_instance_id: input2.cardInstanceId,
38874
+ component_id: input2.componentId
38875
+ });
38876
+ }
38877
+ return { content: [{ type: "text", text: "Card mount recorded." }] };
38878
+ }
38879
+ safeRecordChatTelemetry(host, {
38880
+ event_name: "chat.card.action_clicked",
38881
+ project_id: input2.projectId ?? null,
38882
+ card_interaction_id: input2.cardInteractionId ?? uuidv72(),
38883
+ card_instance_id: input2.cardInstanceId,
38884
+ component_id: input2.componentId,
38885
+ action_id: input2.actionId ?? "download",
38886
+ placement: input2.placement ?? "inline",
38887
+ emphasis: input2.emphasis ?? "secondary",
38888
+ dispatch_mode: "download",
38889
+ status: input2.status,
38890
+ duration_ms: input2.durationMs,
38891
+ ...input2.errorMessage ? { error: new Error(input2.errorMessage) } : {}
38892
+ });
38893
+ return { content: [{ type: "text", text: "Card download telemetry recorded." }] };
38552
38894
  }
38553
38895
  );
38554
38896
  server.registerTool(
@@ -38682,7 +39024,7 @@ function createChatServer(options2) {
38682
39024
  "describe_chat_capability",
38683
39025
  {
38684
39026
  title: "Read a chat contract",
38685
- description: "Read exact schemas for a discovered route. Pass componentId for a reusable component, or kind=nativeOperation for an operation to bind using target.mode=native. Native operation schemas do not imply a chat view or execution permission. Default interface text to English and preserve original creative content.",
39027
+ description: "Read exact schemas for a discovered route. Pass componentId for a reusable component, or kind=nativeOperation for an operation to bind using target.mode=native. Native operation schemas do not imply a chat view or execution permission. Match interface text to the user\u2019s conversation language unless requested otherwise. Preserve original creative content.",
38686
39028
  inputSchema: external_exports.object({
38687
39029
  scope: scopeSchema.default(userScope),
38688
39030
  target,
@@ -38721,7 +39063,7 @@ function createChatServer(options2) {
38721
39063
  "run_studio_action",
38722
39064
  {
38723
39065
  title: "Run Studio action",
38724
- description: "Open a component or declared project card using the scope, target and contract returned by this connection discovery tools. `input` is a JSON object; a JSON-encoded object string is accepted and normalized. Default interface headings, field labels, group headings and buttons to English unless the user requests another interface language. Preserve story names, story text and user input in their original language. User-scope components work without a business project. Project business operations require the selected project scope. Legacy projectId calls remain supported. Preserve requestKey and original input for uncertain recovery.",
39066
+ description: "Open a component or declared project card using the scope, target and contract returned by this connection discovery tools. `input` is a JSON object; a JSON-encoded object string is accepted and normalized. Match interface headings, field labels, group headings and buttons to the user\u2019s conversation language unless requested otherwise. Preserve story names, story text and user input in their original language. User-scope components work without a business project. Project business operations require the selected project scope. Legacy projectId calls remain supported. Preserve requestKey and original input for uncertain recovery.",
38725
39067
  inputSchema: runInput,
38726
39068
  _meta: { ui: { resourceUri: chatResourceUri } }
38727
39069
  },
@@ -38833,6 +39175,7 @@ function activate(context) {
38833
39175
  return { value: normalized, description: normalized?.description };
38834
39176
  });
38835
39177
  const readHtml = () => readFile(new URL("./chat-ui/index.html", import.meta.url), "utf8");
39178
+ const mountedInstances = /* @__PURE__ */ new Set();
38836
39179
  context.http.register({
38837
39180
  id: "mcp",
38838
39181
  method: "POST",
@@ -38847,7 +39190,8 @@ function activate(context) {
38847
39190
  const server = createChatServer({
38848
39191
  host: context.host,
38849
39192
  readHtml,
38850
- resourceDomains: context.config.resourceDomains
39193
+ resourceDomains: context.config.resourceDomains,
39194
+ mountedInstances
38851
39195
  });
38852
39196
  try {
38853
39197
  await server.connect(transport);