@womp/mcp-ui 0.2.1 → 0.2.2

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.
@@ -280,7 +280,7 @@ Boolean requesting whether a visible border and background is provided by the ho
280
280
  - omitted: host decides border`)}),F({method:B(`ui/request-display-mode`),params:F({mode:Uh.describe(`The display mode being requested.`)})}),og=F({mode:Uh.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),sg=L([B(`model`),B(`app`)]).describe(`Tool visibility scope - who can access the tool.`),F({resourceUri:A().optional(),visibility:P(sg).optional().describe(`Who can access this tool. Default: ["model", "app"]
281
281
  - "model": Tool visible to and callable by the agent
282
282
  - "app": Tool callable by the app from this server only`),csp:Hl().optional(),permissions:Hl().optional()}),F({mimeTypes:P(A()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),F({method:B(`ui/download-file`),params:F({contents:P(L([kp,Ap])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),F({method:B(`ui/message`),params:F({role:B(`user`).describe(`Message role, currently only "user" is supported.`),content:P(jp).describe(`Message content blocks (text, image, etc.).`)})}),F({method:B(`ui/notifications/sandbox-resource-ready`),params:F({html:A().describe(`HTML content to load into the inner iframe.`),sandbox:A().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Yh.optional().describe(`CSP configuration from resource metadata.`),permissions:Xh.optional().describe(`Sandbox permissions from resource metadata.`)})}),cg=F({method:B(`ui/notifications/tool-result`),params:Bp.describe(`Standard MCP tool execution result.`)}),lg=F({toolInfo:F({id:rf.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Lp.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Hh.optional().describe(`Current color theme preference.`),styles:tg.optional().describe(`Style configuration for theming the app.`),displayMode:Uh.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:P(Uh).optional().describe(`Display modes the host supports.`),containerDimensions:L([F({height:j().describe(`Fixed container height in pixels.`)}),F({maxHeight:L([j(),zl()]).optional().describe(`Maximum container height in pixels.`)})]).and(L([F({width:j().describe(`Fixed container width in pixels.`)}),F({maxWidth:L([j(),zl()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
283
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() 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(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};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(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>yg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,vg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,_g)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>l(e?.structuredContent),o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),t.onTeardown?.(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}async function gg(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,_g,vg,yg,bg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),_g=2e3,vg=1e4,yg=36e4}));n((()=>{bg();var e=1048576,t=5e3,n=15e3,r={phase:`connecting`},i,a=(e,t=!1)=>{let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)},o=t=>{if(t<e)return`${Math.max(1,Math.round(t/1024))} KB`;let n=t/e;return`${n>=10?n.toFixed(0):n.toFixed(1)} MB`},s=e=>{let t=e.lastIndexOf(`.`);return t<0||t>=e.length-1?``:e.slice(t+1).toLowerCase()},c=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:`until ${t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`};function l(e){for(let t of[`drop`,`progress`,`done`,`expired`])$(t).hidden=t!==e}function u(e){$(`error-text`).textContent=e,$(`error`).hidden=!1}function d(){$(`error`).hidden=!0}function f(){let e=r.summary;if(!e){$(`title`).textContent=r.fileName?`Send ${r.fileName} to Womp`:`Send your 3D model to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,l(null);return}switch($(`title`).textContent=`Send ${e.fileName} to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,r.phase){case`pending`:{$(`drop-text`).textContent=`Drop ${e.fileName} here`;let t=c(e.expiresAt);$(`drop-hint`).textContent=`Only .${e.format} · up to ${e.maxMb} MB${t?` · link valid ${t}`:``}`,$(`file`).accept=`.${e.format}`,l(`drop`);break}case`uploading`:$(`progress-name`).textContent=`Uploading ${r.fileName||e.fileName}…`,l(`progress`);break;case`done`:{$(`done-name`).textContent=r.fileName||e.fileName;let t=r.fileSize??e.fileSize;$(`done-size`).textContent=t?` (${o(t)})`:``,$(`sub`).textContent=`ready to quote`,l(`done`);break}case`expired`:$(`expired-name`).textContent=e.fileName,$(`sub`).textContent=`upload link expired`,l(`expired`);break;default:l(null)}}function ee(e){let t=Math.min(99,Math.round(e*100));$(`fill`).style.width=`${t}%`,$(`progress-pct`).textContent=`${t}%`}function p(e){r.summary=e,e.status===`ready`?(r.phase=`done`,te()):e.status===`expired`?(r.phase=`expired`,te()):r.phase!==`uploading`&&(r.phase=`pending`),d(),e.status===`pending`&&e.lastError&&r.phase===`pending`&&u(`A previous attempt was refused: ${e.lastError}`),f(),a(``),r.phase===`pending`&&ne(t)}function te(){i!==void 0&&(clearTimeout(i),i=void 0)}function ne(e){te();let t=r.summary;if(!t||r.phase!==`pending`)return;let a=new Date(t.expiresAt).getTime();Number.isFinite(a)&&Date.now()>a+6e4||(i=window.setTimeout(async()=>{if(r.phase===`pending`){try{let e=await gg(ae.app,`get_upload`,{uploadId:t.uploadId});if(!e.isError&&e.structuredContent){let n=e.structuredContent;if(n.status!==`pending`||n.lastError!==t.lastError){p(n);return}}}catch{}ne(Math.min(e*1.5,n))}},e))}function re(e,t){let n=s(e.name);return n===t.format?e.size>t.maxBytes?`"${e.name}" is ${o(e.size)}; this account's limit is ${t.maxMb} MB per file.`:null:`This upload expects a .${t.format} file (${t.fileName}); "${e.name}" is a .${n||`?`}. Ask your assistant for a new upload if the format changed.`}function ie(e,t){try{let t=JSON.parse(e);if(t?.error?.message)return t.error.message}catch{}return t?`Upload failed (${t}). Try again.`:``}function m(e){let n=r.summary;if(!n||r.phase!==`pending`)return;d();let i=re(e,n);if(i){u(i);return}te(),r.phase=`uploading`,r.fileName=e.name,r.fileSize=e.size,ee(0),f(),a(``);let o=new XMLHttpRequest;o.open(`PUT`,n.uploadUrl),o.setRequestHeader(`Content-Type`,`application/octet-stream`),o.upload.onprogress=e=>{e.lengthComputable&&ee(e.loaded/e.total)},o.onload=()=>{if(o.status>=200&&o.status<300){let t;try{t=JSON.parse(o.responseText)}catch{}p(t??{...n,status:`ready`,fileSize:e.size});return}if(o.status===409){p({...n,status:`ready`});return}if(o.status===410){p({...n,status:`expired`});return}r.phase=`pending`,f(),u(ie(o.responseText,o.status)||`Upload failed (${o.status}). Try again.`),ne(t)};let s=()=>{r.phase=`pending`,f(),u(`Could not send the file from here. Try again — or ask your assistant to upload it for you.`),a(`PUT to the upload URL got no response — check connectDomains / CORS if this repeats.`,!0),ne(t)};o.onerror=s,o.onabort=s,o.send(e)}var ae=hg(`Womp upload`,{onInput:e=>{typeof e.fileName==`string`&&(r.fileName=e.fileName),f(),a(`Preparing upload…`)},onResult:e=>{let t=e;if(t.status===`running`){f(),a(`Preparing upload…`);return}if(typeof t.uploadId!=`number`||!t.uploadUrl){a(`The upload result is missing its URL — is swan-backend on a build with create_upload?`,!0);return}p(t)}}),oe=$(`drop`),h=$(`file`);$(`choose`).addEventListener(`click`,()=>h.click()),h.addEventListener(`change`,()=>{let e=h.files?.[0];h.value=``,e&&m(e)});for(let e of[`dragenter`,`dragover`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.add(`active`)});for(let e of[`dragleave`,`drop`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.remove(`active`)});oe.addEventListener(`drop`,e=>{let t=e.dataTransfer?.files?.[0];t&&m(t)})}))();</script>
283
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() 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(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};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(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>xg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,bg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,yg)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>{let t=wg(e?._meta)??_g();l(t??e?.structuredContent),t||vg(e=>l(e))},o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),t.onTeardown?.(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}async function gg(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}function _g(){let e=Sg()?.toolResponseMetadata;if(!(!e||typeof e!=`object`))return wg(e)??wg(e.mcp_tool_result?._meta)??wg(e.call_tool_result?._meta)}function vg(e){if(!Sg())return;let t=()=>window.removeEventListener(`openai:set_globals`,n),n=()=>{let n=_g();n!==void 0&&(t(),e(n))};window.addEventListener(`openai:set_globals`,n),setTimeout(t,Tg)}var $,yg,bg,xg,Sg,Cg,wg,Tg,Eg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),yg=2e3,bg=1e4,xg=36e4,Sg=()=>window.openai,Cg=`openai-mcp/card`,wg=e=>e&&typeof e==`object`?e[Cg]:void 0,Tg=1e4}));n((()=>{Eg();var e=1048576,t=5e3,n=15e3,r={phase:`connecting`},i,a=(e,t=!1)=>{let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)},o=t=>{if(t<e)return`${Math.max(1,Math.round(t/1024))} KB`;let n=t/e;return`${n>=10?n.toFixed(0):n.toFixed(1)} MB`},s=e=>{let t=e.lastIndexOf(`.`);return t<0||t>=e.length-1?``:e.slice(t+1).toLowerCase()},c=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:`until ${t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`};function l(e){for(let t of[`drop`,`progress`,`done`,`expired`])$(t).hidden=t!==e}function u(e){$(`error-text`).textContent=e,$(`error`).hidden=!1}function d(){$(`error`).hidden=!0}function f(){let e=r.summary;if(!e){$(`title`).textContent=r.fileName?`Send ${r.fileName} to Womp`:`Send your 3D model to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,l(null);return}switch($(`title`).textContent=`Send ${e.fileName} to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,r.phase){case`pending`:{$(`drop-text`).textContent=`Drop ${e.fileName} here`;let t=c(e.expiresAt);$(`drop-hint`).textContent=`Only .${e.format} · up to ${e.maxMb} MB${t?` · link valid ${t}`:``}`,$(`file`).accept=`.${e.format}`,l(`drop`);break}case`uploading`:$(`progress-name`).textContent=`Uploading ${r.fileName||e.fileName}…`,l(`progress`);break;case`done`:{$(`done-name`).textContent=r.fileName||e.fileName;let t=r.fileSize??e.fileSize;$(`done-size`).textContent=t?` (${o(t)})`:``,$(`sub`).textContent=`ready to quote`,l(`done`);break}case`expired`:$(`expired-name`).textContent=e.fileName,$(`sub`).textContent=`upload link expired`,l(`expired`);break;default:l(null)}}function ee(e){let t=Math.min(99,Math.round(e*100));$(`fill`).style.width=`${t}%`,$(`progress-pct`).textContent=`${t}%`}function p(e){r.summary=e,e.status===`ready`?(r.phase=`done`,te()):e.status===`expired`?(r.phase=`expired`,te()):r.phase!==`uploading`&&(r.phase=`pending`),d(),e.status===`pending`&&e.lastError&&r.phase===`pending`&&u(`A previous attempt was refused: ${e.lastError}`),f(),a(``),r.phase===`pending`&&ne(t)}function te(){i!==void 0&&(clearTimeout(i),i=void 0)}function ne(e){te();let t=r.summary;if(!t||r.phase!==`pending`)return;let a=new Date(t.expiresAt).getTime();Number.isFinite(a)&&Date.now()>a+6e4||(i=window.setTimeout(async()=>{if(r.phase===`pending`){try{let e=await gg(ae.app,`get_upload`,{uploadId:t.uploadId});if(!e.isError&&e.structuredContent){let n=e.structuredContent;if(n.status!==`pending`||n.lastError!==t.lastError){p(n);return}}}catch{}ne(Math.min(e*1.5,n))}},e))}function re(e,t){let n=s(e.name);return n===t.format?e.size>t.maxBytes?`"${e.name}" is ${o(e.size)}; this account's limit is ${t.maxMb} MB per file.`:null:`This upload expects a .${t.format} file (${t.fileName}); "${e.name}" is a .${n||`?`}. Ask your assistant for a new upload if the format changed.`}function ie(e,t){try{let t=JSON.parse(e);if(t?.error?.message)return t.error.message}catch{}return t?`Upload failed (${t}). Try again.`:``}function m(e){let n=r.summary;if(!n||r.phase!==`pending`)return;d();let i=re(e,n);if(i){u(i);return}te(),r.phase=`uploading`,r.fileName=e.name,r.fileSize=e.size,ee(0),f(),a(``);let o=new XMLHttpRequest;o.open(`PUT`,n.uploadUrl),o.setRequestHeader(`Content-Type`,`application/octet-stream`),o.upload.onprogress=e=>{e.lengthComputable&&ee(e.loaded/e.total)},o.onload=()=>{if(o.status>=200&&o.status<300){let t;try{t=JSON.parse(o.responseText)}catch{}p(t??{...n,status:`ready`,fileSize:e.size});return}if(o.status===409){p({...n,status:`ready`});return}if(o.status===410){p({...n,status:`expired`});return}r.phase=`pending`,f(),u(ie(o.responseText,o.status)||`Upload failed (${o.status}). Try again.`),ne(t)};let s=()=>{r.phase=`pending`,f(),u(`Could not send the file from here. Try again — or ask your assistant to upload it for you.`),a(`PUT to the upload URL got no response — check connectDomains / CORS if this repeats.`,!0),ne(t)};o.onerror=s,o.onabort=s,o.send(e)}var ae=hg(`Womp upload`,{onInput:e=>{typeof e.fileName==`string`&&(r.fileName=e.fileName),f(),a(`Preparing upload…`)},onResult:e=>{let t=e;if(t.status===`running`){f(),a(`Preparing upload…`);return}if(typeof t.uploadId!=`number`||!t.uploadUrl){a(`The upload result is missing its URL — is swan-backend on a build with create_upload?`,!0);return}p(t)}}),oe=$(`drop`),h=$(`file`);$(`choose`).addEventListener(`click`,()=>h.click()),h.addEventListener(`change`,()=>{let e=h.files?.[0];h.value=``,e&&m(e)});for(let e of[`dragenter`,`dragover`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.add(`active`)});for(let e of[`dragleave`,`drop`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.remove(`active`)});oe.addEventListener(`drop`,e=>{let t=e.dataTransfer?.files?.[0];t&&m(t)})}))();</script>
284
284
  </head>
