@vivix-labs/studio-chat-mcp 0.1.6 → 0.1.8

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.
@@ -151,7 +151,7 @@ Boolean requesting whether a visible border and background is provided by the ho
151
151
  - "model": Tool visible to and callable by the agent
152
152
  - "app": Tool callable by the app from this server only`),csp:f.never().optional(),permissions:f.never().optional()}),lU=f.object({mimeTypes:f.array(f.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),dU=f.object({method:f.literal("ui/download-file"),params:f.object({contents:f.array(f.union([En,Cn])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),mU=f.object({method:f.literal("ui/message"),params:f.object({role:f.literal("user").describe('Message role, currently only "user" is supported.'),content:f.array(Xt).describe("Message content blocks (text, image, etc.).")})}),pU=f.object({method:f.literal("ui/notifications/sandbox-resource-ready"),params:f.object({html:f.string().describe("HTML content to load into the inner iframe."),sandbox:f.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Qv.optional().describe("CSP configuration from resource metadata."),permissions:e_.optional().describe("Sandbox permissions from resource metadata.")})}),YE=f.object({method:f.literal("ui/notifications/tool-result"),params:Vr.describe("Standard MCP tool execution result.")}),Rz=f.object({toolInfo:f.object({id:Pt.optional().describe("JSON-RPC id of the tools/call request."),tool:qr.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:NE.optional().describe("Current color theme preference."),styles:FE.optional().describe("Style configuration for theming the app."),displayMode:qc.optional().describe("How the UI is currently displayed."),availableDisplayModes:f.array(qc).optional().describe("Display modes the host supports."),containerDimensions:f.union([f.object({height:f.number().describe("Fixed container height in pixels.")}),f.object({maxHeight:f.union([f.number(),f.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(f.union([f.object({width:f.number().describe("Fixed container width in pixels.")}),f.object({maxWidth:f.union([f.number(),f.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
153
153
  container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:f.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:f.string().optional().describe("User's timezone in IANA format."),userAgent:f.string().optional().describe("Host application identifier."),platform:f.union([f.literal("web"),f.literal("desktop"),f.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:f.object({touch:f.boolean().optional().describe("Whether the device supports touch input."),hover:f.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:f.object({top:f.number().describe("Top safe area inset in pixels."),right:f.number().describe("Right safe area inset in pixels."),bottom:f.number().describe("Bottom safe area inset in pixels."),left:f.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XE=f.object({method:f.literal("ui/notifications/host-context-changed"),params:Rz.describe("Partial context update containing only changed fields.")}),fU=f.object({method:f.literal("ui/update-model-context"),params:f.object({content:f.array(Xt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:f.record(f.string(),f.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),hU=f.object({method:f.literal("ui/initialize"),params:f.object({appInfo:Wt.describe("App identification (name and version)."),appCapabilities:KE.describe("Features and capabilities this app provides."),protocolVersion:f.string().describe("Protocol version this app supports.")})}),QE=f.object({protocolVersion:f.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Wt.describe("Host application identification and version."),hostCapabilities:BE.describe("Features and capabilities provided by the host."),hostContext:Rz.describe("Rich context about the host environment.")}).passthrough(),eC={target:"draft-2020-12"};async function Iz(e,t){let n=e["~standard"];if(n.jsonSchema)return n.jsonSchema[t](eC);throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function xz(e,t,n=""){let o=await e["~standard"].validate(t);if(o.issues){let r=o.issues.map(i=>{let a=i.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(n+r)}return o.value}function tC(e,t){let n={...e,...t};return t.experimental!==void 0&&(n.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(n.tools={...e.tools,...t.tools}),n}var Qd=class e extends Mc{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new Wv;_methods=new Yv;setRequestHandler=(...t)=>{let[n,...o]=wz("request",t)??t;this._methods.claim(n,"setRequestHandler"),super.setRequestHandler.call(this,n,...o)};setNotificationHandler=(...t)=>{let[n,...o]=wz("notification",t)??t;this._methods.claim(n,"setNotificationHandler"),super.setNotificationHandler.call(this,n,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...n)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...n)};_assertInitialized(t){if(this._initializedSent)return;let n=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:LE,toolinputpartial:qE,toolresult:YE,toolcancelled:VE,hostcontextchanged:XE};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(t,n){n&&this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.setHandler(t,n)}addEventListener(t,n){this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.addEventListener(t,n)}removeEventListener(t,n){this._events.removeEventListener(t,n)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let n=this.eventSchemas[t];if(!n)throw Error(`Unknown event: ${String(t)}`);this.setNotificationHandler(n.shape.method.value,{params:n.shape.params},o=>{let r=o;t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r}),this._events.dispatch(t,r)}),this._registeredEvents.add(t)}getEventHandler(t){return this._events.getHandler(t)}warnIfRequestHandlerReplaced(t,n,o){n&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,n={},o={autoResize:!0}){super(o),this._appInfo=t,this._appCapabilities=n,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval&&f.config({jitless:!0}),this.replaceRequestHandler("ping",r=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(t){return t}registerAppCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=tC(this._appCapabilities,t)}registerTool(t,n,o){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let r=this,i=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=n.inputSchema!==void 0,s={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(c){Object.assign(this,c),i()},remove(){r._registeredTools[t]===s&&(delete r._registeredTools[t],i())},handler:async(c,u)=>{if(!s.enabled)throw Error(`Tool ${t} is disabled`);let d;if(a){let m=s.inputSchema,p=m?await xz(m,c??{},`Invalid input for tool ${t}: `):c??{};d=await o(p,u)}else d=await o(u);return s.outputSchema&&!d.isError&&(d.structuredContent=await xz(s.outputSchema,d.structuredContent,`Invalid output for tool ${t}: `)),d}};return this._registeredTools[t]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,n)=>{let o=this._registeredTools[t.name];if(!o)throw Error(`Tool ${t.name} not found`);return o.handler(t.arguments,n)},this.onlisttools=async(t,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let i={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Iz(r.inputSchema,"input"):{type:"object",properties:{}}};return r.outputSchema&&(i.outputSchema=await Iz(r.outputSchema,"output")),r.annotations&&(i.annotations=r.annotations),r._meta&&(i._meta=r._meta),i}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler("ui/resource-teardown",{params:HE.shape.params,result:JE},(n,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",(n,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler("tools/list",(n,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,o)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;default:return}}assertNotificationCapability(t){}async callServerTool(t,n){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(t,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},n)}async listServerResources(t,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},n)}async createSamplingMessage(t,n){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:t},n)}sendMessage(t,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},ME,n)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},Mr,n)}openLink(t,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},UE,n)}sendOpenLink=this.openLink;downloadFile(t,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},DE,n)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},GE,n)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,n=0,o=0,r=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let u=Math.ceil(window.innerWidth);(u!==n||c!==o)&&(n=u,o=c,this.sendSizeChanged({width:u,height:c}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(t=new Xv(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(t);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:CE}},QE,n);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};var r_="studio.chat.component.v1";function pe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vc(e){return{content:e.content,structuredContent:pe(e.structuredContent)?e.structuredContent:void 0,_meta:e._meta,isError:e.isError===!0}}function Pz(e){let t=e.content;if(e.isError||e.structuredContent||e._meta?.["studio/view"]||t?.length!==1)return e;let n=t[0]?.text;if(t[0]?.type!=="text"||!n?.startsWith('{"content":')||!n.includes('"studio/view"'))return e;try{let o=JSON.parse(n);if(pe(o)&&Array.isArray(o.content)&&pe(o.structuredContent)&&pe(o._meta)){let r=o._meta["studio/view"];if(pe(r)&&pe(r.ui)){let i={content:o.content,structuredContent:o.structuredContent,_meta:{"studio/view":{...r,ui:{format:r.ui.format,sha256:r.ui.sha256}}}};if(n_(i))return i}}}catch{}return{isError:!0,content:[{type:"text",text:"The saved Studio card could not be read."}]}}function Tz(e){let t=e.structuredContent,n=t&&{...t,bindings:t.bindings??$t(e).bindings};if(!(!n||n.protocolVersion!==1||!pe(n.bindings)||Object.entries(n.bindings).some(([o,r])=>!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o)||typeof r!="string"||!r)||typeof n.component!="string"||!/^[a-zA-Z0-9._/-]+@[1-9]\d*$/.test(n.component)||typeof n.projectId!="string"||!n.projectId||n.scope!==void 0&&(!pe(n.scope)||!["user","project"].includes(String(n.scope.kind))||n.scope.id!==n.projectId||n.scope.kind==="user"&&n.scope.id!=="user")||!pe(n.target)||typeof n.target.instanceId!="string"||!n.target.instanceId||typeof n.target.operationId!="string"||!n.target.operationId))return{component:n.component,bindings:n.bindings,projectId:n.projectId,...n.scope!==void 0&&{scope:n.scope},target:{instanceId:n.target.instanceId,operationId:n.target.operationId}}}function t_(e,t){return pe(e)&&Object.keys(e).length===Object.keys(t).length&&Object.entries(t).every(([n,o])=>e[n]===o)}function $t(e){let t=e._meta?.["studio/view"];return pe(t)?t:{}}function Ez(e,t,n){let o=$t(e),r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||!Array.isArray(o.mediaOrigins)||!o.mediaOrigins.includes(r.origin))throw Error("This media source is not available for download.");let i=a=>Array.isArray(a)?a.some(i):pe(a)?Object.entries(a).some(([s,c])=>(s==="src"||s==="downloadUrl")&&c===t||i(c)):!1;if(!i(o.props))throw Error("This media is not part of the current card.");return{type:"resource_link",uri:t,name:n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_").slice(0,200)||"Media"}}function n_(e){let t=$t(e),n=Tz(e),o=t.ui;if(!(!n||t.protocolVersion!==1||t.component!==n.component||!t_(t.bindings,n.bindings)||t.projectId!==n.projectId||n.scope!==void 0&&(!pe(t.scope)||t.scope.kind!==n.scope.kind||t.scope.id!==n.scope.id)||!pe(t.target)||t.target.instanceId!==n.target.instanceId||t.target.operationId!==n.target.operationId||!pe(t.props)||!pe(o)||o.format!=="iife"||o.javascript!==void 0&&(typeof o.javascript!="string"||!o.javascript.trim())||typeof o.sha256!="string"||!/^[a-f0-9]{64}$/.test(o.sha256)))return{id:n.component,...typeof o.javascript=="string"&&{javascript:o.javascript},sha256:o.sha256}}async function i_(e){if(!e.javascript)return!1;let t=new TextEncoder().encode(e.javascript),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")===e.sha256}function Cz(e,t){let n=e.scope??{kind:"project",id:e.projectId};return"studio://chat-bundles/"+[n.kind,n.id,e.target.instanceId,e.target.operationId,t].map(encodeURIComponent).join("/")}function Un(e){return(e.content??[]).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
154
- `)}function tm(e){let{ui:t,...n}=$t(e);return{text:Un(e),structuredContent:e.structuredContent,view:n,isError:e.isError===!0}}function fo(e,t){return!e||typeof e!="object"?!1:pe(e)&&["image","audio","video"].includes(String(e.kind))&&e.path===t?!0:Object.values(e).some(n=>fo(n,t))}var em=class{constructor(t,n){this.callTool=t;this.sendMessage=n}callTool;sendMessage;result={};identity;pending=!1;lastRequest;receive(t){let n=Tz(t);if(this.identity){let o=t.structuredContent??{};if(o.scope!==void 0){let s=this.identity.scope??{kind:"project",id:this.identity.projectId};if(!pe(o.scope)||o.scope.kind!==s.kind||o.scope.id!==s.id)throw new Error("The reply changed the card scope. Reopen the original card.")}for(let s of["projectId","component"])if(o[s]!==void 0&&o[s]!==this.identity[s])throw new Error("The reply belongs to another card. Reopen the original card.");if(o.target!==void 0&&(!pe(o.target)||o.target.instanceId!==this.identity.target.instanceId||o.target.operationId!==this.identity.target.operationId))throw new Error("The reply changed the source operation. Reopen the original card.");if(o.bindings!==void 0&&!t_(o.bindings,this.identity.bindings)||n!==void 0&&!t_(n.bindings,this.identity.bindings))throw new Error("The reply changed the action bindings. Reopen the original card.");let r=this.result,{error:i,...a}=r.structuredContent??{};this.result={...r,...t,isError:t.isError===!0,structuredContent:{...a,...o},_meta:{...r._meta,...t._meta,"studio/view":{...$t(r),...$t(t)}}}}else this.result=t,this.identity=n}async action(t,n={},o={}){if(!this.identity)throw new Error("Reopen the operation before using this card.");if(this.pending)throw new Error("Wait for the current card action to finish.");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error("Invalid card action.");if(!Object.hasOwn(this.identity.bindings,t))throw new Error("This card does not declare that action.");if(Object.keys(o).some(i=>!["requestKey","approval"].includes(i)))throw new Error("Invalid card invocation options.");let r={...this.identity.scope?.kind==="user"?{scope:this.identity.scope}:{projectId:this.identity.projectId},target:this.identity.target,binding:this.identity.bindings[t],action:t,input:n,requestKey:o.requestKey??`card:${crypto.randomUUID()}`,...o.approval===void 0?{}:{approval:o.approval}};this.lastRequest=r,this.pending=!0;try{let i=await this.callTool({name:"studio_card_action",arguments:r}),a=i._meta?.["studio/message"],{["studio/message"]:s,...c}=i._meta??{},u={...i,_meta:c};if(this.receive(u),a!==void 0&&!i.isError){if(!pe(a)||typeof a.intent!="string"||!a.intent.trim()||!pe(a.data))throw Error("The adapter returned an invalid prepared message. Your draft is retained.");let d=this.sendMessage?await this.sendMessage(r.requestKey,{intent:a.intent,data:a.data}):{status:"failed",message:"This chat client does not support follow-up messages. Your draft is retained."},m=d.status==="sent",p={...u,content:[{type:"text",text:m?"Sent to this conversation. Business changes are not yet confirmed.":d.message}],isError:!m,structuredContent:{...u.structuredContent,...m?{}:{error:{code:d.status==="unknown"?"PROMPT_MESSAGE_UNKNOWN":"PROMPT_MESSAGE_FAILED"}}}};return this.receive(p),p}return u}finally{this.pending=!1}}};function Oz(e,t){let n=t.mediaOrigins??[];if(!Array.isArray(n)||n.some(i=>{if(typeof i!="string")return!0;try{let a=new URL(i);return a.protocol!=="https:"||a.origin!==i||a.hostname.includes("*")||/["';]/.test(i)}catch{return!0}}))throw new Error("The card declared invalid HTTPS media origins.");let o=["data:","blob:",...[...new Set(n)].sort()].join(" ");return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; font-src data:; img-src ${o}; media-src ${o}; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`}"><meta name="referrer" content="no-referrer"><meta name="color-scheme" content="light dark"><div id="root"></div><script>${e.replace(/<\/script/gi,"<\\/script")}<\/script>`}function Nz(){let e="studio.chat.component.v1",t=new Map,n,o=0,r=!1,i=c=>parent.postMessage({channel:e,...c},"*"),a=(c,u={},d={})=>new Promise((m,p)=>{let h=String(++o);t.set(h,{resolve:m,reject:p}),i({type:"action",id:h,action:c,input:u,options:d})}),s=c=>({data:c.view.props,projectId:c.view.projectId,target:c.view.target,action:a,...r&&{download:u=>new Promise((d,m)=>{let p=String(++o);t.set(p,{resolve:()=>d(),reject:m}),i({type:"download",id:p,uri:u.uri,name:u.name})})},readMedia:u=>new Promise((d,m)=>{let p=String(++o);t.set(p,{resolve:d,reject:m}),i({type:"read-media",id:p,input:u})})});window.addEventListener("message",c=>{if(c.source!==parent||c.data?.channel!==e)return;let u=c.data;try{if(u.type==="initialize"&&!n){r=u.downloadsAvailable===!0;let d=document.createElement("script");d.textContent=u.javascript,document.head.append(d);let m=globalThis,p=m.StudioComponent??m.StudioChatCard;if(typeof p?.mount!="function")throw new Error("The registered card has no mount export.");if(n=p.mount(document.querySelector("#root"),s(u.result)),!n||typeof n.update!="function"||typeof n.dispose!="function")throw new Error("The registered card returned an invalid mount.")}else u.type==="result"&&n?n.update(s(u.result)):u.type==="action-result"||u.type==="download-result"?(t.get(u.id)?.resolve(u.result),t.delete(u.id)):u.type==="media-result"?(t.get(u.id)?.resolve(u.value),t.delete(u.id)):u.type==="media-error"?(t.get(u.id)?.reject(new Error(u.message)),t.delete(u.id)):(u.type==="action-error"||u.type==="download-error")&&(t.get(u.id)?.reject(Object.assign(new Error(u.error.message),u.error)),t.delete(u.id))}catch(d){i({type:"component-error",message:d instanceof Error?d.message:"Card failed."})}}),window.addEventListener("error",()=>i({type:"component-error",message:"The registered card could not render."})),window.addEventListener("unhandledrejection",()=>i({type:"component-error",message:"The registered card could not update."})),document.addEventListener("securitypolicyviolation",c=>{if(!["media-src","img-src"].includes(c.effectiveDirective))return;let u="the media source";try{u=new URL(c.blockedURI).origin}catch{}i({type:"component-error",message:`This chat blocked ${u} (${c.effectiveDirective}). Refreshing the URL alone will not change its resource policy.`})}),new ResizeObserver(()=>{i({type:"resize",height:document.documentElement.scrollHeight})}).observe(document.body),window.addEventListener("pagehide",()=>n?.dispose()),i({type:"ready"})}async function jz(e,t,n,o){if(!fo($t(e).props,t))throw Error("This file is not declared by the original card.");let r=0,i=1,a="",s="",c;for(;r<i;){let m=await o({path:t,offset:r,...c&&{expected:c}});if(!m||!Number.isSafeInteger(m.totalBytes)||m.totalBytes<=0||m.totalBytes>2147483648||!Number.isSafeInteger(m.nextOffset)||m.nextOffset<=r||m.nextOffset>m.totalBytes||!m.snapshot||m.snapshot.sizeBytes!==m.totalBytes||!/^(?:audio\/|video\/|image\/(?:png|jpeg|webp)$)/.test(m.mimeType)||c&&(m.totalBytes!==i||m.mimeType!==a||JSON.stringify(m.snapshot)!==JSON.stringify(c)))throw Error("The media reply is incomplete or the file changed during download.");let p=atob(m.base64);if(p.length!==m.nextOffset-r)throw Error("The media download chunk is incomplete.");s+=p,r=m.nextOffset,i=m.totalBytes,a=m.mimeType,c=m.snapshot}let u=t.match(/\.[a-z0-9]{1,10}$/i)?.[0]??"",d=Array.from(n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_")).slice(0,180).join("").replace(/[\ud800-\udfff]/gu,"\uFFFD")||"Media";return u&&!d.toLowerCase().endsWith(u.toLowerCase())&&(d+=u),{type:"resource",resource:{uri:`file:///${encodeURIComponent(d)}`,mimeType:a,blob:btoa(s)}}}var mt=new Qd({name:"Vivix Studio card",version:"1.0.0"},{},{strict:!0}),rC=new cu(mt),Ke=new em(async e=>Vc(await mt.callServerTool(e)),(e,t)=>rC.send(e,t)),Zc=document.querySelector("#summary"),ho=document.querySelector("#status"),nC=document.querySelector("#card"),$e,Fc,rm,Az,Et=!1,vr,Uz,o_=0;function Hr(e){$e?.contentWindow?.postMessage({channel:r_,...e},"*")}function Hc(e){let t=e instanceof Error?e.message:"Studio could not update this card.",n=Ke.lastRequest?.requestKey??Uz;ho.textContent=`${t}${n?`
154
+ `)}function tm(e){let{ui:t,...n}=$t(e);return{text:Un(e),structuredContent:e.structuredContent,view:n,isError:e.isError===!0}}function fo(e,t){return!e||typeof e!="object"?!1:pe(e)&&["image","audio","video"].includes(String(e.kind))&&e.path===t?!0:Object.values(e).some(n=>fo(n,t))}var em=class{constructor(t,n){this.callTool=t;this.sendMessage=n}callTool;sendMessage;result={};identity;pending=!1;lastRequest;receive(t){let n=Tz(t);if(this.identity){let o=t.structuredContent??{};if(o.scope!==void 0){let s=this.identity.scope??{kind:"project",id:this.identity.projectId};if(!pe(o.scope)||o.scope.kind!==s.kind||o.scope.id!==s.id)throw new Error("The reply changed the card scope. Reopen the original card.")}for(let s of["projectId","component"])if(o[s]!==void 0&&o[s]!==this.identity[s])throw new Error("The reply belongs to another card. Reopen the original card.");if(o.target!==void 0&&(!pe(o.target)||o.target.instanceId!==this.identity.target.instanceId||o.target.operationId!==this.identity.target.operationId))throw new Error("The reply changed the source operation. Reopen the original card.");if(o.bindings!==void 0&&!t_(o.bindings,this.identity.bindings)||n!==void 0&&!t_(n.bindings,this.identity.bindings))throw new Error("The reply changed the action bindings. Reopen the original card.");let r=this.result,{error:i,...a}=r.structuredContent??{};this.result={...r,...t,isError:t.isError===!0,structuredContent:{...a,...o},_meta:{...r._meta,...t._meta,"studio/view":{...$t(r),...$t(t)}}}}else this.result=t,this.identity=n}async action(t,n={},o={}){if(!this.identity)throw new Error("Reopen the operation before using this card.");if(this.pending)throw new Error("Wait for the current card action to finish.");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error("Invalid card action.");if(!Object.hasOwn(this.identity.bindings,t))throw new Error("This card does not declare that action.");if(Object.keys(o).some(i=>!["requestKey","approval"].includes(i)))throw new Error("Invalid card invocation options.");let r={...this.identity.scope?.kind==="user"?{scope:this.identity.scope}:{projectId:this.identity.projectId},target:this.identity.target,binding:this.identity.bindings[t],action:t,input:n,requestKey:o.requestKey??`card:${crypto.randomUUID()}`,...o.approval===void 0?{}:{approval:o.approval}};this.lastRequest=r,this.pending=!0;try{let i=await this.callTool({name:"studio_card_action",arguments:r}),a=i._meta?.["studio/message"],{["studio/message"]:s,...c}=i._meta??{},u={...i,_meta:c};if(this.receive(u),a!==void 0&&!i.isError){if(!pe(a)||typeof a.intent!="string"||!a.intent.trim()||!pe(a.data))throw Error("The adapter returned an invalid prepared message. Your draft is retained.");let d=this.sendMessage?await this.sendMessage(r.requestKey,{intent:a.intent,data:a.data}):{status:"failed",message:"This chat client does not support follow-up messages. Your draft is retained."},m=d.status==="sent",p={...u,content:[{type:"text",text:m?"Sent to this conversation. Business changes are not yet confirmed.":d.message}],isError:!m,structuredContent:{...u.structuredContent,...m?{}:{error:{code:d.status==="unknown"?"PROMPT_MESSAGE_UNKNOWN":"PROMPT_MESSAGE_FAILED"}}}};return this.receive(p),p}return u}finally{this.pending=!1}}};function Oz(e,t){let n=t.mediaOrigins??[];if(!Array.isArray(n)||n.some(i=>{if(typeof i!="string")return!0;try{let a=new URL(i);return a.protocol!=="https:"||a.origin!==i||a.hostname.includes("*")||/["';]/.test(i)}catch{return!0}}))throw new Error("The card declared invalid HTTPS media origins.");let o=["data:","blob:",...[...new Set(n)].sort()].join(" ");return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; font-src data:; img-src ${o}; media-src ${o}; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`}"><meta name="referrer" content="no-referrer"><meta name="color-scheme" content="light dark"><div id="root"></div><script>${e.replace(/<\/script/gi,"<\\/script")}<\/script>`}function Nz(){let e="studio.chat.component.v1",t=new Map,n,o=0,r=!1,i=c=>parent.postMessage({channel:e,...c},"*"),a=(c,u={},d={})=>new Promise((m,p)=>{let h=String(++o);t.set(h,{resolve:m,reject:p}),i({type:"action",id:h,action:c,input:u,options:d})}),s=c=>({data:c.view.props,projectId:c.view.projectId,target:c.view.target,action:a,...r&&{download:u=>new Promise((d,m)=>{let p=String(++o);t.set(p,{resolve:()=>d(),reject:m}),i({type:"download",id:p,uri:u.uri,name:u.name})})},readMedia:u=>new Promise((d,m)=>{let p=String(++o);t.set(p,{resolve:d,reject:m}),i({type:"read-media",id:p,input:u})})});window.addEventListener("message",c=>{if(c.source!==parent||c.data?.channel!==e)return;let u=c.data;try{if(u.type==="initialize"&&!n){r=u.downloadsAvailable===!0;let d=document.createElement("script");d.textContent=u.javascript,document.head.append(d);let m=globalThis,p=m.StudioComponent??m.StudioChatCard;if(typeof p?.mount!="function")throw new Error("The registered card has no mount export.");if(n=p.mount(document.querySelector("#root"),s(u.result)),!n||typeof n.update!="function"||typeof n.dispose!="function")throw new Error("The registered card returned an invalid mount.")}else u.type==="result"&&n?n.update(s(u.result)):u.type==="action-result"||u.type==="download-result"?(t.get(u.id)?.resolve(u.result),t.delete(u.id)):u.type==="media-result"?(t.get(u.id)?.resolve(u.value),t.delete(u.id)):u.type==="media-error"?(t.get(u.id)?.reject(new Error(u.message)),t.delete(u.id)):(u.type==="action-error"||u.type==="download-error")&&(t.get(u.id)?.reject(Object.assign(new Error(u.error.message),u.error)),t.delete(u.id))}catch(d){i({type:"component-error",message:d instanceof Error?d.message:"Card failed."})}}),window.addEventListener("error",()=>i({type:"component-error",message:"The registered card could not render."})),window.addEventListener("unhandledrejection",()=>i({type:"component-error",message:"The registered card could not update."})),document.addEventListener("securitypolicyviolation",c=>{if(!["media-src","img-src"].includes(c.effectiveDirective))return;let u="the media source";try{u=new URL(c.blockedURI).origin}catch{}i({type:"component-error",message:`This chat blocked ${u} (${c.effectiveDirective}). Refreshing the URL alone will not change its resource policy.`})}),new ResizeObserver(()=>{i({type:"resize",height:document.documentElement.scrollHeight})}).observe(document.body),window.addEventListener("pagehide",()=>n?.dispose()),i({type:"ready"})}async function jz(e,t,n,o){if(!fo($t(e).props,t))throw Error("This file is not declared by the original card.");let r=0,i=1,a="",s="",c;for(;r<i;){let m=await o({path:t,offset:r,...c&&{expected:c}});if(!m||!Number.isSafeInteger(m.totalBytes)||m.totalBytes<=0||m.totalBytes>2147483648||!Number.isSafeInteger(m.nextOffset)||m.nextOffset<=r||m.nextOffset>m.totalBytes||!m.snapshot||m.snapshot.sizeBytes!==m.totalBytes||!/^(?:audio\/|video\/|image\/(?:png|jpeg|webp)$)/.test(m.mimeType)||c&&(m.totalBytes!==i||m.mimeType!==a||JSON.stringify(m.snapshot)!==JSON.stringify(c)))throw Error("The media reply is incomplete or the file changed during download.");let p=atob(m.base64);if(p.length!==m.nextOffset-r)throw Error("The media download chunk is incomplete.");s+=p,r=m.nextOffset,i=m.totalBytes,a=m.mimeType,c=m.snapshot}let u=t.match(/\.[a-z0-9]{1,10}$/i)?.[0]??"",d=Array.from(n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_")).slice(0,180).join("").replace(/[\ud800-\udfff]/gu,"\uFFFD")||"Media";return u&&!d.toLowerCase().endsWith(u.toLowerCase())&&(d+=u),{type:"resource",resource:{uri:`file:///${encodeURIComponent(d)}`,mimeType:a,blob:btoa(s)}}}var mt=new Qd({name:"Vivix Studio card",version:"1.0.0"},{},{strict:!0,autoResize:!0}),rC=new cu(mt),Ke=new em(async e=>Vc(await mt.callServerTool(e)),(e,t)=>rC.send(e,t)),Zc=document.querySelector("#summary"),ho=document.querySelector("#status"),nC=document.querySelector("#card"),$e,Fc,rm,Az,Et=!1,vr,Uz,o_=0;function Hr(e){$e?.contentWindow?.postMessage({channel:r_,...e},"*")}function Hc(e){let t=e instanceof Error?e.message:"Studio could not update this card.",n=Ke.lastRequest?.requestKey??Uz;ho.textContent=`${t}${n?`
155
155
  Request key: ${String(n)}`:""}`}async function Dz(){let e=++o_,t=Ke.result;Zc.textContent=Un(t)||"Studio card",Zc.hidden=!1,ho.textContent=t.isError?Un(t)||"Studio rejected the card action.":"";let n=n_(t);if(!Ke.identity||!n){vr&&clearTimeout(vr),$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,Et=!1,t.isError||(ho.textContent="The registered card could not load. Reopen the original operation.");return}let o=Oz(`(${Nz.toString()})();`,$t(t));if($e&&rm===n.sha256&&Az===o){Zc.hidden=Et&&!t.isError,Et&&Hr({type:"result",result:tm(t)});return}let r=n.javascript;try{if(!r||!await i_(n)){let i=Cz(Ke.identity,n.sha256),s=(await mt.readServerResource({uri:i})).contents.find(c=>c.uri===i&&c.mimeType==="text/javascript");if(!s||!("text"in s)||!await i_({...n,javascript:s.text}))throw new Error("Card script does not match its saved digest.");r=s.text}}catch{if(e!==o_)return;ho.textContent="The original Studio card script could not be loaded or verified. Reopen the card.",$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,Et=!1;return}e===o_&&(vr&&clearTimeout(vr),$e?.remove(),Et=!1,Fc=r,rm=n.sha256,Az=o,$e=document.createElement("iframe"),$e.id="component",$e.title="Studio card",$e.setAttribute("sandbox","allow-scripts"),$e.setAttribute("referrerpolicy","no-referrer"),$e.srcdoc=o,nC.replaceChildren($e),vr=setTimeout(()=>{Et||(ho.textContent="The card did not initialize. Reopen the original operation.")},1e4))}async function iC(e,t,n,o){try{let i=await Ke.action(e,t,n);await Dz(),o&&Hr({type:"action-result",id:o,result:tm(i)})}catch(r){Hc(r),o&&Hr({type:"action-error",id:o,error:{code:"CARD_ACTION_FAILED",message:r instanceof Error?r.message:"Card action failed.",requestKey:Ke.lastRequest?.requestKey}})}}async function oC(e,t,n){try{if(!mt.getHostCapabilities()?.downloadFile)throw Error("Downloads are unavailable in this chat.");let o=fo($t(Ke.result).props,e)?await jz(Ke.result,e,t,async i=>{let a=await mt.callServerTool({name:"read_local_media",arguments:{...i}});if(a.isError)throw Error(Un(Vc(a))||"Local media could not be read.");return a._meta?.["studio/media"]}):Ez(Ke.result,e,t);if((await mt.downloadFile({contents:[o]})).isError)throw Error("The download was declined by this chat.");Hr({type:"download-result",id:n})}catch(o){Hr({type:"download-error",id:n,error:{message:o instanceof Error?o.message:"Download failed."}})}}window.addEventListener("message",e=>{if(!$e||e.source!==$e.contentWindow||!pe(e.data))return;let t=e.data;if(t.channel===r_)if(t.type==="ready")Et=!0,vr&&clearTimeout(vr),Zc.hidden=!Ke.result.isError,ho.textContent=Ke.result.isError?Un(Ke.result):"",Fc&&Hr({type:"initialize",javascript:Fc,result:tm(Ke.result),downloadsAvailable:!!mt.getHostCapabilities()?.downloadFile});else if(t.type==="component-error"&&typeof t.message=="string")Hc(new Error(t.message));else if(Et&&t.type==="resize"&&typeof t.height=="number"&&Number.isFinite(t.height))$e.style.height=`${Math.max(120,Math.min(2e3,t.height))}px`;else if(Et&&t.type==="download"&&typeof t.id=="string"&&t.id.length>0&&typeof t.uri=="string"&&typeof t.name=="string")oC(t.uri,t.name,t.id);else if(Et&&t.type==="read-media"&&typeof t.id=="string"&&pe(t.input)){let n=$e,o=t.input;(async()=>{try{if(typeof o.path!="string"||!fo($t(Ke.result).props,o.path))throw Error("This media path does not belong to the original card.");let r=await mt.callServerTool({name:"read_local_media",arguments:o});if(r.isError)throw Error(Un(Vc(r))||"Local media could not be read.");let i=r._meta?.["studio/media"];if(!pe(i))throw Error("The local media reply is incomplete.");$e===n&&Hr({type:"media-result",id:t.id,value:i})}catch(r){$e===n&&Hr({type:"media-error",id:t.id,message:r instanceof Error?r.message:"Local media could not be read."})}})()}else Et&&t.type==="action"&&typeof t.id=="string"&&t.id.length>0&&typeof t.action=="string"&&(t.input===void 0||pe(t.input))&&(t.options===void 0||pe(t.options))&&iC(t.action,t.input??{},t.options??{},t.id)});mt.ontoolinput=({arguments:e})=>{Uz=typeof e?.requestKey=="string"?e.requestKey:void 0};mt.ontoolresult=async e=>{try{Ke.receive(Pz(Vc(e))),await Dz()}catch(t){Hc(t)}};mt.ontoolcancelled=()=>{Hc(new Error("The tool was cancelled. Recover with the original request to check whether it was accepted."))};mt.onteardown=async()=>(vr&&clearTimeout(vr),$e?.remove(),{});mt.connect().catch(e=>{Zc.textContent="Studio could not connect to this chat.",Hc(e)});})();
156
156
  /*! Bundled license information:
157
157
 
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.6",
29432
+ version: "0.1.8",
29433
29433
  type: "module",
29434
29434
  engines: {
29435
29435
  node: ">=22.12.0"
package/package.json CHANGED
@@ -1,16 +1,10 @@
1
1
  {
2
2
  "name": "@vivix-labs/studio-chat-mcp",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.12.0"
7
7
  },
8
- "scripts": {
9
- "build": "tsx scripts/build-chat-mcp.ts build",
10
- "package": "tsx scripts/build-chat-mcp.ts package",
11
- "check": "tsc --noEmit",
12
- "test": "tsx --test tests/*.test.ts chat-ui/*.test.ts"
13
- },
14
8
  "devDependencies": {
15
9
  "@modelcontextprotocol/client": "2.4.0",
16
10
  "@modelcontextprotocol/core": "2.4.0",
@@ -46,5 +40,11 @@
46
40
  "access": "public",
47
41
  "registry": "https://registry.npmjs.org/",
48
42
  "tag": "beta"
43
+ },
44
+ "scripts": {
45
+ "build": "tsx scripts/build-chat-mcp.ts build",
46
+ "package": "tsx scripts/build-chat-mcp.ts package",
47
+ "check": "tsc --noEmit",
48
+ "test": "tsx --test tests/*.test.ts chat-ui/*.test.ts"
49
49
  }
50
- }
50
+ }