import{bV as p,bp as t,aJ as y,W as a,bW as q,T as s,aK as f,aH as u,U as m,ba as x,bX as O,bY as fe,bZ as ge,b_ as $,b$ as j,c0 as be,c1 as ye,c2 as B,c3 as Se,c4 as _e,c5 as He,c6 as Me,c7 as ke,c8 as Pe,c9 as qe,ca as Te,cb as Ie,cc as Ee,cd as Le,ce as ze,cf as Ue,cg as Ae,ch as De,ci as Ne,cj as Oe,r as te,e as V,j as b,ck as je,cl as $e,t as Be,c as oe}from"./index-DjCrtoJM.js";import{P as Ve}from"./use-mcp-client-Wf5qUXFF.js";const le=["default-src 'none'","script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'","style-src 'unsafe-inline'","img-src * data: blob:","media-src * data: blob:","font-src data:","connect-src 'none'","frame-src 'none'","worker-src blob:","form-action 'none'","base-uri 'none'"].join("; ");function We(r,e={}){const i=`<meta http-equiv="Content-Security-Policy" content="${Ke(e)}">`,n=/<head(\s[^>]*)?>|<HEAD(\s[^>]*)?>/i,l=r.match(n);if(l){const g=(l.index??0)+l[0].length;return r.slice(0,g)+`
`+i+r.slice(g)}const c=/<html(\s[^>]*)?>|<HTML(\s[^>]*)?>/i,d=r.match(c);if(d){const g=(d.index??0)+d[0].length;return r.slice(0,g)+`
<head>
`+i+`
</head>`+r.slice(g)}const h=/<!DOCTYPE[^>]*>/i,v=r.match(h);if(v){const g=(v.index??0)+v[0].length;return r.slice(0,g)+`
<head>
`+i+`
</head>`+r.slice(g)}return`<head>
`+i+`
</head>
`+r}const Fe=/^https?:\/\/(\*\.)?[a-zA-Z0-9._-]+(:\d+)?\/?$/;function N(r){return!r||r.length===0?[]:r.filter(e=>Fe.test(e))}function Ke(r){if(r.csp)return r.csp;const e=r.resourceCsp;if(!e)return le;const o=N(e.resourceDomains),i=N(e.connectDomains),n=N(e.frameDomains),l=N(e.baseUriDomains),c=o.length>0,d=i.length>0,h=n.length>0,v=l.length>0;if(!c&&!d&&!h&&!v)return le;const g=o.join(" ");return["default-src 'none'",c?`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${g}`:"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",c?`style-src 'unsafe-inline' ${g}`:"style-src 'unsafe-inline'",c?`img-src * data: blob: ${g}`:"img-src * data: blob:",c?`media-src * data: blob: ${g}`:"media-src * data: blob:",c?`font-src data: ${g}`:"font-src data:",d?`connect-src ${i.join(" ")}`:"connect-src 'none'",h?`frame-src ${n.join(" ")}`:"frame-src 'none'","worker-src blob:","form-action 'none'",v?`base-uri ${l.join(" ")}`:"base-uri 'none'"].join("; ")}(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});class Ze extends Ve{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(e,o){}_ensureEventSlot(e){let o=this._eventSlots.get(e);if(!o){let i=this.eventSchemas[e];if(!i)throw Error(`Unknown event: ${String(e)}`);o={listeners:[]},this._eventSlots.set(e,o);let n=i.shape.method.value;this._registeredMethods.add(n);let l=o;super.setNotificationHandler(i,c=>{let d=c.params;this.onEventDispatch(e,d),l.onHandler?.(d);for(let h of[...l.listeners])h(d)})}return o}setEventHandler(e,o){let i=this._ensureEventSlot(e);i.onHandler&&o&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),i.onHandler=o}getEventHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,o){this._ensureEventSlot(e).listeners.push(o)}removeEventListener(e,o){let i=this._eventSlots.get(e);if(!i)return;let n=i.listeners.indexOf(o);n!==-1&&i.listeners.splice(n,1)}setRequestHandler=(e,o)=>{this._assertMethodNotRegistered(e,"setRequestHandler"),super.setRequestHandler(e,o)};setNotificationHandler=(e,o)=>{this._assertMethodNotRegistered(e,"setNotificationHandler"),super.setNotificationHandler(e,o)};warnIfRequestHandlerReplaced(e,o,i){o&&i&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(e,o)=>{let i=e.shape.method.value;this._registeredMethods.add(i),super.setRequestHandler(e,o)};_assertMethodNotRegistered(e,o){let i=e.shape.method.value;if(this._registeredMethods.has(i))throw Error(`Handler for "${i}" already registered (via ${o}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(i)}}var ve="2026-01-26",Je="ui/notifications/tool-input-partial",Ye=p([t("light"),t("dark")]).describe("Color theme preference for the host environment."),T=p([t("inline"),t("fullscreen"),t("pip")]).describe("Display mode for UI presentation."),Qe=p([t("--color-background-primary"),t("--color-background-secondary"),t("--color-background-tertiary"),t("--color-background-inverse"),t("--color-background-ghost"),t("--color-background-info"),t("--color-background-danger"),t("--color-background-success"),t("--color-background-warning"),t("--color-background-disabled"),t("--color-text-primary"),t("--color-text-secondary"),t("--color-text-tertiary"),t("--color-text-inverse"),t("--color-text-ghost"),t("--color-text-info"),t("--color-text-danger"),t("--color-text-success"),t("--color-text-warning"),t("--color-text-disabled"),t("--color-border-primary"),t("--color-border-secondary"),t("--color-border-tertiary"),t("--color-border-inverse"),t("--color-border-ghost"),t("--color-border-info"),t("--color-border-danger"),t("--color-border-success"),t("--color-border-warning"),t("--color-border-disabled"),t("--color-ring-primary"),t("--color-ring-secondary"),t("--color-ring-inverse"),t("--color-ring-info"),t("--color-ring-danger"),t("--color-ring-success"),t("--color-ring-warning"),t("--font-sans"),t("--font-mono"),t("--font-weight-normal"),t("--font-weight-medium"),t("--font-weight-semibold"),t("--font-weight-bold"),t("--font-text-xs-size"),t("--font-text-sm-size"),t("--font-text-md-size"),t("--font-text-lg-size"),t("--font-heading-xs-size"),t("--font-heading-sm-size"),t("--font-heading-md-size"),t("--font-heading-lg-size"),t("--font-heading-xl-size"),t("--font-heading-2xl-size"),t("--font-heading-3xl-size"),t("--font-text-xs-line-height"),t("--font-text-sm-line-height"),t("--font-text-md-line-height"),t("--font-text-lg-line-height"),t("--font-heading-xs-line-height"),t("--font-heading-sm-line-height"),t("--font-heading-md-line-height"),t("--font-heading-lg-line-height"),t("--font-heading-xl-line-height"),t("--font-heading-2xl-line-height"),t("--font-heading-3xl-line-height"),t("--border-radius-xs"),t("--border-radius-sm"),t("--border-radius-md"),t("--border-radius-lg"),t("--border-radius-xl"),t("--border-radius-full"),t("--border-width-regular"),t("--shadow-hairline"),t("--shadow-sm"),t("--shadow-md"),t("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Ge=y(Qe.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.`),p([a(),q()]).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.`),Xe=s({method:t("ui/open-link"),params:s({url:a().describe("URL to open in the host's browser")})});s({isError:f().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();s({isError:f().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();s({isError:f().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();var et=s({method:t("ui/notifications/sandbox-proxy-ready"),params:s({})}),ie=s({connectDomains:u(a()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).

- Maps to CSP \`connect-src\` directive
- Empty or omitted → no network connections (secure default)`),resourceDomains:u(a()).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:u(a()).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:u(a()).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'`)")}),re=s({camera:s({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:s({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:s({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:s({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),tt=s({method:t("ui/notifications/size-changed"),params:s({width:m().optional().describe("New width in pixels."),height:m().optional().describe("New height in pixels.")})});s({method:t("ui/notifications/tool-input"),params:s({arguments:y(a(),x().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});s({method:t("ui/notifications/tool-input-partial"),params:s({arguments:y(a(),x().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});s({method:t("ui/notifications/tool-cancelled"),params:s({reason:a().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var ot=s({fonts:a().optional()}),st=s({variables:Ge.optional().describe("CSS variables for theming the app."),css:ot.optional().describe("CSS blocks that apps can inject.")});s({method:t("ui/resource-teardown"),params:s({})});var it=y(a(),x()),ce=s({text:s({}).optional().describe("Host supports text content blocks."),image:s({}).optional().describe("Host supports image content blocks."),audio:s({}).optional().describe("Host supports audio content blocks."),resource:s({}).optional().describe("Host supports resource content blocks."),resourceLink:s({}).optional().describe("Host supports resource link content blocks."),structuredContent:s({}).optional().describe("Host supports structured content.")}),rt=s({method:t("ui/notifications/request-teardown"),params:s({}).optional()}),nt=s({experimental:s({}).optional().describe("Experimental features (structure TBD)."),openLinks:s({}).optional().describe("Host supports opening external URLs."),downloadFile:s({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:s({listChanged:f().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:s({listChanged:f().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:s({}).optional().describe("Host accepts log messages."),sandbox:s({permissions:re.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:ie.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:ce.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:ce.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:s({tools:s({}).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.")}),at=s({experimental:s({}).optional().describe("Experimental features (structure TBD)."),tools:s({listChanged:f().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:u(T).optional().describe("Display modes the app supports.")}),lt=s({method:t("ui/notifications/initialized"),params:s({}).optional()});s({csp:ie.optional().describe("Content Security Policy configuration for UI resources."),permissions:re.optional().describe("Sandbox permissions requested by the UI resource."),domain:a().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:f().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 de=s({method:t("ui/request-display-mode"),params:s({mode:T.describe("The display mode being requested.")})});s({mode:T.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var ct=p([t("model"),t("app")]).describe("Tool visibility scope - who can access the tool.");s({resourceUri:a().optional(),visibility:u(ct).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:O().optional(),permissions:O().optional()});s({mimeTypes:u(a()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var dt=s({method:t("ui/download-file"),params:s({contents:u(p([fe,ge])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),pt=s({method:t("ui/message"),params:s({role:t("user").describe('Message role, currently only "user" is supported.'),content:u($).describe("Message content blocks (text, image, etc.).")})});s({method:t("ui/notifications/sandbox-resource-ready"),params:s({html:a().describe("HTML content to load into the inner iframe."),sandbox:a().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:ie.optional().describe("CSP configuration from resource metadata."),permissions:re.optional().describe("Sandbox permissions from resource metadata.")})});s({method:t("ui/notifications/tool-result"),params:j.describe("Standard MCP tool execution result.")});var xe=s({toolInfo:s({id:ye.optional().describe("JSON-RPC id of the tools/call request."),tool:be.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Ye.optional().describe("Current color theme preference."),styles:st.optional().describe("Style configuration for theming the app."),displayMode:T.optional().describe("How the UI is currently displayed."),availableDisplayModes:u(T).optional().describe("Display modes the host supports."),containerDimensions:p([s({height:m().describe("Fixed container height in pixels.")}),s({maxHeight:p([m(),q()]).optional().describe("Maximum container height in pixels.")})]).and(p([s({width:m().describe("Fixed container width in pixels.")}),s({maxWidth:p([m(),q()]).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:a().optional().describe("User's language and region preference in BCP 47 format."),timeZone:a().optional().describe("User's timezone in IANA format."),userAgent:a().optional().describe("Host application identifier."),platform:p([t("web"),t("desktop"),t("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:s({touch:f().optional().describe("Whether the device supports touch input."),hover:f().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:s({top:m().describe("Top safe area inset in pixels."),right:m().describe("Right safe area inset in pixels."),bottom:m().describe("Bottom safe area inset in pixels."),left:m().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();s({method:t("ui/notifications/host-context-changed"),params:xe.describe("Partial context update containing only changed fields.")});var ut=s({method:t("ui/update-model-context"),params:s({content:u($).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:y(a(),x().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ht=s({method:t("ui/initialize"),params:s({appInfo:B.describe("App identification (name and version)."),appCapabilities:at.describe("Features and capabilities this app provides."),protocolVersion:a().describe("Protocol version this app supports.")})});s({protocolVersion:a().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:B.describe("Host application identification and version."),hostCapabilities:nt.describe("Features and capabilities provided by the host."),hostContext:xe.describe("Rich context about the host environment.")}).passthrough();class mt{eventTarget;eventSource;messageListener;constructor(e=window.parent,o){this.eventTarget=e,this.eventSource=o,this.messageListener=i=>{if(o&&i.source!==this.eventSource){console.debug("Ignoring message from unknown source",i);return}let n=Oe.safeParse(i.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):i.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,i):(console.error("Failed to parse message",n.error.message,i),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,o){e.method!==Je&&console.debug("Sending message",e),this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ft="ui/resourceUri";function gt(r){let e=r._meta?.ui?.resourceUri;if(e===void 0&&(e=r._meta?.[ft]),typeof e=="string"&&e.startsWith("ui://"))return e;if(e!==void 0)throw Error(`Invalid UI resource URI: ${JSON.stringify(e)}`)}var bt=[ve];class yt extends Ze{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(e,o)=>{this._baseReplaceRequestHandler(e,(i,n)=>(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.`),o(i,n)))};eventSchemas={sizechange:tt,sandboxready:et,initialized:lt,requestteardown:rt,loggingmessage:Se};constructor(e,o,i,n){super(n),this._client=e,this._hostInfo=o,this._capabilities=i,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=n?.hostContext||{},this.setRequestHandler(ht,l=>this._oninitialize(l)),this.setRequestHandler(_e,(l,c)=>(this.onping?.(l.params,c),{})),this.replaceRequestHandler(de,l=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler(pt,async(o,i)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o.params,i)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(Xe,async(o,i)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o.params,i)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(dt,async(o,i)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o.params,i)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler(de,async(o,i)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o.params,i)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler(ut,async(o,i)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o.params,i)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(He,async(o,i)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,i)})}set oncreatesamplingmessage(e){this.setRequestHandler(Me,async(o,i)=>e(o.params,i))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler(ke,async(o,i)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,i)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(Pe,async(o,i)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,i)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(qe,async(o,i)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,i)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler(Te,async(o,i)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,i)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}assertTaskCapability(e){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(e){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(e){let o=e.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=e.params.appCapabilities,this._appInfo=e.params.appInfo,{protocolVersion:bt.includes(o)?o:ve,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let o={},i=!1;for(let n of Object.keys(e)){let l=this._hostContext[n],c=e[n];vt(l,c)||(o[n]=c,i=!0)}i&&(this._hostContext=e,this.sendHostContextChange(o))}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,o){return this.request({method:"ui/resource-teardown",params:e},it,o)}sendResourceTeardown=this.teardownResource;callTool(e,o){return this.request({method:"tools/call",params:e},j,o)}listTools(e,o){return this.request({method:"tools/list",params:e},Ie,o)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(i,n)=>this._client.request({method:"tools/call",params:i},j,{signal:n.signal}),o.tools.listChanged&&this._client.setNotificationHandler(Ee,i=>this.sendToolListChanged(i.params))),o.resources&&(this.onlistresources=async(i,n)=>this._client.request({method:"resources/list",params:i},Le,{signal:n.signal}),this.onlistresourcetemplates=async(i,n)=>this._client.request({method:"resources/templates/list",params:i},ze,{signal:n.signal}),this.onreadresource=async(i,n)=>this._client.request({method:"resources/read",params:i},Ue,{signal:n.signal}),o.resources.listChanged&&this._client.setNotificationHandler(Ae,i=>this.sendResourceListChanged(i.params))),o.prompts&&(this.onlistprompts=async(i,n)=>this._client.request({method:"prompts/list",params:i},De,{signal:n.signal}),o.prompts.listChanged&&this._client.setNotificationHandler(Ne,i=>this.sendPromptListChanged(i.params)))}return super.connect(e)}}function vt(r,e){return JSON.stringify(r)===JSON.stringify(e)}(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var xt=p([t("light"),t("dark")]).describe("Color theme preference for the host environment."),I=p([t("inline"),t("fullscreen"),t("pip")]).describe("Display mode for UI presentation."),wt=p([t("--color-background-primary"),t("--color-background-secondary"),t("--color-background-tertiary"),t("--color-background-inverse"),t("--color-background-ghost"),t("--color-background-info"),t("--color-background-danger"),t("--color-background-success"),t("--color-background-warning"),t("--color-background-disabled"),t("--color-text-primary"),t("--color-text-secondary"),t("--color-text-tertiary"),t("--color-text-inverse"),t("--color-text-ghost"),t("--color-text-info"),t("--color-text-danger"),t("--color-text-success"),t("--color-text-warning"),t("--color-text-disabled"),t("--color-border-primary"),t("--color-border-secondary"),t("--color-border-tertiary"),t("--color-border-inverse"),t("--color-border-ghost"),t("--color-border-info"),t("--color-border-danger"),t("--color-border-success"),t("--color-border-warning"),t("--color-border-disabled"),t("--color-ring-primary"),t("--color-ring-secondary"),t("--color-ring-inverse"),t("--color-ring-info"),t("--color-ring-danger"),t("--color-ring-success"),t("--color-ring-warning"),t("--font-sans"),t("--font-mono"),t("--font-weight-normal"),t("--font-weight-medium"),t("--font-weight-semibold"),t("--font-weight-bold"),t("--font-text-xs-size"),t("--font-text-sm-size"),t("--font-text-md-size"),t("--font-text-lg-size"),t("--font-heading-xs-size"),t("--font-heading-sm-size"),t("--font-heading-md-size"),t("--font-heading-lg-size"),t("--font-heading-xl-size"),t("--font-heading-2xl-size"),t("--font-heading-3xl-size"),t("--font-text-xs-line-height"),t("--font-text-sm-line-height"),t("--font-text-md-line-height"),t("--font-text-lg-line-height"),t("--font-heading-xs-line-height"),t("--font-heading-sm-line-height"),t("--font-heading-md-line-height"),t("--font-heading-lg-line-height"),t("--font-heading-xl-line-height"),t("--font-heading-2xl-line-height"),t("--font-heading-3xl-line-height"),t("--border-radius-xs"),t("--border-radius-sm"),t("--border-radius-md"),t("--border-radius-lg"),t("--border-radius-xl"),t("--border-radius-full"),t("--border-width-regular"),t("--shadow-hairline"),t("--shadow-sm"),t("--shadow-md"),t("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Ct=y(wt.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.`),p([a(),q()]).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.`);s({method:t("ui/open-link"),params:s({url:a().describe("URL to open in the host's browser")})});s({isError:f().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();s({isError:f().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();s({isError:f().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();s({method:t("ui/notifications/sandbox-proxy-ready"),params:s({})});var ne=s({connectDomains:u(a()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).

- Maps to CSP \`connect-src\` directive
- Empty or omitted → no network connections (secure default)`),resourceDomains:u(a()).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:u(a()).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:u(a()).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'`)")}),ae=s({camera:s({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:s({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:s({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:s({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")});s({method:t("ui/notifications/size-changed"),params:s({width:m().optional().describe("New width in pixels."),height:m().optional().describe("New height in pixels.")})});s({method:t("ui/notifications/tool-input"),params:s({arguments:y(a(),x().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});s({method:t("ui/notifications/tool-input-partial"),params:s({arguments:y(a(),x().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});s({method:t("ui/notifications/tool-cancelled"),params:s({reason:a().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var Rt=s({fonts:a().optional()}),St=s({variables:Ct.optional().describe("CSS variables for theming the app."),css:Rt.optional().describe("CSS blocks that apps can inject.")});s({method:t("ui/resource-teardown"),params:s({})});y(a(),x());var pe=s({text:s({}).optional().describe("Host supports text content blocks."),image:s({}).optional().describe("Host supports image content blocks."),audio:s({}).optional().describe("Host supports audio content blocks."),resource:s({}).optional().describe("Host supports resource content blocks."),resourceLink:s({}).optional().describe("Host supports resource link content blocks."),structuredContent:s({}).optional().describe("Host supports structured content.")});s({method:t("ui/notifications/request-teardown"),params:s({}).optional()});var _t=s({experimental:s({}).optional().describe("Experimental features (structure TBD)."),openLinks:s({}).optional().describe("Host supports opening external URLs."),downloadFile:s({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:s({listChanged:f().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:s({listChanged:f().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:s({}).optional().describe("Host accepts log messages."),sandbox:s({permissions:ae.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:ne.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:pe.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:pe.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:s({tools:s({}).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.")}),Ht=s({experimental:s({}).optional().describe("Experimental features (structure TBD)."),tools:s({listChanged:f().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:u(I).optional().describe("Display modes the app supports.")});s({method:t("ui/notifications/initialized"),params:s({}).optional()});s({csp:ne.optional().describe("Content Security Policy configuration for UI resources."),permissions:ae.optional().describe("Sandbox permissions requested by the UI resource."),domain:a().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:f().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`)});s({method:t("ui/request-display-mode"),params:s({mode:I.describe("The display mode being requested.")})});s({mode:I.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var Mt=p([t("model"),t("app")]).describe("Tool visibility scope - who can access the tool.");s({resourceUri:a().optional(),visibility:u(Mt).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:O().optional(),permissions:O().optional()});s({mimeTypes:u(a()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});s({method:t("ui/download-file"),params:s({contents:u(p([fe,ge])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});s({method:t("ui/message"),params:s({role:t("user").describe('Message role, currently only "user" is supported.'),content:u($).describe("Message content blocks (text, image, etc.).")})});s({method:t("ui/notifications/sandbox-resource-ready"),params:s({html:a().describe("HTML content to load into the inner iframe."),sandbox:a().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:ne.optional().describe("CSP configuration from resource metadata."),permissions:ae.optional().describe("Sandbox permissions from resource metadata.")})});s({method:t("ui/notifications/tool-result"),params:j.describe("Standard MCP tool execution result.")});var we=s({toolInfo:s({id:ye.optional().describe("JSON-RPC id of the tools/call request."),tool:be.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:xt.optional().describe("Current color theme preference."),styles:St.optional().describe("Style configuration for theming the app."),displayMode:I.optional().describe("How the UI is currently displayed."),availableDisplayModes:u(I).optional().describe("Display modes the host supports."),containerDimensions:p([s({height:m().describe("Fixed container height in pixels.")}),s({maxHeight:p([m(),q()]).optional().describe("Maximum container height in pixels.")})]).and(p([s({width:m().describe("Fixed container width in pixels.")}),s({maxWidth:p([m(),q()]).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:a().optional().describe("User's language and region preference in BCP 47 format."),timeZone:a().optional().describe("User's timezone in IANA format."),userAgent:a().optional().describe("Host application identifier."),platform:p([t("web"),t("desktop"),t("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:s({touch:f().optional().describe("Whether the device supports touch input."),hover:f().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:s({top:m().describe("Top safe area inset in pixels."),right:m().describe("Right safe area inset in pixels."),bottom:m().describe("Bottom safe area inset in pixels."),left:m().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();s({method:t("ui/notifications/host-context-changed"),params:we.describe("Partial context update containing only changed fields.")});s({method:t("ui/update-model-context"),params:s({content:u($).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:y(a(),x().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});s({method:t("ui/initialize"),params:s({appInfo:B.describe("App identification (name and version)."),appCapabilities:Ht.describe("Features and capabilities this app provides."),protocolVersion:a().describe("Protocol version this app supports.")})});s({protocolVersion:a().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:B.describe("Host application identification and version."),hostCapabilities:_t.describe("Features and capabilities provided by the host."),hostContext:we.describe("Rich context about the host environment.")}).passthrough();function kt(){let r=document.documentElement.getAttribute("data-theme");return r==="dark"||r==="light"?r:document.documentElement.classList.contains("dark")?"dark":"light"}const Pt=[["--background","--color-background-primary"],["--muted","--color-background-secondary"],["--accent","--color-background-tertiary"],["--destructive","--color-background-danger"],["--success","--color-background-success"],["--warning","--color-background-warning"],["--foreground","--color-text-primary"],["--muted-foreground","--color-text-secondary"],["--accent-foreground","--color-text-tertiary"],["--destructive-foreground","--color-text-danger"],["--success-foreground","--color-text-success"],["--warning-foreground","--color-text-warning"],["--border","--color-border-primary"],["--input","--color-border-secondary"],["--ring","--color-ring-primary"],["--font-sans","--font-sans"],["--font-mono","--font-mono"],["--font-weight-normal","--font-weight-normal"],["--font-weight-medium","--font-weight-medium"],["--font-weight-semibold","--font-weight-semibold"],["--font-weight-bold","--font-weight-bold"],["--radius","--border-radius-md"],["--default-border-width","--border-width-regular"],["--shadow-sm","--shadow-sm"],["--shadow-md","--shadow-md"],["--shadow-lg","--shadow-lg"]];function qt(){if(typeof document>"u")return{};const r=getComputedStyle(document.documentElement),e={};for(const[o,i]of Pt){const n=r.getPropertyValue(o).trim();n&&(e[i]=n)}return{variables:e}}const Tt={name:"MCP Mesh",version:"1.0.0"},It={openLinks:{},serverTools:{},serverResources:{},logging:{},message:{},downloadFile:{},updateModelContext:{text:{}}},Et=15e3;function Lt(){return typeof navigator>"u"?"en":navigator.language??"en"}function zt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function Ut(){return typeof navigator>"u"?"web":/Mobi|Android/i.test(navigator.userAgent)?"mobile":"web"}function ue(r,e,o,i){return{theme:kt(),styles:qt(),displayMode:r,availableDisplayModes:["inline","fullscreen"],locale:Lt(),timeZone:zt(),platform:Ut(),...e!=null&&{toolInfo:e},...o!=null&&{containerDimensions:{maxHeight:o}},...i!=null&&{orgId:i}}}const se=new Set;let he=!1;function At(){if(he||typeof document>"u")return;he=!0;const r=()=>se.forEach(e=>e());new MutationObserver(r).observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",r)}function Dt(r){return se.add(r),At(),()=>se.delete(r)}class Nt{bridge=null;timeout=null;disposed=!1;unsubTheme=null;snapshot;listeners=new Set;config;constructor(e){this.config=e,this.snapshot=Object.freeze({height:e.minHeight,isLoading:!0,error:null})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.snapshot;updateConfig(e){const o=this.config;this.config=e,!(!this.bridge||this.disposed)&&(e.displayMode!==o.displayMode&&this.pushHostContext(),e.toolInput!==o.toolInput&&e.toolInput!=null&&this.bridge.sendToolInput({arguments:e.toolInput}),e.toolResult!==o.toolResult&&e.toolResult!=null&&this.bridge.sendToolResult(e.toolResult))}pushHostContext(){if(!this.bridge||this.disposed)return;const{displayMode:e,maxHeight:o,toolInfo:i,orgId:n}=this.config;this.bridge.setHostContext(ue(e,i,o,n))}set(e){const o=this.snapshot,i={...o,...e};if(!(i.height===o.height&&i.isLoading===o.isLoading&&i.error===o.error)){this.snapshot=Object.freeze(i);for(const n of this.listeners)n()}}teardown(){(this.bridge||this.timeout||this.unsubTheme)&&this.config.onTeardown?.(),this.disposed=!0,this.unsubTheme?.(),this.unsubTheme=null,this.bridge&&(this.bridge.teardownResource({}).catch(()=>{}),this.bridge.close(),this.bridge=null),this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}attach=e=>{if(this.teardown(),this.disposed=!1,this.set({height:this.config.minHeight,isLoading:!0,error:null}),!!e){e.onerror=()=>{this.disposed||this.set({error:"Failed to load app",isLoading:!1})};try{const{client:o,displayMode:i,maxHeight:n,toolInfo:l,orgId:c}=this.config,d=ue(i,l,n,c),h=new yt(o,Tt,It,{hostContext:d});this.bridge=h,this.registerHandlers(h),this.startInitTimeout(),this.registerInitHandler(h),this.connectTransport(h,e),this.unsubTheme=Dt(()=>this.pushHostContext())}catch(o){this.clearTimeout(),console.error("Failed to create AppBridge:",o),this.set({error:o instanceof Error?o.message:"Unknown error",isLoading:!1})}}};registerHandlers(e){e.onopenlink=async({url:o})=>{let i=null;try{i=new URL(o)}catch{}if(!i||!["http:","https:"].includes(i.protocol))throw new Error("Only http and https URLs are allowed");return window.open(o,"_blank","noopener,noreferrer"),{}},e.onmessage=async o=>(this.config.onMessage?.(o),{}),e.onupdatemodelcontext=async o=>(this.config.onUpdateModelContext?.(o),{}),e.onsizechange=({height:o})=>{if(!this.disposed&&o!=null){const{minHeight:i,maxHeight:n}=this.config;this.set({height:Math.max(i,Math.min(n,o))})}},e.onloggingmessage=({level:o,data:i})=>{console[o==="error"?"error":"debug"](`[MCP App ${this.config.toolInfo?.tool.name??"unknown"}]`,i)},e.onrequestdisplaymode=async({mode:o})=>({mode:this.config.onRequestDisplayMode?await this.config.onRequestDisplayMode(o):this.config.displayMode}),e.ondownloadfile=async({contents:o})=>{for(const i of o)if(i.type==="resource"){const n=i.resource,l="blob"in n?new Blob([Uint8Array.from(atob(n.blob),h=>h.charCodeAt(0))],{type:n.mimeType}):new Blob([n.text??""],{type:n.mimeType}),c=URL.createObjectURL(l),d=document.createElement("a");d.href=c,d.download=n.uri.split("/").pop()??"download",d.click(),URL.revokeObjectURL(c)}else i.type==="resource_link"&&window.open(i.uri,"_blank");return{}}}registerInitHandler(e){e.oninitialized=()=>{if(this.disposed)return;this.clearTimeout(),this.set({isLoading:!1});const{toolInput:o,toolResult:i}=this.config;o!=null&&e.sendToolInput({arguments:o}),i!=null&&e.sendToolResult(i)}}startInitTimeout(){this.timeout=setTimeout(()=>{this.disposed||this.set({error:"App took too long to load",isLoading:!1})},Et)}clearTimeout(){this.timeout&&(globalThis.clearTimeout(this.timeout),this.timeout=null)}connectTransport(e,o){if(!o.contentWindow){console.warn("iframe contentWindow not yet available");return}const i=new mt(o.contentWindow,o.contentWindow);e.connect(i).catch(n=>{this.disposed||(this.clearTimeout(),console.error("AppBridge connect failed:",n),this.set({error:n instanceof Error?n.message:"Connection failed",isLoading:!1}))})}}function Ot(r){const e=te.useRef(new Nt(r));te.useEffect(()=>{e.current.updateConfig(r)},[r]);const{height:o,isLoading:i,error:n}=te.useSyncExternalStore(e.current.subscribe,e.current.getSnapshot);return{height:o,isLoading:i,error:n,iframeRef:e.current.attach}}const me=new Set;function jt(r){const e=r?.contents?.[0];return!e||!("text"in e)||!e.text?null:We(e.text,{resourceCsp:e._meta?.ui?.csp})}function Ce(r){const e=V.c(39),{html:o,uri:i,orgId:n,toolInfo:l,toolInput:c,toolResult:d,displayMode:h,minHeight:v,maxHeight:g,client:E,onMessage:W,onUpdateModelContext:F,onTeardown:K,onRequestDisplayMode:Z,className:C}=r,w=h===void 0?"inline":h,J=v===void 0?150:v,Y=g===void 0?600:g;i&&!me.has(i)&&(me.add(i),Be("mcp_app_opened",{resource_uri:i,display_mode:w,tool_name:l?.tool?.name??null}));let L;e[0]!==E||e[1]!==w||e[2]!==Y||e[3]!==J||e[4]!==W||e[5]!==Z||e[6]!==K||e[7]!==F||e[8]!==n||e[9]!==l||e[10]!==c||e[11]!==d?(L={client:E,displayMode:w,minHeight:J,maxHeight:Y,orgId:n,toolInfo:l,toolInput:c,toolResult:d,onMessage:W,onUpdateModelContext:F,onTeardown:K,onRequestDisplayMode:Z},e[0]=E,e[1]=w,e[2]=Y,e[3]=J,e[4]=W,e[5]=Z,e[6]=K,e[7]=F,e[8]=n,e[9]=l,e[10]=c,e[11]=d,e[12]=L):L=e[12];const{height:Q,isLoading:z,error:U,iframeRef:G}=Ot(L);if(!o)return null;if(U){let k;e[13]!==C?(k=oe("flex items-center justify-center p-4 text-destructive bg-destructive/10 rounded-lg",C),e[13]=C,e[14]=k):k=e[14];let P;e[15]!==U?(P=b.jsx("span",{className:"text-sm",children:U}),e[15]=U,e[16]=P):P=e[16];let D;return e[17]!==k||e[18]!==P?(D=b.jsx("div",{className:k,children:P}),e[17]=k,e[18]=P,e[19]=D):D=e[19],D}const Re=l?.tool.name;let R;e[20]!==C?(R=oe("relative w-full overflow-hidden rounded-lg",C),e[20]=C,e[21]=R):R=e[21];let S;e[22]!==w||e[23]!==Q?(S=w!=="fullscreen"?{height:`${Q}px`}:void 0,e[22]=w,e[23]=Q,e[24]=S):S=e[24];let _;e[25]!==z?(_=z&&b.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background z-10",children:b.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[b.jsx("div",{className:"size-4 border-2 border-current border-t-transparent rounded-full animate-spin"}),b.jsx("span",{className:"text-sm",children:"Loading app..."})]})}),e[25]=z,e[26]=_):_=e[26];const X=z&&"invisible";let H;e[27]!==X?(H=oe("w-full h-full border-0",X),e[27]=X,e[28]=H):H=e[28];const ee=`MCP App: ${Re??i}`;let M;e[29]!==o||e[30]!==G||e[31]!==ee||e[32]!==H?(M=b.jsx("iframe",{ref:G,srcDoc:o,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups",className:H,title:ee}),e[29]=o,e[30]=G,e[31]=ee,e[32]=H,e[33]=M):M=e[33];let A;return e[34]!==M||e[35]!==R||e[36]!==S||e[37]!==_?(A=b.jsxs("div",{className:R,style:S,children:[_,M]}),e[34]=M,e[35]=R,e[36]=S,e[37]=_,e[38]=A):A=e[38],A}function $t(r){const e=V.c(13);let o,i,n,l;e[0]!==r?({resourceURI:l,orgSlug:n,connectionId:o,...i}=r,e[0]=r,e[1]=o,e[2]=i,e[3]=n,e[4]=l):(o=e[1],i=e[2],n=e[3],l=e[4]);let c;e[5]!==o||e[6]!==n||e[7]!==l?(c={orgSlug:n,connectionId:o,uri:l,staleTime:3e4},e[5]=o,e[6]=n,e[7]=l,e[8]=c):c=e[8];const d=je(c);let h;return e[9]!==i||e[10]!==d.data||e[11]!==l?(h=b.jsx(Ce,{html:d.data,uri:l,...i}),e[9]=i,e[10]=d.data,e[11]=l,e[12]=h):h=e[12],h}function Bt(r){const e=V.c(10);let o,i;e[0]!==r?({resourceURI:i,...o}=r,e[0]=r,e[1]=o,e[2]=i):(o=e[1],i=e[2]);let n;e[3]!==o.client||e[4]!==i?(n={client:o.client,uri:i,staleTime:3e4},e[3]=o.client,e[4]=i,e[5]=n):n=e[5];const{data:l}=$e(n),c=jt(l);let d;return e[6]!==o||e[7]!==c||e[8]!==i?(d=b.jsx(Ce,{html:c,uri:i,...o}),e[6]=o,e[7]=c,e[8]=i,e[9]=d):d=e[9],d}function Ft(r){const e=V.c(4);if(r.orgSlug&&r.connectionId){let i;return e[0]!==r?(i=b.jsx($t,{...r,orgSlug:r.orgSlug,connectionId:r.connectionId}),e[0]=r,e[1]=i):i=e[1],i}let o;return e[2]!==r?(o=b.jsx(Bt,{...r}),e[2]=r,e[3]=o):o=e[3],o}const Kt={view:{minHeight:400,maxHeight:800},fullscreen:{minHeight:600,maxHeight:1200}};function Zt(r){if(!(r==null||typeof r!="object"))try{return gt({_meta:r})}catch{return}}export{Ft as M,Kt as a,Zt as g};