285
285
  <body>
286
286
  <div class="card" id="card">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@womp/mcp-ui",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "MCP Apps widgets for Womp's MCP server — interactive cards rendered inline in Claude and other MCP hosts.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
@@ -1,5 +1,14 @@
1
1
  import { createViewer, type Script, type Viewer, type ViewerError } from "@womp/kakapo-web";
2
- import { $, callTool, createCard, openExternal, pushModelContext, toggleFullscreen } from "../shared/bridge";
2
+ import {
3
+ $,
4
+ callTool,
5
+ createCard,
6
+ openExternal,
7
+ pushModelContext,
8
+ resultData,
9
+ sendChatMessage,
10
+ toggleFullscreen,
11
+ } from "../shared/bridge";
3
12
 
4
13
  /**
5
14
  * The camera card — the OpenAI MCP's first project (swan-backend
@@ -757,8 +766,17 @@ async function order() {
757
766
  try {
758
767
  await syncing;
759
768
  const res = await callTool(app, "checkout_camera", { designId: design.designId });
760
- const quote = res.structuredContent as Quote | undefined;
769
+ // The quote is the card's data, in the result's widget-only `_meta` (the
770
+ // model reads only which design was quoted).
771
+ const quote = resultData<Quote>(res);
761
772
  if (res.isError || typeof quote?.checkoutUrl !== "string") {
773
+ // A host that keeps `_meta` from a card's own calls leaves no link here.
774
+ // Ask in the chat instead: the model's checkout_camera brings the quote
775
+ // card, which gets its data.
776
+ if (!res.isError && (await sendChatMessage(app, "Order it"))) {
777
+ setStatus("Getting your quote in the chat…", 6_000);
778
+ return;
779
+ }
762
780
  setStatus("Couldn't open checkout. Ask in the chat to order it.");
763
781
  return;
764
782
  }
@@ -6,6 +6,10 @@ import { $, createCard, openExternal, type GenerationResult } from "../shared/br
6
6
  * step on a Paid → Printing → Shipped → Delivered tracker, when it should
7
7
  * arrive, and a button to its status page on the web.
8
8
  *
9
+ * What it draws is the result's card data, in its widget-only `_meta`: the
10
+ * model reads only the order's id and status, so it has no summary card of its
11
+ * own to draw.
12
+ *
9
13
  * The server found the order by the ChatGPT user's checkout links, and a link
10
14
  * can be forwarded, so what arrives says nothing that reaches the buyer: no
11
15
  * name, city or money. Track opens the order's status page — the masked view
@@ -121,6 +125,15 @@ const card = createCard("Order", {
121
125
  const data = raw as unknown as Partial<Payload>;
122
126
  // The bridge also calls this with a bare { status: "running" } placeholder.
123
127
  if (!Array.isArray(data.orders)) return;
128
+ if (data.order && !Array.isArray(data.order.items)) {
129
+ // Only the model's part ({ id, statusLabel }): the order itself is the
130
+ // card's data, in the result's `_meta`, which may follow a moment later.
131
+ const waitingFor = data.order.id;
132
+ window.setTimeout(() => {
133
+ if (order?.id !== waitingFor) setStatus("Couldn't show the order here. Ask in the chat where it is again.");
134
+ }, 10_000);
135
+ return;
136
+ }
124
137
  order = data.order;
125
138
  if (order) render(order);
126
139
  else renderEmpty();
@@ -90,7 +90,15 @@ const card = createCard("Quote", {
90
90
  onResult: (raw: GenerationResult) => {
91
91
  const data = raw as unknown as Partial<Quote>;
92
92
  // The bridge also calls this with a bare { status: "running" } placeholder.
93
- if (typeof data.checkoutUrl !== "string" || typeof data.designId !== "string") return;
93
+ if (typeof data.designId !== "string") return;
94
+ if (typeof data.checkoutUrl !== "string") {
95
+ // Only the model's part ({ designId, rev }): the quote itself is the
96
+ // card's data, in the result's `_meta`, which may follow a moment later.
97
+ window.setTimeout(() => {
98
+ if (!quote) setStatus("Couldn't show the quote here. Ask in the chat to order it again.");
99
+ }, 10_000);
100
+ return;
101
+ }
94
102
  quote = data as Quote;
95
103
  render(quote);
96
104
  },
@@ -161,7 +161,13 @@ export function createCard(name: string, hooks: CardHooks): Card {
161
161
  hooks.onInput?.(((params as any)?.arguments as Record<string, unknown>) || {});
162
162
  hooks.onResult({ status: "running" });
163
163
  };
164
- app.ontoolresult = (params) => handle(params?.structuredContent as GenerationResult);
164
+ app.ontoolresult = (params) => {
165
+ const data = cardDataIn(params?._meta) ?? openAiCardData();
166
+ handle((data ?? params?.structuredContent) as GenerationResult);
167
+ // ChatGPT keeps a result's `_meta` out of this notification and sets it on
168
+ // window.openai, possibly a moment later: render again once it lands.
169
+ if (!data) awaitOpenAiCardData((late) => handle(late as GenerationResult));
170
+ };
165
171
  app.onhostcontextchanged = (ctx) => {
166
172
  if (ctx?.theme) applyDocumentTheme(ctx.theme);
167
173
  if (ctx?.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
@@ -240,9 +246,59 @@ export function toggleFullscreen(app: App) {
240
246
  interface OpenAiBridge {
241
247
  openExternal?: (args: { href: string; redirectUrl?: false }) => unknown;
242
248
  sendFollowUpMessage?: (args: { prompt: string }) => unknown;
249
+ /** The rendering result's widget-only data: in ChatGPT, the whole MCP result, `_meta` included. */
250
+ toolResponseMetadata?: unknown;
243
251
  }
