UNPKG

decocms

Version:

Deco CMS — Self-hostable MCP Gateway for managing AI connections and tools

78 lines (53 loc) • 42.3 kB
import{dC as l,dH as e,dD as h,aK as r,gN as b,aJ as t,ct as p,bF as d,bn as c,dB as m,dF as v,gO as E,gP as I,gQ as w,db as x,eu as T,gR as z,gS as C,gT as A,cS as O,gU as B,dt as V,gV as W,gW as $,gX as F,gY as K,dp as J,dc as Z,dl as j,dm as Q,dn as Y,de as G,dk as X,dd as ee,dx as te}from"./index-DoEtSiIe.js";import{P as oe}from"./use-mcp-client-86j-Nolb.js";(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(o,s)=>(typeof require<"u"?require:o)[s]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class se extends oe{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(o,s){}_ensureEventSlot(o){let s=this._eventSlots.get(o);if(!s){let i=this.eventSchemas[o];if(!i)throw Error(`Unknown event: ${String(o)}`);s={listeners:[]},this._eventSlots.set(o,s);let a=i.shape.method.value;this._registeredMethods.add(a);let u=s;super.setNotificationHandler(i,g=>{let R=g.params;this.onEventDispatch(o,R),u.onHandler?.(R);for(let D of[...u.listeners])D(R)})}return s}setEventHandler(o,s){let i=this._ensureEventSlot(o);i.onHandler&&s&&console.warn(`[MCP Apps] on${String(o)} handler replaced. Use addEventListener("${String(o)}", …) to add multiple listeners without replacing.`),i.onHandler=s}getEventHandler(o){return this._eventSlots.get(o)?.onHandler}addEventListener(o,s){this._ensureEventSlot(o).listeners.push(s)}removeEventListener(o,s){let i=this._eventSlots.get(o);if(!i)return;let a=i.listeners.indexOf(s);a!==-1&&i.listeners.splice(a,1)}setRequestHandler=(o,s)=>{this._assertMethodNotRegistered(o,"setRequestHandler"),super.setRequestHandler(o,s)};setNotificationHandler=(o,s)=>{this._assertMethodNotRegistered(o,"setNotificationHandler"),super.setNotificationHandler(o,s)};warnIfRequestHandlerReplaced(o,s,i){s&&i&&console.warn(`[MCP Apps] ${o} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(o,s)=>{let i=o.shape.method.value;this._registeredMethods.add(i),super.setRequestHandler(o,s)};_assertMethodNotRegistered(o,s){let i=o.shape.method.value;if(this._registeredMethods.has(i))throw Error(`Handler for "${i}" already registered (via ${s}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(i)}}var L="2026-01-26",ie="ui/notifications/tool-input-partial",re=l([e("light"),e("dark")]).describe("Color theme preference for the host environment."),f=l([e("inline"),e("fullscreen"),e("pip")]).describe("Display mode for UI presentation."),ae=l([e("--color-background-primary"),e("--color-background-secondary"),e("--color-background-tertiary"),e("--color-background-inverse"),e("--color-background-ghost"),e("--color-background-info"),e("--color-background-danger"),e("--color-background-success"),e("--color-background-warning"),e("--color-background-disabled"),e("--color-text-primary"),e("--color-text-secondary"),e("--color-text-tertiary"),e("--color-text-inverse"),e("--color-text-ghost"),e("--color-text-info"),e("--color-text-danger"),e("--color-text-success"),e("--color-text-warning"),e("--color-text-disabled"),e("--color-border-primary"),e("--color-border-secondary"),e("--color-border-tertiary"),e("--color-border-inverse"),e("--color-border-ghost"),e("--color-border-info"),e("--color-border-danger"),e("--color-border-success"),e("--color-border-warning"),e("--color-border-disabled"),e("--color-ring-primary"),e("--color-ring-secondary"),e("--color-ring-inverse"),e("--color-ring-info"),e("--color-ring-danger"),e("--color-ring-success"),e("--color-ring-warning"),e("--font-sans"),e("--font-mono"),e("--font-weight-normal"),e("--font-weight-medium"),e("--font-weight-semibold"),e("--font-weight-bold"),e("--font-text-xs-size"),e("--font-text-sm-size"),e("--font-text-md-size"),e("--font-text-lg-size"),e("--font-heading-xs-size"),e("--font-heading-sm-size"),e("--font-heading-md-size"),e("--font-heading-lg-size"),e("--font-heading-xl-size"),e("--font-heading-2xl-size"),e("--font-heading-3xl-size"),e("--font-text-xs-line-height"),e("--font-text-sm-line-height"),e("--font-text-md-line-height"),e("--font-text-lg-line-height"),e("--font-heading-xs-line-height"),e("--font-heading-sm-line-height"),e("--font-heading-md-line-height"),e("--font-heading-lg-line-height"),e("--font-heading-xl-line-height"),e("--font-heading-2xl-line-height"),e("--font-heading-3xl-line-height"),e("--border-radius-xs"),e("--border-radius-sm"),e("--border-radius-md"),e("--border-radius-lg"),e("--border-radius-xl"),e("--border-radius-full"),e("--border-width-regular"),e("--shadow-hairline"),e("--shadow-sm"),e("--shadow-md"),e("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),ne=h(ae.describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),l([r(),b()]).describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),le=t({method:e("ui/open-link"),params:t({url:r().describe("URL to open in the host's browser")})});t({isError:p().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();t({isError:p().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();t({isError:p().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();var de=t({method:e("ui/notifications/sandbox-proxy-ready"),params:t({})}),_=t({connectDomains:d(r()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). - Maps to CSP \`connect-src\` directive - Empty or omitted → no network connections (secure default)`),resourceDomains:d(r()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:d(r()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:d(r()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),S=t({camera:t({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:t({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:t({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:t({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),ce=t({method:e("ui/notifications/size-changed"),params:t({width:c().optional().describe("New width in pixels."),height:c().optional().describe("New height in pixels.")})});t({method:e("ui/notifications/tool-input"),params:t({arguments:h(r(),m().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});t({method:e("ui/notifications/tool-input-partial"),params:t({arguments:h(r(),m().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});t({method:e("ui/notifications/tool-cancelled"),params:t({reason:r().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var pe=t({fonts:r().optional()}),he=t({variables:ne.optional().describe("CSS variables for theming the app."),css:pe.optional().describe("CSS blocks that apps can inject.")});t({method:e("ui/resource-teardown"),params:t({})});var ue=h(r(),m()),k=t({text:t({}).optional().describe("Host supports text content blocks."),image:t({}).optional().describe("Host supports image content blocks."),audio:t({}).optional().describe("Host supports audio content blocks."),resource:t({}).optional().describe("Host supports resource content blocks."),resourceLink:t({}).optional().describe("Host supports resource link content blocks."),structuredContent:t({}).optional().describe("Host supports structured content.")}),me=t({method:e("ui/notifications/request-teardown"),params:t({}).optional()}),ge=t({experimental:t({}).optional().describe("Experimental features (structure TBD)."),openLinks:t({}).optional().describe("Host supports opening external URLs."),downloadFile:t({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:t({listChanged:p().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:t({listChanged:p().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:t({}).optional().describe("Host accepts log messages."),sandbox:t({permissions:S.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:_.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:k.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:k.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:t({tools:t({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),be=t({experimental:t({}).optional().describe("Experimental features (structure TBD)."),tools:t({listChanged:p().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:d(f).optional().describe("Display modes the app supports.")}),fe=t({method:e("ui/notifications/initialized"),params:t({}).optional()});t({csp:_.optional().describe("Content Security Policy configuration for UI resources."),permissions:S.optional().describe("Sandbox permissions requested by the UI resource."),domain:r().optional().describe(`Dedicated origin for view sandbox. Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. **Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:p().optional().describe(`Visual boundary preference - true if view prefers a visible border. Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. - \`true\`: request visible border + background - \`false\`: request no visible border + background - omitted: host decides border`)});var P=t({method:e("ui/request-display-mode"),params:t({mode:f.describe("The display mode being requested.")})});t({mode:f.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var ye=l([e("model"),e("app")]).describe("Tool visibility scope - who can access the tool.");t({resourceUri:r().optional(),visibility:d(ye).optional().describe(`Who can access this tool. Default: ["model", "app"] - "model": Tool visible to and callable by the agent - "app": Tool callable by the app from this server only`),csp:v().optional(),permissions:v().optional()});t({mimeTypes:d(r()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var ve=t({method:e("ui/download-file"),params:t({contents:d(l([E,I])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),xe=t({method:e("ui/message"),params:t({role:e("user").describe('Message role, currently only "user" is supported.'),content:d(w).describe("Message content blocks (text, image, etc.).")})});t({method:e("ui/notifications/sandbox-resource-ready"),params:t({html:r().describe("HTML content to load into the inner iframe."),sandbox:r().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:_.optional().describe("CSP configuration from resource metadata."),permissions:S.optional().describe("Sandbox permissions from resource metadata.")})});t({method:e("ui/notifications/tool-result"),params:x.describe("Standard MCP tool execution result.")});var N=t({toolInfo:t({id:z.optional().describe("JSON-RPC id of the tools/call request."),tool:T.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:re.optional().describe("Current color theme preference."),styles:he.optional().describe("Style configuration for theming the app."),displayMode:f.optional().describe("How the UI is currently displayed."),availableDisplayModes:d(f).optional().describe("Display modes the host supports."),containerDimensions:l([t({height:c().describe("Fixed container height in pixels.")}),t({maxHeight:l([c(),b()]).optional().describe("Maximum container height in pixels.")})]).and(l([t({width:c().describe("Fixed container width in pixels.")}),t({maxWidth:l([c(),b()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:r().optional().describe("User's language and region preference in BCP 47 format."),timeZone:r().optional().describe("User's timezone in IANA format."),userAgent:r().optional().describe("Host application identifier."),platform:l([e("web"),e("desktop"),e("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:t({touch:p().optional().describe("Whether the device supports touch input."),hover:p().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:t({top:c().describe("Top safe area inset in pixels."),right:c().describe("Right safe area inset in pixels."),bottom:c().describe("Bottom safe area inset in pixels."),left:c().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();t({method:e("ui/notifications/host-context-changed"),params:N.describe("Partial context update containing only changed fields.")});var we=t({method:e("ui/update-model-context"),params:t({content:d(w).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:h(r(),m().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),Ce=t({method:e("ui/initialize"),params:t({appInfo:C.describe("App identification (name and version)."),appCapabilities:be.describe("Features and capabilities this app provides."),protocolVersion:r().describe("Protocol version this app supports.")})});t({protocolVersion:r().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:C.describe("Host application identification and version."),hostCapabilities:ge.describe("Features and capabilities provided by the host."),hostContext:N.describe("Rich context about the host environment.")}).passthrough();class Ue{eventTarget;eventSource;messageListener;constructor(o=window.parent,s){this.eventTarget=o,this.eventSource=s,this.messageListener=i=>{if(s&&i.source!==this.eventSource){console.debug("Ignoring message from unknown source",i);return}let a=te.safeParse(i.data);a.success?(console.debug("Parsed message",a.data),this.onmessage?.(a.data)):i.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",a.error.message,i):(console.error("Failed to parse message",a.error.message,i),this.onerror?.(Error("Invalid JSON-RPC message received: "+a.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(o,s){o.method!==ie&&console.debug("Sending message",o),this.eventTarget.postMessage(o,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var Re="ui/resourceUri";function _e(n){let o=n._meta?.ui?.resourceUri;if(o===void 0&&(o=n._meta?.[Re]),typeof o=="string"&&o.startsWith("ui://"))return o;if(o!==void 0)throw Error(`Invalid UI resource URI: ${JSON.stringify(o)}`)}var Se=[L];class De extends se{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(o,s)=>{this._baseReplaceRequestHandler(o,(i,a)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${i.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),s(i,a)))};eventSchemas={sizechange:ce,sandboxready:de,initialized:fe,requestteardown:me,loggingmessage:A};constructor(o,s,i,a){super(a),this._client=o,this._hostInfo=s,this._capabilities=i,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=a?.hostContext||{},this.setRequestHandler(Ce,u=>this._oninitialize(u)),this.setRequestHandler(O,(u,g)=>(this.onping?.(u.params,g),{})),this.replaceRequestHandler(P,u=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(o){this.setEventHandler("sizechange",o)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(o){this.setEventHandler("sandboxready",o)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(o){this.setEventHandler("initialized",o)}_onmessage;get onmessage(){return this._onmessage}set onmessage(o){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,o),this._onmessage=o,this.replaceRequestHandler(xe,async(s,i)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(s.params,i)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(o){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,o),this._onopenlink=o,this.replaceRequestHandler(le,async(s,i)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(s.params,i)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(o){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,o),this._ondownloadfile=o,this.replaceRequestHandler(ve,async(s,i)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(s.params,i)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(o){this.setEventHandler("requestteardown",o)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(o){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,o),this._onrequestdisplaymode=o,this.replaceRequestHandler(P,async(s,i)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(s.params,i)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(o){this.setEventHandler("loggingmessage",o)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(o){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,o),this._onupdatemodelcontext=o,this.replaceRequestHandler(we,async(s,i)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(s.params,i)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(o){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,o),this._oncalltool=o,this.replaceRequestHandler(B,async(s,i)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(s.params,i)})}set oncreatesamplingmessage(o){this.setRequestHandler(V,async(s,i)=>o(s.params,i))}sendToolListChanged(o={}){return this.notification({method:"notifications/tools/list_changed",params:o})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(o){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,o),this._onlistresources=o,this.replaceRequestHandler(W,async(s,i)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(s.params,i)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(o){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,o),this._onlistresourcetemplates=o,this.replaceRequestHandler($,async(s,i)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(s.params,i)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(o){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,o),this._onreadresource=o,this.replaceRequestHandler(F,async(s,i)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(s.params,i)})}sendResourceListChanged(o={}){return this.notification({method:"notifications/resources/list_changed",params:o})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(o){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,o),this._onlistprompts=o,this.replaceRequestHandler(K,async(s,i)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(s.params,i)})}sendPromptListChanged(o={}){return this.notification({method:"notifications/prompts/list_changed",params:o})}assertCapabilityForMethod(o){}assertRequestHandlerCapability(o){}assertNotificationCapability(o){}assertTaskCapability(o){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(o){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(o){let s=o.params.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=o.params.appCapabilities,this._appInfo=o.params.appInfo,{protocolVersion:Se.includes(s)?s:L,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(o){let s={},i=!1;for(let a of Object.keys(o)){let u=this._hostContext[a],g=o[a];He(u,g)||(s[a]=g,i=!0)}i&&(this._hostContext=o,this.sendHostContextChange(s))}sendHostContextChange(o){return this.notification({method:"ui/notifications/host-context-changed",params:o})}sendToolInput(o){return this.notification({method:"ui/notifications/tool-input",params:o})}sendToolInputPartial(o){return this.notification({method:"ui/notifications/tool-input-partial",params:o})}sendToolResult(o){return this.notification({method:"ui/notifications/tool-result",params:o})}sendToolCancelled(o){return this.notification({method:"ui/notifications/tool-cancelled",params:o})}sendSandboxResourceReady(o){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:o})}teardownResource(o,s){return this.request({method:"ui/resource-teardown",params:o},ue,s)}sendResourceTeardown=this.teardownResource;callTool(o,s){return this.request({method:"tools/call",params:o},x,s)}listTools(o,s){return this.request({method:"tools/list",params:o},J,s)}async connect(o){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let s=this._client.getServerCapabilities();if(!s)throw Error("Client server capabilities not available");s.tools&&(this.oncalltool=async(i,a)=>this._client.request({method:"tools/call",params:i},x,{signal:a.signal}),s.tools.listChanged&&this._client.setNotificationHandler(Z,i=>this.sendToolListChanged(i.params))),s.resources&&(this.onlistresources=async(i,a)=>this._client.request({method:"resources/list",params:i},j,{signal:a.signal}),this.onlistresourcetemplates=async(i,a)=>this._client.request({method:"resources/templates/list",params:i},Q,{signal:a.signal}),this.onreadresource=async(i,a)=>this._client.request({method:"resources/read",params:i},Y,{signal:a.signal}),s.resources.listChanged&&this._client.setNotificationHandler(G,i=>this.sendResourceListChanged(i.params))),s.prompts&&(this.onlistprompts=async(i,a)=>this._client.request({method:"prompts/list",params:i},X,{signal:a.signal}),s.prompts.listChanged&&this._client.setNotificationHandler(ee,i=>this.sendPromptListChanged(i.params)))}return super.connect(o)}}function He(n,o){return JSON.stringify(n)===JSON.stringify(o)}(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(o,s)=>(typeof require<"u"?require:o)[s]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var qe=l([e("light"),e("dark")]).describe("Color theme preference for the host environment."),y=l([e("inline"),e("fullscreen"),e("pip")]).describe("Display mode for UI presentation."),ke=l([e("--color-background-primary"),e("--color-background-secondary"),e("--color-background-tertiary"),e("--color-background-inverse"),e("--color-background-ghost"),e("--color-background-info"),e("--color-background-danger"),e("--color-background-success"),e("--color-background-warning"),e("--color-background-disabled"),e("--color-text-primary"),e("--color-text-secondary"),e("--color-text-tertiary"),e("--color-text-inverse"),e("--color-text-ghost"),e("--color-text-info"),e("--color-text-danger"),e("--color-text-success"),e("--color-text-warning"),e("--color-text-disabled"),e("--color-border-primary"),e("--color-border-secondary"),e("--color-border-tertiary"),e("--color-border-inverse"),e("--color-border-ghost"),e("--color-border-info"),e("--color-border-danger"),e("--color-border-success"),e("--color-border-warning"),e("--color-border-disabled"),e("--color-ring-primary"),e("--color-ring-secondary"),e("--color-ring-inverse"),e("--color-ring-info"),e("--color-ring-danger"),e("--color-ring-success"),e("--color-ring-warning"),e("--font-sans"),e("--font-mono"),e("--font-weight-normal"),e("--font-weight-medium"),e("--font-weight-semibold"),e("--font-weight-bold"),e("--font-text-xs-size"),e("--font-text-sm-size"),e("--font-text-md-size"),e("--font-text-lg-size"),e("--font-heading-xs-size"),e("--font-heading-sm-size"),e("--font-heading-md-size"),e("--font-heading-lg-size"),e("--font-heading-xl-size"),e("--font-heading-2xl-size"),e("--font-heading-3xl-size"),e("--font-text-xs-line-height"),e("--font-text-sm-line-height"),e("--font-text-md-line-height"),e("--font-text-lg-line-height"),e("--font-heading-xs-line-height"),e("--font-heading-sm-line-height"),e("--font-heading-md-line-height"),e("--font-heading-lg-line-height"),e("--font-heading-xl-line-height"),e("--font-heading-2xl-line-height"),e("--font-heading-3xl-line-height"),e("--border-radius-xs"),e("--border-radius-sm"),e("--border-radius-md"),e("--border-radius-lg"),e("--border-radius-xl"),e("--border-radius-full"),e("--border-width-regular"),e("--shadow-hairline"),e("--shadow-sm"),e("--shadow-md"),e("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Pe=h(ke.describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),l([r(),b()]).describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. Individual style keys are optional - hosts may provide any subset of these values. Values are strings containing CSS values (colors, sizes, font stacks, etc.). Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);t({method:e("ui/open-link"),params:t({url:r().describe("URL to open in the host's browser")})});t({isError:p().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();t({isError:p().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();t({isError:p().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();t({method:e("ui/notifications/sandbox-proxy-ready"),params:t({})});var H=t({connectDomains:d(r()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). - Maps to CSP \`connect-src\` directive - Empty or omitted → no network connections (secure default)`),resourceDomains:d(r()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:d(r()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:d(r()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),q=t({camera:t({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:t({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:t({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:t({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")});t({method:e("ui/notifications/size-changed"),params:t({width:c().optional().describe("New width in pixels."),height:c().optional().describe("New height in pixels.")})});t({method:e("ui/notifications/tool-input"),params:t({arguments:h(r(),m().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});t({method:e("ui/notifications/tool-input-partial"),params:t({arguments:h(r(),m().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});t({method:e("ui/notifications/tool-cancelled"),params:t({reason:r().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var Me=t({fonts:r().optional()}),Ee=t({variables:Pe.optional().describe("CSS variables for theming the app."),css:Me.optional().describe("CSS blocks that apps can inject.")});t({method:e("ui/resource-teardown"),params:t({})});h(r(),m());var M=t({text:t({}).optional().describe("Host supports text content blocks."),image:t({}).optional().describe("Host supports image content blocks."),audio:t({}).optional().describe("Host supports audio content blocks."),resource:t({}).optional().describe("Host supports resource content blocks."),resourceLink:t({}).optional().describe("Host supports resource link content blocks."),structuredContent:t({}).optional().describe("Host supports structured content.")});t({method:e("ui/notifications/request-teardown"),params:t({}).optional()});var Ie=t({experimental:t({}).optional().describe("Experimental features (structure TBD)."),openLinks:t({}).optional().describe("Host supports opening external URLs."),downloadFile:t({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:t({listChanged:p().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:t({listChanged:p().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:t({}).optional().describe("Host accepts log messages."),sandbox:t({permissions:q.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:H.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:M.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:M.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:t({tools:t({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Te=t({experimental:t({}).optional().describe("Experimental features (structure TBD)."),tools:t({listChanged:p().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:d(y).optional().describe("Display modes the app supports.")});t({method:e("ui/notifications/initialized"),params:t({}).optional()});t({csp:H.optional().describe("Content Security Policy configuration for UI resources."),permissions:q.optional().describe("Sandbox permissions requested by the UI resource."),domain:r().optional().describe(`Dedicated origin for view sandbox. Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. **Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:p().optional().describe(`Visual boundary preference - true if view prefers a visible border. Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. - \`true\`: request visible border + background - \`false\`: request no visible border + background - omitted: host decides border`)});t({method:e("ui/request-display-mode"),params:t({mode:y.describe("The display mode being requested.")})});t({mode:y.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var ze=l([e("model"),e("app")]).describe("Tool visibility scope - who can access the tool.");t({resourceUri:r().optional(),visibility:d(ze).optional().describe(`Who can access this tool. Default: ["model", "app"] - "model": Tool visible to and callable by the agent - "app": Tool callable by the app from this server only`),csp:v().optional(),permissions:v().optional()});t({mimeTypes:d(r()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});t({method:e("ui/download-file"),params:t({contents:d(l([E,I])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});t({method:e("ui/message"),params:t({role:e("user").describe('Message role, currently only "user" is supported.'),content:d(w).describe("Message content blocks (text, image, etc.).")})});t({method:e("ui/notifications/sandbox-resource-ready"),params:t({html:r().describe("HTML content to load into the inner iframe."),sandbox:r().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:H.optional().describe("CSP configuration from resource metadata."),permissions:q.optional().describe("Sandbox permissions from resource metadata.")})});t({method:e("ui/notifications/tool-result"),params:x.describe("Standard MCP tool execution result.")});var U=t({toolInfo:t({id:z.optional().describe("JSON-RPC id of the tools/call request."),tool:T.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:qe.optional().describe("Current color theme preference."),styles:Ee.optional().describe("Style configuration for theming the app."),displayMode:y.optional().describe("How the UI is currently displayed."),availableDisplayModes:d(y).optional().describe("Display modes the host supports."),containerDimensions:l([t({height:c().describe("Fixed container height in pixels.")}),t({maxHeight:l([c(),b()]).optional().describe("Maximum container height in pixels.")})]).and(l([t({width:c().describe("Fixed container width in pixels.")}),t({maxWidth:l([c(),b()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:r().optional().describe("User's language and region preference in BCP 47 format."),timeZone:r().optional().describe("User's timezone in IANA format."),userAgent:r().optional().describe("Host application identifier."),platform:l([e("web"),e("desktop"),e("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:t({touch:p().optional().describe("Whether the device supports touch input."),hover:p().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:t({top:c().describe("Top safe area inset in pixels."),right:c().describe("Right safe area inset in pixels."),bottom:c().describe("Bottom safe area inset in pixels."),left:c().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();t({method:e("ui/notifications/host-context-changed"),params:U.describe("Partial context update containing only changed fields.")});t({method:e("ui/update-model-context"),params:t({content:d(w).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:h(r(),m().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});t({method:e("ui/initialize"),params:t({appInfo:C.describe("App identification (name and version)."),appCapabilities:Te.describe("Features and capabilities this app provides."),protocolVersion:r().describe("Protocol version this app supports.")})});t({protocolVersion:r().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:C.describe("Host application identification and version."),hostCapabilities:Ie.describe("Features and capabilities provided by the host."),hostContext:U.describe("Rich context about the host environment.")}).passthrough();function Ae(){let n=document.documentElement.getAttribute("data-theme");return n==="dark"||n==="light"?n:document.documentElement.classList.contains("dark")?"dark":"light"}const Oe={view:{minHeight:400,maxHeight:800},fullscreen:{minHeight:600,maxHeight:1200}};function Be(n){if(!(n==null||typeof n!="object"))try{return _e({_meta:n})}catch{return}}export{Ae as C,De as D,Ue as E,Oe as M,Be as g};