UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

72 lines 66.4 kB
import{i as e,n as t}from"./rolldown-runtime-DkW27tQK.js";import{R as n,la as r,vt as i,wr as a,yt as o,z as s}from"./control-ui-foundation-Cydpkyqa.js";import{Eo as c,Oo as l}from"./control-ui-core-Rwzhj6nO.js";import{$ as u,C as d,K as f,X as ee,b as te,dt as p,q as ne,st as m,x as re}from"./lit-runtime-CV_MH99K.js";import{_ as ie,g as ae}from"./control-ui-core-YphAl4aM.js";import{Xt as oe,Yt as se,en as h}from"./control-ui-core-vvcQQV2m.js";import{B as ce,U as le,z as ue}from"./control-ui-boot-shared-BYq7Cchl.js";import{C as de,E as fe,S as g,T as pe,_ as me,a as _,c as he,d as v,f as y,g as b,h as x,i as ge,l as _e,m as S,n as ve,o as C,p as ye,r as be,s as xe,t as w,u as Se,v as T,w as Ce,x as E,y as D}from"./config-runtime-D-5ybyEi.js";import{Fn as we,In as Te,Nn as Ee,Pn as De,jn as Oe}from"./control-ui-boot-chat-_QSl8fbH.js";import{ba as ke,xa as Ae}from"./control-ui-boot-shared-CXVvK2AW.js";var O,k,je,Me,Ne,Pe,Fe,A,j,Ie,M,N,P,F,I,Le,Re,ze,Be,Ve,L,R,He,Ue,We,Ge,Ke,qe,Je,z,B,V,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,H,at,ot,st,ct,U,W,lt,G,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt,bt,xt,St,Ct,K,q,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,Nt,Pt,Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,J,$t,en,tn,nn,rn,an,on,sn,Y,cn,ln,un,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,X,tr;function nr(){return(nr=t((()=>{_e(),Ce(),O=`io.modelcontextprotocol/related-task`,k=xe(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),je=E([D(),S().int()]),Me=D(),y({ttl:S().optional(),pollInterval:S().optional()}),Ne=x({ttl:S().optional()}),Pe=x({taskId:D()}),Fe=y({progressToken:je.optional(),[O]:Pe.optional()}),A=x({_meta:Fe.optional()}),j=A.extend({task:Ne.optional()}),Ie=e=>j.safeParse(e).success,M=x({method:D(),params:A.loose().optional()}),N=x({_meta:Fe.optional()}),P=x({method:D(),params:N.loose().optional()}),F=y({_meta:Fe.optional()}),I=E([D(),S().int()]),Le=x({jsonrpc:v(`2.0`),id:I,...M.shape}).strict(),Re=e=>Le.safeParse(e).success,ze=x({jsonrpc:v(`2.0`),...P.shape}).strict(),Be=e=>ze.safeParse(e).success,Ve=x({jsonrpc:v(`2.0`),id:I,result:F}).strict(),L=e=>Ve.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(R||={}),He=x({jsonrpc:v(`2.0`),id:I.optional(),error:x({code:S().int(),message:D(),data:g().optional()})}).strict(),Ue=e=>He.safeParse(e).success,We=E([Le,ze,Ve,He]),E([Ve,He]),Ge=F.strict(),Ke=N.extend({requestId:I.optional(),reason:D().optional()}),qe=P.extend({method:v(`notifications/cancelled`),params:Ke}),Je=x({src:D(),mimeType:D().optional(),sizes:_(D()).optional(),theme:w([`light`,`dark`]).optional()}),z=x({icons:_(Je).optional()}),B=x({name:D(),title:D().optional()}),V=B.extend({...B.shape,...z.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),Ye=Se(x({applyDefaults:C().optional()}),T(D(),g())),Xe=me(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Se(x({form:Ye.optional(),url:k.optional()}),T(D(),g()).optional())),Ze=y({list:k.optional(),cancel:k.optional(),requests:y({sampling:y({createMessage:k.optional()}).optional(),elicitation:y({create:k.optional()}).optional()}).optional()}),Qe=y({list:k.optional(),cancel:k.optional(),requests:y({tools:y({call:k.optional()}).optional()}).optional()}),$e=x({experimental:T(D(),k).optional(),sampling:x({context:k.optional(),tools:k.optional()}).optional(),elicitation:Xe.optional(),roots:x({listChanged:C().optional()}).optional(),tasks:Ze.optional(),extensions:T(D(),k).optional()}),et=A.extend({protocolVersion:D(),capabilities:$e,clientInfo:V}),tt=M.extend({method:v(`initialize`),params:et}),nt=x({experimental:T(D(),k).optional(),logging:k.optional(),completions:k.optional(),prompts:x({listChanged:C().optional()}).optional(),resources:x({subscribe:C().optional(),listChanged:C().optional()}).optional(),tools:x({listChanged:C().optional()}).optional(),tasks:Qe.optional(),extensions:T(D(),k).optional()}),rt=F.extend({protocolVersion:D(),capabilities:nt,serverInfo:V,instructions:D().optional()}),it=P.extend({method:v(`notifications/initialized`),params:N.optional()}),H=M.extend({method:v(`ping`),params:A.optional()}),at=x({progress:S(),total:b(S()),message:b(D())}),ot=x({...N.shape,...at.shape,progressToken:je}),st=P.extend({method:v(`notifications/progress`),params:ot}),ct=A.extend({cursor:Me.optional()}),U=M.extend({params:ct.optional()}),W=F.extend({nextCursor:Me.optional()}),lt=w([`working`,`input_required`,`completed`,`failed`,`cancelled`]),G=x({taskId:D(),status:lt,ttl:E([S(),ve()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:b(S()),statusMessage:b(D())}),ut=F.extend({task:G}),dt=N.merge(G),ft=P.extend({method:v(`notifications/tasks/status`),params:dt}),pt=M.extend({method:v(`tasks/get`),params:A.extend({taskId:D()})}),mt=F.merge(G),ht=M.extend({method:v(`tasks/result`),params:A.extend({taskId:D()})}),F.loose(),gt=U.extend({method:v(`tasks/list`)}),_t=W.extend({tasks:_(G)}),vt=M.extend({method:v(`tasks/cancel`),params:A.extend({taskId:D()})}),yt=F.merge(G),bt=x({uri:D(),mimeType:b(D()),_meta:T(D(),g()).optional()}),xt=bt.extend({text:D()}),St=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ct=bt.extend({blob:St}),K=w([`user`,`assistant`]),q=x({audience:_(K).optional(),priority:S().min(0).max(1).optional(),lastModified:de({offset:!0}).optional()}),wt=x({...B.shape,...z.shape,uri:D(),description:b(D()),mimeType:b(D()),size:b(S()),annotations:q.optional(),_meta:b(y({}))}),Tt=x({...B.shape,...z.shape,uriTemplate:D(),description:b(D()),mimeType:b(D()),annotations:q.optional(),_meta:b(y({}))}),Et=U.extend({method:v(`resources/list`)}),Dt=W.extend({resources:_(wt)}),Ot=U.extend({method:v(`resources/templates/list`)}),kt=W.extend({resourceTemplates:_(Tt)}),At=A.extend({uri:D()}),jt=At,Mt=M.extend({method:v(`resources/read`),params:jt}),Nt=F.extend({contents:_(E([xt,Ct]))}),Pt=P.extend({method:v(`notifications/resources/list_changed`),params:N.optional()}),Ft=At,It=M.extend({method:v(`resources/subscribe`),params:Ft}),Lt=At,Rt=M.extend({method:v(`resources/unsubscribe`),params:Lt}),zt=N.extend({uri:D()}),Bt=P.extend({method:v(`notifications/resources/updated`),params:zt}),Vt=x({name:D(),description:b(D()),required:b(C())}),Ht=x({...B.shape,...z.shape,description:b(D()),arguments:b(_(Vt)),_meta:b(y({}))}),Ut=U.extend({method:v(`prompts/list`)}),Wt=W.extend({prompts:_(Ht)}),Gt=A.extend({name:D(),arguments:T(D(),D()).optional()}),Kt=M.extend({method:v(`prompts/get`),params:Gt}),qt=x({type:v(`text`),text:D(),annotations:q.optional(),_meta:T(D(),g()).optional()}),Jt=x({type:v(`image`),data:St,mimeType:D(),annotations:q.optional(),_meta:T(D(),g()).optional()}),Yt=x({type:v(`audio`),data:St,mimeType:D(),annotations:q.optional(),_meta:T(D(),g()).optional()}),Xt=x({type:v(`tool_use`),name:D(),id:D(),input:T(D(),g()),_meta:T(D(),g()).optional()}),Zt=x({type:v(`resource`),resource:E([xt,Ct]),annotations:q.optional(),_meta:T(D(),g()).optional()}),Qt=wt.extend({type:v(`resource_link`)}),J=E([qt,Jt,Yt,Qt,Zt]),$t=x({role:K,content:J}),en=F.extend({description:D().optional(),messages:_($t)}),tn=P.extend({method:v(`notifications/prompts/list_changed`),params:N.optional()}),nn=x({title:D().optional(),readOnlyHint:C().optional(),destructiveHint:C().optional(),idempotentHint:C().optional(),openWorldHint:C().optional()}),rn=x({taskSupport:w([`required`,`optional`,`forbidden`]).optional()}),an=x({...B.shape,...z.shape,description:D().optional(),inputSchema:x({type:v(`object`),properties:T(D(),k).optional(),required:_(D()).optional()}).catchall(g()),outputSchema:x({type:v(`object`),properties:T(D(),k).optional(),required:_(D()).optional()}).catchall(g()).optional(),annotations:nn.optional(),execution:rn.optional(),_meta:T(D(),g()).optional()}),on=U.extend({method:v(`tools/list`)}),sn=W.extend({tools:_(an)}),Y=F.extend({content:_(J).default([]),structuredContent:T(D(),g()).optional(),isError:C().optional()}),Y.or(F.extend({toolResult:g()})),cn=j.extend({name:D(),arguments:T(D(),g()).optional()}),ln=M.extend({method:v(`tools/call`),params:cn}),un=P.extend({method:v(`notifications/tools/list_changed`),params:N.optional()}),x({autoRefresh:C().default(!0),debounceMs:S().int().nonnegative().default(300)}),dn=w([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),fn=A.extend({level:dn}),pn=M.extend({method:v(`logging/setLevel`),params:fn}),mn=N.extend({level:dn,logger:D().optional(),data:g()}),hn=P.extend({method:v(`notifications/message`),params:mn}),gn=x({name:D().optional()}),_n=x({hints:_(gn).optional(),costPriority:S().min(0).max(1).optional(),speedPriority:S().min(0).max(1).optional(),intelligencePriority:S().min(0).max(1).optional()}),vn=x({mode:w([`auto`,`required`,`none`]).optional()}),yn=x({type:v(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:_(J).default([]),structuredContent:x({}).loose().optional(),isError:C().optional(),_meta:T(D(),g()).optional()}),bn=he(`type`,[qt,Jt,Yt]),xn=he(`type`,[qt,Jt,Yt,Xt,yn]),Sn=x({role:K,content:E([xn,_(xn)]),_meta:T(D(),g()).optional()}),Cn=j.extend({messages:_(Sn),modelPreferences:_n.optional(),systemPrompt:D().optional(),includeContext:w([`none`,`thisServer`,`allServers`]).optional(),temperature:S().optional(),maxTokens:S().int(),stopSequences:_(D()).optional(),metadata:k.optional(),tools:_(an).optional(),toolChoice:vn.optional()}),wn=M.extend({method:v(`sampling/createMessage`),params:Cn}),Tn=F.extend({model:D(),stopReason:b(w([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:K,content:bn}),En=F.extend({model:D(),stopReason:b(w([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:K,content:E([xn,_(xn)])}),Dn=x({type:v(`boolean`),title:D().optional(),description:D().optional(),default:C().optional()}),On=x({type:v(`string`),title:D().optional(),description:D().optional(),minLength:S().optional(),maxLength:S().optional(),format:w([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),kn=x({type:w([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:S().optional(),maximum:S().optional(),default:S().optional()}),An=x({type:v(`string`),title:D().optional(),description:D().optional(),enum:_(D()),default:D().optional()}),jn=x({type:v(`string`),title:D().optional(),description:D().optional(),oneOf:_(x({const:D(),title:D()})),default:D().optional()}),Mn=x({type:v(`string`),title:D().optional(),description:D().optional(),enum:_(D()),enumNames:_(D()).optional(),default:D().optional()}),Nn=E([An,jn]),Pn=x({type:v(`array`),title:D().optional(),description:D().optional(),minItems:S().optional(),maxItems:S().optional(),items:x({type:v(`string`),enum:_(D())}),default:_(D()).optional()}),Fn=x({type:v(`array`),title:D().optional(),description:D().optional(),minItems:S().optional(),maxItems:S().optional(),items:x({anyOf:_(x({const:D(),title:D()}))}),default:_(D()).optional()}),In=E([Pn,Fn]),Ln=E([Mn,Nn,In]),Rn=E([Ln,Dn,On,kn]),zn=j.extend({mode:v(`form`).optional(),message:D(),requestedSchema:x({type:v(`object`),properties:T(D(),Rn),required:_(D()).optional()})}),Bn=j.extend({mode:v(`url`),message:D(),elicitationId:D(),url:D().url()}),Vn=E([zn,Bn]),Hn=M.extend({method:v(`elicitation/create`),params:Vn}),Un=N.extend({elicitationId:D()}),Wn=P.extend({method:v(`notifications/elicitation/complete`),params:Un}),Gn=F.extend({action:w([`accept`,`decline`,`cancel`]),content:me(e=>e===null?void 0:e,T(D(),E([D(),S(),C(),_(D())])).optional())}),Kn=x({type:v(`ref/resource`),uri:D()}),qn=x({type:v(`ref/prompt`),name:D()}),Jn=A.extend({ref:E([qn,Kn]),argument:x({name:D(),value:D()}),context:x({arguments:T(D(),D()).optional()}).optional()}),Yn=M.extend({method:v(`completion/complete`),params:Jn}),Xn=F.extend({completion:y({values:_(D()).max(100),total:b(S().int()),hasMore:b(C())})}),Zn=x({uri:D().startsWith(`file://`),name:D().optional(),_meta:T(D(),g()).optional()}),Qn=M.extend({method:v(`roots/list`),params:A.optional()}),$n=F.extend({roots:_(Zn)}),er=P.extend({method:v(`notifications/roots/list_changed`),params:N.optional()}),E([H,tt,Yn,pn,Kt,Ut,Et,Ot,Mt,It,Rt,ln,on,pt,ht,gt,vt]),E([qe,st,it,er,ft]),E([Ge,Tn,En,Gn,$n,mt,_t,ut]),E([H,wn,Hn,Qn,pt,ht,gt,vt]),E([qe,st,hn,Bt,Pt,un,tn,ft,Wn]),E([Ge,rt,Xn,en,Wt,Dt,kt,Nt,Y,sn,mt,_t,ut]),X=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===R.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new tr(e.elicitations,n)}return new e(t,n,r)}},tr=class extends X{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(R.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}})))()}function rr(e){return!!e._zod}function ir(e,t){return rr(e)?fe(e,t):e.safeParse(t)}function ar(e){if(!e)return;let t;if(t=rr(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function or(e){if(rr(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}function sr(){return(sr=t((()=>{pe()})))()}function Z(e){return e===`completed`||e===`failed`||e===`cancelled`}function cr(e){let t=ar(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=or(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function lr(e,t){let n=ir(e,t);if(!n.success)throw n.error;return n.data}function ur(){return(ur=t((()=>{sr()})))()}var dr;function fr(){return(fr=t((()=>{sr(),nr(),ur(),dr=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(qe,e=>{this._oncancel(e)}),this.setNotificationHandler(st,e=>{this._onprogress(e)}),this.setRequestHandler(H,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(pt,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new X(R.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(ht,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new X(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new X(R.InvalidParams,`Task not found: ${r}`);if(!Z(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Z(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[O]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(gt,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new X(R.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(vt,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new X(R.InvalidParams,`Task not found: ${e.params.taskId}`);if(Z(n.status))throw new X(R.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new X(R.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof X?e:new X(R.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),X.fromError(R.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),L(e)||Ue(e)?this._onresponse(e):Re(e)?this._onrequest(e,t):Be(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=X.fromError(R.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[O]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:R.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=Ie(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new X(R.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:R.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),L(e)?n(e):n(new X(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(L(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),L(e)?r(e):r(X.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof X?e:new X(R.InternalError,String(e))}}return}let i;try{let r=await this.request(e,ut,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new X(R.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Z(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new X(R.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new X(R.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof X?e:new X(R.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[O]:s}});let ee=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof X?e:new X(R.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=ir(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{ee(n?.signal?.reason)});let te=n?.timeout??6e4;this._setupTimeout(d,te,n?.maxTotalTimeout,()=>ee(X.fromError(R.RequestTimeout,`Request timed out`,{timeout:te})),n?.resetTimeoutOnProgress??!1);let p=s?.taskId;p?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(p,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},mt,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},_t,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},yt,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[O]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[O]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[O]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=cr(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=lr(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=cr(e);this._notificationHandlers.set(n,n=>{let r=lr(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Re(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new X(R.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new X(R.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new X(R.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new X(R.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=ft.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Z(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new X(R.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Z(a.status))throw new X(R.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=ft.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Z(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}})))()}function pr(e,t){return JSON.stringify(e)===JSON.stringify(t)}var mr,hr,gr,Q,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr;function Hr(){return(Hr=t((()=>{nr(),fr(),_e(),(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),mr=class extends dr{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(e,t){}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t){let n=this.eventSchemas[e];if(!n)throw Error(`Unknown event: ${String(e)}`);t={listeners:[]},this._eventSlots.set(e,t);let r=n.shape.method.value;this._registeredMethods.add(r);let i=t;super.setNotificationHandler(n,t=>{let n=t.params;this.onEventDispatch(e,n),i.onHandler?.(n);for(let e of[...i.listeners])e(n)})}return t}setEventHandler(e,t){let n=this._ensureEventSlot(e);n.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),n.onHandler=t}getEventHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let n=this._eventSlots.get(e);if(!n)return;let r=n.listeners.indexOf(t);r!==-1&&n.listeners.splice(r,1)}setRequestHandler=(e,t)=>{this._assertMethodNotRegistered(e,`setRequestHandler`),super.setRequestHandler(e,t)};setNotificationHandler=(e,t)=>{this._assertMethodNotRegistered(e,`setNotificationHandler`),super.setNotificationHandler(e,t)};warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(e,t)=>{let n=e.shape.method.value;this._registeredMethods.add(n),super.setRequestHandler(e,t)};_assertMethodNotRegistered(e,t){let n=e.shape.method.value;if(this._registeredMethods.has(n))throw Error(`Handler for "${n}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(n)}},hr=`2026-01-26`,gr=E([v(`light`),v(`dark`)]).describe(`Color theme preference for the host environment.`),Q=E([v(`inline`),v(`fullscreen`),v(`pip`)]).describe(`Display mode for UI presentation.`),_r=E([v(`--color-background-primary`),v(`--color-background-secondary`),v(`--color-background-tertiary`),v(`--color-background-inverse`),v(`--color-background-ghost`),v(`--color-background-info`),v(`--color-background-danger`),v(`--color-background-success`),v(`--color-background-warning`),v(`--color-background-disabled`),v(`--color-text-primary`),v(`--color-text-secondary`),v(`--color-text-tertiary`),v(`--color-text-inverse`),v(`--color-text-ghost`),v(`--color-text-info`),v(`--color-text-danger`),v(`--color-text-success`),v(`--color-text-warning`),v(`--color-text-disabled`),v(`--color-border-primary`),v(`--color-border-secondary`),v(`--color-border-tertiary`),v(`--color-border-inverse`),v(`--color-border-ghost`),v(`--color-border-info`),v(`--color-border-danger`),v(`--color-border-success`),v(`--color-border-warning`),v(`--color-border-disabled`),v(`--color-ring-primary`),v(`--color-ring-secondary`),v(`--color-ring-inverse`),v(`--color-ring-info`),v(`--color-ring-danger`),v(`--color-ring-success`),v(`--color-ring-warning`),v(`--font-sans`),v(`--font-mono`),v(`--font-weight-normal`),v(`--font-weight-medium`),v(`--font-weight-semibold`),v(`--font-weight-bold`),v(`--font-text-xs-size`),v(`--font-text-sm-size`),v(`--font-text-md-size`),v(`--font-text-lg-size`),v(`--font-heading-xs-size`),v(`--font-heading-sm-size`),v(`--font-heading-md-size`),v(`--font-heading-lg-size`),v(`--font-heading-xl-size`),v(`--font-heading-2xl-size`),v(`--font-heading-3xl-size`),v(`--font-text-xs-line-height`),v(`--font-text-sm-line-height`),v(`--font-text-md-line-height`),v(`--font-text-lg-line-height`),v(`--font-heading-xs-line-height`),v(`--font-heading-sm-line-height`),v(`--font-heading-md-line-height`),v(`--font-heading-lg-line-height`),v(`--font-heading-xl-line-height`),v(`--font-heading-2xl-line-height`),v(`--font-heading-3xl-line-height`),v(`--border-radius-xs`),v(`--border-radius-sm`),v(`--border-radius-md`),v(`--border-radius-lg`),v(`--border-radius-xl`),v(`--border-radius-full`),v(`--border-width-regular`),v(`--shadow-hairline`),v(`--shadow-sm`),v(`--shadow-md`),v(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),vr=T(_r.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.`),E([D(),be()]).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.`),yr=x({method:v(`ui/open-link`),params:x({url:D().describe(`URL to open in the host's browser`)})}),x({isError:C().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),x({isError:C().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),x({isError:C().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),br=x({method:v(`ui/notifications/sandbox-proxy-ready`),params:x({})}),xr=x({connectDomains:_(D()).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()).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()).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()).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'`)")}),Sr=x({camera:x({}).optional().describe(`Request camera access.

Maps to Permission Policy \`camera\` feature.`),microphone:x({}).optional().describe(`Request microphone access.

Maps to Permission Policy \`microphone\` feature.`),geolocation:x({}).optional().describe(`Request geolocation access.

Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:x({}).optional().describe(`Request clipboard write access.

Maps to Permission Policy \`clipboard-write\` feature.`)}),Cr=x({method:v(`ui/notifications/size-changed`),params:x({width:S().optional().describe(`New width in pixels.`),height:S().optional().describe(`New height in pixels.`)})}),x({method:v(`ui/notifications/tool-input`),params:x({arguments:T(D(),g().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),x({method:v(`ui/notifications/tool-input-partial`),params:x({arguments:T(D(),g().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),x({method:v(`ui/notifications/tool-cancelled`),params:x({reason:D().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})}),wr=x({fonts:D().optional()}),Tr=x({variables:vr.optional().describe(`CSS variables for theming the app.`),css:wr.optional().describe(`CSS blocks that apps can inject.`)}),x({method:v(`ui/resource-teardown`),params:x({})}),Er=T(D(),g()),Dr=x({text:x({}).optional().describe(`Host supports text content blocks.`),image:x({}).optional().describe(`Host supports image content blocks.`),audio:x({}).optional().describe(`Host supports audio content blocks.`),resource:x({}).optional().describe(`Host supports resource content blocks.`),resourceLink:x({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:x({}).optional().describe(`Host supports structured content.`)}),Or=x({method:v(`ui/notifications/request-teardown`),params:x({}).optional()}),kr=x({experimental:T(D(),T(D(),ge()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:x({}).optional().describe(`Host supports opening external URLs.`),downloadFile:x({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:x({listChanged:C().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:x({listChanged:C().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:x({}).optional().describe(`Host accepts log messages.`),sandbox:x({permissions:Sr.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:xr.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Dr.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Dr.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:x({tools:x({}).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.")}),Ar=x({experimental:T(D(),T(D(),ge()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:x({listChanged:C().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:_(Q).optional().describe(`Display modes the app supports.`)}),jr=x({method:v(`ui/notifications/initialized`),params:x({}).optional()}),x({csp:xr.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:Sr.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:D().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:C().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`)}),Mr=x({method:v(`ui/request-display-mode`),params:x({mode:Q.describe(`The display mode being requested.`)})}),x({mode:Q.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),Nr=E([v(`model`),v(`app`)]).describe(`Tool visibility scope - who can access the tool.`),x({resourceUri:D().optional(),visibility:_(Nr).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:ye().optional(),permissions:ye().optional()}),x({mimeTypes:_(D()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),Pr=x({method:v(`ui/download-file`),params:x({contents:_(E([Zt,Qt])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),Fr=x({method:v(`ui/message`),params:x({role:v(`user`).describe(`Message role, currently only "user" is supported.`),content:_(J).describe(`Message content blocks (text, image, etc.).`)})}),x({method:v(`ui/notifications/sandbox-resource-ready`),params:x({html:D().describe(`HTML content to load into the inner iframe.`),sandbox:D().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:xr.optional().describe(`CSP configuration from resource metadata.`),permissions:Sr.optional().describe(`Sandbox permissions from resource metadata.`)})}),x({method:v(`ui/notifications/tool-result`),params:Y.describe(`Standard MCP tool execution result.`)}),Ir=x({toolInfo:x({id:I.optional().describe(`JSON-RPC id of the tools/call request.`),tool:an.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:gr.optional().describe(`Current color theme preference.`),styles:Tr.optional().describe(`Style configuration for theming the app.`),displayMode:Q.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:_(Q).optional().describe(`Display modes the host supports.`),containerDimensions:E([x({height:S().describe(`Fixed container height in pixels.`)}),x({maxHeight:E([S(),be()]).optional().describe(`Maximum container height in pixels.`)})]).and(E([x({width:S().describe(`Fixed container width in pixels.`)}),x({maxWidth:E([S(),be()]).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:D().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:D().optional().describe(`User's timezone in IANA format.`),userAgent:D().optional().describe(`Host application identifier.`),platform:E([v(`web`),v(`desktop`),v(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:x({touch:C().optional().describe(`Whether the device supports touch input.`),hover:C().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:x({top:S().describe(`Top safe area inset in pixels.`),right:S().describe(`Right safe area inset in pixels.`),bottom:S().describe(`Bottom safe area inset in pixels.`),left:S().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),x({method:v(`ui/notifications/host-context-changed`),params:Ir.describe(`Partial context update containing only changed fields.`)}),Lr=x({method:v(`ui/update-model-context`),params:x({content:_(J).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:T(D(),g().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),Rr=x({method:v(`ui/initialize`),params:x({appInfo:V.describe(`App identification (name and version).`),appCapabilities:Ar.describe(`Features and capabilities this app provides.`),protocolVersion:D().describe(`Protocol version this app supports.`)})}),x({protocolVersion:D().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:V.describe(`Host application identification and version.`),hostCapabilities:kr.describe(`Features and capabilities provided by the host.`),hostContext:Ir.describe(`Rich context about the host environment.`)}).passthrough(),zr=class{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource){console.debug(`Ignoring message from unknown source`,e);return}let n=We.safeParse(e.data);n.success?(console.debug(`Parsed message`,n.data),this.onmessage?.(n.data)):e.data?.jsonrpc===`2.0`?(console.error(`Failed to parse message`,n.error.message,e),this.onerror?.(Error(`Invalid JSON-RPC message received: `+n.error.message))):console.debug(`Ignoring non-JSON-RPC message`,n.error.message,e)}}async start(){window.addEventListener(`message`,this.messageListener)}async send(e,t){e.method!==`ui/notifications/tool-input-partial`&&console.debug(`Sending message`,e),this.eventTarget.postMessage(e,`*`)}async close(){window.removeEventListener(`message`,this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion},Br=[hr],Vr=class extends mr{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(e,t)=>{this._baseReplaceRequestHandler(e,(e,n)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${e.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),t(e,n)))};eventSchemas={sizechange:Cr,sandboxready:br,initialized:jr,requestteardown:Or,loggingmessage:hn};constructor(e,t,n,r){super(r),this._client=e,this._hostInfo=t,this._capabilities=n,this.addEventListener(`initialized`,()=>{this._initializedReceived=!0}),this._hostContext=r?.hostContext||{},this.setRequestHandler(Rr,e=>this._oninitialize(e)),this.setRequestHandler(H,(e,t)=>(this.onping?.(e.params,t),{})),this.replaceRequestHandler(Mr,e=>({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(Fr,async(e,t)=>{if(!this._onmessage)throw Error(`No onmessage handler set`);return this._onmessage(e.params,t)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced(`onopenlink`,this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(yr,async(e,t)=>{if(!this._onopenlink)throw Error(`No onopenlink handler set`);return this._onopenlink(e.params,t)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced(`ondownloadfile`,this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(Pr,async(e,t)=>{if(!this._ondownloadfile)throw Error(`No ondownloadfile handler set`);return this._ondownloadfile(e.params,t)})}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(Mr,async(e,t)=>{if(!this._onrequestdisplaymode)throw Error(`No onrequestdisplaymode handler set`);return this._onrequestdisplaymode(e.params,t)})}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(Lr,async(e,t)=>{if(!this._onupdatemodelcontext)throw Error(`No onupdatemodelcontext handler set`);return this._onupdatemodelcontext(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(ln,async(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}set oncreatesamplingmessage(e){this.setRequestHandler(wn,async(t,n)=>e(t.params,n))}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(Et,async(e,t)=>{if(!this._onlistresources)throw Error(`No onlistresources handler set`);return this._onlistresources(e.params,t)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced(`onlistresourcetemplates`,this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(Ot,async(e,t)=>{if(!this._onlistresourcetemplates)throw Error(`No onlistresourcetemplates handler set`);return this._onlistresourcetemplates(e.params,t)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced(`onreadresource`,this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(Mt,async(e,t)=>{if(!this._onreadresource)throw Error(`No onreadresource handler set`);return this._onreadresource(e.params,t)})}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(Ut,async(e,t)=>{if(!this._onlistprompts)throw Error(`No onlistprompts handler set`);return this._onlistprompts(e.params,t)})}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 t=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:Br.includes(t)?t:hr,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let r of Object.keys(e)){let i=this._hostContext[r],a=e[r];pr(i,a)||(t[r]=a,n=!0)}n&&(this._hostContext=e,this.sendHostContextChange(t))}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,t){return this.request({method:`ui/resource-teardown`,params:e},Er,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:`tools/call`,params:e},Y,t)}listTools(e,t){return this.request({method:`tools/list`,params:e},sn,t)}async connect(e){if(this.transport)throw Error(`AppBridge is already connected. Call close() before connecting again.`);if(this._initializedReceived=!1,this._client){let e=this._client.getServerCapabilities();if(!e)throw Error(`Client server capabilities not available`);e.tools&&(this.oncalltool=async(e,t)=>this._client.request({method:`tools/call`,params:e},Y,{signal:t.signal}),e.tools.listChanged&&this._client.setNotificationHandler(un,e=>this.sendToolListChanged(e.params))),e.resources&&(this.onlistresources=async(e,t)=>this._client.request({method:`resources/list`,params:e},Dt,{signal:t.signal}),this.onlistresourcetemplates=async(e,t)=>this._client.request({method:`resources/templates/list`,params:e},kt,{signal:t.signal}),this.onreadresource=async(e,t)=>this._client.request({method:`resources/read`,params:e},Nt,{signal:t.signal}),e.resources.listChanged&&this._client.setNotificationHandler(Pt,e=>this.sendResourceListChanged(e.params))),e.prompts&&(this.onlistprompts=async(e,t)=>this._client.request({method:`prompts/list`,params:e},Wt,{signal:t.signal}),e.prompts.listChanged&&this._client.setNotificationHandler(tn,e=>this.sendPromptListChanged(e.params)))}return super.connect(e)}}})))()}function Ur(e=document.documentElement){if(!e)return;let t=getComputedStyle(e),n={...Gr};for(let[e,r]of Object.entries(Wr)){let i=t.getPropertyValue(r).trim();i&&(n[e]=i)}return n}var Wr,Gr;function Kr(){return(Kr=t((()=>{Wr={"--color-background-primary":`--card`,"--color-background-secondary":`--bg`,"--color-background-tertiary":`--bg-elevated`,"--color-background-inverse":`--text`,"--color-background-disabled":`--bg-muted`,"--color-background-success":`--ok-subtle`,"--color-background-warning":`--warn-subtle`,"--color-background-danger":`--danger-subtle`,"--color-text-primary":`--text`,"--color-text-secondary":`--muted-strong`,"--color-text-tertiary":`--muted`,"--color-text-inverse":`--bg`,"--color-text-success":`--ok`,"--color-text-warning":`--warn`,"--color-text-danger":`--danger`,"--color-text-info":`--info`,"--color-border-primary":`--border`,"--color-border-secondary":`--border-strong`,"--color-border-inverse":`--bg`,"--color-ring-primary":`--ring`,"--font-text-xs-size":`--control-ui-text-xs`,"--font-text-sm-size":`--control-ui-text-sm`,"--font-text-md-size":`--control-ui-text-md`,"--font-text-lg-size":`--control-ui-text-lg`,"--border-radius-xs":`--radius-sm`,"--border-radius-sm":`--radius-sm`,"--border-radius-md":`--radius`,"--border-radius-lg":`--radius-lg`,"--border-radius-xl":`--radius-xl`,"--border-radius-full":`--radius-full`,"--shadow-sm":`--shadow-sm`,"--shadow-md":`--shadow-md`,"--shadow-lg":`--shadow-lg`},Gr={"--border-width-regular":`1px`,"--font-weight-normal":`400`,"--font-weight-medium":`500`,"--font-weight-semibold":`600`,"--font-weight-bold":`700`,"--font-sans":`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable Text", "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji"`,"--font-mono":`ui-monospace, "SFMono-Regular", "SF Mono", Menlo, Consolas, "Liberation Mono", monospace`}})))()}async function qr(e=window.requestAnimationFrame.bind(window),t=window.setTimeout.bind(window)){await Promise.race([new Promise(t=>{e(()=>{e(()=>t())})}),new Promise(e=>{t(e,1e3)})])}function Jr(e,t){let n=e?.getBoundingClientRect(),r=navigator.maxTouchPoints>0||window.matchMedia?.(`(pointer: coarse)`).matches,i=document.documentElement.dataset.themeMode;return{theme:i===`light`||i===`dark`?i:window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,displayMode:`inline`,availableDisplayModes:[`inline`],containerDimensions:{width:Math.max(1,Math.round(n?.width||window.innerWidth)),height:t},locale:navigator.language||void 0,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:r&&window.innerWidth<768?`mobile`:`web`,deviceCapabilities:{touch:r,hover:window.matchMedia?.(`(hover: hover)`).matches},safeAreaInsets:{top:0,right:0,bottom:0,left:0},styles:{variables:Ur()}}}var Yr,Xr,$;function Zr(){return(Zr=t((()=>{s(),ue(),Hr(),nr(),i(),f(),u(),te(),ie(),se(),l(),ke(),we(),Kr(),Yr=250,Xr=class extends Vr{setMessageHandler(e){Reflect.set(this,`onmessage`,e)}setUpdateModelContextHandler(e){Reflect.set(this,`onupdatemodelcontext`,e)}setListToolsHandler(e){this.replaceRequestHandler(on,t=>e(t.params))}},$=class extends r{constructor(...e){super(...e),this.sessionKey=``,this.viewId=``,this.height=600,this.fixedHeight=!1,this.title=``,this.i18nController=new oe(this),this.mount=re(),this.resources=null,this.teardownPromise=null,this.setupTask=new ce(this,{autoRun:`afterUpdate`,args:()=>[this.context?.gateway.snapshot.client??null,this.sessionKey,this.viewId],task:async([e,t,n],{signal:r})=>{if(await this.teardownResources(this.resources),!t||!n)return null;if(!e)throw Error(h(`mcpApp.errors.gatewayUnavailable`));return this.setupResources({client:e,sessionKey:t,viewId:n},r)}})}static{this.styles=p`
    :host {
      display: block;
      width: 100%;
    }
    .mount {
      width: 100%;
      min-height: 160px;
    }
    .mount:empty {
      min-height: 0;
    }
    iframe {
      display: block;
      width: 100%;
      border: 0;
      background: var(--board-surface, transparent);
    }
    .error {
      padding: 14px;
      color: var(--danger, #dc2626);
      font-size: 13px;
    }
  `}disconnectedCallback(){this.teardown(),super.disconnectedCallback()}updated(e){this.resources&&(this.resources.iframe.title=this.title||h(`mcpApp.title`),(e.has(`height`)||e.has(`fixedHeight`)&&this.fixedHeight)&&(this.resources.frameHeight=this.height,this.resources.iframe.style.height=`${this.height}px`,this.resources.bridge?.setHostContext(Jr(this.mount.value,this.height))))}async request(e,t,n,r){try{let i={sessionKey:e.sessionKey,viewId:e.viewId,...n};return await(r?e.client.request(t,i,{signal:r}):e.client.request(t,i))}catch(e){throw o(e)&&this.dispatchEvent(new CustomEvent(Oe,{bubbles:!0,composed:!0})),e}}addResourceCleanup(e,t){return e.cleanups.add(t),()=>{e.cleanups.delete(t)&&t()}}runResourceCleanups(e){for(let t of e.cleanups)e.cleanups.delete(t),t()}async teardownResources(e){if(!e||e.disposed){await this.teardownPromise;return}e.disposed=!0,this.resources===e&&(this.resources=null),this.runResourceCleanups(e);let t=(async()=>{if(e.bridge){let t;try{await Promise.race([e.bridge.teardownResource({}).catch(()=>void 0),new Promise(e=>{t=window.setTimeout(e,Yr)})])}finally{t!==void 0&&window.clearTimeout(t)}}await e.transport?.close().catch(()=>void 0),e.iframe.remove()})();this.teardownPromise=t;try{await t}finally{this.teardownPromise===t&&(this.teardownPromise=null)}}async teardown(){this.setupTask.abort(),await this.teardownResources(this.resources)}restartAfterTeardown(){!this.isConnected||this.resources||this.teardownPromise||this.setupTask.run()}async setupResources(e,t){let{sessionKey:n,viewId:r}=e,i=null;try{let a=await this.request(e,`mcp.app.view`,{},t),o=this.mount.value;if(t.throwIfAborted(),!o)throw Error(h(`mcpApp.errors.mountUnavailable`));let s=document.createElement(`iframe`);s.title=this.title||h(`mcpApp.title`),s.referrerPolicy=`origin`,s.style.height=`${this.height}px`,s.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`),o.appendChild(s);let c={bridge:null,cleanups:new Set,frameHeight:this.height,iframe:s,transport:null,disposed:!1};i=c,this.resources=c,t.addEventListener(`abort`,()=>void this.teardownResources(c),{once:!0});let l=new Promise((e,t)=>{let n=window.setTimeout(()=>{i(),t(Error(h(`mcpApp.errors.sandboxTimedOut`)))},15e3),r=t=>{t.source===s.contentWindow&&t.data?.method===`ui/notifications/sandbox-proxy-ready`&&(i(),e())},i=this.addResourceCleanup(c,()=>{window.clearTimeout(n),window.removeEventListener(`message`,r)});window.addEventListener(`message`,r)});if(s.src=Te(a.sandboxUrl,a.sandboxPort,a.sandboxOrigin,this.context?.gateway.connection.gatewayUrl??``,window.location.origin),await l,t.throwIfAborted(),!s.contentWindow)throw Error(h(`mcpApp.errors.sandboxUnavailable`));let u=new Xr(null,{name:`OpenClaw`,version:`1.0.0`},Ee(a.csp,a.messageSupported===!0,a.updateModelContextSupported===!0,a.messageSupported===!0),{hostContext:Jr(o,this.height)});c.bridge=u;let d=(t,n)=>this.request(e,t,n),f=()=>{this.teardown()};if(u.onrequestteardown=f,this.addResourceCleanup(c,()=>{u.onrequestteardown===f&&(u.onrequestteardown=void 0)}),a.messageSupported===!0){let e=`${n}\0${r}`;u.setMessageHandler(async({content:t})=>{let n=t.length===1?t[0]:void 0,r=n?.type===`text`?n.text:null;return De(s,r,e,e=>window.confirm(`${h(`common.confirm`)}:\n\n${e}`))?{}:{isError:!0}})}a.updateModelContextSupported===!0&&u.setUpdateModelContextHandler(async e=>(await d(`mcp.app.updateModelContext`,{...e}),{})),u.oncalltool=async e=>await d(`mcp.app.callTool`,{toolName:e.name,arguments:e.arguments}),u.setListToolsHandler(async e=>await d(`mcp.app.listTools`,e?.cursor?{cursor:e.cursor}:{})),u.onlistresources=async e=>await d(`mcp.app.listResources`,e?.cursor?{cursor:e.cursor}:{}),u.onlistresourcetemplates=async e=>await d(`mcp.app.listResourceTemplates`,e?.cursor?{cursor:e.cursor}:{}),u.onreadresource=async e=>await d(`mcp.app.readResource`,{uri:e.uri}),u.onopenlink=async({url:e})=>Ae(e)?{}:{isError:!0},u.onsizechange=({height:e})=>{if(e!==void 0&&!this.fixedHeight){let t=Math.min(1200,Math.max(160,Math.round(e)));c.frameHeight=t,s.style.height=`${t}px`,u.setHostContext(Jr(o,t))}};let ee=new Promise(e=>{u.oninitialized=()=>e()}),te=new zr(s.contentWindow,s.contentWindow);c.transport=te,await u.connect(te),t.throwIfAborted(),await u.sendSandboxResourceReady({html:a.html,csp:a.csp});let p,ne=this.addResourceCleanup(c,()=>{p!==void 0&&window.clearTimeout(p)});try{await Promise.race([ee,new Promise((e,t)=>{p=window.setTimeout(()=>t(Error(h(`mcpApp.errors.initializationTimedOut`))),15e3)})])}finally{ne()}t.throwIfAborted();let m=()=>u.setHostContext(Jr(o,c.frameHeight)),re=this.context?.theme.subscribe(m);if(re&&this.addResourceCleanup(c,re),typeof ResizeObserver<`u`){let e=new ResizeObserver(m);e.observe(o),this.addResourceCleanup(c,()=>e.disconnect())}return await qr(),t.throwIfAborted(),await u.sendToolInput({arguments:a.toolInput&&typeof a.toolInput==`object`&&!Array.isArray(a.toolInput)?a.toolInput:{}}),await u.sendToolResult(a.toolResult),t.throwIfAborted(),c}catch(e){throw await this.teardownResources(i),e}}render(){let e=this.setupTask.status===le.ERROR?this.setupTask.error:null,t=e?h(`mcpApp.unavailable`,{error:c(e,h(`mcpApp.errors.requestFailed`))}):null;return ee`<div ${d(this.mount)} class="mount"></div>
      ${t?ee`<div class="error">${t}</div>`:ne}`}},a([n({context:ae,subscribe:!0})],$.prototype,`context`,void 0),a([m({attribute:!1})],$.prototype,`sessionKey`,void 0),a([m({attribute:!1})],$.prototype,`viewId`,void 0),a([m({type:Number})],$.prototype,`height`,void 0),a([m({type:Boolean})],$.prototype,`fixedHeight`,void 0),a([m()],$.prototype,`title`,void 0)})))()}function Qr(){customElements.get(`mcp-app-view`)||customElements.define(`mcp-app-view`,$)}function $r(){return($r=t((()=>{Zr(),Qr()})))()}$r();export{Qr as registerMcpAppView};
//# sourceMappingURL=mcp-app-view-registration-BuAQbPJ2.js.map