244
252
  const openAiBridge = () => (window as Window & { openai?: OpenAiBridge }).openai;
245
253
 
254
+ /**
255
+ * Where a server puts what its card draws: the result's `_meta`, which the host
256
+ * hands to the card and never to the model. The OpenAI MCP does this for the
257
+ * quote and the order (swan-backend docs/OPENAI_MCP.md): GPT-6 drew a summary
258
+ * card of its own from whatever the model read.
259
+ */
260
+ export const CARD_DATA_KEY = "openai-mcp/card";
261
+
262
+ const cardDataIn = (meta: unknown): unknown =>
263
+ meta && typeof meta === "object" ? (meta as Record<string, unknown>)[CARD_DATA_KEY] : undefined;
264
+
265
+ /**
266
+ * The card data ChatGPT keeps on window.openai. Its toolResponseMetadata holds
267
+ * the whole MCP result (`mcp_tool_result`, `call_tool_result`), or, as the Apps
268
+ * SDK first shipped it, the `_meta` alone.
269
+ */
270
+ function openAiCardData(): unknown {
271
+ const meta = openAiBridge()?.toolResponseMetadata as Record<string, { _meta?: unknown } | undefined> | undefined;
272
+ if (!meta || typeof meta !== "object") return undefined;
273
+ return cardDataIn(meta) ?? cardDataIn(meta.mcp_tool_result?._meta) ?? cardDataIn(meta.call_tool_result?._meta);
274
+ }
275
+
276
+ /** How long a result may wait for ChatGPT to set its card data; a result with none never gets any. */
277
+ const CARD_DATA_WAIT_MS = 10_000;
278
+
279
+ /** Hand over the card data once ChatGPT sets it on window.openai (its `openai:set_globals` event). */
280
+ function awaitOpenAiCardData(onData: (data: unknown) => void) {
281
+ if (!openAiBridge()) return;
282
+ const stop = () => window.removeEventListener("openai:set_globals", check);
283
+ const check = () => {
284
+ const data = openAiCardData();
285
+ if (data === undefined) return;
286
+ stop();
287
+ onData(data);
288
+ };
289
+ window.addEventListener("openai:set_globals", check);
290
+ setTimeout(stop, CARD_DATA_WAIT_MS);
291
+ }
292
+
293
+ /**
294
+ * What a result says for its card: its card data when the server put it in
295
+ * `_meta`, else its structuredContent (a server from before the split). For the
296
+ * results of a card's own tool calls, which come straight back to the card.
297
+ */
298
+ export function resultData<T>(result: { structuredContent?: unknown; _meta?: unknown }): T | undefined {
299
+ return (cardDataIn(result._meta) ?? result.structuredContent) as T | undefined;
300
+ }
301
+
246
302
  /**
247
303
  * Open a page outside the chat, such as a checkout. ChatGPT opens a URL on one
248
304
  * of the card's declared redirect domains (`openai/widgetCSP.redirect_domains`)