var p=((X)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(X,{get:(Y,Z)=>(typeof require<"u"?require:Y)[Z]}):X)(function(X){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+X+'" is not supported')});import{mergeCapabilities as xQ}from"@modelcontextprotocol/sdk/shared/protocol.js";import{CallToolRequestSchema as yQ,CallToolResultSchema as gQ,CreateMessageResultSchema as vQ,CreateMessageResultWithToolsSchema as fQ,EmptyResultSchema as uQ,ListResourcesResultSchema as dQ,ListToolsRequestSchema as hQ,PingRequestSchema as iQ,ReadResourceResultSchema as mQ}from"@modelcontextprotocol/sdk/types.js";import{Protocol as c}from"@modelcontextprotocol/sdk/shared/protocol.js";class _ extends c{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(X,Y){}_ensureEventSlot(X){let Y=this._eventSlots.get(X);if(!Y){let Z=this.eventSchemas[X];if(!Z)throw Error(`Unknown event: ${String(X)}`);Y={listeners:[]},this._eventSlots.set(X,Y);let $=Z.shape.method.value;this._registeredMethods.add($);let D=Y;super.setNotificationHandler(Z,(J)=>{let K=J.params;this.onEventDispatch(X,K),D.onHandler?.(K);for(let G of[...D.listeners])G(K)})}return Y}setEventHandler(X,Y){let Z=this._ensureEventSlot(X);if(Z.onHandler&&Y)console.warn(`[MCP Apps] on${String(X)} handler replaced. Use addEventListener("${String(X)}", …) to add multiple listeners without replacing.`);Z.onHandler=Y}getEventHandler(X){return this._eventSlots.get(X)?.onHandler}addEventListener(X,Y){this._ensureEventSlot(X).listeners.push(Y)}removeEventListener(X,Y){let Z=this._eventSlots.get(X);if(!Z)return;let $=Z.listeners.indexOf(Y);if($!==-1)Z.listeners.splice($,1)}setRequestHandler=(X,Y)=>{this._assertMethodNotRegistered(X,"setRequestHandler"),super.setRequestHandler(X,Y)};setNotificationHandler=(X,Y)=>{this._assertMethodNotRegistered(X,"setNotificationHandler"),super.setNotificationHandler(X,Y)};warnIfRequestHandlerReplaced(X,Y,Z){if(Y&&Z)console.warn(`[MCP Apps] ${X} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(X,Y)=>{let Z=X.shape.method.value;this._registeredMethods.add(Z),super.setRequestHandler(X,Y)};_assertMethodNotRegistered(X,Y){let Z=X.shape.method.value;if(this._registeredMethods.has(Z))throw Error(`Handler for "${Z}" already registered (via ${Y}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(Z)}}import{JSONRPCMessageSchema as KQ}from"@modelcontextprotocol/sdk/types.js";var E="2026-01-26",l="ui/open-link",r="ui/download-file",n="ui/message",a="ui/notifications/sandbox-proxy-ready",o="ui/notifications/sandbox-resource-ready",s="ui/notifications/size-changed",t="ui/notifications/tool-input",O="ui/notifications/tool-input-partial",e="ui/notifications/tool-result",QQ="ui/notifications/tool-cancelled",XQ="ui/notifications/host-context-changed",YQ="ui/notifications/request-teardown",ZQ="ui/resource-teardown",$Q="ui/initialize",DQ="ui/notifications/initialized",JQ="ui/request-display-mode";class j{eventTarget;eventSource;messageListener;constructor(X=window.parent,Y){this.eventTarget=X;this.eventSource=Y;this.messageListener=(Z)=>{if(Y&&Z.source!==this.eventSource){console.debug("Ignoring message from unknown source",Z);return}let $=KQ.safeParse(Z.data);if($.success)console.debug("Parsed message",$.data),this.onmessage?.($.data);else if(Z.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",$.error.message,Z);else console.error("Failed to parse message",$.error.message,Z),this.onerror?.(Error("Invalid JSON-RPC message received: "+$.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(X,Y){if(X.method!==O)console.debug("Sending message",X);this.eventTarget.postMessage(X,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}import{z as Q}from"zod/v4";import{ContentBlockSchema as x,CallToolResultSchema as GQ,EmbeddedResourceSchema as NQ,ImplementationSchema as y,RequestIdSchema as VQ,ResourceLinkSchema as WQ,ToolSchema as jQ}from"@modelcontextprotocol/sdk/types.js";var g=Q.union([Q.literal("light"),Q.literal("dark")]).describe("Color theme preference for the host environment."),W=Q.union([Q.literal("inline"),Q.literal("fullscreen"),Q.literal("pip")]).describe("Display mode for UI presentation."),LQ=Q.union([Q.literal("--color-background-primary"),Q.literal("--color-background-secondary"),Q.literal("--color-background-tertiary"),Q.literal("--color-background-inverse"),Q.literal("--color-background-ghost"),Q.literal("--color-background-info"),Q.literal("--color-background-danger"),Q.literal("--color-background-success"),Q.literal("--color-background-warning"),Q.literal("--color-background-disabled"),Q.literal("--color-text-primary"),Q.literal("--color-text-secondary"),Q.literal("--color-text-tertiary"),Q.literal("--color-text-inverse"),Q.literal("--color-text-ghost"),Q.literal("--color-text-info"),Q.literal("--color-text-danger"),Q.literal("--color-text-success"),Q.literal("--color-text-warning"),Q.literal("--color-text-disabled"),Q.literal("--color-border-primary"),Q.literal("--color-border-secondary"),Q.literal("--color-border-tertiary"),Q.literal("--color-border-inverse"),Q.literal("--color-border-ghost"),Q.literal("--color-border-info"),Q.literal("--color-border-danger"),Q.literal("--color-border-success"),Q.literal("--color-border-warning"),Q.literal("--color-border-disabled"),Q.literal("--color-ring-primary"),Q.literal("--color-ring-secondary"),Q.literal("--color-ring-inverse"),Q.literal("--color-ring-info"),Q.literal("--color-ring-danger"),Q.literal("--color-ring-success"),Q.literal("--color-ring-warning"),Q.literal("--font-sans"),Q.literal("--font-mono"),Q.literal("--font-weight-normal"),Q.literal("--font-weight-medium"),Q.literal("--font-weight-semibold"),Q.literal("--font-weight-bold"),Q.literal("--font-text-xs-size"),Q.literal("--font-text-sm-size"),Q.literal("--font-text-md-size"),Q.literal("--font-text-lg-size"),Q.literal("--font-heading-xs-size"),Q.literal("--font-heading-sm-size"),Q.literal("--font-heading-md-size"),Q.literal("--font-heading-lg-size"),Q.literal("--font-heading-xl-size"),Q.literal("--font-heading-2xl-size"),Q.literal("--font-heading-3xl-size"),Q.literal("--font-text-xs-line-height"),Q.literal("--font-text-sm-line-height"),Q.literal("--font-text-md-line-height"),Q.literal("--font-text-lg-line-height"),Q.literal("--font-heading-xs-line-height"),Q.literal("--font-heading-sm-line-height"),Q.literal("--font-heading-md-line-height"),Q.literal("--font-heading-lg-line-height"),Q.literal("--font-heading-xl-line-height"),Q.literal("--font-heading-2xl-line-height"),Q.literal("--font-heading-3xl-line-height"),Q.literal("--border-radius-xs"),Q.literal("--border-radius-sm"),Q.literal("--border-radius-md"),Q.literal("--border-radius-lg"),Q.literal("--border-radius-xl"),Q.literal("--border-radius-full"),Q.literal("--border-width-regular"),Q.literal("--shadow-hairline"),Q.literal("--shadow-sm"),Q.literal("--shadow-md"),Q.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),BQ=Q.record(LQ.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\` rather than \`Partial>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Q.union([Q.string(),Q.undefined()]).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\` rather than \`Partial>\` 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\` rather than \`Partial>\` for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),_Q=Q.object({method:Q.literal("ui/open-link"),params:Q.object({url:Q.string().describe("URL to open in the host's browser")})}),I=Q.object({isError:Q.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),F=Q.object({isError:Q.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),q=Q.object({isError:Q.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),EQ=Q.object({method:Q.literal("ui/notifications/sandbox-proxy-ready"),params:Q.object({})}),L=Q.object({connectDomains:Q.array(Q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). - Maps to CSP \`connect-src\` directive - Empty or omitted → no network connections (secure default)`),resourceDomains:Q.array(Q.string()).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:Q.array(Q.string()).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:Q.array(Q.string()).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'`)")}),B=Q.object({camera:Q.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:Q.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:Q.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:Q.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),OQ=Q.object({method:Q.literal("ui/notifications/size-changed"),params:Q.object({width:Q.number().optional().describe("New width in pixels."),height:Q.number().optional().describe("New height in pixels.")})}),P=Q.object({method:Q.literal("ui/notifications/tool-input"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),w=Q.object({method:Q.literal("ui/notifications/tool-input-partial"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),A=Q.object({method:Q.literal("ui/notifications/tool-cancelled"),params:Q.object({reason:Q.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),v=Q.object({fonts:Q.string().optional()}),f=Q.object({variables:BQ.optional().describe("CSS variables for theming the app."),css:v.optional().describe("CSS blocks that apps can inject.")}),R=Q.object({method:Q.literal("ui/resource-teardown"),params:Q.object({})}),zQ=Q.record(Q.string(),Q.unknown()),z=Q.object({text:Q.object({}).optional().describe("Host supports text content blocks."),image:Q.object({}).optional().describe("Host supports image content blocks."),audio:Q.object({}).optional().describe("Host supports audio content blocks."),resource:Q.object({}).optional().describe("Host supports resource content blocks."),resourceLink:Q.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:Q.object({}).optional().describe("Host supports structured content.")}),IQ=Q.object({method:Q.literal("ui/notifications/request-teardown"),params:Q.object({}).optional()}),u=Q.object({experimental:Q.object({}).optional().describe("Experimental features (structure TBD)."),openLinks:Q.object({}).optional().describe("Host supports opening external URLs."),downloadFile:Q.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:Q.object({listChanged:Q.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:Q.object({listChanged:Q.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:Q.object({}).optional().describe("Host accepts log messages."),sandbox:Q.object({permissions:B.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:L.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:z.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:z.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:Q.object({tools:Q.object({}).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.")}),d=Q.object({experimental:Q.object({}).optional().describe("Experimental features (structure TBD)."),tools:Q.object({listChanged:Q.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:Q.array(W).optional().describe("Display modes the app supports.")}),FQ=Q.object({method:Q.literal("ui/notifications/initialized"),params:Q.object({}).optional()}),qQ=Q.object({csp:L.optional().describe("Content Security Policy configuration for UI resources."),permissions:B.optional().describe("Sandbox permissions requested by the UI resource."),domain:Q.string().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:Q.boolean().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`)}),PQ=Q.object({method:Q.literal("ui/request-display-mode"),params:Q.object({mode:W.describe("The display mode being requested.")})}),U=Q.object({mode:W.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),h=Q.union([Q.literal("model"),Q.literal("app")]).describe("Tool visibility scope - who can access the tool."),wQ=Q.object({resourceUri:Q.string().optional(),visibility:Q.array(h).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:Q.never().optional(),permissions:Q.never().optional()}),YX=Q.object({mimeTypes:Q.array(Q.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),AQ=Q.object({method:Q.literal("ui/download-file"),params:Q.object({contents:Q.array(Q.union([NQ,WQ])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),RQ=Q.object({method:Q.literal("ui/message"),params:Q.object({role:Q.literal("user").describe('Message role, currently only "user" is supported.'),content:Q.array(x).describe("Message content blocks (text, image, etc.).")})}),UQ=Q.object({method:Q.literal("ui/notifications/sandbox-resource-ready"),params:Q.object({html:Q.string().describe("HTML content to load into the inner iframe."),sandbox:Q.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:L.optional().describe("CSP configuration from resource metadata."),permissions:B.optional().describe("Sandbox permissions from resource metadata.")})}),H=Q.object({method:Q.literal("ui/notifications/tool-result"),params:GQ.describe("Standard MCP tool execution result.")}),T=Q.object({toolInfo:Q.object({id:VQ.optional().describe("JSON-RPC id of the tools/call request."),tool:jQ.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:g.optional().describe("Current color theme preference."),styles:f.optional().describe("Style configuration for theming the app."),displayMode:W.optional().describe("How the UI is currently displayed."),availableDisplayModes:Q.array(W).optional().describe("Display modes the host supports."),containerDimensions:Q.union([Q.object({height:Q.number().describe("Fixed container height in pixels.")}),Q.object({maxHeight:Q.union([Q.number(),Q.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(Q.union([Q.object({width:Q.number().describe("Fixed container width in pixels.")}),Q.object({maxWidth:Q.union([Q.number(),Q.undefined()]).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:Q.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:Q.string().optional().describe("User's timezone in IANA format."),userAgent:Q.string().optional().describe("Host application identifier."),platform:Q.union([Q.literal("web"),Q.literal("desktop"),Q.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:Q.object({touch:Q.boolean().optional().describe("Whether the device supports touch input."),hover:Q.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:Q.object({top:Q.number().describe("Top safe area inset in pixels."),right:Q.number().describe("Right safe area inset in pixels."),bottom:Q.number().describe("Bottom safe area inset in pixels."),left:Q.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),M=Q.object({method:Q.literal("ui/notifications/host-context-changed"),params:T.describe("Partial context update containing only changed fields.")}),HQ=Q.object({method:Q.literal("ui/update-model-context"),params:Q.object({content:Q.array(x).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Q.record(Q.string(),Q.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),TQ=Q.object({method:Q.literal("ui/initialize"),params:Q.object({appInfo:y.describe("App identification (name and version)."),appCapabilities:d.describe("Features and capabilities this app provides."),protocolVersion:Q.string().describe("Protocol version this app supports.")})}),C=Q.object({protocolVersion:Q.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:y.describe("Host application identification and version."),hostCapabilities:u.describe("Features and capabilities provided by the host."),hostContext:T.describe("Rich context about the host environment.")}).passthrough();var MQ={target:"draft-2020-12"};async function k(X,Y){let Z=X["~standard"];if(Z.jsonSchema)return Z.jsonSchema[Y](MQ);if(Z.vendor==="zod"){let{z:$}=await import("zod/v4");return $.toJSONSchema(X,{io:Y})}throw Error(`Schema (vendor: ${Z.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function b(X,Y,Z=""){let $=await X["~standard"].validate(Y);if($.issues){let D=$.issues.map((J)=>{let K=J.path?.map((G)=>typeof G==="object"?G.key:G).join(".");return K?`${K}: ${J.message}`:J.message}).join("; ");throw Error(Z+D)}return $.value}import{z as pQ}from"zod/v4";function CQ(){let X=document.documentElement.getAttribute("data-theme");if(X==="dark"||X==="light")return X;return document.documentElement.classList.contains("dark")?"dark":"light"}function kQ(X){let Y=document.documentElement;Y.setAttribute("data-theme",X),Y.style.colorScheme=X}function bQ(X,Y=document.documentElement){for(let[Z,$]of Object.entries(X))if($!==void 0)Y.style.setProperty(Z,$)}function SQ(X){if(document.getElementById("__mcp-host-fonts"))return;let Z=document.createElement("style");Z.id="__mcp-host-fonts",Z.textContent=X,document.head.appendChild(Z)}var eX="ui/resourceUri",QY="text/html;profile=mcp-app";class i extends _{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(X){if(this._initializedSent)return;let Y=`[ext-apps] App.${X}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(Y);console.warn(`${Y}. This will throw in a future release.`)}eventSchemas={toolinput:P,toolinputpartial:w,toolresult:H,toolcancelled:A,hostcontextchanged:M};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(X){if(!i.ONE_SHOT_EVENTS.has(X)||this._everHadListener.has(X))return;if(this._everHadListener.add(X),!this._initializedSent)return;let Y=`[ext-apps] "${String(X)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(Y);console.warn(Y)}setEventHandler(X,Y){if(Y)this._assertHandlerTiming(X);super.setEventHandler(X,Y)}addEventListener(X,Y){this._assertHandlerTiming(X),super.addEventListener(X,Y)}onEventDispatch(X,Y){if(X==="hostcontextchanged")this._hostContext={...this._hostContext,...Y}}constructor(X,Y={},Z={autoResize:!0}){super(Z);this._appInfo=X;this._capabilities=Y;this.options=Z;if(!Z.allowUnsafeEval)pQ.config({jitless:!0});this.setRequestHandler(iQ,($)=>{return console.log("Received ping:",$.params),{}}),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(X){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=xQ(this._capabilities,X)}registerTool(X,Y,Z){if(this._registeredTools[X])throw Error(`Tool ${X} is already registered`);let $=this,D=()=>{if($._initializedSent&&$._capabilities.tools?.listChanged)$.sendToolListChanged()},J=Y.inputSchema!==void 0,K={title:Y.title,description:Y.description,inputSchema:Y.inputSchema,outputSchema:Y.outputSchema,annotations:Y.annotations,_meta:Y._meta,enabled:!0,enable(){this.enabled=!0,D()},disable(){this.enabled=!1,D()},update(G){Object.assign(this,G),D()},remove(){if($._registeredTools[X]!==K)return;delete $._registeredTools[X],D()},handler:async(G,N)=>{if(!K.enabled)throw Error(`Tool ${X} is disabled`);let V;if(J){let S=K.inputSchema,m=S?await b(S,G??{},`Invalid input for tool ${X}: `):G??{};V=await Z(m,N)}else V=await Z(N);if(K.outputSchema&&!V.isError)V.structuredContent=await b(K.outputSchema,V.structuredContent,`Invalid output for tool ${X}: `);return V}};if(this._registeredTools[X]=K,!this._capabilities.tools&&!this.transport)this.registerCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),D(),K}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(X,Y)=>{let Z=this._registeredTools[X.name];if(!Z)throw Error(`Tool ${X.name} not found`);return Z.handler(X.arguments,Y)},this.onlisttools=async(X,Y)=>{return{tools:await Promise.all(Object.entries(this._registeredTools).filter(([$,D])=>D.enabled).map(async([$,D])=>{let J={name:$,title:D.title,description:D.description,inputSchema:D.inputSchema?await k(D.inputSchema,"input"):{type:"object",properties:{}}};if(D.outputSchema)J.outputSchema=await k(D.outputSchema,"output");if(D.annotations)J.annotations=D.annotations;if(D._meta)J._meta=D._meta;return J}))}}}async sendToolListChanged(X={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:X})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(X){this.setEventHandler("toolinput",X)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(X){this.setEventHandler("toolinputpartial",X)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(X){this.setEventHandler("toolresult",X)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(X){this.setEventHandler("toolcancelled",X)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(X){this.setEventHandler("hostcontextchanged",X)}_onteardown;get onteardown(){return this._onteardown}set onteardown(X){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,X),this._onteardown=X,this.replaceRequestHandler(R,(Y,Z)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(Y.params,Z)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(X){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,X),this._oncalltool=X,this.replaceRequestHandler(yQ,(Y,Z)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(Y.params,Z)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(X){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,X),this._onlisttools=X,this.replaceRequestHandler(hQ,(Y,Z)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(Y.params,Z)})}assertCapabilityForMethod(X){switch(X){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${X})`);break}}assertRequestHandlerCapability(X){switch(X){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${X})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${X} registered`)}}assertNotificationCapability(X){}assertTaskCapability(X){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(X){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(X,Y){if(this._assertInitialized("callServerTool"),typeof X==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${X}"). Did you mean: callServerTool({ name: "${X}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:X},gQ,{onprogress:()=>{},resetTimeoutOnProgress:!0,...Y})}async readServerResource(X,Y){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:X},mQ,Y)}async listServerResources(X,Y){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:X},dQ,Y)}async createSamplingMessage(X,Y){this._assertInitialized("createSamplingMessage");let Z=X.tools?fQ:vQ;return await this.request({method:"sampling/createMessage",params:X},Z,Y)}sendMessage(X,Y){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:X},q,Y)}sendLog(X){return this.notification({method:"notifications/message",params:X})}updateModelContext(X,Y){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:X},uQ,Y)}openLink(X,Y){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:X},I,Y)}sendOpenLink=this.openLink;downloadFile(X,Y){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:X},F,Y)}requestTeardown(X={}){return this.notification({method:"ui/notifications/request-teardown",params:X})}requestDisplayMode(X,Y){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:X},U,Y)}sendSizeChanged(X){return this.notification({method:"ui/notifications/size-changed",params:X})}setupSizeChangedNotifications(){let X=!1,Y=0,Z=0,$=()=>{if(X)return;X=!0,requestAnimationFrame(()=>{X=!1;let J=document.documentElement,K=J.style.height;J.style.height="max-content";let G=Math.ceil(J.getBoundingClientRect().height);J.style.height=K;let N=Math.ceil(window.innerWidth);if(N!==Y||G!==Z)Y=N,Z=G,this.sendSizeChanged({width:N,height:G})})};$();let D=new ResizeObserver($);return D.observe(document.documentElement),D.observe(document.body),()=>D.disconnect()}async connect(X=new j(window.parent,window.parent),Y){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(X);try{let Z=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:E}},C,Y);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(this._hostCapabilities=Z.hostCapabilities,this._hostInfo=Z.hostInfo,this._hostContext=Z.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(Z){throw this.close(),Z}}}export{CQ as getDocumentTheme,bQ as applyHostStyleVariables,SQ as applyHostFonts,kQ as applyDocumentTheme,e as TOOL_RESULT_METHOD,O as TOOL_INPUT_PARTIAL_METHOD,t as TOOL_INPUT_METHOD,QQ as TOOL_CANCELLED_METHOD,s as SIZE_CHANGED_METHOD,o as SANDBOX_RESOURCE_READY_METHOD,a as SANDBOX_PROXY_READY_METHOD,eX as RESOURCE_URI_META_KEY,ZQ as RESOURCE_TEARDOWN_METHOD,QY as RESOURCE_MIME_TYPE,YQ as REQUEST_TEARDOWN_METHOD,JQ as REQUEST_DISPLAY_MODE_METHOD,_ as ProtocolWithEvents,j as PostMessageTransport,l as OPEN_LINK_METHOD,HQ as McpUiUpdateModelContextRequestSchema,h as McpUiToolVisibilitySchema,H as McpUiToolResultNotificationSchema,wQ as McpUiToolMetaSchema,w as McpUiToolInputPartialNotificationSchema,P as McpUiToolInputNotificationSchema,A as McpUiToolCancelledNotificationSchema,g as McpUiThemeSchema,z as McpUiSupportedContentBlockModalitiesSchema,OQ as McpUiSizeChangedNotificationSchema,UQ as McpUiSandboxResourceReadyNotificationSchema,EQ as McpUiSandboxProxyReadyNotificationSchema,zQ as McpUiResourceTeardownResultSchema,R as McpUiResourceTeardownRequestSchema,B as McpUiResourcePermissionsSchema,qQ as McpUiResourceMetaSchema,L as McpUiResourceCspSchema,IQ as McpUiRequestTeardownNotificationSchema,U as McpUiRequestDisplayModeResultSchema,PQ as McpUiRequestDisplayModeRequestSchema,I as McpUiOpenLinkResultSchema,_Q as McpUiOpenLinkRequestSchema,q as McpUiMessageResultSchema,RQ as McpUiMessageRequestSchema,FQ as McpUiInitializedNotificationSchema,C as McpUiInitializeResultSchema,TQ as McpUiInitializeRequestSchema,f as McpUiHostStylesSchema,v as McpUiHostCssSchema,T as McpUiHostContextSchema,M as McpUiHostContextChangedNotificationSchema,u as McpUiHostCapabilitiesSchema,F as McpUiDownloadFileResultSchema,AQ as McpUiDownloadFileRequestSchema,W as McpUiDisplayModeSchema,d as McpUiAppCapabilitiesSchema,n as MESSAGE_METHOD,E as LATEST_PROTOCOL_VERSION,$Q as INITIALIZE_METHOD,DQ as INITIALIZED_METHOD,XQ as HOST_CONTEXT_CHANGED_METHOD,r as DOWNLOAD_FILE_METHOD,i as App};