@mcp-apps-kit/ui
Advanced tools
+1
-1
@@ -1,2 +0,2 @@ | ||
| 'use strict';var extApps=require('@modelcontextprotocol/ext-apps');var L="2025-11-05",D="text/html;profile=mcp-app",F="ui/resourceUri";function x(n){if(typeof document>"u")return;let e=n==="os"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":n;document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e);}function H(){if(typeof document>"u")return "light";let n=document.documentElement.getAttribute("data-theme");return n==="dark"||n==="light"?n:document.documentElement.classList.contains("dark")?"dark":"light"}var w="mcp-apps-host-fonts";function k(n){if(typeof document>"u")return;let e=document.documentElement;for(let[t,o]of Object.entries(n)){let s=t.startsWith("--")?t:`--${t}`;e.style.setProperty(s,o);}}function b(n){if(typeof document>"u")return;let e=document.getElementById(w);e||(e=document.createElement("style"),e.id=w,document.head.appendChild(e)),e.textContent=n;}function A(){if(typeof document>"u")return;let n=document.getElementById(w);n&&n.remove();}function I(n){if(typeof document>"u")return;let e=document.documentElement;for(let t of Object.keys(n)){let o=t.startsWith("--")?t:`--${t}`;e.style.removeProperty(o);}}var u={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",NOT_CONNECTED:"NOT_CONNECTED",PROTOCOL_ERROR:"PROTOCOL_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",TOOL_CALL_FAILED:"TOOL_CALL_FAILED",TOOL_NOT_FOUND:"TOOL_NOT_FOUND",STATE_ERROR:"STATE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},d=class extends Error{constructor(t,o,s,r){super(o);this.code=t;this.details=s;this.cause=r;this.name="UIError";}formatMessage(){let t=`[${this.code}] ${this.message}`;return this.details&&(t+=` ${JSON.stringify(this.details)}`),t}};var O={debug:0,info:1,warn:2,error:3};function S(n,e){return O[n]>=O[e]}function R(){let n=new WeakSet;return (e,t)=>{if(typeof t=="object"&&t!==null){if(n.has(t))return "[Circular]";n.add(t);}return t}}function M(n){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};try{return JSON.stringify(n),n}catch{try{let e=JSON.stringify(n,R());return JSON.parse(e)}catch{return "[Unserializable]"}}}function P(n){if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="string")return n;if(n instanceof Error)return `${n.name}: ${n.message}`;try{return JSON.stringify(n,R())}catch{return "[Unstringifiable]"}}var h=class{constructor(e={}){this.adapter=null;this.buffer=[];this.flushTimer=null;this.isFlushing=false;this.mcpTransportFailed=false;this.config={enabled:e.enabled??false,level:e.level??"info",batchSize:e.batchSize??10,maxBufferSize:e.maxBufferSize??100,flushIntervalMs:e.flushIntervalMs??5e3,source:e.source??"mcp-apps-ui"};}setAdapter(e){this.adapter=e,this.mcpTransportFailed=false;}configure(e){e.enabled!==void 0&&(this.config.enabled=e.enabled),e.level!==void 0&&(this.config.level=e.level),e.batchSize!==void 0&&(this.config.batchSize=e.batchSize),e.maxBufferSize!==void 0&&(this.config.maxBufferSize=e.maxBufferSize),e.flushIntervalMs!==void 0&&(this.config.flushIntervalMs=e.flushIntervalMs,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.scheduleFlush()),e.source!==void 0&&(this.config.source=e.source);}canUseMcpTransport(){return this.config.enabled&&!this.mcpTransportFailed&&this.adapter?.isConnected()===true}createEntry(e,t,o){return {level:e,message:t,data:o!==void 0?M(o):void 0,timestamp:new Date().toISOString(),source:this.config.source}}scheduleFlush(){this.flushTimer||this.buffer.length===0||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}async flush(){if(this.isFlushing||this.buffer.length===0)return;if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.canUseMcpTransport()){for(let t of this.buffer)this.outputToConsole(t);this.buffer=[];return}this.isFlushing=true;let e=[...this.buffer];this.buffer=[];try{this.adapter&&await this.adapter.callTool("log_debug",{entries:e});}catch{this.mcpTransportFailed||(this.mcpTransportFailed=true,console.info("[ClientDebugLogger] MCP log transport unavailable, using console fallback"));for(let t of e)this.outputToConsole(t);}finally{this.isFlushing=false,this.buffer.length>0&&this.scheduleFlush();}}outputToConsole(e){let t=`[${e.timestamp}] [${e.level.toUpperCase()}]`,o=e.data!==void 0?`${e.message} ${P(e.data)}`:e.message,s=`${t} ${o}`;try{switch(e.level){case "debug":console.debug(s);break;case "info":console.info(s);break;case "warn":console.warn(s);break;case "error":console.error(s);break}}catch{}}addToBuffer(e){if(this.buffer.length>=this.config.maxBufferSize){let t=this.buffer.shift();t&&this.outputToConsole(t);}if(this.buffer.push(e),e.level==="error"){this.flush();return}if(this.buffer.length>=this.config.batchSize){this.flush();return}this.scheduleFlush();}log(e,t,o){if(!S(e,this.config.level))return;let s=this.createEntry(e,t,o);if(!this.canUseMcpTransport()){this.outputToConsole(s);return}this.addToBuffer(s);}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}destroy(){if(this.buffer.length>0){for(let e of this.buffer)this.outputToConsole(e);this.buffer=[];}this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.adapter=null;}},v=new h;var c=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.mockHostCapabilities={logging:{},openLinks:{},theming:{themes:["light","dark","os"]},displayModes:{modes:["inline","fullscreen","pip","panel"]},statePersistence:{persistent:true},serverTools:{listChanged:false},serverResources:{listChanged:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false},fileUpload:{},safeAreaInsets:{},views:{}};this.mockHostVersion={name:"MockHost",version:"1.0.0"};this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}async connect(){this.connected=true,console.log("[MockAdapter] Connected");}isConnected(){return this.connected}async callTool(e,t){console.log(`[MockAdapter] callTool("${e}",`,t,")");let o={_mock:true,tool:e,args:t,timestamp:Date.now()};return this.currentToolOutput=o,o}async sendMessage(e){console.log("[MockAdapter] sendMessage:",e);}async openLink(e){console.log(`[MockAdapter] openLink("${e}")`);}async requestDisplayMode(e){return console.log(`[MockAdapter] requestDisplayMode("${e}")`),this.context={...this.context,displayMode:e},this.notifyHostContextChange(),{mode:e}}requestClose(){console.log("[MockAdapter] requestClose()");}getState(){return this.state}setState(e){this.state=e,console.log("[MockAdapter] setState:",e);}async readResource(e){return console.log(`[MockAdapter] readResource("${e}")`),{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MockAdapter]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}emitToolResult(e){this.currentToolOutput=e;for(let t of this.toolResultHandlers)t(e);}emitToolInput(e){this.currentToolInput=e;for(let t of this.toolInputHandlers)t(e);}setHostContext(e){this.context={...this.context,...e},this.notifyHostContextChange();}emitContextChange(e){this.context=e,this.notifyHostContextChange();}setToolInput(e){this.currentToolInput=e;}emitToolCancelled(e){for(let t of this.toolCancelledHandlers)t(e);}emitTeardown(e){for(let t of this.teardownHandlers)t(e);}notifyHostContextChange(){for(let e of this.hostContextHandlers)e(this.context);}getHostCapabilities(){return this.mockHostCapabilities}getHostVersion(){return this.mockHostVersion}async sendLog(e,t){console.log(`[MockAdapter] sendLog(${e}):`,t);}async sendSizeChanged(e){console.log("[MockAdapter] sendSizeChanged:",e);}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e,console.log("[MockAdapter] setCallToolHandler: handler registered");}setListToolsHandler(e){this.listToolsHandler=e,console.log("[MockAdapter] setListToolsHandler: handler registered");}emitToolInputPartial(e){for(let t of this.toolInputPartialHandlers)t(e);}setMockHostCapabilities(e){this.mockHostCapabilities={...this.mockHostCapabilities,...e};}setMockHostVersion(e){this.mockHostVersion=e;}async simulateHostToolCall(e,t){if(!this.callToolHandler)throw new d(u.TOOL_NOT_FOUND,"No call tool handler registered");return this.callToolHandler(e,t)}async simulateHostListTools(){return this.listToolsHandler?this.listToolsHandler():{tools:[]}}};var _={parse:n=>n},g=class{constructor(){this.connected=false;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"desktop"}}async connect(){if(this.connected)return;if(typeof window>"u"){this.connected=true;return}this.app=new extApps.App({name:"@mcp-apps-kit/ui",version:"0.0.0"},{tools:{}}),this.app.onerror=t=>{this.log("error",t);},this.app.onhostcontextchanged=t=>{let o=t.hostContext??t;this.context=this.mapHostContext(o),this.currentToolMeta=this.extractToolMeta(o);for(let s of this.hostContextHandlers)s(this.context);},this.app.ontoolinput=t=>{let o=t.arguments;if(o){this.currentToolInput=o;for(let s of this.toolInputHandlers)s(o);}},this.app.ontoolinputpartial=t=>{let o=t.arguments;if(o)for(let s of this.toolInputPartialHandlers)s(o);},this.app.oncalltool=async t=>{let{name:o,arguments:s}=t;try{if(this.callToolHandler){let r=await this.callToolHandler(o,s??{});return {content:[{type:"text",text:JSON.stringify(r)}]}}return {content:[{type:"text",text:`No handler registered for tool: ${o}`}],isError:!0}}catch(r){return {content:[{type:"text",text:r instanceof Error?r.message:String(r)}],isError:true}}},this.app.onlisttools=async()=>this.listToolsHandler?{tools:(await this.listToolsHandler()).map(o=>o.name)}:{tools:[]},this.app.ontoolresult=t=>{let o=this.extractToolOutput(t);this.currentToolOutput=o;let s=this.getToolNameFromContext(),r=s?{[s]:o}:o;for(let i of this.toolResultHandlers)i(r);},this.app.ontoolcancelled=t=>{let o=t.reason;for(let s of this.toolCancelledHandlers)s(o);},this.app.onteardown=async t=>{let o=t.reason;for(let s of this.teardownHandlers)s(o);return {}},await this.app.connect();let e=this.app.getHostContext();e&&(this.context=this.mapHostContext(e),this.currentToolMeta=this.extractToolMeta(e)),this.connected=true;}isConnected(){return this.connected}mapHostContext(e){let t=e??{},o=this.createDefaultContext(),s=t.theme==="dark"?"dark":t.theme==="light"?"light":o.theme,r=t.displayMode==="fullscreen"||t.displayMode==="pip"||t.displayMode==="inline"?t.displayMode:o.displayMode,i=Array.isArray(t.availableDisplayModes)?t.availableDisplayModes.filter(p=>typeof p=="string"):o.availableDisplayModes,m=(p=>p!==null&&typeof p=="object"&&!Array.isArray(p))(t.viewport)?{...o.viewport,...t.viewport}:o.viewport,l=typeof t.locale=="string"?t.locale:o.locale,C=typeof t.timeZone=="string"?t.timeZone:o.timeZone,E=o.platform;return {...o,theme:s,displayMode:r,availableDisplayModes:i,viewport:m,locale:l,timeZone:C,platform:E,userAgent:typeof t.userAgent=="string"?t.userAgent:o.userAgent,deviceCapabilities:t.deviceCapabilities,safeAreaInsets:t.safeAreaInsets,styles:t.styles,view:typeof t.view=="string"?t.view:o.view}}extractToolMeta(e){if(e===null||typeof e!="object")return;let t=e;if(!(!t.toolInfo||typeof t.toolInfo!="object"))return {toolInfo:t.toolInfo}}getToolNameFromContext(){if(!this.app)return;let e=this.app.getHostContext();return e?e.toolInfo?.tool?.name:void 0}extractToolOutput(e){let t=e.structuredContent,o=e._meta,s=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(o&&typeof o=="object"&&!Array.isArray(o))return {...s,_meta:o};if(Object.keys(s).length===0){let r=e.content;if(Array.isArray(r)&&r.length>0){let i=r[0];if(i?.type==="text"&&typeof i.text=="string")try{let a=JSON.parse(i.text);if(a!==null&&typeof a=="object"&&!Array.isArray(a))return a}catch{}}}return s}async callTool(e,t){if(!this.app)throw new Error("MCP Apps adapter not connected");let o=await this.app.callServerTool({name:e,arguments:t});return this.extractToolOutput(o)}async sendMessage(e){if(!this.app)throw new Error("MCP Apps adapter not connected");if(e.type!=="text")throw new Error(`Unsupported message content type: ${e.type}`);await this.app.sendMessage({role:"user",content:[{type:"text",text:e.text}]});}async openLink(e){if(!this.app)throw new Error("MCP Apps adapter not connected");await this.app.openLink({url:e});}async requestDisplayMode(e){if(!this.app)throw new Error("MCP Apps adapter not connected");return await this.app.requestDisplayMode({mode:e})}requestClose(){}getState(){return null}setState(e){}async readResource(e){if(!this.app)throw new Error("MCP Apps adapter not connected");let o=await this.app.request.bind(this.app)({method:"resources/read",params:{uri:e}},_);return {contents:(Array.isArray(o.contents)?o.contents:[]).map(s=>{let r={uri:s.uri,mimeType:s.mimeType??"application/octet-stream"};if("text"in s&&typeof s.text=="string")return {...r,text:s.text};if("blob"in s&&typeof s.blob=="string"){let i=Uint8Array.from(atob(s.blob),a=>a.charCodeAt(0));return {...r,blob:i}}return r})}}log(e,t){if(this.app){let i={level:["debug","info","notice","warning","error","critical","alert","emergency"].includes(e)?e:"info",data:t,logger:"@mcp-apps-kit/ui"};try{this.app.sendLog(i);return}catch{}}({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MCP Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){if(!this.app)return;let e=this.app.getHostCapabilities();if(!e)return;let t=e,s=this.app.getHostContext()?.availableDisplayModes;return {logging:t.logging,openLinks:t.openLinks,serverResources:t.serverResources,serverTools:t.serverTools,experimental:t.experimental,theming:{themes:["light","dark"]},displayModes:s?{modes:s}:void 0,statePersistence:{persistent:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false}}}getHostVersion(){if(!this.app)return;let e=this.app.getHostVersion();if(e)return {name:e.name,version:e.version}}async sendLog(e,t){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendLog({level:e,data:t,logger:"@mcp-apps-kit/ui"});}async sendSizeChanged(e){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendSizeChanged({width:e.width,height:e.height});}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e;}setListToolsHandler(e){this.listToolsHandler=e;}};var f=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}readContextFromSDK(){let e=this.getOpenAI();if(!e)return;let t=typeof window<"u";if(typeof e.theme=="string"&&(this.context.theme=e.theme),typeof e.displayMode=="string"&&(this.context.displayMode=e.displayMode),typeof e.locale=="string"&&(this.context.locale=e.locale),typeof e.userAgent=="string"&&Object.assign(this.context,{userAgent:e.userAgent}),typeof e.view=="string"&&(this.context.view=e.view),e.safeArea&&typeof e.safeArea=="object"){let o=e.safeArea;this.context.safeAreaInsets={top:typeof o.top=="number"?o.top:0,right:typeof o.right=="number"?o.right:0,bottom:typeof o.bottom=="number"?o.bottom:0,left:typeof o.left=="number"?o.left:0};}typeof e.maxHeight=="number"&&(this.context.viewport={width:t?window.innerWidth:800,height:e.maxHeight}),console.log("[OpenAI Adapter] Read context from SDK:",this.context);}notifyContextChange(){console.log(`[OpenAI Adapter] Notifying ${String(this.hostContextHandlers.size)} context change handlers`);let e={...this.context};for(let t of this.hostContextHandlers)t(e);}getOpenAI(){return typeof window<"u"&&"openai"in window?window.openai:null}getToolNameFromSDK(){let e=this.getOpenAI();if(e){if(e.toolResponseMetadata&&typeof e.toolResponseMetadata=="object"){let t=e.toolResponseMetadata;if(typeof t.toolName=="string")return t.toolName}if(typeof e.toolName=="string")return e.toolName}}async connect(){await this.waitForOpenAI();let e=this.getOpenAI();if(e){console.log("[OpenAI Adapter] Available SDK methods:",Object.keys(e)),this.readContextFromSDK();let t=this.getToolNameFromSDK();if(typeof e.getToolOutput=="function"?(this.currentToolOutput=e.getToolOutput(),console.log("[OpenAI Adapter] Got tool output from SDK")):e.toolOutput?(this.currentToolOutput=e.toolOutput,console.log("[OpenAI Adapter] Got tool output from SDK property")):e.result&&(this.currentToolOutput=e.result,console.log("[OpenAI Adapter] Got result from SDK")),this.currentToolOutput&&Object.keys(this.currentToolOutput).length>0){let o=t?{[t]:this.currentToolOutput}:this.currentToolOutput;for(let s of this.toolResultHandlers)s(o);}typeof e.getToolInput=="function"?this.currentToolInput=e.getToolInput():e.toolInput?this.currentToolInput=e.toolInput:e.input&&(this.currentToolInput=e.input),typeof e.init=="function"&&await e.init();}this.setupGlobalsListener(),this.connected=true;}setupGlobalsListener(){typeof window>"u"||(this.globalsHandler=e=>{let t=e.data;(t==="openai:set_globals"||typeof t=="object"&&t!==null&&"type"in t&&t.type==="openai:set_globals"||typeof t=="object"&&t!==null&&"message"in t&&t.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals event, refreshing context"),setTimeout(()=>{let s=this.context.theme,r=this.context.locale,i=this.context.displayMode;this.readContextFromSDK(),(this.context.theme!==s||this.context.locale!==r||this.context.displayMode!==i)&&(console.log("[OpenAI Adapter] Context changed, notifying handlers"),this.notifyContextChange());},10));},window.addEventListener("message",this.globalsHandler));}async waitForOpenAI(e=5e3){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai already available");return}return console.log("[OpenAI Adapter] Waiting for window.openai..."),new Promise(t=>{let o=Date.now(),s=false,r=()=>{s||(s=true,window.removeEventListener("message",a),t());},i=()=>{if(!s){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai found via polling"),r();return}if(Date.now()-o>e){console.warn("[OpenAI Adapter] window.openai not found after timeout, proceeding anyway"),r();return}setTimeout(i,50);}},a=m=>{let l=m.data;(l==="openai:set_globals"||typeof l=="object"&&l!==null&&"type"in l&&l.type==="openai:set_globals"||typeof l=="object"&&l!==null&&"message"in l&&l.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals message"),setTimeout(()=>{this.getOpenAI()?(console.log("[OpenAI Adapter] window.openai available after set_globals"),r()):console.log("[OpenAI Adapter] window.openai still not available after set_globals, continuing poll");},50));};window.addEventListener("message",a),i();})}isConnected(){return this.connected}async callTool(e,t){let o=this.getOpenAI();if(o&&typeof o.callTool=="function")return o.callTool(e,t);throw new Error("OpenAI SDK not available")}async sendMessage(e){let t=this.getOpenAI();t&&typeof t.sendMessage=="function"&&await t.sendMessage(e);}async openLink(e){let t=this.getOpenAI();t&&typeof t.openLink=="function"?await t.openLink(e):window.open(e,"_blank");}async requestDisplayMode(e){let t=this.getOpenAI();if(t&&typeof t.requestDisplayMode=="function"){let o=await t.requestDisplayMode({mode:e});return this.context={...this.context,displayMode:o.mode},this.notifyContextChange(),o}return this.context={...this.context,displayMode:e},this.notifyContextChange(),{mode:e}}requestClose(){let e=this.getOpenAI();e&&typeof e.close=="function"&&e.close();}getState(){return this.state}setState(e){this.state=e;let t=this.getOpenAI();t&&typeof t.setState=="function"&&t.setState(e);}async uploadFile(e){let t=this.getOpenAI();if(t&&typeof t.uploadFile=="function")return t.uploadFile(e);throw new Error("File upload not supported")}async getFileDownloadUrl(e){let t=this.getOpenAI();if(t&&typeof t.getFileDownloadUrl=="function")return t.getFileDownloadUrl(e);throw new Error("File download not supported")}async readResource(e){let t=this.getOpenAI();return t&&typeof t.readResource=="function"?t.readResource(e):{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[ChatGPT Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),console.log(`[OpenAI Adapter] Host context handler added, total: ${String(this.hostContextHandlers.size)}`),()=>{this.hostContextHandlers.delete(e),console.log(`[OpenAI Adapter] Host context handler removed, total: ${String(this.hostContextHandlers.size)}`);}}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){if(!this.currentToolOutput)return;let e=this.getToolNameFromSDK();return e?{[e]:this.currentToolOutput}:this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){let e=this.getOpenAI(),t=e&&typeof e.uploadFile=="function",o=this.context.safeAreaInsets!==void 0,s=this.context.view!==void 0;return {openLinks:{},logging:{},theming:{themes:["light","dark"]},displayModes:{modes:["inline","fullscreen","pip"]},statePersistence:{persistent:false},fileUpload:t?{}:void 0,safeAreaInsets:o?{}:void 0,views:s?{}:void 0}}getHostVersion(){}async sendLog(e,t){let o={debug:"debug",info:"info",notice:"info",warning:"warning",error:"error",critical:"error",alert:"error",emergency:"error"};this.log(o[e],t);}async sendSizeChanged(e){let t=this.getOpenAI();t&&typeof t.notifyIntrinsicHeight=="function"&&t.notifyIntrinsicHeight(e.height);}onToolInputPartial(e){return this.log("debug","onToolInputPartial is not supported on ChatGPT"),()=>{}}setCallToolHandler(e){this.log("debug","setCallToolHandler is not supported on ChatGPT");}setListToolsHandler(e){this.log("debug","setListToolsHandler is not supported on ChatGPT");}};function U(){let n=window.location.href;if(n.includes("/api/apps/chatgpt/")||n.includes("chatgpt")||n.includes("sandbox-proxy")||n.includes("widget-content"))return true;let e=document.referrer;return !!(e.includes("chatgpt")||e.includes("openai.com"))}function y(){return typeof window>"u"?"mock":"openai"in window||U()?"openai":window.parent!==window?"mcp":"mock"}function T(n){return {async callTool(t,o){return await n.callTool(t,o)},async sendMessage(t){await n.sendMessage(t);},async sendFollowUpMessage(t){await n.sendMessage({type:"text",text:t});},async openLink(t){await n.openLink(t);},async requestDisplayMode(t){return n.requestDisplayMode(t)},requestClose(){n.requestClose();},getState(){return n.getState()},setState(t){n.setState(t);},...n.uploadFile&&{uploadFile:t=>{if(n.uploadFile)return n.uploadFile(t);throw new Error("uploadFile not supported")}},...n.getFileDownloadUrl&&{getFileDownloadUrl:t=>{if(n.getFileDownloadUrl)return n.getFileDownloadUrl(t);throw new Error("getFileDownloadUrl not supported")}},async readResource(t){return n.readResource(t)},log(t,o){n.log(t,o);},onToolResult(t){return n.onToolResult(t)},onToolInput(t){return n.onToolInput(t)},onToolCancelled(t){return n.onToolCancelled(t)},onHostContextChange(t){return n.onHostContextChange(t)},onTeardown(t){return n.onTeardown(t)},onToolInputPartial(t){return n.onToolInputPartial(t)},getHostCapabilities(){return n.getHostCapabilities()},getHostVersion(){return n.getHostVersion()},async sendLog(t,o){return n.sendLog(t,o)},async sendSizeChanged(t){return n.sendSizeChanged(t)},setupSizeChangedNotifications(){if(typeof window>"u"||typeof ResizeObserver>"u")return ()=>{};let t=new ResizeObserver(o=>{for(let s of o){let{width:r,height:i}=s.contentRect;n.sendSizeChanged({width:Math.round(r),height:Math.round(i)});}});return t.observe(document.body),()=>{t.disconnect();}},setCallToolHandler(t){n.setCallToolHandler(t);},setListToolsHandler(t){n.setListToolsHandler(t);},get hostContext(){return n.getHostContext()},get toolInput(){return n.getToolInput()},get toolOutput(){return n.getToolOutput()},get toolMeta(){return n.getToolMeta()}}}function z(n){switch(n){case "mcp":return new g;case "openai":return new f;case "mock":return new c;default:throw new Error(`Unknown adapter type: ${n}`)}}async function de(n){let e=n?.forceAdapter??y();if(!["mcp","openai","mock"].includes(e))throw new Error(`Unknown adapter type: ${e}`);let t=z(e);return await t.connect(),v.setAdapter(t),T(t)}exports.ClientDebugLogger=h;exports.LATEST_PROTOCOL_VERSION=L;exports.McpAdapter=g;exports.MockAdapter=c;exports.OpenAIAdapter=f;exports.RESOURCE_MIME_TYPE=D;exports.RESOURCE_URI_META_KEY=F;exports.UIError=d;exports.UIErrorCode=u;exports.applyDocumentTheme=x;exports.applyHostFonts=b;exports.applyHostStyleVariables=k;exports.clearHostStyleVariables=I;exports.clientDebugLogger=v;exports.createAppsClient=T;exports.createClient=de;exports.detectProtocol=y;exports.getDocumentTheme=H;exports.removeHostFonts=A;exports.safeSerialize=M;exports.safeStringify=P;exports.shouldLog=S;//# sourceMappingURL=index.cjs.map | ||
| 'use strict';var extApps=require('@modelcontextprotocol/ext-apps');var L="2025-11-05",D="text/html;profile=mcp-app",F="ui/resourceUri";function x(n){if(typeof document>"u")return;let e=n==="os"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":n;document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e);}function H(){if(typeof document>"u")return "light";let n=document.documentElement.getAttribute("data-theme");return n==="dark"||n==="light"?n:document.documentElement.classList.contains("dark")?"dark":"light"}var w="mcp-apps-host-fonts";function b(n){if(typeof document>"u")return;let e=document.documentElement;for(let[t,s]of Object.entries(n)){let o=t.startsWith("--")?t:`--${t}`;e.style.setProperty(o,s);}}function k(n){if(typeof document>"u")return;let e=document.getElementById(w);e||(e=document.createElement("style"),e.id=w,document.head.appendChild(e)),e.textContent=n;}function I(){if(typeof document>"u")return;let n=document.getElementById(w);n&&n.remove();}function A(n){if(typeof document>"u")return;let e=document.documentElement;for(let t of Object.keys(n)){let s=t.startsWith("--")?t:`--${t}`;e.style.removeProperty(s);}}var u={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",NOT_CONNECTED:"NOT_CONNECTED",PROTOCOL_ERROR:"PROTOCOL_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",TOOL_CALL_FAILED:"TOOL_CALL_FAILED",TOOL_NOT_FOUND:"TOOL_NOT_FOUND",STATE_ERROR:"STATE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},d=class extends Error{constructor(t,s,o,r){super(s);this.code=t;this.details=o;this.cause=r;this.name="UIError";}formatMessage(){let t=`[${this.code}] ${this.message}`;return this.details&&(t+=` ${JSON.stringify(this.details)}`),t}};var O={debug:0,info:1,warn:2,error:3};function S(n,e){return O[n]>=O[e]}function R(){let n=new WeakSet;return (e,t)=>{if(typeof t=="object"&&t!==null){if(n.has(t))return "[Circular]";n.add(t);}return t}}function M(n){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};try{return JSON.stringify(n),n}catch{try{let e=JSON.stringify(n,R());return JSON.parse(e)}catch{return "[Unserializable]"}}}function P(n){if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="string")return n;if(n instanceof Error)return `${n.name}: ${n.message}`;try{return JSON.stringify(n,R())}catch{return "[Unstringifiable]"}}var m=class{constructor(e={}){this.adapter=null;this.buffer=[];this.flushTimer=null;this.isFlushing=false;this.mcpTransportFailed=false;this.config={enabled:e.enabled??false,level:e.level??"info",batchSize:e.batchSize??10,maxBufferSize:e.maxBufferSize??100,flushIntervalMs:e.flushIntervalMs??5e3,source:e.source??"mcp-apps-ui"};}setAdapter(e){this.adapter=e,this.mcpTransportFailed=false;}configure(e){e.enabled!==void 0&&(this.config.enabled=e.enabled),e.level!==void 0&&(this.config.level=e.level),e.batchSize!==void 0&&(this.config.batchSize=e.batchSize),e.maxBufferSize!==void 0&&(this.config.maxBufferSize=e.maxBufferSize),e.flushIntervalMs!==void 0&&(this.config.flushIntervalMs=e.flushIntervalMs,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.scheduleFlush()),e.source!==void 0&&(this.config.source=e.source);}canUseMcpTransport(){return this.config.enabled&&!this.mcpTransportFailed&&this.adapter?.isConnected()===true}createEntry(e,t,s){return {level:e,message:t,data:s!==void 0?M(s):void 0,timestamp:new Date().toISOString(),source:this.config.source}}scheduleFlush(){this.flushTimer||this.buffer.length===0||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}async flush(){if(this.isFlushing||this.buffer.length===0)return;if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.canUseMcpTransport()){for(let t of this.buffer)this.outputToConsole(t);this.buffer=[];return}this.isFlushing=true;let e=[...this.buffer];this.buffer=[];try{this.adapter&&await this.adapter.callTool("log_debug",{entries:e});}catch{this.mcpTransportFailed||(this.mcpTransportFailed=true,console.info("[ClientDebugLogger] MCP log transport unavailable, using console fallback"));for(let t of e)this.outputToConsole(t);}finally{this.isFlushing=false,this.buffer.length>0&&this.scheduleFlush();}}outputToConsole(e){let t=`[${e.timestamp}] [${e.level.toUpperCase()}]`,s=e.data!==void 0?`${e.message} ${P(e.data)}`:e.message,o=`${t} ${s}`;try{switch(e.level){case "debug":console.debug(o);break;case "info":console.info(o);break;case "warn":console.warn(o);break;case "error":console.error(o);break}}catch{}}addToBuffer(e){if(this.buffer.length>=this.config.maxBufferSize){let t=this.buffer.shift();t&&this.outputToConsole(t);}if(this.buffer.push(e),e.level==="error"){this.flush();return}if(this.buffer.length>=this.config.batchSize){this.flush();return}this.scheduleFlush();}log(e,t,s){if(!S(e,this.config.level))return;let o=this.createEntry(e,t,s);if(!this.canUseMcpTransport()){this.outputToConsole(o);return}this.addToBuffer(o);}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}destroy(){if(this.buffer.length>0){for(let e of this.buffer)this.outputToConsole(e);this.buffer=[];}this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.adapter=null;}},y=new m;var g=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.mockHostCapabilities={logging:{},openLinks:{},theming:{themes:["light","dark","os"]},displayModes:{modes:["inline","fullscreen","pip","panel"]},statePersistence:{persistent:true},serverTools:{listChanged:false},serverResources:{listChanged:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false},fileUpload:{},safeAreaInsets:{},views:{}};this.mockHostVersion={name:"MockHost",version:"1.0.0"};this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}async connect(){this.connected=true,console.log("[MockAdapter] Connected");}isConnected(){return this.connected}async callTool(e,t){console.log(`[MockAdapter] callTool("${e}",`,t,")");let s={_mock:true,tool:e,args:t,timestamp:Date.now()};return this.currentToolOutput=s,s}async sendMessage(e){console.log("[MockAdapter] sendMessage:",e);}async openLink(e){console.log(`[MockAdapter] openLink("${e}")`);}async requestDisplayMode(e){return console.log(`[MockAdapter] requestDisplayMode("${e}")`),this.context={...this.context,displayMode:e},this.notifyHostContextChange(),{mode:e}}requestClose(){console.log("[MockAdapter] requestClose()");}getState(){return this.state}setState(e){this.state=e,console.log("[MockAdapter] setState:",e);}async readResource(e){return console.log(`[MockAdapter] readResource("${e}")`),{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MockAdapter]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}emitToolResult(e){this.currentToolOutput=e;for(let t of this.toolResultHandlers)t(e);}emitToolInput(e){this.currentToolInput=e;for(let t of this.toolInputHandlers)t(e);}setHostContext(e){this.context={...this.context,...e},this.notifyHostContextChange();}emitContextChange(e){this.context=e,this.notifyHostContextChange();}setToolInput(e){this.currentToolInput=e;}emitToolCancelled(e){for(let t of this.toolCancelledHandlers)t(e);}emitTeardown(e){for(let t of this.teardownHandlers)t(e);}notifyHostContextChange(){for(let e of this.hostContextHandlers)e(this.context);}getHostCapabilities(){return this.mockHostCapabilities}getHostVersion(){return this.mockHostVersion}async sendLog(e,t){console.log(`[MockAdapter] sendLog(${e}):`,t);}async sendSizeChanged(e){console.log("[MockAdapter] sendSizeChanged:",e);}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e,console.log("[MockAdapter] setCallToolHandler: handler registered");}setListToolsHandler(e){this.listToolsHandler=e,console.log("[MockAdapter] setListToolsHandler: handler registered");}emitToolInputPartial(e){for(let t of this.toolInputPartialHandlers)t(e);}setMockHostCapabilities(e){this.mockHostCapabilities={...this.mockHostCapabilities,...e};}setMockHostVersion(e){this.mockHostVersion=e;}async simulateHostToolCall(e,t){if(!this.callToolHandler)throw new d(u.TOOL_NOT_FOUND,"No call tool handler registered");return this.callToolHandler(e,t)}async simulateHostListTools(){return this.listToolsHandler?this.listToolsHandler():{tools:[]}}};var _={parse:n=>n},f=class{constructor(){this.connected=false;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"desktop"}}async connect(){if(this.connected)return;if(typeof window>"u"){this.connected=true;return}this.app=new extApps.App({name:"@mcp-apps-kit/ui",version:"0.0.0"},{tools:{}}),this.app.onerror=t=>{this.log("error",t);},this.app.onhostcontextchanged=t=>{let s=t.hostContext??t;this.context=this.mapHostContext(s),this.currentToolMeta=this.extractToolMeta(s);for(let o of this.hostContextHandlers)o(this.context);},this.app.ontoolinput=t=>{let s=t.arguments;if(s){this.currentToolInput=s;for(let o of this.toolInputHandlers)o(s);}},this.app.ontoolinputpartial=t=>{let s=t.arguments;if(s)for(let o of this.toolInputPartialHandlers)o(s);},this.app.oncalltool=async t=>{let{name:s,arguments:o}=t;try{if(this.callToolHandler){let r=await this.callToolHandler(s,o??{});return {content:[{type:"text",text:JSON.stringify(r)}]}}return {content:[{type:"text",text:`No handler registered for tool: ${s}`}],isError:!0}}catch(r){return {content:[{type:"text",text:r instanceof Error?r.message:String(r)}],isError:true}}},this.app.onlisttools=async()=>this.listToolsHandler?{tools:(await this.listToolsHandler()).map(s=>s.name)}:{tools:[]},this.app.ontoolresult=t=>{let s=this.extractToolOutput(t);this.currentToolOutput=s;let o=this.getToolNameFromContext(),r=o?{[o]:s}:s;for(let i of this.toolResultHandlers)i(r);},this.app.ontoolcancelled=t=>{let s=t.reason;for(let o of this.toolCancelledHandlers)o(s);},this.app.onteardown=async t=>{let s=t.reason;for(let o of this.teardownHandlers)o(s);return {}},await this.app.connect();let e=this.app.getHostContext();e&&(this.context=this.mapHostContext(e),this.currentToolMeta=this.extractToolMeta(e)),this.connected=true;}isConnected(){return this.connected}mapHostContext(e){let t=e??{},s=this.createDefaultContext(),o=t.theme==="dark"?"dark":t.theme==="light"?"light":s.theme,r=t.displayMode==="fullscreen"||t.displayMode==="pip"||t.displayMode==="inline"?t.displayMode:s.displayMode,i=Array.isArray(t.availableDisplayModes)?t.availableDisplayModes.filter(c=>typeof c=="string"):s.availableDisplayModes,p=(c=>c!==null&&typeof c=="object"&&!Array.isArray(c))(t.viewport)?{...s.viewport,...t.viewport}:s.viewport,a=typeof t.locale=="string"?t.locale:s.locale,C=typeof t.timeZone=="string"?t.timeZone:s.timeZone,E=s.platform;return {...s,theme:o,displayMode:r,availableDisplayModes:i,viewport:p,locale:a,timeZone:C,platform:E,userAgent:typeof t.userAgent=="string"?t.userAgent:s.userAgent,deviceCapabilities:t.deviceCapabilities,safeAreaInsets:t.safeAreaInsets,styles:t.styles,view:typeof t.view=="string"?t.view:s.view}}extractToolMeta(e){if(e===null||typeof e!="object")return;let t=e;if(!(!t.toolInfo||typeof t.toolInfo!="object"))return {toolInfo:t.toolInfo}}getToolNameFromContext(){if(!this.app)return;let e=this.app.getHostContext();return e?e.toolInfo?.tool?.name:void 0}extractToolOutput(e){let t=e.structuredContent,s=e._meta,o=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(s&&typeof s=="object"&&!Array.isArray(s))return {...o,_meta:s};if(Object.keys(o).length===0){let r=e.content;if(Array.isArray(r)&&r.length>0){let i=r[0];if(i?.type==="text"&&typeof i.text=="string")try{let l=JSON.parse(i.text);if(l!==null&&typeof l=="object"&&!Array.isArray(l))return l}catch{}}}return o}async callTool(e,t){if(!this.app)throw new Error("MCP Apps adapter not connected");let s=await this.app.callServerTool({name:e,arguments:t});return this.extractToolOutput(s)}async sendMessage(e){if(!this.app)throw new Error("MCP Apps adapter not connected");if(e.type!=="text")throw new Error(`Unsupported message content type: ${e.type}`);await this.app.sendMessage({role:"user",content:[{type:"text",text:e.text}]});}async openLink(e){if(!this.app)throw new Error("MCP Apps adapter not connected");await this.app.openLink({url:e});}async requestDisplayMode(e){if(!this.app)throw new Error("MCP Apps adapter not connected");return await this.app.requestDisplayMode({mode:e})}requestClose(){}getState(){return null}setState(e){}async readResource(e){if(!this.app)throw new Error("MCP Apps adapter not connected");let s=await this.app.request.bind(this.app)({method:"resources/read",params:{uri:e}},_);return {contents:(Array.isArray(s.contents)?s.contents:[]).map(o=>{let r={uri:o.uri,mimeType:o.mimeType??"application/octet-stream"};if("text"in o&&typeof o.text=="string")return {...r,text:o.text};if("blob"in o&&typeof o.blob=="string"){let i=Uint8Array.from(atob(o.blob),l=>l.charCodeAt(0));return {...r,blob:i}}return r})}}log(e,t){if(this.app){let i={level:["debug","info","notice","warning","error","critical","alert","emergency"].includes(e)?e:"info",data:t,logger:"@mcp-apps-kit/ui"};try{this.app.sendLog(i);return}catch{}}({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MCP Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){if(!this.app)return;let e=this.app.getHostCapabilities();if(!e)return;let t=e,o=this.app.getHostContext()?.availableDisplayModes;return {logging:t.logging,openLinks:t.openLinks,serverResources:t.serverResources,serverTools:t.serverTools,experimental:t.experimental,theming:{themes:["light","dark"]},displayModes:o?{modes:o}:void 0,statePersistence:{persistent:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false}}}getHostVersion(){if(!this.app)return;let e=this.app.getHostVersion();if(e)return {name:e.name,version:e.version}}async sendLog(e,t){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendLog({level:e,data:t,logger:"@mcp-apps-kit/ui"});}async sendSizeChanged(e){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendSizeChanged({width:e.width,height:e.height});}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e;}setListToolsHandler(e){this.listToolsHandler=e;}};var h=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}readContextFromSDK(){let e=this.getOpenAI();if(!e)return;let t=typeof window<"u";if(typeof e.theme=="string"&&(this.context.theme=e.theme),typeof e.displayMode=="string"&&(this.context.displayMode=e.displayMode),typeof e.locale=="string"&&(this.context.locale=e.locale),typeof e.userAgent=="string"&&Object.assign(this.context,{userAgent:e.userAgent}),typeof e.view=="string"&&(this.context.view=e.view),e.safeArea&&typeof e.safeArea=="object"){let s=e.safeArea;this.context.safeAreaInsets={top:typeof s.top=="number"?s.top:0,right:typeof s.right=="number"?s.right:0,bottom:typeof s.bottom=="number"?s.bottom:0,left:typeof s.left=="number"?s.left:0};}typeof e.maxHeight=="number"&&(this.context.viewport={width:t?window.innerWidth:800,height:e.maxHeight}),console.log("[OpenAI Adapter] Read context from SDK:",this.context);}notifyContextChange(){console.log(`[OpenAI Adapter] Notifying ${String(this.hostContextHandlers.size)} context change handlers`);let e={...this.context};for(let t of this.hostContextHandlers)t(e);}getOpenAI(){return typeof window<"u"&&"openai"in window?window.openai:null}getToolNameFromSDK(){let e=this.getOpenAI();if(e){if(e.toolResponseMetadata&&typeof e.toolResponseMetadata=="object"){let t=e.toolResponseMetadata;if(typeof t.toolName=="string")return t.toolName}if(typeof e.toolName=="string")return e.toolName}}async connect(){await this.waitForOpenAI();let e=this.getOpenAI();if(e){console.log("[OpenAI Adapter] Available SDK methods:",Object.keys(e)),this.readContextFromSDK();let t=this.getToolNameFromSDK();if(typeof e.getToolOutput=="function"?(this.currentToolOutput=e.getToolOutput(),console.log("[OpenAI Adapter] Got tool output from SDK")):e.toolOutput?(this.currentToolOutput=e.toolOutput,console.log("[OpenAI Adapter] Got tool output from SDK property")):e.result&&(this.currentToolOutput=e.result,console.log("[OpenAI Adapter] Got result from SDK")),this.currentToolOutput&&Object.keys(this.currentToolOutput).length>0){let s=t?{[t]:this.currentToolOutput}:this.currentToolOutput;for(let o of this.toolResultHandlers)o(s);}typeof e.getToolInput=="function"?this.currentToolInput=e.getToolInput():e.toolInput?this.currentToolInput=e.toolInput:e.input&&(this.currentToolInput=e.input),typeof e.init=="function"&&await e.init();}this.setupGlobalsListener(),this.connected=true;}setupGlobalsListener(){typeof window>"u"||(this.globalsHandler=e=>{let t=e.data;(t==="openai:set_globals"||typeof t=="object"&&t!==null&&"type"in t&&t.type==="openai:set_globals"||typeof t=="object"&&t!==null&&"message"in t&&t.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals event, refreshing context"),setTimeout(()=>{let o=this.context.theme,r=this.context.locale,i=this.context.displayMode;this.readContextFromSDK(),(this.context.theme!==o||this.context.locale!==r||this.context.displayMode!==i)&&(console.log("[OpenAI Adapter] Context changed, notifying handlers"),this.notifyContextChange());},10));},window.addEventListener("message",this.globalsHandler));}async waitForOpenAI(e=5e3){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai already available");return}return console.log("[OpenAI Adapter] Waiting for window.openai..."),new Promise(t=>{let s=Date.now(),o=false,r=()=>{o||(o=true,window.removeEventListener("message",l),t());},i=()=>{if(!o){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai found via polling"),r();return}if(Date.now()-s>e){console.warn("[OpenAI Adapter] window.openai not found after timeout, proceeding anyway"),r();return}setTimeout(i,50);}},l=p=>{let a=p.data;(a==="openai:set_globals"||typeof a=="object"&&a!==null&&"type"in a&&a.type==="openai:set_globals"||typeof a=="object"&&a!==null&&"message"in a&&a.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals message"),setTimeout(()=>{this.getOpenAI()?(console.log("[OpenAI Adapter] window.openai available after set_globals"),r()):console.log("[OpenAI Adapter] window.openai still not available after set_globals, continuing poll");},50));};window.addEventListener("message",l),i();})}isConnected(){return this.connected}async callTool(e,t){let s=this.getOpenAI();if(s&&typeof s.callTool=="function")return s.callTool(e,t);throw new Error("OpenAI SDK not available")}async sendMessage(e){let t=this.getOpenAI();t&&typeof t.sendMessage=="function"&&await t.sendMessage(e);}async openLink(e){let t=this.getOpenAI();t&&typeof t.openLink=="function"?await t.openLink(e):window.open(e,"_blank");}async requestDisplayMode(e){let t=this.getOpenAI();if(t&&typeof t.requestDisplayMode=="function"){let s=await t.requestDisplayMode({mode:e});return this.context={...this.context,displayMode:s.mode},this.notifyContextChange(),s}return this.context={...this.context,displayMode:e},this.notifyContextChange(),{mode:e}}requestClose(){let e=this.getOpenAI();e&&typeof e.close=="function"&&e.close();}getState(){return this.state}setState(e){this.state=e;let t=this.getOpenAI();t&&typeof t.setState=="function"&&t.setState(e);}async uploadFile(e){let t=this.getOpenAI();if(t&&typeof t.uploadFile=="function")return t.uploadFile(e);throw new Error("File upload not supported")}async getFileDownloadUrl(e){let t=this.getOpenAI();if(t&&typeof t.getFileDownloadUrl=="function")return t.getFileDownloadUrl(e);throw new Error("File download not supported")}async readResource(e){let t=this.getOpenAI();return t&&typeof t.readResource=="function"?t.readResource(e):{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[ChatGPT Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),console.log(`[OpenAI Adapter] Host context handler added, total: ${String(this.hostContextHandlers.size)}`),()=>{this.hostContextHandlers.delete(e),console.log(`[OpenAI Adapter] Host context handler removed, total: ${String(this.hostContextHandlers.size)}`);}}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){if(!this.currentToolOutput)return;let e=this.getToolNameFromSDK();return e?{[e]:this.currentToolOutput}:this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){let e=this.getOpenAI(),t=e&&typeof e.uploadFile=="function",s=this.context.safeAreaInsets!==void 0,o=this.context.view!==void 0;return {openLinks:{},logging:{},theming:{themes:["light","dark"]},displayModes:{modes:["inline","fullscreen","pip"]},statePersistence:{persistent:false},fileUpload:t?{}:void 0,safeAreaInsets:s?{}:void 0,views:o?{}:void 0}}getHostVersion(){}async sendLog(e,t){let s={debug:"debug",info:"info",notice:"info",warning:"warning",error:"error",critical:"error",alert:"error",emergency:"error"};this.log(s[e],t);}async sendSizeChanged(e){let t=this.getOpenAI();t&&typeof t.notifyIntrinsicHeight=="function"&&t.notifyIntrinsicHeight(e.height);}onToolInputPartial(e){return this.log("debug","onToolInputPartial is not supported on ChatGPT"),()=>{}}setCallToolHandler(e){this.log("debug","setCallToolHandler is not supported on ChatGPT");}setListToolsHandler(e){this.log("debug","setListToolsHandler is not supported on ChatGPT");}};function U(){let n=window.location.href;if(n.includes("/api/apps/chatgpt/")||n.includes("chatgpt")||n.includes("sandbox-proxy")||n.includes("widget-content"))return true;let e=document.referrer;return !!(e.includes("chatgpt")||e.includes("openai.com"))}function v(){return typeof window>"u"?"mock":"openai"in window||U()?"openai":window.parent!==window?"mcp":"mock"}function z(n){return new Proxy({},{get(e,t){if(typeof t!="string"||!t.startsWith("call"))return;let s=t.slice(4);if(s.length===0)return;let o=s.charAt(0).toLowerCase()+s.slice(1);return r=>n(o,r)},has(e,t){return typeof t=="string"&&t.startsWith("call")&&t.length>4},ownKeys(){return []},getOwnPropertyDescriptor(e,t){if(typeof t=="string"&&t.startsWith("call")&&t.length>4)return {configurable:true,enumerable:true,writable:false}}})}function T(n){async function e(o,r){return await n.callTool(o,r)}let t=z(e);return {callTool:e,tools:t,async sendMessage(o){await n.sendMessage(o);},async sendFollowUpMessage(o){await n.sendMessage({type:"text",text:o});},async openLink(o){await n.openLink(o);},async requestDisplayMode(o){return n.requestDisplayMode(o)},requestClose(){n.requestClose();},getState(){return n.getState()},setState(o){n.setState(o);},...n.uploadFile&&{uploadFile:o=>{if(n.uploadFile)return n.uploadFile(o);throw new Error("uploadFile not supported")}},...n.getFileDownloadUrl&&{getFileDownloadUrl:o=>{if(n.getFileDownloadUrl)return n.getFileDownloadUrl(o);throw new Error("getFileDownloadUrl not supported")}},async readResource(o){return n.readResource(o)},log(o,r){n.log(o,r);},onToolResult(o){return n.onToolResult(o)},onToolInput(o){return n.onToolInput(o)},onToolCancelled(o){return n.onToolCancelled(o)},onHostContextChange(o){return n.onHostContextChange(o)},onTeardown(o){return n.onTeardown(o)},onToolInputPartial(o){return n.onToolInputPartial(o)},getHostCapabilities(){return n.getHostCapabilities()},getHostVersion(){return n.getHostVersion()},async sendLog(o,r){return n.sendLog(o,r)},async sendSizeChanged(o){return n.sendSizeChanged(o)},setupSizeChangedNotifications(){if(typeof window>"u"||typeof ResizeObserver>"u")return ()=>{};let o=new ResizeObserver(r=>{for(let i of r){let{width:l,height:p}=i.contentRect;n.sendSizeChanged({width:Math.round(l),height:Math.round(p)});}});return o.observe(document.body),()=>{o.disconnect();}},setCallToolHandler(o){n.setCallToolHandler(o);},setListToolsHandler(o){n.setListToolsHandler(o);},get hostContext(){return n.getHostContext()},get toolInput(){return n.getToolInput()},get toolOutput(){return n.getToolOutput()},get toolMeta(){return n.getToolMeta()}}}function V(n){switch(n){case "mcp":return new f;case "openai":return new h;case "mock":return new g;default:throw new Error(`Unknown adapter type: ${n}`)}}async function ue(n){let e=n?.forceAdapter??v();if(!["mcp","openai","mock"].includes(e))throw new Error(`Unknown adapter type: ${e}`);let t=V(e);return await t.connect(),y.setAdapter(t),T(t)}exports.ClientDebugLogger=m;exports.LATEST_PROTOCOL_VERSION=L;exports.McpAdapter=f;exports.MockAdapter=g;exports.OpenAIAdapter=h;exports.RESOURCE_MIME_TYPE=D;exports.RESOURCE_URI_META_KEY=F;exports.UIError=d;exports.UIErrorCode=u;exports.applyDocumentTheme=x;exports.applyHostFonts=k;exports.applyHostStyleVariables=b;exports.clearHostStyleVariables=A;exports.clientDebugLogger=y;exports.createAppsClient=T;exports.createClient=ue;exports.detectProtocol=v;exports.getDocumentTheme=H;exports.removeHostFonts=I;exports.safeSerialize=M;exports.safeStringify=P;exports.shouldLog=S;//# sourceMappingURL=index.cjs.map | ||
| //# sourceMappingURL=index.cjs.map |
+120
-1
@@ -7,2 +7,4 @@ /** | ||
| * Protocol-agnostic interface covering features from both MCP Apps and ChatGPT. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -69,2 +71,4 @@ interface HostCapabilities { | ||
| * Host version information returned after connection. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -80,2 +84,4 @@ interface HostVersion { | ||
| * Tells the host what this app supports. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -93,2 +99,4 @@ interface AppCapabilities { | ||
| * Parameters for size changed notifications. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -104,2 +112,4 @@ interface SizeChangedParams { | ||
| * Used when the app exposes tools that the host can call. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -119,2 +129,4 @@ interface AppToolDefinition { | ||
| * @returns Tool result | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -125,2 +137,4 @@ type CallToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>; | ||
| * @returns Array of tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -130,2 +144,4 @@ type ListToolsHandler = () => Promise<AppToolDefinition[]>; | ||
| * Viewport dimensions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -140,2 +156,4 @@ interface Viewport { | ||
| * Safe area insets (mobile devices) | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -150,2 +168,4 @@ interface SafeAreaInsets { | ||
| * Device capabilities | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -158,2 +178,4 @@ interface DeviceCapabilities { | ||
| * Host-provided styling | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -200,2 +222,4 @@ interface HostStyles { | ||
| * Resource content from readResource | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -210,2 +234,4 @@ interface ResourceContent { | ||
| * Generic tool definitions type (for type inference) | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -218,2 +244,4 @@ type ToolDefs = Record<string, { | ||
| * Extract output types from tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -225,2 +253,4 @@ type InferToolOutputs<T extends ToolDefs> = { | ||
| * Extract input types from tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -231,3 +261,23 @@ type InferToolInputs<T extends ToolDefs> = { | ||
| /** | ||
| * Typed tool methods generated from tool definitions. | ||
| * | ||
| * Creates a method for each tool with the naming convention `call{ToolName}`. | ||
| * For example, a tool named "greet" becomes `callGreet()`. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // Instead of: | ||
| * await client.callTool("greet", { name: "Alice" }); | ||
| * | ||
| * // You can use: | ||
| * await client.tools.callGreet({ name: "Alice" }); | ||
| * ``` | ||
| */ | ||
| type ToolMethods<T extends ToolDefs> = { | ||
| [K in keyof T as K extends string ? `call${Capitalize<K>}` : never]: (args: InferToolInputs<T>[K]) => Promise<InferToolOutputs<T>[K]>; | ||
| }; | ||
| /** | ||
| * Tool result with optional metadata | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -252,2 +302,18 @@ type ToolResult<T extends ToolDefs> = { | ||
| /** | ||
| * Typed tool methods object. | ||
| * | ||
| * Provides direct method access to tools with the naming convention `call{ToolName}`. | ||
| * This is an alternative to using `callTool()` that provides a more ergonomic API. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // Instead of: | ||
| * await client.callTool("greet", { name: "Alice" }); | ||
| * | ||
| * // You can use: | ||
| * await client.tools.callGreet({ name: "Alice" }); | ||
| * ``` | ||
| */ | ||
| readonly tools: ToolMethods<T>; | ||
| /** | ||
| * Send a message to the conversation | ||
@@ -534,2 +600,4 @@ * | ||
| * Detected protocol type | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -541,2 +609,3 @@ type DetectedProtocol = "mcp" | "openai" | "mock"; | ||
| * | ||
| * @internal | ||
| * @packageDocumentation | ||
@@ -547,2 +616,4 @@ */ | ||
| * Used during client-host handshake to ensure compatibility. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -553,2 +624,4 @@ declare const LATEST_PROTOCOL_VERSION = "2025-11-05"; | ||
| * Used when registering UI resources with the MCP server. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -559,2 +632,4 @@ declare const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app"; | ||
| * Used to link tools to their associated UI widgets. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -702,2 +777,4 @@ declare const RESOURCE_URI_META_KEY = "ui/resourceUri"; | ||
| * the unified AppsClient API to platform-specific implementations. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -714,2 +791,4 @@ | ||
| * Each adapter translates the unified API to the platform-specific SDK. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -911,2 +990,4 @@ interface ProtocolAdapter { | ||
| * Factory function type for creating protocol adapters | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -916,2 +997,4 @@ type AdapterFactory = () => ProtocolAdapter; | ||
| * Adapter type identifiers | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -931,2 +1014,4 @@ type AdapterType = "mcp" | "openai" | "mock"; | ||
| * Log level for debug logging | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -936,2 +1021,4 @@ type DebugLogLevel = "debug" | "info" | "warn" | "error"; | ||
| * A single log entry | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -952,2 +1039,4 @@ interface LogEntry { | ||
| * Debug configuration for the client logger | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -989,2 +1078,4 @@ interface ClientDebugConfig { | ||
| * Check if a log level should be output given the minimum level | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -994,2 +1085,4 @@ declare function shouldLog(level: DebugLogLevel, minLevel: DebugLogLevel): boolean; | ||
| * Safely serialize data for transport, handling circular references | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -999,2 +1092,4 @@ declare function safeSerialize(data: unknown): unknown; | ||
| * Safely stringify data for console output | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1014,2 +1109,4 @@ declare function safeStringify(data: unknown): string; | ||
| * - Graceful degradation in restricted environments | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1099,2 +1196,4 @@ declare class ClientDebugLogger { | ||
| * connecting to the MCP server. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1107,2 +1206,4 @@ declare const clientDebugLogger: ClientDebugLogger; | ||
| * Provides a working implementation without requiring a host platform. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1114,2 +1215,4 @@ | ||
| * All operations are simulated locally with console logging. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1225,2 +1328,4 @@ declare class MockAdapter implements ProtocolAdapter { | ||
| * Uses @modelcontextprotocol/ext-apps (JSON-RPC over postMessage + ui/initialize). | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1231,2 +1336,4 @@ | ||
| * | ||
| * @internal | ||
| * | ||
| * Communicates with the host via postMessage through iframe boundary. | ||
@@ -1301,2 +1408,4 @@ * State management is a graceful no-op (not supported in MCP Apps). | ||
| * Would integrate with the OpenAI Apps SDK when available. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1309,2 +1418,4 @@ | ||
| * Integrates with the OpenAI Apps SDK. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1391,2 +1502,4 @@ declare class OpenAIAdapter implements ProtocolAdapter { | ||
| * Protocol detection for auto-selecting the correct adapter | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1404,2 +1517,4 @@ | ||
| * @returns Detected protocol type | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1412,2 +1527,4 @@ declare function detectProtocol(): DetectedProtocol; | ||
| * Wraps protocol adapters to provide the unified AppsClient interface. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1417,2 +1534,4 @@ | ||
| * Create an AppsClient that wraps a protocol adapter | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1467,2 +1586,2 @@ declare function createAppsClient<T extends ToolDefs = ToolDefs>(adapter: ProtocolAdapter): AppsClient<T>; | ||
| export { type AdapterFactory, type AdapterType, type AppCapabilities, type AppToolDefinition, type AppsClient, type CallToolHandler, type ClientDebugConfig, ClientDebugLogger, type CreateClientOptions, type DebugLogLevel, type DetectedProtocol, type DeviceCapabilities, type HostCapabilities, type HostContext, type HostStyles, type HostVersion, type InferToolInputs, type InferToolOutputs, LATEST_PROTOCOL_VERSION, type ListToolsHandler, type LogEntry, McpAdapter, MockAdapter, type ModalButton, type ModalInput, type ModalOptions, type ModalResult, OpenAIAdapter, type ProtocolAdapter, RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY, type ResourceContent, type SafeAreaInsets, type SizeChangedParams, type Theme, type ToolDefs, type ToolResult, UIError, UIErrorCode, type UIErrorCodeType, type Viewport, applyDocumentTheme, applyHostFonts, applyHostStyleVariables, clearHostStyleVariables, clientDebugLogger, createAppsClient, createClient, detectProtocol, getDocumentTheme, removeHostFonts, safeSerialize, safeStringify, shouldLog }; | ||
| export { type AdapterFactory, type AdapterType, type AppCapabilities, type AppToolDefinition, type AppsClient, type CallToolHandler, type ClientDebugConfig, ClientDebugLogger, type CreateClientOptions, type DebugLogLevel, type DetectedProtocol, type DeviceCapabilities, type HostCapabilities, type HostContext, type HostStyles, type HostVersion, type InferToolInputs, type InferToolOutputs, LATEST_PROTOCOL_VERSION, type ListToolsHandler, type LogEntry, McpAdapter, MockAdapter, type ModalButton, type ModalInput, type ModalOptions, type ModalResult, OpenAIAdapter, type ProtocolAdapter, RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY, type ResourceContent, type SafeAreaInsets, type SizeChangedParams, type Theme, type ToolDefs, type ToolMethods, type ToolResult, UIError, UIErrorCode, type UIErrorCodeType, type Viewport, applyDocumentTheme, applyHostFonts, applyHostStyleVariables, clearHostStyleVariables, clientDebugLogger, createAppsClient, createClient, detectProtocol, getDocumentTheme, removeHostFonts, safeSerialize, safeStringify, shouldLog }; |
+120
-1
@@ -7,2 +7,4 @@ /** | ||
| * Protocol-agnostic interface covering features from both MCP Apps and ChatGPT. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -69,2 +71,4 @@ interface HostCapabilities { | ||
| * Host version information returned after connection. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -80,2 +84,4 @@ interface HostVersion { | ||
| * Tells the host what this app supports. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -93,2 +99,4 @@ interface AppCapabilities { | ||
| * Parameters for size changed notifications. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -104,2 +112,4 @@ interface SizeChangedParams { | ||
| * Used when the app exposes tools that the host can call. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -119,2 +129,4 @@ interface AppToolDefinition { | ||
| * @returns Tool result | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -125,2 +137,4 @@ type CallToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>; | ||
| * @returns Array of tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -130,2 +144,4 @@ type ListToolsHandler = () => Promise<AppToolDefinition[]>; | ||
| * Viewport dimensions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -140,2 +156,4 @@ interface Viewport { | ||
| * Safe area insets (mobile devices) | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -150,2 +168,4 @@ interface SafeAreaInsets { | ||
| * Device capabilities | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -158,2 +178,4 @@ interface DeviceCapabilities { | ||
| * Host-provided styling | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -200,2 +222,4 @@ interface HostStyles { | ||
| * Resource content from readResource | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -210,2 +234,4 @@ interface ResourceContent { | ||
| * Generic tool definitions type (for type inference) | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -218,2 +244,4 @@ type ToolDefs = Record<string, { | ||
| * Extract output types from tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -225,2 +253,4 @@ type InferToolOutputs<T extends ToolDefs> = { | ||
| * Extract input types from tool definitions | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -231,3 +261,23 @@ type InferToolInputs<T extends ToolDefs> = { | ||
| /** | ||
| * Typed tool methods generated from tool definitions. | ||
| * | ||
| * Creates a method for each tool with the naming convention `call{ToolName}`. | ||
| * For example, a tool named "greet" becomes `callGreet()`. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // Instead of: | ||
| * await client.callTool("greet", { name: "Alice" }); | ||
| * | ||
| * // You can use: | ||
| * await client.tools.callGreet({ name: "Alice" }); | ||
| * ``` | ||
| */ | ||
| type ToolMethods<T extends ToolDefs> = { | ||
| [K in keyof T as K extends string ? `call${Capitalize<K>}` : never]: (args: InferToolInputs<T>[K]) => Promise<InferToolOutputs<T>[K]>; | ||
| }; | ||
| /** | ||
| * Tool result with optional metadata | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -252,2 +302,18 @@ type ToolResult<T extends ToolDefs> = { | ||
| /** | ||
| * Typed tool methods object. | ||
| * | ||
| * Provides direct method access to tools with the naming convention `call{ToolName}`. | ||
| * This is an alternative to using `callTool()` that provides a more ergonomic API. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // Instead of: | ||
| * await client.callTool("greet", { name: "Alice" }); | ||
| * | ||
| * // You can use: | ||
| * await client.tools.callGreet({ name: "Alice" }); | ||
| * ``` | ||
| */ | ||
| readonly tools: ToolMethods<T>; | ||
| /** | ||
| * Send a message to the conversation | ||
@@ -534,2 +600,4 @@ * | ||
| * Detected protocol type | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -541,2 +609,3 @@ type DetectedProtocol = "mcp" | "openai" | "mock"; | ||
| * | ||
| * @internal | ||
| * @packageDocumentation | ||
@@ -547,2 +616,4 @@ */ | ||
| * Used during client-host handshake to ensure compatibility. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -553,2 +624,4 @@ declare const LATEST_PROTOCOL_VERSION = "2025-11-05"; | ||
| * Used when registering UI resources with the MCP server. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -559,2 +632,4 @@ declare const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app"; | ||
| * Used to link tools to their associated UI widgets. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -702,2 +777,4 @@ declare const RESOURCE_URI_META_KEY = "ui/resourceUri"; | ||
| * the unified AppsClient API to platform-specific implementations. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -714,2 +791,4 @@ | ||
| * Each adapter translates the unified API to the platform-specific SDK. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -911,2 +990,4 @@ interface ProtocolAdapter { | ||
| * Factory function type for creating protocol adapters | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -916,2 +997,4 @@ type AdapterFactory = () => ProtocolAdapter; | ||
| * Adapter type identifiers | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -931,2 +1014,4 @@ type AdapterType = "mcp" | "openai" | "mock"; | ||
| * Log level for debug logging | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -936,2 +1021,4 @@ type DebugLogLevel = "debug" | "info" | "warn" | "error"; | ||
| * A single log entry | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -952,2 +1039,4 @@ interface LogEntry { | ||
| * Debug configuration for the client logger | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -989,2 +1078,4 @@ interface ClientDebugConfig { | ||
| * Check if a log level should be output given the minimum level | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -994,2 +1085,4 @@ declare function shouldLog(level: DebugLogLevel, minLevel: DebugLogLevel): boolean; | ||
| * Safely serialize data for transport, handling circular references | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -999,2 +1092,4 @@ declare function safeSerialize(data: unknown): unknown; | ||
| * Safely stringify data for console output | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1014,2 +1109,4 @@ declare function safeStringify(data: unknown): string; | ||
| * - Graceful degradation in restricted environments | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1099,2 +1196,4 @@ declare class ClientDebugLogger { | ||
| * connecting to the MCP server. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1107,2 +1206,4 @@ declare const clientDebugLogger: ClientDebugLogger; | ||
| * Provides a working implementation without requiring a host platform. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1114,2 +1215,4 @@ | ||
| * All operations are simulated locally with console logging. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1225,2 +1328,4 @@ declare class MockAdapter implements ProtocolAdapter { | ||
| * Uses @modelcontextprotocol/ext-apps (JSON-RPC over postMessage + ui/initialize). | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1231,2 +1336,4 @@ | ||
| * | ||
| * @internal | ||
| * | ||
| * Communicates with the host via postMessage through iframe boundary. | ||
@@ -1301,2 +1408,4 @@ * State management is a graceful no-op (not supported in MCP Apps). | ||
| * Would integrate with the OpenAI Apps SDK when available. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1309,2 +1418,4 @@ | ||
| * Integrates with the OpenAI Apps SDK. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1391,2 +1502,4 @@ declare class OpenAIAdapter implements ProtocolAdapter { | ||
| * Protocol detection for auto-selecting the correct adapter | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1404,2 +1517,4 @@ | ||
| * @returns Detected protocol type | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1412,2 +1527,4 @@ declare function detectProtocol(): DetectedProtocol; | ||
| * Wraps protocol adapters to provide the unified AppsClient interface. | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1417,2 +1534,4 @@ | ||
| * Create an AppsClient that wraps a protocol adapter | ||
| * | ||
| * @internal | ||
| */ | ||
@@ -1467,2 +1586,2 @@ declare function createAppsClient<T extends ToolDefs = ToolDefs>(adapter: ProtocolAdapter): AppsClient<T>; | ||
| export { type AdapterFactory, type AdapterType, type AppCapabilities, type AppToolDefinition, type AppsClient, type CallToolHandler, type ClientDebugConfig, ClientDebugLogger, type CreateClientOptions, type DebugLogLevel, type DetectedProtocol, type DeviceCapabilities, type HostCapabilities, type HostContext, type HostStyles, type HostVersion, type InferToolInputs, type InferToolOutputs, LATEST_PROTOCOL_VERSION, type ListToolsHandler, type LogEntry, McpAdapter, MockAdapter, type ModalButton, type ModalInput, type ModalOptions, type ModalResult, OpenAIAdapter, type ProtocolAdapter, RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY, type ResourceContent, type SafeAreaInsets, type SizeChangedParams, type Theme, type ToolDefs, type ToolResult, UIError, UIErrorCode, type UIErrorCodeType, type Viewport, applyDocumentTheme, applyHostFonts, applyHostStyleVariables, clearHostStyleVariables, clientDebugLogger, createAppsClient, createClient, detectProtocol, getDocumentTheme, removeHostFonts, safeSerialize, safeStringify, shouldLog }; | ||
| export { type AdapterFactory, type AdapterType, type AppCapabilities, type AppToolDefinition, type AppsClient, type CallToolHandler, type ClientDebugConfig, ClientDebugLogger, type CreateClientOptions, type DebugLogLevel, type DetectedProtocol, type DeviceCapabilities, type HostCapabilities, type HostContext, type HostStyles, type HostVersion, type InferToolInputs, type InferToolOutputs, LATEST_PROTOCOL_VERSION, type ListToolsHandler, type LogEntry, McpAdapter, MockAdapter, type ModalButton, type ModalInput, type ModalOptions, type ModalResult, OpenAIAdapter, type ProtocolAdapter, RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY, type ResourceContent, type SafeAreaInsets, type SizeChangedParams, type Theme, type ToolDefs, type ToolMethods, type ToolResult, UIError, UIErrorCode, type UIErrorCodeType, type Viewport, applyDocumentTheme, applyHostFonts, applyHostStyleVariables, clearHostStyleVariables, clientDebugLogger, createAppsClient, createClient, detectProtocol, getDocumentTheme, removeHostFonts, safeSerialize, safeStringify, shouldLog }; |
+1
-1
@@ -1,2 +0,2 @@ | ||
| import {App}from'@modelcontextprotocol/ext-apps';var L="2025-11-05",D="text/html;profile=mcp-app",F="ui/resourceUri";function x(n){if(typeof document>"u")return;let e=n==="os"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":n;document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e);}function H(){if(typeof document>"u")return "light";let n=document.documentElement.getAttribute("data-theme");return n==="dark"||n==="light"?n:document.documentElement.classList.contains("dark")?"dark":"light"}var w="mcp-apps-host-fonts";function k(n){if(typeof document>"u")return;let e=document.documentElement;for(let[t,o]of Object.entries(n)){let s=t.startsWith("--")?t:`--${t}`;e.style.setProperty(s,o);}}function b(n){if(typeof document>"u")return;let e=document.getElementById(w);e||(e=document.createElement("style"),e.id=w,document.head.appendChild(e)),e.textContent=n;}function A(){if(typeof document>"u")return;let n=document.getElementById(w);n&&n.remove();}function I(n){if(typeof document>"u")return;let e=document.documentElement;for(let t of Object.keys(n)){let o=t.startsWith("--")?t:`--${t}`;e.style.removeProperty(o);}}var u={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",NOT_CONNECTED:"NOT_CONNECTED",PROTOCOL_ERROR:"PROTOCOL_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",TOOL_CALL_FAILED:"TOOL_CALL_FAILED",TOOL_NOT_FOUND:"TOOL_NOT_FOUND",STATE_ERROR:"STATE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},d=class extends Error{constructor(t,o,s,r){super(o);this.code=t;this.details=s;this.cause=r;this.name="UIError";}formatMessage(){let t=`[${this.code}] ${this.message}`;return this.details&&(t+=` ${JSON.stringify(this.details)}`),t}};var O={debug:0,info:1,warn:2,error:3};function S(n,e){return O[n]>=O[e]}function R(){let n=new WeakSet;return (e,t)=>{if(typeof t=="object"&&t!==null){if(n.has(t))return "[Circular]";n.add(t);}return t}}function M(n){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};try{return JSON.stringify(n),n}catch{try{let e=JSON.stringify(n,R());return JSON.parse(e)}catch{return "[Unserializable]"}}}function P(n){if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="string")return n;if(n instanceof Error)return `${n.name}: ${n.message}`;try{return JSON.stringify(n,R())}catch{return "[Unstringifiable]"}}var h=class{constructor(e={}){this.adapter=null;this.buffer=[];this.flushTimer=null;this.isFlushing=false;this.mcpTransportFailed=false;this.config={enabled:e.enabled??false,level:e.level??"info",batchSize:e.batchSize??10,maxBufferSize:e.maxBufferSize??100,flushIntervalMs:e.flushIntervalMs??5e3,source:e.source??"mcp-apps-ui"};}setAdapter(e){this.adapter=e,this.mcpTransportFailed=false;}configure(e){e.enabled!==void 0&&(this.config.enabled=e.enabled),e.level!==void 0&&(this.config.level=e.level),e.batchSize!==void 0&&(this.config.batchSize=e.batchSize),e.maxBufferSize!==void 0&&(this.config.maxBufferSize=e.maxBufferSize),e.flushIntervalMs!==void 0&&(this.config.flushIntervalMs=e.flushIntervalMs,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.scheduleFlush()),e.source!==void 0&&(this.config.source=e.source);}canUseMcpTransport(){return this.config.enabled&&!this.mcpTransportFailed&&this.adapter?.isConnected()===true}createEntry(e,t,o){return {level:e,message:t,data:o!==void 0?M(o):void 0,timestamp:new Date().toISOString(),source:this.config.source}}scheduleFlush(){this.flushTimer||this.buffer.length===0||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}async flush(){if(this.isFlushing||this.buffer.length===0)return;if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.canUseMcpTransport()){for(let t of this.buffer)this.outputToConsole(t);this.buffer=[];return}this.isFlushing=true;let e=[...this.buffer];this.buffer=[];try{this.adapter&&await this.adapter.callTool("log_debug",{entries:e});}catch{this.mcpTransportFailed||(this.mcpTransportFailed=true,console.info("[ClientDebugLogger] MCP log transport unavailable, using console fallback"));for(let t of e)this.outputToConsole(t);}finally{this.isFlushing=false,this.buffer.length>0&&this.scheduleFlush();}}outputToConsole(e){let t=`[${e.timestamp}] [${e.level.toUpperCase()}]`,o=e.data!==void 0?`${e.message} ${P(e.data)}`:e.message,s=`${t} ${o}`;try{switch(e.level){case "debug":console.debug(s);break;case "info":console.info(s);break;case "warn":console.warn(s);break;case "error":console.error(s);break}}catch{}}addToBuffer(e){if(this.buffer.length>=this.config.maxBufferSize){let t=this.buffer.shift();t&&this.outputToConsole(t);}if(this.buffer.push(e),e.level==="error"){this.flush();return}if(this.buffer.length>=this.config.batchSize){this.flush();return}this.scheduleFlush();}log(e,t,o){if(!S(e,this.config.level))return;let s=this.createEntry(e,t,o);if(!this.canUseMcpTransport()){this.outputToConsole(s);return}this.addToBuffer(s);}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}destroy(){if(this.buffer.length>0){for(let e of this.buffer)this.outputToConsole(e);this.buffer=[];}this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.adapter=null;}},v=new h;var c=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.mockHostCapabilities={logging:{},openLinks:{},theming:{themes:["light","dark","os"]},displayModes:{modes:["inline","fullscreen","pip","panel"]},statePersistence:{persistent:true},serverTools:{listChanged:false},serverResources:{listChanged:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false},fileUpload:{},safeAreaInsets:{},views:{}};this.mockHostVersion={name:"MockHost",version:"1.0.0"};this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}async connect(){this.connected=true,console.log("[MockAdapter] Connected");}isConnected(){return this.connected}async callTool(e,t){console.log(`[MockAdapter] callTool("${e}",`,t,")");let o={_mock:true,tool:e,args:t,timestamp:Date.now()};return this.currentToolOutput=o,o}async sendMessage(e){console.log("[MockAdapter] sendMessage:",e);}async openLink(e){console.log(`[MockAdapter] openLink("${e}")`);}async requestDisplayMode(e){return console.log(`[MockAdapter] requestDisplayMode("${e}")`),this.context={...this.context,displayMode:e},this.notifyHostContextChange(),{mode:e}}requestClose(){console.log("[MockAdapter] requestClose()");}getState(){return this.state}setState(e){this.state=e,console.log("[MockAdapter] setState:",e);}async readResource(e){return console.log(`[MockAdapter] readResource("${e}")`),{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MockAdapter]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}emitToolResult(e){this.currentToolOutput=e;for(let t of this.toolResultHandlers)t(e);}emitToolInput(e){this.currentToolInput=e;for(let t of this.toolInputHandlers)t(e);}setHostContext(e){this.context={...this.context,...e},this.notifyHostContextChange();}emitContextChange(e){this.context=e,this.notifyHostContextChange();}setToolInput(e){this.currentToolInput=e;}emitToolCancelled(e){for(let t of this.toolCancelledHandlers)t(e);}emitTeardown(e){for(let t of this.teardownHandlers)t(e);}notifyHostContextChange(){for(let e of this.hostContextHandlers)e(this.context);}getHostCapabilities(){return this.mockHostCapabilities}getHostVersion(){return this.mockHostVersion}async sendLog(e,t){console.log(`[MockAdapter] sendLog(${e}):`,t);}async sendSizeChanged(e){console.log("[MockAdapter] sendSizeChanged:",e);}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e,console.log("[MockAdapter] setCallToolHandler: handler registered");}setListToolsHandler(e){this.listToolsHandler=e,console.log("[MockAdapter] setListToolsHandler: handler registered");}emitToolInputPartial(e){for(let t of this.toolInputPartialHandlers)t(e);}setMockHostCapabilities(e){this.mockHostCapabilities={...this.mockHostCapabilities,...e};}setMockHostVersion(e){this.mockHostVersion=e;}async simulateHostToolCall(e,t){if(!this.callToolHandler)throw new d(u.TOOL_NOT_FOUND,"No call tool handler registered");return this.callToolHandler(e,t)}async simulateHostListTools(){return this.listToolsHandler?this.listToolsHandler():{tools:[]}}};var _={parse:n=>n},g=class{constructor(){this.connected=false;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"desktop"}}async connect(){if(this.connected)return;if(typeof window>"u"){this.connected=true;return}this.app=new App({name:"@mcp-apps-kit/ui",version:"0.0.0"},{tools:{}}),this.app.onerror=t=>{this.log("error",t);},this.app.onhostcontextchanged=t=>{let o=t.hostContext??t;this.context=this.mapHostContext(o),this.currentToolMeta=this.extractToolMeta(o);for(let s of this.hostContextHandlers)s(this.context);},this.app.ontoolinput=t=>{let o=t.arguments;if(o){this.currentToolInput=o;for(let s of this.toolInputHandlers)s(o);}},this.app.ontoolinputpartial=t=>{let o=t.arguments;if(o)for(let s of this.toolInputPartialHandlers)s(o);},this.app.oncalltool=async t=>{let{name:o,arguments:s}=t;try{if(this.callToolHandler){let r=await this.callToolHandler(o,s??{});return {content:[{type:"text",text:JSON.stringify(r)}]}}return {content:[{type:"text",text:`No handler registered for tool: ${o}`}],isError:!0}}catch(r){return {content:[{type:"text",text:r instanceof Error?r.message:String(r)}],isError:true}}},this.app.onlisttools=async()=>this.listToolsHandler?{tools:(await this.listToolsHandler()).map(o=>o.name)}:{tools:[]},this.app.ontoolresult=t=>{let o=this.extractToolOutput(t);this.currentToolOutput=o;let s=this.getToolNameFromContext(),r=s?{[s]:o}:o;for(let i of this.toolResultHandlers)i(r);},this.app.ontoolcancelled=t=>{let o=t.reason;for(let s of this.toolCancelledHandlers)s(o);},this.app.onteardown=async t=>{let o=t.reason;for(let s of this.teardownHandlers)s(o);return {}},await this.app.connect();let e=this.app.getHostContext();e&&(this.context=this.mapHostContext(e),this.currentToolMeta=this.extractToolMeta(e)),this.connected=true;}isConnected(){return this.connected}mapHostContext(e){let t=e??{},o=this.createDefaultContext(),s=t.theme==="dark"?"dark":t.theme==="light"?"light":o.theme,r=t.displayMode==="fullscreen"||t.displayMode==="pip"||t.displayMode==="inline"?t.displayMode:o.displayMode,i=Array.isArray(t.availableDisplayModes)?t.availableDisplayModes.filter(p=>typeof p=="string"):o.availableDisplayModes,m=(p=>p!==null&&typeof p=="object"&&!Array.isArray(p))(t.viewport)?{...o.viewport,...t.viewport}:o.viewport,l=typeof t.locale=="string"?t.locale:o.locale,C=typeof t.timeZone=="string"?t.timeZone:o.timeZone,E=o.platform;return {...o,theme:s,displayMode:r,availableDisplayModes:i,viewport:m,locale:l,timeZone:C,platform:E,userAgent:typeof t.userAgent=="string"?t.userAgent:o.userAgent,deviceCapabilities:t.deviceCapabilities,safeAreaInsets:t.safeAreaInsets,styles:t.styles,view:typeof t.view=="string"?t.view:o.view}}extractToolMeta(e){if(e===null||typeof e!="object")return;let t=e;if(!(!t.toolInfo||typeof t.toolInfo!="object"))return {toolInfo:t.toolInfo}}getToolNameFromContext(){if(!this.app)return;let e=this.app.getHostContext();return e?e.toolInfo?.tool?.name:void 0}extractToolOutput(e){let t=e.structuredContent,o=e._meta,s=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(o&&typeof o=="object"&&!Array.isArray(o))return {...s,_meta:o};if(Object.keys(s).length===0){let r=e.content;if(Array.isArray(r)&&r.length>0){let i=r[0];if(i?.type==="text"&&typeof i.text=="string")try{let a=JSON.parse(i.text);if(a!==null&&typeof a=="object"&&!Array.isArray(a))return a}catch{}}}return s}async callTool(e,t){if(!this.app)throw new Error("MCP Apps adapter not connected");let o=await this.app.callServerTool({name:e,arguments:t});return this.extractToolOutput(o)}async sendMessage(e){if(!this.app)throw new Error("MCP Apps adapter not connected");if(e.type!=="text")throw new Error(`Unsupported message content type: ${e.type}`);await this.app.sendMessage({role:"user",content:[{type:"text",text:e.text}]});}async openLink(e){if(!this.app)throw new Error("MCP Apps adapter not connected");await this.app.openLink({url:e});}async requestDisplayMode(e){if(!this.app)throw new Error("MCP Apps adapter not connected");return await this.app.requestDisplayMode({mode:e})}requestClose(){}getState(){return null}setState(e){}async readResource(e){if(!this.app)throw new Error("MCP Apps adapter not connected");let o=await this.app.request.bind(this.app)({method:"resources/read",params:{uri:e}},_);return {contents:(Array.isArray(o.contents)?o.contents:[]).map(s=>{let r={uri:s.uri,mimeType:s.mimeType??"application/octet-stream"};if("text"in s&&typeof s.text=="string")return {...r,text:s.text};if("blob"in s&&typeof s.blob=="string"){let i=Uint8Array.from(atob(s.blob),a=>a.charCodeAt(0));return {...r,blob:i}}return r})}}log(e,t){if(this.app){let i={level:["debug","info","notice","warning","error","critical","alert","emergency"].includes(e)?e:"info",data:t,logger:"@mcp-apps-kit/ui"};try{this.app.sendLog(i);return}catch{}}({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MCP Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){if(!this.app)return;let e=this.app.getHostCapabilities();if(!e)return;let t=e,s=this.app.getHostContext()?.availableDisplayModes;return {logging:t.logging,openLinks:t.openLinks,serverResources:t.serverResources,serverTools:t.serverTools,experimental:t.experimental,theming:{themes:["light","dark"]},displayModes:s?{modes:s}:void 0,statePersistence:{persistent:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false}}}getHostVersion(){if(!this.app)return;let e=this.app.getHostVersion();if(e)return {name:e.name,version:e.version}}async sendLog(e,t){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendLog({level:e,data:t,logger:"@mcp-apps-kit/ui"});}async sendSizeChanged(e){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendSizeChanged({width:e.width,height:e.height});}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e;}setListToolsHandler(e){this.listToolsHandler=e;}};var f=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}readContextFromSDK(){let e=this.getOpenAI();if(!e)return;let t=typeof window<"u";if(typeof e.theme=="string"&&(this.context.theme=e.theme),typeof e.displayMode=="string"&&(this.context.displayMode=e.displayMode),typeof e.locale=="string"&&(this.context.locale=e.locale),typeof e.userAgent=="string"&&Object.assign(this.context,{userAgent:e.userAgent}),typeof e.view=="string"&&(this.context.view=e.view),e.safeArea&&typeof e.safeArea=="object"){let o=e.safeArea;this.context.safeAreaInsets={top:typeof o.top=="number"?o.top:0,right:typeof o.right=="number"?o.right:0,bottom:typeof o.bottom=="number"?o.bottom:0,left:typeof o.left=="number"?o.left:0};}typeof e.maxHeight=="number"&&(this.context.viewport={width:t?window.innerWidth:800,height:e.maxHeight}),console.log("[OpenAI Adapter] Read context from SDK:",this.context);}notifyContextChange(){console.log(`[OpenAI Adapter] Notifying ${String(this.hostContextHandlers.size)} context change handlers`);let e={...this.context};for(let t of this.hostContextHandlers)t(e);}getOpenAI(){return typeof window<"u"&&"openai"in window?window.openai:null}getToolNameFromSDK(){let e=this.getOpenAI();if(e){if(e.toolResponseMetadata&&typeof e.toolResponseMetadata=="object"){let t=e.toolResponseMetadata;if(typeof t.toolName=="string")return t.toolName}if(typeof e.toolName=="string")return e.toolName}}async connect(){await this.waitForOpenAI();let e=this.getOpenAI();if(e){console.log("[OpenAI Adapter] Available SDK methods:",Object.keys(e)),this.readContextFromSDK();let t=this.getToolNameFromSDK();if(typeof e.getToolOutput=="function"?(this.currentToolOutput=e.getToolOutput(),console.log("[OpenAI Adapter] Got tool output from SDK")):e.toolOutput?(this.currentToolOutput=e.toolOutput,console.log("[OpenAI Adapter] Got tool output from SDK property")):e.result&&(this.currentToolOutput=e.result,console.log("[OpenAI Adapter] Got result from SDK")),this.currentToolOutput&&Object.keys(this.currentToolOutput).length>0){let o=t?{[t]:this.currentToolOutput}:this.currentToolOutput;for(let s of this.toolResultHandlers)s(o);}typeof e.getToolInput=="function"?this.currentToolInput=e.getToolInput():e.toolInput?this.currentToolInput=e.toolInput:e.input&&(this.currentToolInput=e.input),typeof e.init=="function"&&await e.init();}this.setupGlobalsListener(),this.connected=true;}setupGlobalsListener(){typeof window>"u"||(this.globalsHandler=e=>{let t=e.data;(t==="openai:set_globals"||typeof t=="object"&&t!==null&&"type"in t&&t.type==="openai:set_globals"||typeof t=="object"&&t!==null&&"message"in t&&t.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals event, refreshing context"),setTimeout(()=>{let s=this.context.theme,r=this.context.locale,i=this.context.displayMode;this.readContextFromSDK(),(this.context.theme!==s||this.context.locale!==r||this.context.displayMode!==i)&&(console.log("[OpenAI Adapter] Context changed, notifying handlers"),this.notifyContextChange());},10));},window.addEventListener("message",this.globalsHandler));}async waitForOpenAI(e=5e3){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai already available");return}return console.log("[OpenAI Adapter] Waiting for window.openai..."),new Promise(t=>{let o=Date.now(),s=false,r=()=>{s||(s=true,window.removeEventListener("message",a),t());},i=()=>{if(!s){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai found via polling"),r();return}if(Date.now()-o>e){console.warn("[OpenAI Adapter] window.openai not found after timeout, proceeding anyway"),r();return}setTimeout(i,50);}},a=m=>{let l=m.data;(l==="openai:set_globals"||typeof l=="object"&&l!==null&&"type"in l&&l.type==="openai:set_globals"||typeof l=="object"&&l!==null&&"message"in l&&l.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals message"),setTimeout(()=>{this.getOpenAI()?(console.log("[OpenAI Adapter] window.openai available after set_globals"),r()):console.log("[OpenAI Adapter] window.openai still not available after set_globals, continuing poll");},50));};window.addEventListener("message",a),i();})}isConnected(){return this.connected}async callTool(e,t){let o=this.getOpenAI();if(o&&typeof o.callTool=="function")return o.callTool(e,t);throw new Error("OpenAI SDK not available")}async sendMessage(e){let t=this.getOpenAI();t&&typeof t.sendMessage=="function"&&await t.sendMessage(e);}async openLink(e){let t=this.getOpenAI();t&&typeof t.openLink=="function"?await t.openLink(e):window.open(e,"_blank");}async requestDisplayMode(e){let t=this.getOpenAI();if(t&&typeof t.requestDisplayMode=="function"){let o=await t.requestDisplayMode({mode:e});return this.context={...this.context,displayMode:o.mode},this.notifyContextChange(),o}return this.context={...this.context,displayMode:e},this.notifyContextChange(),{mode:e}}requestClose(){let e=this.getOpenAI();e&&typeof e.close=="function"&&e.close();}getState(){return this.state}setState(e){this.state=e;let t=this.getOpenAI();t&&typeof t.setState=="function"&&t.setState(e);}async uploadFile(e){let t=this.getOpenAI();if(t&&typeof t.uploadFile=="function")return t.uploadFile(e);throw new Error("File upload not supported")}async getFileDownloadUrl(e){let t=this.getOpenAI();if(t&&typeof t.getFileDownloadUrl=="function")return t.getFileDownloadUrl(e);throw new Error("File download not supported")}async readResource(e){let t=this.getOpenAI();return t&&typeof t.readResource=="function"?t.readResource(e):{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[ChatGPT Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),console.log(`[OpenAI Adapter] Host context handler added, total: ${String(this.hostContextHandlers.size)}`),()=>{this.hostContextHandlers.delete(e),console.log(`[OpenAI Adapter] Host context handler removed, total: ${String(this.hostContextHandlers.size)}`);}}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){if(!this.currentToolOutput)return;let e=this.getToolNameFromSDK();return e?{[e]:this.currentToolOutput}:this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){let e=this.getOpenAI(),t=e&&typeof e.uploadFile=="function",o=this.context.safeAreaInsets!==void 0,s=this.context.view!==void 0;return {openLinks:{},logging:{},theming:{themes:["light","dark"]},displayModes:{modes:["inline","fullscreen","pip"]},statePersistence:{persistent:false},fileUpload:t?{}:void 0,safeAreaInsets:o?{}:void 0,views:s?{}:void 0}}getHostVersion(){}async sendLog(e,t){let o={debug:"debug",info:"info",notice:"info",warning:"warning",error:"error",critical:"error",alert:"error",emergency:"error"};this.log(o[e],t);}async sendSizeChanged(e){let t=this.getOpenAI();t&&typeof t.notifyIntrinsicHeight=="function"&&t.notifyIntrinsicHeight(e.height);}onToolInputPartial(e){return this.log("debug","onToolInputPartial is not supported on ChatGPT"),()=>{}}setCallToolHandler(e){this.log("debug","setCallToolHandler is not supported on ChatGPT");}setListToolsHandler(e){this.log("debug","setListToolsHandler is not supported on ChatGPT");}};function U(){let n=window.location.href;if(n.includes("/api/apps/chatgpt/")||n.includes("chatgpt")||n.includes("sandbox-proxy")||n.includes("widget-content"))return true;let e=document.referrer;return !!(e.includes("chatgpt")||e.includes("openai.com"))}function y(){return typeof window>"u"?"mock":"openai"in window||U()?"openai":window.parent!==window?"mcp":"mock"}function T(n){return {async callTool(t,o){return await n.callTool(t,o)},async sendMessage(t){await n.sendMessage(t);},async sendFollowUpMessage(t){await n.sendMessage({type:"text",text:t});},async openLink(t){await n.openLink(t);},async requestDisplayMode(t){return n.requestDisplayMode(t)},requestClose(){n.requestClose();},getState(){return n.getState()},setState(t){n.setState(t);},...n.uploadFile&&{uploadFile:t=>{if(n.uploadFile)return n.uploadFile(t);throw new Error("uploadFile not supported")}},...n.getFileDownloadUrl&&{getFileDownloadUrl:t=>{if(n.getFileDownloadUrl)return n.getFileDownloadUrl(t);throw new Error("getFileDownloadUrl not supported")}},async readResource(t){return n.readResource(t)},log(t,o){n.log(t,o);},onToolResult(t){return n.onToolResult(t)},onToolInput(t){return n.onToolInput(t)},onToolCancelled(t){return n.onToolCancelled(t)},onHostContextChange(t){return n.onHostContextChange(t)},onTeardown(t){return n.onTeardown(t)},onToolInputPartial(t){return n.onToolInputPartial(t)},getHostCapabilities(){return n.getHostCapabilities()},getHostVersion(){return n.getHostVersion()},async sendLog(t,o){return n.sendLog(t,o)},async sendSizeChanged(t){return n.sendSizeChanged(t)},setupSizeChangedNotifications(){if(typeof window>"u"||typeof ResizeObserver>"u")return ()=>{};let t=new ResizeObserver(o=>{for(let s of o){let{width:r,height:i}=s.contentRect;n.sendSizeChanged({width:Math.round(r),height:Math.round(i)});}});return t.observe(document.body),()=>{t.disconnect();}},setCallToolHandler(t){n.setCallToolHandler(t);},setListToolsHandler(t){n.setListToolsHandler(t);},get hostContext(){return n.getHostContext()},get toolInput(){return n.getToolInput()},get toolOutput(){return n.getToolOutput()},get toolMeta(){return n.getToolMeta()}}}function z(n){switch(n){case "mcp":return new g;case "openai":return new f;case "mock":return new c;default:throw new Error(`Unknown adapter type: ${n}`)}}async function de(n){let e=n?.forceAdapter??y();if(!["mcp","openai","mock"].includes(e))throw new Error(`Unknown adapter type: ${e}`);let t=z(e);return await t.connect(),v.setAdapter(t),T(t)}export{h as ClientDebugLogger,L as LATEST_PROTOCOL_VERSION,g as McpAdapter,c as MockAdapter,f as OpenAIAdapter,D as RESOURCE_MIME_TYPE,F as RESOURCE_URI_META_KEY,d as UIError,u as UIErrorCode,x as applyDocumentTheme,b as applyHostFonts,k as applyHostStyleVariables,I as clearHostStyleVariables,v as clientDebugLogger,T as createAppsClient,de as createClient,y as detectProtocol,H as getDocumentTheme,A as removeHostFonts,M as safeSerialize,P as safeStringify,S as shouldLog};//# sourceMappingURL=index.js.map | ||
| import {App}from'@modelcontextprotocol/ext-apps';var L="2025-11-05",D="text/html;profile=mcp-app",F="ui/resourceUri";function x(n){if(typeof document>"u")return;let e=n==="os"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":n;document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e);}function H(){if(typeof document>"u")return "light";let n=document.documentElement.getAttribute("data-theme");return n==="dark"||n==="light"?n:document.documentElement.classList.contains("dark")?"dark":"light"}var w="mcp-apps-host-fonts";function b(n){if(typeof document>"u")return;let e=document.documentElement;for(let[t,s]of Object.entries(n)){let o=t.startsWith("--")?t:`--${t}`;e.style.setProperty(o,s);}}function k(n){if(typeof document>"u")return;let e=document.getElementById(w);e||(e=document.createElement("style"),e.id=w,document.head.appendChild(e)),e.textContent=n;}function I(){if(typeof document>"u")return;let n=document.getElementById(w);n&&n.remove();}function A(n){if(typeof document>"u")return;let e=document.documentElement;for(let t of Object.keys(n)){let s=t.startsWith("--")?t:`--${t}`;e.style.removeProperty(s);}}var u={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",NOT_CONNECTED:"NOT_CONNECTED",PROTOCOL_ERROR:"PROTOCOL_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",TOOL_CALL_FAILED:"TOOL_CALL_FAILED",TOOL_NOT_FOUND:"TOOL_NOT_FOUND",STATE_ERROR:"STATE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},d=class extends Error{constructor(t,s,o,r){super(s);this.code=t;this.details=o;this.cause=r;this.name="UIError";}formatMessage(){let t=`[${this.code}] ${this.message}`;return this.details&&(t+=` ${JSON.stringify(this.details)}`),t}};var O={debug:0,info:1,warn:2,error:3};function S(n,e){return O[n]>=O[e]}function R(){let n=new WeakSet;return (e,t)=>{if(typeof t=="object"&&t!==null){if(n.has(t))return "[Circular]";n.add(t);}return t}}function M(n){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};try{return JSON.stringify(n),n}catch{try{let e=JSON.stringify(n,R());return JSON.parse(e)}catch{return "[Unserializable]"}}}function P(n){if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="string")return n;if(n instanceof Error)return `${n.name}: ${n.message}`;try{return JSON.stringify(n,R())}catch{return "[Unstringifiable]"}}var m=class{constructor(e={}){this.adapter=null;this.buffer=[];this.flushTimer=null;this.isFlushing=false;this.mcpTransportFailed=false;this.config={enabled:e.enabled??false,level:e.level??"info",batchSize:e.batchSize??10,maxBufferSize:e.maxBufferSize??100,flushIntervalMs:e.flushIntervalMs??5e3,source:e.source??"mcp-apps-ui"};}setAdapter(e){this.adapter=e,this.mcpTransportFailed=false;}configure(e){e.enabled!==void 0&&(this.config.enabled=e.enabled),e.level!==void 0&&(this.config.level=e.level),e.batchSize!==void 0&&(this.config.batchSize=e.batchSize),e.maxBufferSize!==void 0&&(this.config.maxBufferSize=e.maxBufferSize),e.flushIntervalMs!==void 0&&(this.config.flushIntervalMs=e.flushIntervalMs,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.scheduleFlush()),e.source!==void 0&&(this.config.source=e.source);}canUseMcpTransport(){return this.config.enabled&&!this.mcpTransportFailed&&this.adapter?.isConnected()===true}createEntry(e,t,s){return {level:e,message:t,data:s!==void 0?M(s):void 0,timestamp:new Date().toISOString(),source:this.config.source}}scheduleFlush(){this.flushTimer||this.buffer.length===0||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}async flush(){if(this.isFlushing||this.buffer.length===0)return;if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.canUseMcpTransport()){for(let t of this.buffer)this.outputToConsole(t);this.buffer=[];return}this.isFlushing=true;let e=[...this.buffer];this.buffer=[];try{this.adapter&&await this.adapter.callTool("log_debug",{entries:e});}catch{this.mcpTransportFailed||(this.mcpTransportFailed=true,console.info("[ClientDebugLogger] MCP log transport unavailable, using console fallback"));for(let t of e)this.outputToConsole(t);}finally{this.isFlushing=false,this.buffer.length>0&&this.scheduleFlush();}}outputToConsole(e){let t=`[${e.timestamp}] [${e.level.toUpperCase()}]`,s=e.data!==void 0?`${e.message} ${P(e.data)}`:e.message,o=`${t} ${s}`;try{switch(e.level){case "debug":console.debug(o);break;case "info":console.info(o);break;case "warn":console.warn(o);break;case "error":console.error(o);break}}catch{}}addToBuffer(e){if(this.buffer.length>=this.config.maxBufferSize){let t=this.buffer.shift();t&&this.outputToConsole(t);}if(this.buffer.push(e),e.level==="error"){this.flush();return}if(this.buffer.length>=this.config.batchSize){this.flush();return}this.scheduleFlush();}log(e,t,s){if(!S(e,this.config.level))return;let o=this.createEntry(e,t,s);if(!this.canUseMcpTransport()){this.outputToConsole(o);return}this.addToBuffer(o);}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}destroy(){if(this.buffer.length>0){for(let e of this.buffer)this.outputToConsole(e);this.buffer=[];}this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.adapter=null;}},y=new m;var g=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.mockHostCapabilities={logging:{},openLinks:{},theming:{themes:["light","dark","os"]},displayModes:{modes:["inline","fullscreen","pip","panel"]},statePersistence:{persistent:true},serverTools:{listChanged:false},serverResources:{listChanged:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false},fileUpload:{},safeAreaInsets:{},views:{}};this.mockHostVersion={name:"MockHost",version:"1.0.0"};this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}async connect(){this.connected=true,console.log("[MockAdapter] Connected");}isConnected(){return this.connected}async callTool(e,t){console.log(`[MockAdapter] callTool("${e}",`,t,")");let s={_mock:true,tool:e,args:t,timestamp:Date.now()};return this.currentToolOutput=s,s}async sendMessage(e){console.log("[MockAdapter] sendMessage:",e);}async openLink(e){console.log(`[MockAdapter] openLink("${e}")`);}async requestDisplayMode(e){return console.log(`[MockAdapter] requestDisplayMode("${e}")`),this.context={...this.context,displayMode:e},this.notifyHostContextChange(),{mode:e}}requestClose(){console.log("[MockAdapter] requestClose()");}getState(){return this.state}setState(e){this.state=e,console.log("[MockAdapter] setState:",e);}async readResource(e){return console.log(`[MockAdapter] readResource("${e}")`),{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MockAdapter]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}emitToolResult(e){this.currentToolOutput=e;for(let t of this.toolResultHandlers)t(e);}emitToolInput(e){this.currentToolInput=e;for(let t of this.toolInputHandlers)t(e);}setHostContext(e){this.context={...this.context,...e},this.notifyHostContextChange();}emitContextChange(e){this.context=e,this.notifyHostContextChange();}setToolInput(e){this.currentToolInput=e;}emitToolCancelled(e){for(let t of this.toolCancelledHandlers)t(e);}emitTeardown(e){for(let t of this.teardownHandlers)t(e);}notifyHostContextChange(){for(let e of this.hostContextHandlers)e(this.context);}getHostCapabilities(){return this.mockHostCapabilities}getHostVersion(){return this.mockHostVersion}async sendLog(e,t){console.log(`[MockAdapter] sendLog(${e}):`,t);}async sendSizeChanged(e){console.log("[MockAdapter] sendSizeChanged:",e);}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e,console.log("[MockAdapter] setCallToolHandler: handler registered");}setListToolsHandler(e){this.listToolsHandler=e,console.log("[MockAdapter] setListToolsHandler: handler registered");}emitToolInputPartial(e){for(let t of this.toolInputPartialHandlers)t(e);}setMockHostCapabilities(e){this.mockHostCapabilities={...this.mockHostCapabilities,...e};}setMockHostVersion(e){this.mockHostVersion=e;}async simulateHostToolCall(e,t){if(!this.callToolHandler)throw new d(u.TOOL_NOT_FOUND,"No call tool handler registered");return this.callToolHandler(e,t)}async simulateHostListTools(){return this.listToolsHandler?this.listToolsHandler():{tools:[]}}};var _={parse:n=>n},f=class{constructor(){this.connected=false;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolInputPartialHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"desktop"}}async connect(){if(this.connected)return;if(typeof window>"u"){this.connected=true;return}this.app=new App({name:"@mcp-apps-kit/ui",version:"0.0.0"},{tools:{}}),this.app.onerror=t=>{this.log("error",t);},this.app.onhostcontextchanged=t=>{let s=t.hostContext??t;this.context=this.mapHostContext(s),this.currentToolMeta=this.extractToolMeta(s);for(let o of this.hostContextHandlers)o(this.context);},this.app.ontoolinput=t=>{let s=t.arguments;if(s){this.currentToolInput=s;for(let o of this.toolInputHandlers)o(s);}},this.app.ontoolinputpartial=t=>{let s=t.arguments;if(s)for(let o of this.toolInputPartialHandlers)o(s);},this.app.oncalltool=async t=>{let{name:s,arguments:o}=t;try{if(this.callToolHandler){let r=await this.callToolHandler(s,o??{});return {content:[{type:"text",text:JSON.stringify(r)}]}}return {content:[{type:"text",text:`No handler registered for tool: ${s}`}],isError:!0}}catch(r){return {content:[{type:"text",text:r instanceof Error?r.message:String(r)}],isError:true}}},this.app.onlisttools=async()=>this.listToolsHandler?{tools:(await this.listToolsHandler()).map(s=>s.name)}:{tools:[]},this.app.ontoolresult=t=>{let s=this.extractToolOutput(t);this.currentToolOutput=s;let o=this.getToolNameFromContext(),r=o?{[o]:s}:s;for(let i of this.toolResultHandlers)i(r);},this.app.ontoolcancelled=t=>{let s=t.reason;for(let o of this.toolCancelledHandlers)o(s);},this.app.onteardown=async t=>{let s=t.reason;for(let o of this.teardownHandlers)o(s);return {}},await this.app.connect();let e=this.app.getHostContext();e&&(this.context=this.mapHostContext(e),this.currentToolMeta=this.extractToolMeta(e)),this.connected=true;}isConnected(){return this.connected}mapHostContext(e){let t=e??{},s=this.createDefaultContext(),o=t.theme==="dark"?"dark":t.theme==="light"?"light":s.theme,r=t.displayMode==="fullscreen"||t.displayMode==="pip"||t.displayMode==="inline"?t.displayMode:s.displayMode,i=Array.isArray(t.availableDisplayModes)?t.availableDisplayModes.filter(c=>typeof c=="string"):s.availableDisplayModes,p=(c=>c!==null&&typeof c=="object"&&!Array.isArray(c))(t.viewport)?{...s.viewport,...t.viewport}:s.viewport,a=typeof t.locale=="string"?t.locale:s.locale,C=typeof t.timeZone=="string"?t.timeZone:s.timeZone,E=s.platform;return {...s,theme:o,displayMode:r,availableDisplayModes:i,viewport:p,locale:a,timeZone:C,platform:E,userAgent:typeof t.userAgent=="string"?t.userAgent:s.userAgent,deviceCapabilities:t.deviceCapabilities,safeAreaInsets:t.safeAreaInsets,styles:t.styles,view:typeof t.view=="string"?t.view:s.view}}extractToolMeta(e){if(e===null||typeof e!="object")return;let t=e;if(!(!t.toolInfo||typeof t.toolInfo!="object"))return {toolInfo:t.toolInfo}}getToolNameFromContext(){if(!this.app)return;let e=this.app.getHostContext();return e?e.toolInfo?.tool?.name:void 0}extractToolOutput(e){let t=e.structuredContent,s=e._meta,o=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(s&&typeof s=="object"&&!Array.isArray(s))return {...o,_meta:s};if(Object.keys(o).length===0){let r=e.content;if(Array.isArray(r)&&r.length>0){let i=r[0];if(i?.type==="text"&&typeof i.text=="string")try{let l=JSON.parse(i.text);if(l!==null&&typeof l=="object"&&!Array.isArray(l))return l}catch{}}}return o}async callTool(e,t){if(!this.app)throw new Error("MCP Apps adapter not connected");let s=await this.app.callServerTool({name:e,arguments:t});return this.extractToolOutput(s)}async sendMessage(e){if(!this.app)throw new Error("MCP Apps adapter not connected");if(e.type!=="text")throw new Error(`Unsupported message content type: ${e.type}`);await this.app.sendMessage({role:"user",content:[{type:"text",text:e.text}]});}async openLink(e){if(!this.app)throw new Error("MCP Apps adapter not connected");await this.app.openLink({url:e});}async requestDisplayMode(e){if(!this.app)throw new Error("MCP Apps adapter not connected");return await this.app.requestDisplayMode({mode:e})}requestClose(){}getState(){return null}setState(e){}async readResource(e){if(!this.app)throw new Error("MCP Apps adapter not connected");let s=await this.app.request.bind(this.app)({method:"resources/read",params:{uri:e}},_);return {contents:(Array.isArray(s.contents)?s.contents:[]).map(o=>{let r={uri:o.uri,mimeType:o.mimeType??"application/octet-stream"};if("text"in o&&typeof o.text=="string")return {...r,text:o.text};if("blob"in o&&typeof o.blob=="string"){let i=Uint8Array.from(atob(o.blob),l=>l.charCodeAt(0));return {...r,blob:i}}return r})}}log(e,t){if(this.app){let i={level:["debug","info","notice","warning","error","critical","alert","emergency"].includes(e)?e:"info",data:t,logger:"@mcp-apps-kit/ui"};try{this.app.sendLog(i);return}catch{}}({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[MCP Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),()=>this.hostContextHandlers.delete(e)}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){return this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){if(!this.app)return;let e=this.app.getHostCapabilities();if(!e)return;let t=e,o=this.app.getHostContext()?.availableDisplayModes;return {logging:t.logging,openLinks:t.openLinks,serverResources:t.serverResources,serverTools:t.serverTools,experimental:t.experimental,theming:{themes:["light","dark"]},displayModes:o?{modes:o}:void 0,statePersistence:{persistent:false},sizeNotifications:{},partialToolInput:{},appTools:{listChanged:false}}}getHostVersion(){if(!this.app)return;let e=this.app.getHostVersion();if(e)return {name:e.name,version:e.version}}async sendLog(e,t){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendLog({level:e,data:t,logger:"@mcp-apps-kit/ui"});}async sendSizeChanged(e){if(!this.app)throw new d(u.NOT_CONNECTED,"MCP Apps adapter not connected");await this.app.sendSizeChanged({width:e.width,height:e.height});}onToolInputPartial(e){return this.toolInputPartialHandlers.add(e),()=>this.toolInputPartialHandlers.delete(e)}setCallToolHandler(e){this.callToolHandler=e;}setListToolsHandler(e){this.listToolsHandler=e;}};var h=class{constructor(){this.connected=false;this.state=null;this.toolResultHandlers=new Set;this.toolInputHandlers=new Set;this.toolCancelledHandlers=new Set;this.hostContextHandlers=new Set;this.teardownHandlers=new Set;this.context=this.createDefaultContext();}createDefaultContext(){let e=typeof window<"u";return {theme:"light",displayMode:"inline",availableDisplayModes:["inline","fullscreen","pip"],viewport:{width:e?window.innerWidth:800,height:e?window.innerHeight:600},locale:e?navigator.language:"en-US",timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web",deviceCapabilities:{touch:e?"ontouchstart"in window:false,hover:true}}}readContextFromSDK(){let e=this.getOpenAI();if(!e)return;let t=typeof window<"u";if(typeof e.theme=="string"&&(this.context.theme=e.theme),typeof e.displayMode=="string"&&(this.context.displayMode=e.displayMode),typeof e.locale=="string"&&(this.context.locale=e.locale),typeof e.userAgent=="string"&&Object.assign(this.context,{userAgent:e.userAgent}),typeof e.view=="string"&&(this.context.view=e.view),e.safeArea&&typeof e.safeArea=="object"){let s=e.safeArea;this.context.safeAreaInsets={top:typeof s.top=="number"?s.top:0,right:typeof s.right=="number"?s.right:0,bottom:typeof s.bottom=="number"?s.bottom:0,left:typeof s.left=="number"?s.left:0};}typeof e.maxHeight=="number"&&(this.context.viewport={width:t?window.innerWidth:800,height:e.maxHeight}),console.log("[OpenAI Adapter] Read context from SDK:",this.context);}notifyContextChange(){console.log(`[OpenAI Adapter] Notifying ${String(this.hostContextHandlers.size)} context change handlers`);let e={...this.context};for(let t of this.hostContextHandlers)t(e);}getOpenAI(){return typeof window<"u"&&"openai"in window?window.openai:null}getToolNameFromSDK(){let e=this.getOpenAI();if(e){if(e.toolResponseMetadata&&typeof e.toolResponseMetadata=="object"){let t=e.toolResponseMetadata;if(typeof t.toolName=="string")return t.toolName}if(typeof e.toolName=="string")return e.toolName}}async connect(){await this.waitForOpenAI();let e=this.getOpenAI();if(e){console.log("[OpenAI Adapter] Available SDK methods:",Object.keys(e)),this.readContextFromSDK();let t=this.getToolNameFromSDK();if(typeof e.getToolOutput=="function"?(this.currentToolOutput=e.getToolOutput(),console.log("[OpenAI Adapter] Got tool output from SDK")):e.toolOutput?(this.currentToolOutput=e.toolOutput,console.log("[OpenAI Adapter] Got tool output from SDK property")):e.result&&(this.currentToolOutput=e.result,console.log("[OpenAI Adapter] Got result from SDK")),this.currentToolOutput&&Object.keys(this.currentToolOutput).length>0){let s=t?{[t]:this.currentToolOutput}:this.currentToolOutput;for(let o of this.toolResultHandlers)o(s);}typeof e.getToolInput=="function"?this.currentToolInput=e.getToolInput():e.toolInput?this.currentToolInput=e.toolInput:e.input&&(this.currentToolInput=e.input),typeof e.init=="function"&&await e.init();}this.setupGlobalsListener(),this.connected=true;}setupGlobalsListener(){typeof window>"u"||(this.globalsHandler=e=>{let t=e.data;(t==="openai:set_globals"||typeof t=="object"&&t!==null&&"type"in t&&t.type==="openai:set_globals"||typeof t=="object"&&t!==null&&"message"in t&&t.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals event, refreshing context"),setTimeout(()=>{let o=this.context.theme,r=this.context.locale,i=this.context.displayMode;this.readContextFromSDK(),(this.context.theme!==o||this.context.locale!==r||this.context.displayMode!==i)&&(console.log("[OpenAI Adapter] Context changed, notifying handlers"),this.notifyContextChange());},10));},window.addEventListener("message",this.globalsHandler));}async waitForOpenAI(e=5e3){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai already available");return}return console.log("[OpenAI Adapter] Waiting for window.openai..."),new Promise(t=>{let s=Date.now(),o=false,r=()=>{o||(o=true,window.removeEventListener("message",l),t());},i=()=>{if(!o){if(this.getOpenAI()){console.log("[OpenAI Adapter] window.openai found via polling"),r();return}if(Date.now()-s>e){console.warn("[OpenAI Adapter] window.openai not found after timeout, proceeding anyway"),r();return}setTimeout(i,50);}},l=p=>{let a=p.data;(a==="openai:set_globals"||typeof a=="object"&&a!==null&&"type"in a&&a.type==="openai:set_globals"||typeof a=="object"&&a!==null&&"message"in a&&a.message==="openai:set_globals")&&(console.log("[OpenAI Adapter] Received set_globals message"),setTimeout(()=>{this.getOpenAI()?(console.log("[OpenAI Adapter] window.openai available after set_globals"),r()):console.log("[OpenAI Adapter] window.openai still not available after set_globals, continuing poll");},50));};window.addEventListener("message",l),i();})}isConnected(){return this.connected}async callTool(e,t){let s=this.getOpenAI();if(s&&typeof s.callTool=="function")return s.callTool(e,t);throw new Error("OpenAI SDK not available")}async sendMessage(e){let t=this.getOpenAI();t&&typeof t.sendMessage=="function"&&await t.sendMessage(e);}async openLink(e){let t=this.getOpenAI();t&&typeof t.openLink=="function"?await t.openLink(e):window.open(e,"_blank");}async requestDisplayMode(e){let t=this.getOpenAI();if(t&&typeof t.requestDisplayMode=="function"){let s=await t.requestDisplayMode({mode:e});return this.context={...this.context,displayMode:s.mode},this.notifyContextChange(),s}return this.context={...this.context,displayMode:e},this.notifyContextChange(),{mode:e}}requestClose(){let e=this.getOpenAI();e&&typeof e.close=="function"&&e.close();}getState(){return this.state}setState(e){this.state=e;let t=this.getOpenAI();t&&typeof t.setState=="function"&&t.setState(e);}async uploadFile(e){let t=this.getOpenAI();if(t&&typeof t.uploadFile=="function")return t.uploadFile(e);throw new Error("File upload not supported")}async getFileDownloadUrl(e){let t=this.getOpenAI();if(t&&typeof t.getFileDownloadUrl=="function")return t.getFileDownloadUrl(e);throw new Error("File download not supported")}async readResource(e){let t=this.getOpenAI();return t&&typeof t.readResource=="function"?t.readResource(e):{contents:[]}}log(e,t){({debug:console.debug,info:console.info,warning:console.warn,error:console.error}[e]??console.log)("[ChatGPT Apps]",t);}onToolResult(e){return this.toolResultHandlers.add(e),()=>this.toolResultHandlers.delete(e)}onToolInput(e){return this.toolInputHandlers.add(e),()=>this.toolInputHandlers.delete(e)}onToolCancelled(e){return this.toolCancelledHandlers.add(e),()=>this.toolCancelledHandlers.delete(e)}onHostContextChange(e){return this.hostContextHandlers.add(e),console.log(`[OpenAI Adapter] Host context handler added, total: ${String(this.hostContextHandlers.size)}`),()=>{this.hostContextHandlers.delete(e),console.log(`[OpenAI Adapter] Host context handler removed, total: ${String(this.hostContextHandlers.size)}`);}}onTeardown(e){return this.teardownHandlers.add(e),()=>this.teardownHandlers.delete(e)}getHostContext(){return this.context}getToolInput(){return this.currentToolInput}getToolOutput(){if(!this.currentToolOutput)return;let e=this.getToolNameFromSDK();return e?{[e]:this.currentToolOutput}:this.currentToolOutput}getToolMeta(){return this.currentToolMeta}getHostCapabilities(){let e=this.getOpenAI(),t=e&&typeof e.uploadFile=="function",s=this.context.safeAreaInsets!==void 0,o=this.context.view!==void 0;return {openLinks:{},logging:{},theming:{themes:["light","dark"]},displayModes:{modes:["inline","fullscreen","pip"]},statePersistence:{persistent:false},fileUpload:t?{}:void 0,safeAreaInsets:s?{}:void 0,views:o?{}:void 0}}getHostVersion(){}async sendLog(e,t){let s={debug:"debug",info:"info",notice:"info",warning:"warning",error:"error",critical:"error",alert:"error",emergency:"error"};this.log(s[e],t);}async sendSizeChanged(e){let t=this.getOpenAI();t&&typeof t.notifyIntrinsicHeight=="function"&&t.notifyIntrinsicHeight(e.height);}onToolInputPartial(e){return this.log("debug","onToolInputPartial is not supported on ChatGPT"),()=>{}}setCallToolHandler(e){this.log("debug","setCallToolHandler is not supported on ChatGPT");}setListToolsHandler(e){this.log("debug","setListToolsHandler is not supported on ChatGPT");}};function U(){let n=window.location.href;if(n.includes("/api/apps/chatgpt/")||n.includes("chatgpt")||n.includes("sandbox-proxy")||n.includes("widget-content"))return true;let e=document.referrer;return !!(e.includes("chatgpt")||e.includes("openai.com"))}function v(){return typeof window>"u"?"mock":"openai"in window||U()?"openai":window.parent!==window?"mcp":"mock"}function z(n){return new Proxy({},{get(e,t){if(typeof t!="string"||!t.startsWith("call"))return;let s=t.slice(4);if(s.length===0)return;let o=s.charAt(0).toLowerCase()+s.slice(1);return r=>n(o,r)},has(e,t){return typeof t=="string"&&t.startsWith("call")&&t.length>4},ownKeys(){return []},getOwnPropertyDescriptor(e,t){if(typeof t=="string"&&t.startsWith("call")&&t.length>4)return {configurable:true,enumerable:true,writable:false}}})}function T(n){async function e(o,r){return await n.callTool(o,r)}let t=z(e);return {callTool:e,tools:t,async sendMessage(o){await n.sendMessage(o);},async sendFollowUpMessage(o){await n.sendMessage({type:"text",text:o});},async openLink(o){await n.openLink(o);},async requestDisplayMode(o){return n.requestDisplayMode(o)},requestClose(){n.requestClose();},getState(){return n.getState()},setState(o){n.setState(o);},...n.uploadFile&&{uploadFile:o=>{if(n.uploadFile)return n.uploadFile(o);throw new Error("uploadFile not supported")}},...n.getFileDownloadUrl&&{getFileDownloadUrl:o=>{if(n.getFileDownloadUrl)return n.getFileDownloadUrl(o);throw new Error("getFileDownloadUrl not supported")}},async readResource(o){return n.readResource(o)},log(o,r){n.log(o,r);},onToolResult(o){return n.onToolResult(o)},onToolInput(o){return n.onToolInput(o)},onToolCancelled(o){return n.onToolCancelled(o)},onHostContextChange(o){return n.onHostContextChange(o)},onTeardown(o){return n.onTeardown(o)},onToolInputPartial(o){return n.onToolInputPartial(o)},getHostCapabilities(){return n.getHostCapabilities()},getHostVersion(){return n.getHostVersion()},async sendLog(o,r){return n.sendLog(o,r)},async sendSizeChanged(o){return n.sendSizeChanged(o)},setupSizeChangedNotifications(){if(typeof window>"u"||typeof ResizeObserver>"u")return ()=>{};let o=new ResizeObserver(r=>{for(let i of r){let{width:l,height:p}=i.contentRect;n.sendSizeChanged({width:Math.round(l),height:Math.round(p)});}});return o.observe(document.body),()=>{o.disconnect();}},setCallToolHandler(o){n.setCallToolHandler(o);},setListToolsHandler(o){n.setListToolsHandler(o);},get hostContext(){return n.getHostContext()},get toolInput(){return n.getToolInput()},get toolOutput(){return n.getToolOutput()},get toolMeta(){return n.getToolMeta()}}}function V(n){switch(n){case "mcp":return new f;case "openai":return new h;case "mock":return new g;default:throw new Error(`Unknown adapter type: ${n}`)}}async function ue(n){let e=n?.forceAdapter??v();if(!["mcp","openai","mock"].includes(e))throw new Error(`Unknown adapter type: ${e}`);let t=V(e);return await t.connect(),y.setAdapter(t),T(t)}export{m as ClientDebugLogger,L as LATEST_PROTOCOL_VERSION,f as McpAdapter,g as MockAdapter,h as OpenAIAdapter,D as RESOURCE_MIME_TYPE,F as RESOURCE_URI_META_KEY,d as UIError,u as UIErrorCode,x as applyDocumentTheme,k as applyHostFonts,b as applyHostStyleVariables,A as clearHostStyleVariables,y as clientDebugLogger,T as createAppsClient,ue as createClient,v as detectProtocol,H as getDocumentTheme,I as removeHostFonts,M as safeSerialize,P as safeStringify,S as shouldLog};//# sourceMappingURL=index.js.map | ||
| //# sourceMappingURL=index.js.map |
+1
-1
| { | ||
| "name": "@mcp-apps-kit/ui", | ||
| "version": "0.2.6", | ||
| "version": "0.2.7", | ||
| "description": "Client-side SDK for MCP applications (vanilla JavaScript)", | ||
@@ -5,0 +5,0 @@ "type": "module", |
+24
-0
@@ -74,5 +74,11 @@ # @mcp-apps-kit/ui | ||
| // Option 1: Using callTool with tool name string | ||
| await client.callTool("search_restaurants", { location: "Paris" }); | ||
| // Option 2: Using the typed tools proxy (recommended) | ||
| await client.tools.callSearchRestaurants({ location: "Paris" }); | ||
| ``` | ||
| The `tools` property provides a typed proxy with methods like `callGreet()`, `callSearchRestaurants()`, etc. Method names are generated from tool names by prepending "call" and capitalizing the first letter. | ||
| ### Local testing | ||
@@ -127,2 +133,20 @@ | ||
| ### Typed Tools Proxy | ||
| The `client.tools` property provides typed method wrappers for tool calls: | ||
| ```ts | ||
| import type { AppClientTools } from "../server"; | ||
| const client = await createClient<AppClientTools>(); | ||
| // Tool name "greet" becomes method "callGreet" | ||
| const result = await client.tools.callGreet({ name: "Alice" }); | ||
| // Tool name "searchRestaurants" becomes "callSearchRestaurants" | ||
| const restaurants = await client.tools.callSearchRestaurants({ location: "Paris" }); | ||
| ``` | ||
| This is equivalent to `client.callTool("greet", { name: "Alice" })` but provides better IDE autocomplete and type checking. | ||
| ### Host Capabilities | ||
@@ -129,0 +153,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
418759
2.88%1743
7.59%259
10.21%