@grackle-ai/web 0.134.0 → 0.135.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Mt=Object.defineProperty;var Nt=(l,o,e)=>o in l?Mt(l,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[o]=e;var m=(l,o,e)=>Nt(l,typeof o!="symbol"?o+"":o,e);import{b as K,j as Lt}from"./dagview-B70jDsRo.js";import{l as a,k as x,r as S,m as h,u as f,o as r,s as n,n as v,q as p,_ as $,v as z,x as At,y as q,z as zt,B as Xe,E as et,F as Ut,H as tt,I as Ot,J as we,K as Je}from"./grpc-CHXyF1mC.js";const Dt={"--color-background-primary":"light-dark(#ffffff, #1a1a1a)","--color-background-secondary":"light-dark(#f5f5f5, #2d2d2d)","--color-background-tertiary":"light-dark(#e5e5e5, #404040)","--color-background-inverse":"light-dark(#1a1a1a, #ffffff)","--color-background-ghost":"light-dark(rgba(255,255,255,0), rgba(26,26,26,0))","--color-background-info":"light-dark(#eff6ff, #1e3a5f)","--color-background-danger":"light-dark(#fef2f2, #7f1d1d)","--color-background-success":"light-dark(#f0fdf4, #14532d)","--color-background-warning":"light-dark(#fefce8, #713f12)","--color-background-disabled":"light-dark(rgba(255,255,255,0.5), rgba(26,26,26,0.5))","--color-text-primary":"light-dark(#1f2937, #f3f4f6)","--color-text-secondary":"light-dark(#6b7280, #9ca3af)","--color-text-tertiary":"light-dark(#9ca3af, #6b7280)","--color-text-inverse":"light-dark(#f3f4f6, #1f2937)","--color-text-ghost":"light-dark(rgba(107,114,128,0.5), rgba(156,163,175,0.5))","--color-text-info":"light-dark(#1d4ed8, #60a5fa)","--color-text-danger":"light-dark(#b91c1c, #f87171)","--color-text-success":"light-dark(#15803d, #4ade80)","--color-text-warning":"light-dark(#a16207, #fbbf24)","--color-text-disabled":"light-dark(rgba(31,41,55,0.5), rgba(243,244,246,0.5))","--color-border-primary":"light-dark(#e5e7eb, #404040)","--color-border-secondary":"light-dark(#d1d5db, #525252)","--color-border-tertiary":"light-dark(#f3f4f6, #374151)","--color-border-inverse":"light-dark(rgba(255,255,255,0.3), rgba(0,0,0,0.3))","--color-border-ghost":"light-dark(rgba(229,231,235,0), rgba(64,64,64,0))","--color-border-info":"light-dark(#93c5fd, #1e40af)","--color-border-danger":"light-dark(#fca5a5, #991b1b)","--color-border-success":"light-dark(#86efac, #166534)","--color-border-warning":"light-dark(#fde047, #854d0e)","--color-border-disabled":"light-dark(rgba(229,231,235,0.5), rgba(64,64,64,0.5))","--color-ring-primary":"light-dark(#3b82f6, #60a5fa)","--color-ring-secondary":"light-dark(#6b7280, #9ca3af)","--color-ring-inverse":"light-dark(#ffffff, #1f2937)","--color-ring-info":"light-dark(#2563eb, #3b82f6)","--color-ring-danger":"light-dark(#dc2626, #ef4444)","--color-ring-success":"light-dark(#16a34a, #22c55e)","--color-ring-warning":"light-dark(#ca8a04, #eab308)","--font-sans":"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif","--font-mono":"ui-monospace, 'SF Mono', Monaco, 'Cascadia Code', monospace","--font-weight-normal":"400","--font-weight-medium":"500","--font-weight-semibold":"600","--font-weight-bold":"700","--font-text-xs-size":"0.75rem","--font-text-sm-size":"0.875rem","--font-text-md-size":"1rem","--font-text-lg-size":"1.125rem","--font-heading-xs-size":"0.75rem","--font-heading-sm-size":"0.875rem","--font-heading-md-size":"1rem","--font-heading-lg-size":"1.25rem","--font-heading-xl-size":"1.5rem","--font-heading-2xl-size":"1.875rem","--font-heading-3xl-size":"2.25rem","--font-text-xs-line-height":"1.4","--font-text-sm-line-height":"1.4","--font-text-md-line-height":"1.5","--font-text-lg-line-height":"1.5","--font-heading-xs-line-height":"1.4","--font-heading-sm-line-height":"1.4","--font-heading-md-line-height":"1.4","--font-heading-lg-line-height":"1.3","--font-heading-xl-line-height":"1.25","--font-heading-2xl-line-height":"1.2","--font-heading-3xl-line-height":"1.1","--border-radius-xs":"2px","--border-radius-sm":"4px","--border-radius-md":"6px","--border-radius-lg":"8px","--border-radius-xl":"12px","--border-radius-full":"9999px","--border-width-regular":"1px","--shadow-hairline":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--shadow-sm":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)","--shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)","--shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},$t={"--color-background-primary":"--bg-base","--color-background-secondary":"--bg-surface","--color-background-tertiary":"--bg-elevated","--color-text-primary":"--text-primary","--color-text-secondary":"--text-secondary","--color-text-tertiary":"--text-tertiary","--color-border-primary":"--border-primary","--color-border-secondary":"--border-subtle","--font-sans":"--font-sans","--font-mono":"--font-mono","--border-radius-sm":"--radius-sm","--border-radius-md":"--radius-md","--border-radius-lg":"--radius-lg","--border-radius-full":"--radius-full"};function Ve(){const l={...Dt};if(typeof window>"u"||typeof document>"u")return l;const o=window.getComputedStyle(document.documentElement),e=l;for(const[t,s]of Object.entries($t)){const i=o.getPropertyValue(s).trim();i&&(e[t]=i)}return l}const Y="io.modelcontextprotocol/related-task",ye="2.0",H=At(l=>l!==null&&(typeof l=="object"||typeof l=="function")),st=f([n(),p().int()]),ot=n();z({ttl:p().optional(),pollInterval:p().optional()});const Ft=r({ttl:p().optional()}),jt=r({taskId:n()}),xe=z({progressToken:st.optional(),[Y]:jt.optional()}),U=r({_meta:xe.optional()}),ne=U.extend({task:Ft.optional()}),Bt=l=>ne.safeParse(l).success,N=r({method:n(),params:U.loose().optional()}),F=r({_meta:xe.optional()}),j=r({method:n(),params:F.loose().optional()}),L=z({_meta:xe.optional()}),re=f([n(),p().int()]),at=r({jsonrpc:a(ye),id:re,...N.shape}).strict(),Qe=l=>at.safeParse(l).success,nt=r({jsonrpc:a(ye),...j.shape}).strict(),Jt=l=>nt.safeParse(l).success,Re=r({jsonrpc:a(ye),id:re,result:L}).strict(),fe=l=>Re.safeParse(l).success;var k;(function(l){l[l.ConnectionClosed=-32e3]="ConnectionClosed",l[l.RequestTimeout=-32001]="RequestTimeout",l[l.ParseError=-32700]="ParseError",l[l.InvalidRequest=-32600]="InvalidRequest",l[l.MethodNotFound=-32601]="MethodNotFound",l[l.InvalidParams=-32602]="InvalidParams",l[l.InternalError=-32603]="InternalError",l[l.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(k||(k={}));const ve=r({jsonrpc:a(ye),id:re.optional(),error:r({code:p().int(),message:n(),data:v().optional()})}).strict(),Vt=l=>ve.safeParse(l).success,Qt=f([at,nt,Re,ve]);f([Re,ve]);const rt=L.strict(),Wt=F.extend({requestId:re.optional(),reason:n().optional()}),Te=j.extend({method:a("notifications/cancelled"),params:Wt}),Kt=r({src:n(),mimeType:n().optional(),sizes:h(n()).optional(),theme:$(["light","dark"]).optional()}),ie=r({icons:h(Kt).optional()}),Z=r({name:n(),title:n().optional()}),Se=Z.extend({...Z.shape,...ie.shape,version:n(),websiteUrl:n().optional(),description:n().optional()}),Gt=Xe(r({applyDefaults:x().optional()}),S(n(),v())),Yt=et(l=>l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length===0?{form:{}}:l,Xe(r({form:Gt.optional(),url:H.optional()}),S(n(),v()).optional())),Zt=z({list:H.optional(),cancel:H.optional(),requests:z({sampling:z({createMessage:H.optional()}).optional(),elicitation:z({create:H.optional()}).optional()}).optional()}),Xt=z({list:H.optional(),cancel:H.optional(),requests:z({tools:z({call:H.optional()}).optional()}).optional()}),es=r({experimental:S(n(),H).optional(),sampling:r({context:H.optional(),tools:H.optional()}).optional(),elicitation:Yt.optional(),roots:r({listChanged:x().optional()}).optional(),tasks:Zt.optional(),extensions:S(n(),H).optional()}),ts=U.extend({protocolVersion:n(),capabilities:es,clientInfo:Se}),ss=N.extend({method:a("initialize"),params:ts}),os=r({experimental:S(n(),H).optional(),logging:H.optional(),completions:H.optional(),prompts:r({listChanged:x().optional()}).optional(),resources:r({subscribe:x().optional(),listChanged:x().optional()}).optional(),tools:r({listChanged:x().optional()}).optional(),tasks:Xt.optional(),extensions:S(n(),H).optional()}),as=L.extend({protocolVersion:n(),capabilities:os,serverInfo:Se,instructions:n().optional()}),ns=j.extend({method:a("notifications/initialized"),params:F.optional()}),ke=N.extend({method:a("ping"),params:U.optional()}),rs=r({progress:p(),total:q(p()),message:q(n())}),is=r({...F.shape,...rs.shape,progressToken:st}),qe=j.extend({method:a("notifications/progress"),params:is}),ls=U.extend({cursor:ot.optional()}),le=N.extend({params:ls.optional()}),ce=L.extend({nextCursor:ot.optional()}),cs=$(["working","input_required","completed","failed","cancelled"]),de=r({taskId:n(),status:cs,ttl:f([p(),zt()]),createdAt:n(),lastUpdatedAt:n(),pollInterval:q(p()),statusMessage:q(n())}),Ce=L.extend({task:de}),ds=F.merge(de),ge=j.extend({method:a("notifications/tasks/status"),params:ds}),Ie=N.extend({method:a("tasks/get"),params:U.extend({taskId:n()})}),Pe=L.merge(de),He=N.extend({method:a("tasks/result"),params:U.extend({taskId:n()})});L.loose();const Ee=le.extend({method:a("tasks/list")}),Me=ce.extend({tasks:h(de)}),Ne=N.extend({method:a("tasks/cancel"),params:U.extend({taskId:n()})}),us=L.merge(de),it=r({uri:n(),mimeType:q(n()),_meta:S(n(),v()).optional()}),lt=it.extend({text:n()}),Le=n().refine(l=>{try{return atob(l),!0}catch{return!1}},{message:"Invalid Base64 string"}),ct=it.extend({blob:Le}),ue=$(["user","assistant"]),X=r({audience:h(ue).optional(),priority:p().min(0).max(1).optional(),lastModified:Ut({offset:!0}).optional()}),dt=r({...Z.shape,...ie.shape,uri:n(),description:q(n()),mimeType:q(n()),size:q(p()),annotations:X.optional(),_meta:q(z({}))}),hs=r({...Z.shape,...ie.shape,uriTemplate:n(),description:q(n()),mimeType:q(n()),annotations:X.optional(),_meta:q(z({}))}),ut=le.extend({method:a("resources/list")}),ht=ce.extend({resources:h(dt)}),pt=le.extend({method:a("resources/templates/list")}),mt=ce.extend({resourceTemplates:h(hs)}),Ae=U.extend({uri:n()}),ps=Ae,ft=N.extend({method:a("resources/read"),params:ps}),gt=L.extend({contents:h(f([lt,ct]))}),bt=j.extend({method:a("notifications/resources/list_changed"),params:F.optional()}),ms=Ae,fs=N.extend({method:a("resources/subscribe"),params:ms}),gs=Ae,bs=N.extend({method:a("resources/unsubscribe"),params:gs}),ys=F.extend({uri:n()}),Ss=j.extend({method:a("notifications/resources/updated"),params:ys}),ks=r({name:n(),description:q(n()),required:q(x())}),_s=r({...Z.shape,...ie.shape,description:q(n()),arguments:q(h(ks)),_meta:q(z({}))}),yt=le.extend({method:a("prompts/list")}),St=ce.extend({prompts:h(_s)}),ws=U.extend({name:n(),arguments:S(n(),n()).optional()}),xs=N.extend({method:a("prompts/get"),params:ws}),ze=r({type:a("text"),text:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Ue=r({type:a("image"),data:Le,mimeType:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Oe=r({type:a("audio"),data:Le,mimeType:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Rs=r({type:a("tool_use"),name:n(),id:n(),input:S(n(),v()),_meta:S(n(),v()).optional()}),kt=r({type:a("resource"),resource:f([lt,ct]),annotations:X.optional(),_meta:S(n(),v()).optional()}),_t=dt.extend({type:a("resource_link")}),he=f([ze,Ue,Oe,_t,kt]),vs=r({role:ue,content:he}),Ts=L.extend({description:n().optional(),messages:h(vs)}),wt=j.extend({method:a("notifications/prompts/list_changed"),params:F.optional()}),qs=r({title:n().optional(),readOnlyHint:x().optional(),destructiveHint:x().optional(),idempotentHint:x().optional(),openWorldHint:x().optional()}),Cs=r({taskSupport:$(["required","optional","forbidden"]).optional()}),De=r({...Z.shape,...ie.shape,description:n().optional(),inputSchema:r({type:a("object"),properties:S(n(),H).optional(),required:h(n()).optional()}).catchall(v()),outputSchema:r({type:a("object"),properties:S(n(),H).optional(),required:h(n()).optional()}).catchall(v()).optional(),annotations:qs.optional(),execution:Cs.optional(),_meta:S(n(),v()).optional()}),Is=le.extend({method:a("tools/list")}),xt=ce.extend({tools:h(De)}),oe=L.extend({content:h(he).default([]),structuredContent:S(n(),v()).optional(),isError:x().optional()});oe.or(L.extend({toolResult:v()}));const Ps=ne.extend({name:n(),arguments:S(n(),v()).optional()}),Rt=N.extend({method:a("tools/call"),params:Ps}),vt=j.extend({method:a("notifications/tools/list_changed"),params:F.optional()});r({autoRefresh:x().default(!0),debounceMs:p().int().nonnegative().default(300)});const Tt=$(["debug","info","notice","warning","error","critical","alert","emergency"]),Hs=U.extend({level:Tt}),Es=N.extend({method:a("logging/setLevel"),params:Hs}),Ms=F.extend({level:Tt,logger:n().optional(),data:v()}),qt=j.extend({method:a("notifications/message"),params:Ms}),Ns=r({name:n().optional()}),Ls=r({hints:h(Ns).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),As=r({mode:$(["auto","required","none"]).optional()}),zs=r({type:a("tool_result"),toolUseId:n().describe("The unique identifier for the corresponding tool call."),content:h(he).default([]),structuredContent:r({}).loose().optional(),isError:x().optional(),_meta:S(n(),v()).optional()}),Us=tt("type",[ze,Ue,Oe]),be=tt("type",[ze,Ue,Oe,Rs,zs]),Os=r({role:ue,content:f([be,h(be)]),_meta:S(n(),v()).optional()}),Ds=ne.extend({messages:h(Os),modelPreferences:Ls.optional(),systemPrompt:n().optional(),includeContext:$(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:h(n()).optional(),metadata:H.optional(),tools:h(De).optional(),toolChoice:As.optional()}),Ct=N.extend({method:a("sampling/createMessage"),params:Ds}),$s=L.extend({model:n(),stopReason:q($(["endTurn","stopSequence","maxTokens"]).or(n())),role:ue,content:Us}),Fs=L.extend({model:n(),stopReason:q($(["endTurn","stopSequence","maxTokens","toolUse"]).or(n())),role:ue,content:f([be,h(be)])}),js=r({type:a("boolean"),title:n().optional(),description:n().optional(),default:x().optional()}),Bs=r({type:a("string"),title:n().optional(),description:n().optional(),minLength:p().optional(),maxLength:p().optional(),format:$(["email","uri","date","date-time"]).optional(),default:n().optional()}),Js=r({type:$(["number","integer"]),title:n().optional(),description:n().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),Vs=r({type:a("string"),title:n().optional(),description:n().optional(),enum:h(n()),default:n().optional()}),Qs=r({type:a("string"),title:n().optional(),description:n().optional(),oneOf:h(r({const:n(),title:n()})),default:n().optional()}),Ws=r({type:a("string"),title:n().optional(),description:n().optional(),enum:h(n()),enumNames:h(n()).optional(),default:n().optional()}),Ks=f([Vs,Qs]),Gs=r({type:a("array"),title:n().optional(),description:n().optional(),minItems:p().optional(),maxItems:p().optional(),items:r({type:a("string"),enum:h(n())}),default:h(n()).optional()}),Ys=r({type:a("array"),title:n().optional(),description:n().optional(),minItems:p().optional(),maxItems:p().optional(),items:r({anyOf:h(r({const:n(),title:n()}))}),default:h(n()).optional()}),Zs=f([Gs,Ys]),Xs=f([Ws,Ks,Zs]),eo=f([Xs,js,Bs,Js]),to=ne.extend({mode:a("form").optional(),message:n(),requestedSchema:r({type:a("object"),properties:S(n(),eo),required:h(n()).optional()})}),so=ne.extend({mode:a("url"),message:n(),elicitationId:n(),url:n().url()}),oo=f([to,so]),ao=N.extend({method:a("elicitation/create"),params:oo}),no=F.extend({elicitationId:n()}),ro=j.extend({method:a("notifications/elicitation/complete"),params:no}),io=L.extend({action:$(["accept","decline","cancel"]),content:et(l=>l===null?void 0:l,S(n(),f([n(),p(),x(),h(n())])).optional())}),lo=r({type:a("ref/resource"),uri:n()}),co=r({type:a("ref/prompt"),name:n()}),uo=U.extend({ref:f([co,lo]),argument:r({name:n(),value:n()}),context:r({arguments:S(n(),n()).optional()}).optional()}),ho=N.extend({method:a("completion/complete"),params:uo}),po=L.extend({completion:z({values:h(n()).max(100),total:q(p().int()),hasMore:q(x())})}),mo=r({uri:n().startsWith("file://"),name:n().optional(),_meta:S(n(),v()).optional()}),fo=N.extend({method:a("roots/list"),params:U.optional()}),go=L.extend({roots:h(mo)}),bo=j.extend({method:a("notifications/roots/list_changed"),params:F.optional()});f([ke,ss,ho,Es,xs,yt,ut,pt,ft,fs,bs,Rt,Is,Ie,He,Ee,Ne]);f([Te,qe,ns,bo,ge]);f([rt,$s,Fs,io,go,Pe,Me,Ce]);f([ke,Ct,ao,fo,Ie,He,Ee,Ne]);f([Te,qe,qt,Ss,bt,vt,wt,ge,ro]);f([rt,as,po,Ts,St,ht,mt,gt,oe,xt,Pe,Me,Ce]);class y extends Error{constructor(o,e,t){super(`MCP error ${o}: ${e}`),this.code=o,this.data=t,this.name="McpError"}static fromError(o,e,t){if(o===k.UrlElicitationRequired&&t){const s=t;if(s.elicitations)return new yo(s.elicitations,e)}return new y(o,e,t)}}class yo extends y{constructor(o,e=`URL elicitation${o.length>1?"s":""} required`){super(k.UrlElicitationRequired,e,{elicitations:o})}get elicitations(){var o;return((o=this.data)==null?void 0:o.elicitations)??[]}}function $e(l){return!!l._zod}function It(l,o){return $e(l)?Ot(l,o):l.safeParse(o)}function So(l){var e,t;if(!l)return;let o;if($e(l)?o=(t=(e=l._zod)==null?void 0:e.def)==null?void 0:t.shape:o=l.shape,!!o){if(typeof o=="function")try{return o()}catch{return}return o}}function ko(l){var s;if($e(l)){const c=(s=l._zod)==null?void 0:s.def;if(c){if(c.value!==void 0)return c.value;if(Array.isArray(c.values)&&c.values.length>0)return c.values[0]}}const e=l._def;if(e){if(e.value!==void 0)return e.value;if(Array.isArray(e.values)&&e.values.length>0)return e.values[0]}const t=l.value;if(t!==void 0)return t}function G(l){return l==="completed"||l==="failed"||l==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function We(l){const o=So(l),e=o==null?void 0:o.method;if(!e)throw new Error("Schema is missing a method literal");const t=ko(e);if(typeof t!="string")throw new Error("Schema method literal must be a string");return t}function Ke(l,o){const e=It(l,o);if(!e.success)throw e.error;return e.data}const _o=6e4;class wo{constructor(o){this._options=o,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(Te,e=>{this._oncancel(e)}),this.setNotificationHandler(qe,e=>{this._onprogress(e)}),this.setRequestHandler(ke,e=>({})),this._taskStore=o==null?void 0:o.taskStore,this._taskMessageQueue=o==null?void 0:o.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ie,async(e,t)=>{const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new y(k.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(He,async(e,t)=>{const s=async()=>{var u;const i=e.params.taskId;if(this._taskMessageQueue){let d;for(;d=await this._taskMessageQueue.dequeue(i,t.sessionId);){if(d.type==="response"||d.type==="error"){const g=d.message,w=g.id,_=this._requestResolvers.get(w);if(_)if(this._requestResolvers.delete(w),d.type==="response")_(g);else{const b=g,P=new y(b.error.code,b.error.message,b.error.data);_(P)}else{const b=d.type==="response"?"Response":"Error";this._onerror(new Error(`${b} handler missing for request ${w}`))}continue}await((u=this._transport)==null?void 0:u.send(d.message,{relatedRequestId:t.requestId}))}}const c=await this._taskStore.getTask(i,t.sessionId);if(!c)throw new y(k.InvalidParams,`Task not found: ${i}`);if(!G(c.status))return await this._waitForTaskUpdate(i,t.signal),await s();if(G(c.status)){const d=await this._taskStore.getTaskResult(i,t.sessionId);return this._clearTaskQueue(i),{...d,_meta:{...d._meta,[Y]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(Ee,async(e,t)=>{var s;try{const{tasks:i,nextCursor:c}=await this._taskStore.listTasks((s=e.params)==null?void 0:s.cursor,t.sessionId);return{tasks:i,nextCursor:c,_meta:{}}}catch(i){throw new y(k.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Ne,async(e,t)=>{try{const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new y(k.InvalidParams,`Task not found: ${e.params.taskId}`);if(G(s.status))throw new y(k.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const i=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!i)throw new y(k.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof y?s:new y(k.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(o){if(!o.params.requestId)return;const e=this._requestHandlerAbortControllers.get(o.params.requestId);e==null||e.abort(o.params.reason)}_setupTimeout(o,e,t,s,i=!1){this._timeoutInfo.set(o,{timeoutId:setTimeout(s,e),startTime:Date.now(),timeout:e,maxTotalTimeout:t,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(o){const e=this._timeoutInfo.get(o);if(!e)return!1;const t=Date.now()-e.startTime;if(e.maxTotalTimeout&&t>=e.maxTotalTimeout)throw this._timeoutInfo.delete(o),y.fromError(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:e.maxTotalTimeout,totalElapsed:t});return clearTimeout(e.timeoutId),e.timeoutId=setTimeout(e.onTimeout,e.timeout),!0}_cleanupTimeout(o){const e=this._timeoutInfo.get(o);e&&(clearTimeout(e.timeoutId),this._timeoutInfo.delete(o))}async connect(o){var i,c,u;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=o;const e=(i=this.transport)==null?void 0:i.onclose;this._transport.onclose=()=>{e==null||e(),this._onclose()};const t=(c=this.transport)==null?void 0:c.onerror;this._transport.onerror=d=>{t==null||t(d),this._onerror(d)};const s=(u=this._transport)==null?void 0:u.onmessage;this._transport.onmessage=(d,g)=>{s==null||s(d,g),fe(d)||Vt(d)?this._onresponse(d):Qe(d)?this._onrequest(d,g):Jt(d)?this._onnotification(d):this._onerror(new Error(`Unknown message type: ${JSON.stringify(d)}`))},await this._transport.start()}_onclose(){var t;const o=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const s of this._timeoutInfo.values())clearTimeout(s.timeoutId);this._timeoutInfo.clear();for(const s of this._requestHandlerAbortControllers.values())s.abort();this._requestHandlerAbortControllers.clear();const e=y.fromError(k.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)==null||t.call(this);for(const s of o.values())s(e)}_onerror(o){var e;(e=this.onerror)==null||e.call(this,o)}_onnotification(o){const e=this._notificationHandlers.get(o.method)??this.fallbackNotificationHandler;e!==void 0&&Promise.resolve().then(()=>e(o)).catch(t=>this._onerror(new Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(o,e){var w,_,b,P;const t=this._requestHandlers.get(o.method)??this.fallbackRequestHandler,s=this._transport,i=(b=(_=(w=o.params)==null?void 0:w._meta)==null?void 0:_[Y])==null?void 0:b.taskId;if(t===void 0){const R={jsonrpc:"2.0",id:o.id,error:{code:k.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:R,timestamp:Date.now()},s==null?void 0:s.sessionId).catch(C=>this._onerror(new Error(`Failed to enqueue error response: ${C}`))):s==null||s.send(R).catch(C=>this._onerror(new Error(`Failed to send an error response: ${C}`)));return}const c=new AbortController;this._requestHandlerAbortControllers.set(o.id,c);const u=Bt(o.params)?o.params.task:void 0,d=this._taskStore?this.requestTaskStore(o,s==null?void 0:s.sessionId):void 0,g={signal:c.signal,sessionId:s==null?void 0:s.sessionId,_meta:(P=o.params)==null?void 0:P._meta,sendNotification:async R=>{if(c.signal.aborted)return;const C={relatedRequestId:o.id};i&&(C.relatedTask={taskId:i}),await this.notification(R,C)},sendRequest:async(R,C,V)=>{var D;if(c.signal.aborted)throw new y(k.ConnectionClosed,"Request was cancelled");const O={...V,relatedRequestId:o.id};i&&!O.relatedTask&&(O.relatedTask={taskId:i});const Q=((D=O.relatedTask)==null?void 0:D.taskId)??i;return Q&&d&&await d.updateTaskStatus(Q,"input_required"),await this.request(R,C,O)},authInfo:e==null?void 0:e.authInfo,requestId:o.id,requestInfo:e==null?void 0:e.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u==null?void 0:u.ttl,closeSSEStream:e==null?void 0:e.closeSSEStream,closeStandaloneSSEStream:e==null?void 0:e.closeStandaloneSSEStream};Promise.resolve().then(()=>{u&&this.assertTaskHandlerCapability(o.method)}).then(()=>t(o,g)).then(async R=>{if(c.signal.aborted)return;const C={result:R,jsonrpc:"2.0",id:o.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:C,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(C))},async R=>{if(c.signal.aborted)return;const C={jsonrpc:"2.0",id:o.id,error:{code:Number.isSafeInteger(R.code)?R.code:k.InternalError,message:R.message??"Internal error",...R.data!==void 0&&{data:R.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:C,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(C))}).catch(R=>this._onerror(new Error(`Failed to send response: ${R}`))).finally(()=>{this._requestHandlerAbortControllers.get(o.id)===c&&this._requestHandlerAbortControllers.delete(o.id)})}_onprogress(o){const{progressToken:e,...t}=o.params,s=Number(e),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(o)}`));return}const c=this._responseHandlers.get(s),u=this._timeoutInfo.get(s);if(u&&c&&u.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(d){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),c(d);return}i(t)}_onresponse(o){const e=Number(o.id),t=this._requestResolvers.get(e);if(t){if(this._requestResolvers.delete(e),fe(o))t(o);else{const c=new y(o.error.code,o.error.message,o.error.data);t(c)}return}const s=this._responseHandlers.get(e);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(o)}`));return}this._responseHandlers.delete(e),this._cleanupTimeout(e);let i=!1;if(fe(o)&&o.result&&typeof o.result=="object"){const c=o.result;if(c.task&&typeof c.task=="object"){const u=c.task;typeof u.taskId=="string"&&(i=!0,this._taskProgressTokens.set(u.taskId,e))}}if(i||this._progressHandlers.delete(e),fe(o))s(o);else{const c=y.fromError(o.error.code,o.error.message,o.error.data);s(c)}}get transport(){return this._transport}async close(){var o;await((o=this._transport)==null?void 0:o.close())}async*requestStream(o,e,t){var c,u;const{task:s}=t??{};if(!s){try{yield{type:"result",result:await this.request(o,e,t)}}catch(d){yield{type:"error",error:d instanceof y?d:new y(k.InternalError,String(d))}}return}let i;try{const d=await this.request(o,Ce,t);if(d.task)i=d.task.taskId,yield{type:"taskCreated",task:d.task};else throw new y(k.InternalError,"Task creation did not return a task");for(;;){const g=await this.getTask({taskId:i},t);if(yield{type:"taskStatus",task:g},G(g.status)){g.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},e,t)}:g.status==="failed"?yield{type:"error",error:new y(k.InternalError,`Task ${i} failed`)}:g.status==="cancelled"&&(yield{type:"error",error:new y(k.InternalError,`Task ${i} was cancelled`)});return}if(g.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},e,t)};return}const w=g.pollInterval??((c=this._options)==null?void 0:c.defaultTaskPollInterval)??1e3;await new Promise(_=>setTimeout(_,w)),(u=t==null?void 0:t.signal)==null||u.throwIfAborted()}}catch(d){yield{type:"error",error:d instanceof y?d:new y(k.InternalError,String(d))}}}request(o,e,t){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c,task:u,relatedTask:d}=t??{};return new Promise((g,w)=>{var Q,D,pe,me,I;const _=T=>{w(T)};if(!this._transport){_(new Error("Not connected"));return}if(((Q=this._options)==null?void 0:Q.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(o.method),u&&this.assertTaskCapability(o.method)}catch(T){_(T);return}(D=t==null?void 0:t.signal)==null||D.throwIfAborted();const b=this._requestMessageId++,P={...o,jsonrpc:"2.0",id:b};t!=null&&t.onprogress&&(this._progressHandlers.set(b,t.onprogress),P.params={...o.params,_meta:{...((pe=o.params)==null?void 0:pe._meta)||{},progressToken:b}}),u&&(P.params={...P.params,task:u}),d&&(P.params={...P.params,_meta:{...((me=P.params)==null?void 0:me._meta)||{},[Y]:d}});const R=T=>{var A;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(A=this._transport)==null||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(T)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c}).catch(ee=>this._onerror(new Error(`Failed to send cancellation: ${ee}`)));const B=T instanceof y?T:new y(k.RequestTimeout,String(T));w(B)};this._responseHandlers.set(b,T=>{var B;if(!((B=t==null?void 0:t.signal)!=null&&B.aborted)){if(T instanceof Error)return w(T);try{const A=It(e,T.result);A.success?g(A.data):w(A.error)}catch(A){w(A)}}}),(I=t==null?void 0:t.signal)==null||I.addEventListener("abort",()=>{var T;R((T=t==null?void 0:t.signal)==null?void 0:T.reason)});const C=(t==null?void 0:t.timeout)??_o,V=()=>R(y.fromError(k.RequestTimeout,"Request timed out",{timeout:C}));this._setupTimeout(b,C,t==null?void 0:t.maxTotalTimeout,V,(t==null?void 0:t.resetTimeoutOnProgress)??!1);const O=d==null?void 0:d.taskId;if(O){const T=B=>{const A=this._responseHandlers.get(b);A?A(B):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,T),this._enqueueTaskMessage(O,{type:"request",message:P,timestamp:Date.now()}).catch(B=>{this._cleanupTimeout(b),w(B)})}else this._transport.send(P,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c}).catch(T=>{this._cleanupTimeout(b),w(T)})})}async getTask(o,e){return this.request({method:"tasks/get",params:o},Pe,e)}async getTaskResult(o,e,t){return this.request({method:"tasks/result",params:o},e,t)}async listTasks(o,e){return this.request({method:"tasks/list",params:o},Me,e)}async cancelTask(o,e){return this.request({method:"tasks/cancel",params:o},us,e)}async notification(o,e){var u,d,g,w;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(o.method);const t=(u=e==null?void 0:e.relatedTask)==null?void 0:u.taskId;if(t){const _={...o,jsonrpc:"2.0",params:{...o.params,_meta:{...((d=o.params)==null?void 0:d._meta)||{},[Y]:e.relatedTask}}};await this._enqueueTaskMessage(t,{type:"notification",message:_,timestamp:Date.now()});return}if((((g=this._options)==null?void 0:g.debouncedNotificationMethods)??[]).includes(o.method)&&!o.params&&!(e!=null&&e.relatedRequestId)&&!(e!=null&&e.relatedTask)){if(this._pendingDebouncedNotifications.has(o.method))return;this._pendingDebouncedNotifications.add(o.method),Promise.resolve().then(()=>{var b,P;if(this._pendingDebouncedNotifications.delete(o.method),!this._transport)return;let _={...o,jsonrpc:"2.0"};e!=null&&e.relatedTask&&(_={..._,params:{..._.params,_meta:{...((b=_.params)==null?void 0:b._meta)||{},[Y]:e.relatedTask}}}),(P=this._transport)==null||P.send(_,e).catch(R=>this._onerror(R))});return}let c={...o,jsonrpc:"2.0"};e!=null&&e.relatedTask&&(c={...c,params:{...c.params,_meta:{...((w=c.params)==null?void 0:w._meta)||{},[Y]:e.relatedTask}}}),await this._transport.send(c,e)}setRequestHandler(o,e){const t=We(o);this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(s,i)=>{const c=Ke(o,s);return Promise.resolve(e(c,i))})}removeRequestHandler(o){this._requestHandlers.delete(o)}assertCanSetRequestHandler(o){if(this._requestHandlers.has(o))throw new Error(`A request handler for ${o} already exists, which would be overridden`)}setNotificationHandler(o,e){const t=We(o);this._notificationHandlers.set(t,s=>{const i=Ke(o,s);return Promise.resolve(e(i))})}removeNotificationHandler(o){this._notificationHandlers.delete(o)}_cleanupTaskProgressHandler(o){const e=this._taskProgressTokens.get(o);e!==void 0&&(this._progressHandlers.delete(e),this._taskProgressTokens.delete(o))}async _enqueueTaskMessage(o,e,t){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(i=this._options)==null?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(o,e,t,s)}async _clearTaskQueue(o,e){if(this._taskMessageQueue){const t=await this._taskMessageQueue.dequeueAll(o,e);for(const s of t)if(s.type==="request"&&Qe(s.message)){const i=s.message.id,c=this._requestResolvers.get(i);c?(c(new y(k.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${o} cleanup`))}}}async _waitForTaskUpdate(o,e){var s,i;let t=((s=this._options)==null?void 0:s.defaultTaskPollInterval)??1e3;try{const c=await((i=this._taskStore)==null?void 0:i.getTask(o));c!=null&&c.pollInterval&&(t=c.pollInterval)}catch{}return new Promise((c,u)=>{if(e.aborted){u(new y(k.InvalidRequest,"Request cancelled"));return}const d=setTimeout(c,t);e.addEventListener("abort",()=>{clearTimeout(d),u(new y(k.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(o,e){const t=this._taskStore;if(!t)throw new Error("No task store configured");return{createTask:async s=>{if(!o)throw new Error("No request provided");return await t.createTask(s,o.id,{method:o.method,params:o.params},e)},getTask:async s=>{const i=await t.getTask(s,e);if(!i)throw new y(k.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,c)=>{await t.storeTaskResult(s,i,c,e);const u=await t.getTask(s,e);if(u){const d=ge.parse({method:"notifications/tasks/status",params:u});await this.notification(d),G(u.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>t.getTaskResult(s,e),updateTaskStatus:async(s,i,c)=>{const u=await t.getTask(s,e);if(!u)throw new y(k.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(G(u.status))throw new y(k.InvalidParams,`Cannot update task "${s}" from terminal status "${u.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await t.updateTaskStatus(s,i,c,e);const d=await t.getTask(s,e);if(d){const g=ge.parse({method:"notifications/tasks/status",params:d});await this.notification(g),G(d.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>t.listTasks(s,e)}}}(l=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(l,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):l)(function(l){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+l+'" is not supported')});class xo extends wo{constructor(){super(...arguments);m(this,"_registeredMethods",new Set);m(this,"_eventSlots",new Map);m(this,"setRequestHandler",(e,t)=>{this._assertMethodNotRegistered(e,"setRequestHandler"),super.setRequestHandler(e,t)});m(this,"setNotificationHandler",(e,t)=>{this._assertMethodNotRegistered(e,"setNotificationHandler"),super.setNotificationHandler(e,t)});m(this,"replaceRequestHandler",(e,t)=>{let s=e.shape.method.value;this._registeredMethods.add(s),super.setRequestHandler(e,t)})}onEventDispatch(e,t){}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t){let s=this.eventSchemas[e];if(!s)throw Error(`Unknown event: ${String(e)}`);t={listeners:[]},this._eventSlots.set(e,t);let i=s.shape.method.value;this._registeredMethods.add(i);let c=t;super.setNotificationHandler(s,u=>{var g;let d=u.params;this.onEventDispatch(e,d),(g=c.onHandler)==null||g.call(c,d);for(let w of[...c.listeners])w(d)})}return t}setEventHandler(e,t){let s=this._ensureEventSlot(e);s.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),s.onHandler=t}getEventHandler(e){var t;return(t=this._eventSlots.get(e))==null?void 0:t.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let s=this._eventSlots.get(e);if(!s)return;let i=s.listeners.indexOf(t);i!==-1&&s.listeners.splice(i,1)}warnIfRequestHandlerReplaced(e,t,s){t&&s&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(e,t){let s=e.shape.method.value;if(this._registeredMethods.has(s))throw Error(`Handler for "${s}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(s)}}var Pt="2026-01-26",Ro="ui/notifications/tool-input-partial",vo=f([a("light"),a("dark")]).describe("Color theme preference for the host environment."),ae=f([a("inline"),a("fullscreen"),a("pip")]).describe("Display mode for UI presentation."),To=f([a("--color-background-primary"),a("--color-background-secondary"),a("--color-background-tertiary"),a("--color-background-inverse"),a("--color-background-ghost"),a("--color-background-info"),a("--color-background-danger"),a("--color-background-success"),a("--color-background-warning"),a("--color-background-disabled"),a("--color-text-primary"),a("--color-text-secondary"),a("--color-text-tertiary"),a("--color-text-inverse"),a("--color-text-ghost"),a("--color-text-info"),a("--color-text-danger"),a("--color-text-success"),a("--color-text-warning"),a("--color-text-disabled"),a("--color-border-primary"),a("--color-border-secondary"),a("--color-border-tertiary"),a("--color-border-inverse"),a("--color-border-ghost"),a("--color-border-info"),a("--color-border-danger"),a("--color-border-success"),a("--color-border-warning"),a("--color-border-disabled"),a("--color-ring-primary"),a("--color-ring-secondary"),a("--color-ring-inverse"),a("--color-ring-info"),a("--color-ring-danger"),a("--color-ring-success"),a("--color-ring-warning"),a("--font-sans"),a("--font-mono"),a("--font-weight-normal"),a("--font-weight-medium"),a("--font-weight-semibold"),a("--font-weight-bold"),a("--font-text-xs-size"),a("--font-text-sm-size"),a("--font-text-md-size"),a("--font-text-lg-size"),a("--font-heading-xs-size"),a("--font-heading-sm-size"),a("--font-heading-md-size"),a("--font-heading-lg-size"),a("--font-heading-xl-size"),a("--font-heading-2xl-size"),a("--font-heading-3xl-size"),a("--font-text-xs-line-height"),a("--font-text-sm-line-height"),a("--font-text-md-line-height"),a("--font-text-lg-line-height"),a("--font-heading-xs-line-height"),a("--font-heading-sm-line-height"),a("--font-heading-md-line-height"),a("--font-heading-lg-line-height"),a("--font-heading-xl-line-height"),a("--font-heading-2xl-line-height"),a("--font-heading-3xl-line-height"),a("--border-radius-xs"),a("--border-radius-sm"),a("--border-radius-md"),a("--border-radius-lg"),a("--border-radius-xl"),a("--border-radius-full"),a("--border-width-regular"),a("--shadow-hairline"),a("--shadow-sm"),a("--shadow-md"),a("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),qo=S(To.describe(`Style variables for theming MCP apps.
1
+ var Mt=Object.defineProperty;var Nt=(l,o,e)=>o in l?Mt(l,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[o]=e;var m=(l,o,e)=>Nt(l,typeof o!="symbol"?o+"":o,e);import{b as K,j as Lt}from"./dagview-B70jDsRo.js";import{o as a,q as x,r as S,s as h,u as f,v as r,x as n,y as v,z as p,_ as $,B as z,E as At,F as q,H as zt,I as Xe,J as et,K as Ut,L as tt,N as Ot,P as we,Q as Je}from"./grpc-D84KWgEK.js";const Dt={"--color-background-primary":"light-dark(#ffffff, #1a1a1a)","--color-background-secondary":"light-dark(#f5f5f5, #2d2d2d)","--color-background-tertiary":"light-dark(#e5e5e5, #404040)","--color-background-inverse":"light-dark(#1a1a1a, #ffffff)","--color-background-ghost":"light-dark(rgba(255,255,255,0), rgba(26,26,26,0))","--color-background-info":"light-dark(#eff6ff, #1e3a5f)","--color-background-danger":"light-dark(#fef2f2, #7f1d1d)","--color-background-success":"light-dark(#f0fdf4, #14532d)","--color-background-warning":"light-dark(#fefce8, #713f12)","--color-background-disabled":"light-dark(rgba(255,255,255,0.5), rgba(26,26,26,0.5))","--color-text-primary":"light-dark(#1f2937, #f3f4f6)","--color-text-secondary":"light-dark(#6b7280, #9ca3af)","--color-text-tertiary":"light-dark(#9ca3af, #6b7280)","--color-text-inverse":"light-dark(#f3f4f6, #1f2937)","--color-text-ghost":"light-dark(rgba(107,114,128,0.5), rgba(156,163,175,0.5))","--color-text-info":"light-dark(#1d4ed8, #60a5fa)","--color-text-danger":"light-dark(#b91c1c, #f87171)","--color-text-success":"light-dark(#15803d, #4ade80)","--color-text-warning":"light-dark(#a16207, #fbbf24)","--color-text-disabled":"light-dark(rgba(31,41,55,0.5), rgba(243,244,246,0.5))","--color-border-primary":"light-dark(#e5e7eb, #404040)","--color-border-secondary":"light-dark(#d1d5db, #525252)","--color-border-tertiary":"light-dark(#f3f4f6, #374151)","--color-border-inverse":"light-dark(rgba(255,255,255,0.3), rgba(0,0,0,0.3))","--color-border-ghost":"light-dark(rgba(229,231,235,0), rgba(64,64,64,0))","--color-border-info":"light-dark(#93c5fd, #1e40af)","--color-border-danger":"light-dark(#fca5a5, #991b1b)","--color-border-success":"light-dark(#86efac, #166534)","--color-border-warning":"light-dark(#fde047, #854d0e)","--color-border-disabled":"light-dark(rgba(229,231,235,0.5), rgba(64,64,64,0.5))","--color-ring-primary":"light-dark(#3b82f6, #60a5fa)","--color-ring-secondary":"light-dark(#6b7280, #9ca3af)","--color-ring-inverse":"light-dark(#ffffff, #1f2937)","--color-ring-info":"light-dark(#2563eb, #3b82f6)","--color-ring-danger":"light-dark(#dc2626, #ef4444)","--color-ring-success":"light-dark(#16a34a, #22c55e)","--color-ring-warning":"light-dark(#ca8a04, #eab308)","--font-sans":"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif","--font-mono":"ui-monospace, 'SF Mono', Monaco, 'Cascadia Code', monospace","--font-weight-normal":"400","--font-weight-medium":"500","--font-weight-semibold":"600","--font-weight-bold":"700","--font-text-xs-size":"0.75rem","--font-text-sm-size":"0.875rem","--font-text-md-size":"1rem","--font-text-lg-size":"1.125rem","--font-heading-xs-size":"0.75rem","--font-heading-sm-size":"0.875rem","--font-heading-md-size":"1rem","--font-heading-lg-size":"1.25rem","--font-heading-xl-size":"1.5rem","--font-heading-2xl-size":"1.875rem","--font-heading-3xl-size":"2.25rem","--font-text-xs-line-height":"1.4","--font-text-sm-line-height":"1.4","--font-text-md-line-height":"1.5","--font-text-lg-line-height":"1.5","--font-heading-xs-line-height":"1.4","--font-heading-sm-line-height":"1.4","--font-heading-md-line-height":"1.4","--font-heading-lg-line-height":"1.3","--font-heading-xl-line-height":"1.25","--font-heading-2xl-line-height":"1.2","--font-heading-3xl-line-height":"1.1","--border-radius-xs":"2px","--border-radius-sm":"4px","--border-radius-md":"6px","--border-radius-lg":"8px","--border-radius-xl":"12px","--border-radius-full":"9999px","--border-width-regular":"1px","--shadow-hairline":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--shadow-sm":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)","--shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)","--shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},$t={"--color-background-primary":"--bg-base","--color-background-secondary":"--bg-surface","--color-background-tertiary":"--bg-elevated","--color-text-primary":"--text-primary","--color-text-secondary":"--text-secondary","--color-text-tertiary":"--text-tertiary","--color-border-primary":"--border-primary","--color-border-secondary":"--border-subtle","--font-sans":"--font-sans","--font-mono":"--font-mono","--border-radius-sm":"--radius-sm","--border-radius-md":"--radius-md","--border-radius-lg":"--radius-lg","--border-radius-full":"--radius-full"};function Qe(){const l={...Dt};if(typeof window>"u"||typeof document>"u")return l;const o=window.getComputedStyle(document.documentElement),e=l;for(const[t,s]of Object.entries($t)){const i=o.getPropertyValue(s).trim();i&&(e[t]=i)}return l}const Y="io.modelcontextprotocol/related-task",ye="2.0",H=At(l=>l!==null&&(typeof l=="object"||typeof l=="function")),st=f([n(),p().int()]),ot=n();z({ttl:p().optional(),pollInterval:p().optional()});const Ft=r({ttl:p().optional()}),jt=r({taskId:n()}),xe=z({progressToken:st.optional(),[Y]:jt.optional()}),U=r({_meta:xe.optional()}),ne=U.extend({task:Ft.optional()}),Bt=l=>ne.safeParse(l).success,N=r({method:n(),params:U.loose().optional()}),F=r({_meta:xe.optional()}),j=r({method:n(),params:F.loose().optional()}),L=z({_meta:xe.optional()}),re=f([n(),p().int()]),at=r({jsonrpc:a(ye),id:re,...N.shape}).strict(),Ve=l=>at.safeParse(l).success,nt=r({jsonrpc:a(ye),...j.shape}).strict(),Jt=l=>nt.safeParse(l).success,Re=r({jsonrpc:a(ye),id:re,result:L}).strict(),fe=l=>Re.safeParse(l).success;var k;(function(l){l[l.ConnectionClosed=-32e3]="ConnectionClosed",l[l.RequestTimeout=-32001]="RequestTimeout",l[l.ParseError=-32700]="ParseError",l[l.InvalidRequest=-32600]="InvalidRequest",l[l.MethodNotFound=-32601]="MethodNotFound",l[l.InvalidParams=-32602]="InvalidParams",l[l.InternalError=-32603]="InternalError",l[l.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(k||(k={}));const ve=r({jsonrpc:a(ye),id:re.optional(),error:r({code:p().int(),message:n(),data:v().optional()})}).strict(),Qt=l=>ve.safeParse(l).success,Vt=f([at,nt,Re,ve]);f([Re,ve]);const rt=L.strict(),Wt=F.extend({requestId:re.optional(),reason:n().optional()}),Te=j.extend({method:a("notifications/cancelled"),params:Wt}),Kt=r({src:n(),mimeType:n().optional(),sizes:h(n()).optional(),theme:$(["light","dark"]).optional()}),ie=r({icons:h(Kt).optional()}),Z=r({name:n(),title:n().optional()}),Se=Z.extend({...Z.shape,...ie.shape,version:n(),websiteUrl:n().optional(),description:n().optional()}),Gt=Xe(r({applyDefaults:x().optional()}),S(n(),v())),Yt=et(l=>l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length===0?{form:{}}:l,Xe(r({form:Gt.optional(),url:H.optional()}),S(n(),v()).optional())),Zt=z({list:H.optional(),cancel:H.optional(),requests:z({sampling:z({createMessage:H.optional()}).optional(),elicitation:z({create:H.optional()}).optional()}).optional()}),Xt=z({list:H.optional(),cancel:H.optional(),requests:z({tools:z({call:H.optional()}).optional()}).optional()}),es=r({experimental:S(n(),H).optional(),sampling:r({context:H.optional(),tools:H.optional()}).optional(),elicitation:Yt.optional(),roots:r({listChanged:x().optional()}).optional(),tasks:Zt.optional(),extensions:S(n(),H).optional()}),ts=U.extend({protocolVersion:n(),capabilities:es,clientInfo:Se}),ss=N.extend({method:a("initialize"),params:ts}),os=r({experimental:S(n(),H).optional(),logging:H.optional(),completions:H.optional(),prompts:r({listChanged:x().optional()}).optional(),resources:r({subscribe:x().optional(),listChanged:x().optional()}).optional(),tools:r({listChanged:x().optional()}).optional(),tasks:Xt.optional(),extensions:S(n(),H).optional()}),as=L.extend({protocolVersion:n(),capabilities:os,serverInfo:Se,instructions:n().optional()}),ns=j.extend({method:a("notifications/initialized"),params:F.optional()}),ke=N.extend({method:a("ping"),params:U.optional()}),rs=r({progress:p(),total:q(p()),message:q(n())}),is=r({...F.shape,...rs.shape,progressToken:st}),qe=j.extend({method:a("notifications/progress"),params:is}),ls=U.extend({cursor:ot.optional()}),le=N.extend({params:ls.optional()}),ce=L.extend({nextCursor:ot.optional()}),cs=$(["working","input_required","completed","failed","cancelled"]),de=r({taskId:n(),status:cs,ttl:f([p(),zt()]),createdAt:n(),lastUpdatedAt:n(),pollInterval:q(p()),statusMessage:q(n())}),Ce=L.extend({task:de}),ds=F.merge(de),ge=j.extend({method:a("notifications/tasks/status"),params:ds}),Ie=N.extend({method:a("tasks/get"),params:U.extend({taskId:n()})}),Pe=L.merge(de),He=N.extend({method:a("tasks/result"),params:U.extend({taskId:n()})});L.loose();const Ee=le.extend({method:a("tasks/list")}),Me=ce.extend({tasks:h(de)}),Ne=N.extend({method:a("tasks/cancel"),params:U.extend({taskId:n()})}),us=L.merge(de),it=r({uri:n(),mimeType:q(n()),_meta:S(n(),v()).optional()}),lt=it.extend({text:n()}),Le=n().refine(l=>{try{return atob(l),!0}catch{return!1}},{message:"Invalid Base64 string"}),ct=it.extend({blob:Le}),ue=$(["user","assistant"]),X=r({audience:h(ue).optional(),priority:p().min(0).max(1).optional(),lastModified:Ut({offset:!0}).optional()}),dt=r({...Z.shape,...ie.shape,uri:n(),description:q(n()),mimeType:q(n()),size:q(p()),annotations:X.optional(),_meta:q(z({}))}),hs=r({...Z.shape,...ie.shape,uriTemplate:n(),description:q(n()),mimeType:q(n()),annotations:X.optional(),_meta:q(z({}))}),ut=le.extend({method:a("resources/list")}),ht=ce.extend({resources:h(dt)}),pt=le.extend({method:a("resources/templates/list")}),mt=ce.extend({resourceTemplates:h(hs)}),Ae=U.extend({uri:n()}),ps=Ae,ft=N.extend({method:a("resources/read"),params:ps}),gt=L.extend({contents:h(f([lt,ct]))}),bt=j.extend({method:a("notifications/resources/list_changed"),params:F.optional()}),ms=Ae,fs=N.extend({method:a("resources/subscribe"),params:ms}),gs=Ae,bs=N.extend({method:a("resources/unsubscribe"),params:gs}),ys=F.extend({uri:n()}),Ss=j.extend({method:a("notifications/resources/updated"),params:ys}),ks=r({name:n(),description:q(n()),required:q(x())}),_s=r({...Z.shape,...ie.shape,description:q(n()),arguments:q(h(ks)),_meta:q(z({}))}),yt=le.extend({method:a("prompts/list")}),St=ce.extend({prompts:h(_s)}),ws=U.extend({name:n(),arguments:S(n(),n()).optional()}),xs=N.extend({method:a("prompts/get"),params:ws}),ze=r({type:a("text"),text:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Ue=r({type:a("image"),data:Le,mimeType:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Oe=r({type:a("audio"),data:Le,mimeType:n(),annotations:X.optional(),_meta:S(n(),v()).optional()}),Rs=r({type:a("tool_use"),name:n(),id:n(),input:S(n(),v()),_meta:S(n(),v()).optional()}),kt=r({type:a("resource"),resource:f([lt,ct]),annotations:X.optional(),_meta:S(n(),v()).optional()}),_t=dt.extend({type:a("resource_link")}),he=f([ze,Ue,Oe,_t,kt]),vs=r({role:ue,content:he}),Ts=L.extend({description:n().optional(),messages:h(vs)}),wt=j.extend({method:a("notifications/prompts/list_changed"),params:F.optional()}),qs=r({title:n().optional(),readOnlyHint:x().optional(),destructiveHint:x().optional(),idempotentHint:x().optional(),openWorldHint:x().optional()}),Cs=r({taskSupport:$(["required","optional","forbidden"]).optional()}),De=r({...Z.shape,...ie.shape,description:n().optional(),inputSchema:r({type:a("object"),properties:S(n(),H).optional(),required:h(n()).optional()}).catchall(v()),outputSchema:r({type:a("object"),properties:S(n(),H).optional(),required:h(n()).optional()}).catchall(v()).optional(),annotations:qs.optional(),execution:Cs.optional(),_meta:S(n(),v()).optional()}),Is=le.extend({method:a("tools/list")}),xt=ce.extend({tools:h(De)}),oe=L.extend({content:h(he).default([]),structuredContent:S(n(),v()).optional(),isError:x().optional()});oe.or(L.extend({toolResult:v()}));const Ps=ne.extend({name:n(),arguments:S(n(),v()).optional()}),Rt=N.extend({method:a("tools/call"),params:Ps}),vt=j.extend({method:a("notifications/tools/list_changed"),params:F.optional()});r({autoRefresh:x().default(!0),debounceMs:p().int().nonnegative().default(300)});const Tt=$(["debug","info","notice","warning","error","critical","alert","emergency"]),Hs=U.extend({level:Tt}),Es=N.extend({method:a("logging/setLevel"),params:Hs}),Ms=F.extend({level:Tt,logger:n().optional(),data:v()}),qt=j.extend({method:a("notifications/message"),params:Ms}),Ns=r({name:n().optional()}),Ls=r({hints:h(Ns).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),As=r({mode:$(["auto","required","none"]).optional()}),zs=r({type:a("tool_result"),toolUseId:n().describe("The unique identifier for the corresponding tool call."),content:h(he).default([]),structuredContent:r({}).loose().optional(),isError:x().optional(),_meta:S(n(),v()).optional()}),Us=tt("type",[ze,Ue,Oe]),be=tt("type",[ze,Ue,Oe,Rs,zs]),Os=r({role:ue,content:f([be,h(be)]),_meta:S(n(),v()).optional()}),Ds=ne.extend({messages:h(Os),modelPreferences:Ls.optional(),systemPrompt:n().optional(),includeContext:$(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:h(n()).optional(),metadata:H.optional(),tools:h(De).optional(),toolChoice:As.optional()}),Ct=N.extend({method:a("sampling/createMessage"),params:Ds}),$s=L.extend({model:n(),stopReason:q($(["endTurn","stopSequence","maxTokens"]).or(n())),role:ue,content:Us}),Fs=L.extend({model:n(),stopReason:q($(["endTurn","stopSequence","maxTokens","toolUse"]).or(n())),role:ue,content:f([be,h(be)])}),js=r({type:a("boolean"),title:n().optional(),description:n().optional(),default:x().optional()}),Bs=r({type:a("string"),title:n().optional(),description:n().optional(),minLength:p().optional(),maxLength:p().optional(),format:$(["email","uri","date","date-time"]).optional(),default:n().optional()}),Js=r({type:$(["number","integer"]),title:n().optional(),description:n().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),Qs=r({type:a("string"),title:n().optional(),description:n().optional(),enum:h(n()),default:n().optional()}),Vs=r({type:a("string"),title:n().optional(),description:n().optional(),oneOf:h(r({const:n(),title:n()})),default:n().optional()}),Ws=r({type:a("string"),title:n().optional(),description:n().optional(),enum:h(n()),enumNames:h(n()).optional(),default:n().optional()}),Ks=f([Qs,Vs]),Gs=r({type:a("array"),title:n().optional(),description:n().optional(),minItems:p().optional(),maxItems:p().optional(),items:r({type:a("string"),enum:h(n())}),default:h(n()).optional()}),Ys=r({type:a("array"),title:n().optional(),description:n().optional(),minItems:p().optional(),maxItems:p().optional(),items:r({anyOf:h(r({const:n(),title:n()}))}),default:h(n()).optional()}),Zs=f([Gs,Ys]),Xs=f([Ws,Ks,Zs]),eo=f([Xs,js,Bs,Js]),to=ne.extend({mode:a("form").optional(),message:n(),requestedSchema:r({type:a("object"),properties:S(n(),eo),required:h(n()).optional()})}),so=ne.extend({mode:a("url"),message:n(),elicitationId:n(),url:n().url()}),oo=f([to,so]),ao=N.extend({method:a("elicitation/create"),params:oo}),no=F.extend({elicitationId:n()}),ro=j.extend({method:a("notifications/elicitation/complete"),params:no}),io=L.extend({action:$(["accept","decline","cancel"]),content:et(l=>l===null?void 0:l,S(n(),f([n(),p(),x(),h(n())])).optional())}),lo=r({type:a("ref/resource"),uri:n()}),co=r({type:a("ref/prompt"),name:n()}),uo=U.extend({ref:f([co,lo]),argument:r({name:n(),value:n()}),context:r({arguments:S(n(),n()).optional()}).optional()}),ho=N.extend({method:a("completion/complete"),params:uo}),po=L.extend({completion:z({values:h(n()).max(100),total:q(p().int()),hasMore:q(x())})}),mo=r({uri:n().startsWith("file://"),name:n().optional(),_meta:S(n(),v()).optional()}),fo=N.extend({method:a("roots/list"),params:U.optional()}),go=L.extend({roots:h(mo)}),bo=j.extend({method:a("notifications/roots/list_changed"),params:F.optional()});f([ke,ss,ho,Es,xs,yt,ut,pt,ft,fs,bs,Rt,Is,Ie,He,Ee,Ne]);f([Te,qe,ns,bo,ge]);f([rt,$s,Fs,io,go,Pe,Me,Ce]);f([ke,Ct,ao,fo,Ie,He,Ee,Ne]);f([Te,qe,qt,Ss,bt,vt,wt,ge,ro]);f([rt,as,po,Ts,St,ht,mt,gt,oe,xt,Pe,Me,Ce]);class y extends Error{constructor(o,e,t){super(`MCP error ${o}: ${e}`),this.code=o,this.data=t,this.name="McpError"}static fromError(o,e,t){if(o===k.UrlElicitationRequired&&t){const s=t;if(s.elicitations)return new yo(s.elicitations,e)}return new y(o,e,t)}}class yo extends y{constructor(o,e=`URL elicitation${o.length>1?"s":""} required`){super(k.UrlElicitationRequired,e,{elicitations:o})}get elicitations(){var o;return((o=this.data)==null?void 0:o.elicitations)??[]}}function $e(l){return!!l._zod}function It(l,o){return $e(l)?Ot(l,o):l.safeParse(o)}function So(l){var e,t;if(!l)return;let o;if($e(l)?o=(t=(e=l._zod)==null?void 0:e.def)==null?void 0:t.shape:o=l.shape,!!o){if(typeof o=="function")try{return o()}catch{return}return o}}function ko(l){var s;if($e(l)){const c=(s=l._zod)==null?void 0:s.def;if(c){if(c.value!==void 0)return c.value;if(Array.isArray(c.values)&&c.values.length>0)return c.values[0]}}const e=l._def;if(e){if(e.value!==void 0)return e.value;if(Array.isArray(e.values)&&e.values.length>0)return e.values[0]}const t=l.value;if(t!==void 0)return t}function G(l){return l==="completed"||l==="failed"||l==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function We(l){const o=So(l),e=o==null?void 0:o.method;if(!e)throw new Error("Schema is missing a method literal");const t=ko(e);if(typeof t!="string")throw new Error("Schema method literal must be a string");return t}function Ke(l,o){const e=It(l,o);if(!e.success)throw e.error;return e.data}const _o=6e4;class wo{constructor(o){this._options=o,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(Te,e=>{this._oncancel(e)}),this.setNotificationHandler(qe,e=>{this._onprogress(e)}),this.setRequestHandler(ke,e=>({})),this._taskStore=o==null?void 0:o.taskStore,this._taskMessageQueue=o==null?void 0:o.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ie,async(e,t)=>{const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new y(k.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(He,async(e,t)=>{const s=async()=>{var u;const i=e.params.taskId;if(this._taskMessageQueue){let d;for(;d=await this._taskMessageQueue.dequeue(i,t.sessionId);){if(d.type==="response"||d.type==="error"){const g=d.message,w=g.id,_=this._requestResolvers.get(w);if(_)if(this._requestResolvers.delete(w),d.type==="response")_(g);else{const b=g,P=new y(b.error.code,b.error.message,b.error.data);_(P)}else{const b=d.type==="response"?"Response":"Error";this._onerror(new Error(`${b} handler missing for request ${w}`))}continue}await((u=this._transport)==null?void 0:u.send(d.message,{relatedRequestId:t.requestId}))}}const c=await this._taskStore.getTask(i,t.sessionId);if(!c)throw new y(k.InvalidParams,`Task not found: ${i}`);if(!G(c.status))return await this._waitForTaskUpdate(i,t.signal),await s();if(G(c.status)){const d=await this._taskStore.getTaskResult(i,t.sessionId);return this._clearTaskQueue(i),{...d,_meta:{...d._meta,[Y]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(Ee,async(e,t)=>{var s;try{const{tasks:i,nextCursor:c}=await this._taskStore.listTasks((s=e.params)==null?void 0:s.cursor,t.sessionId);return{tasks:i,nextCursor:c,_meta:{}}}catch(i){throw new y(k.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Ne,async(e,t)=>{try{const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new y(k.InvalidParams,`Task not found: ${e.params.taskId}`);if(G(s.status))throw new y(k.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const i=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!i)throw new y(k.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof y?s:new y(k.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(o){if(!o.params.requestId)return;const e=this._requestHandlerAbortControllers.get(o.params.requestId);e==null||e.abort(o.params.reason)}_setupTimeout(o,e,t,s,i=!1){this._timeoutInfo.set(o,{timeoutId:setTimeout(s,e),startTime:Date.now(),timeout:e,maxTotalTimeout:t,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(o){const e=this._timeoutInfo.get(o);if(!e)return!1;const t=Date.now()-e.startTime;if(e.maxTotalTimeout&&t>=e.maxTotalTimeout)throw this._timeoutInfo.delete(o),y.fromError(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:e.maxTotalTimeout,totalElapsed:t});return clearTimeout(e.timeoutId),e.timeoutId=setTimeout(e.onTimeout,e.timeout),!0}_cleanupTimeout(o){const e=this._timeoutInfo.get(o);e&&(clearTimeout(e.timeoutId),this._timeoutInfo.delete(o))}async connect(o){var i,c,u;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=o;const e=(i=this.transport)==null?void 0:i.onclose;this._transport.onclose=()=>{e==null||e(),this._onclose()};const t=(c=this.transport)==null?void 0:c.onerror;this._transport.onerror=d=>{t==null||t(d),this._onerror(d)};const s=(u=this._transport)==null?void 0:u.onmessage;this._transport.onmessage=(d,g)=>{s==null||s(d,g),fe(d)||Qt(d)?this._onresponse(d):Ve(d)?this._onrequest(d,g):Jt(d)?this._onnotification(d):this._onerror(new Error(`Unknown message type: ${JSON.stringify(d)}`))},await this._transport.start()}_onclose(){var t;const o=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const s of this._timeoutInfo.values())clearTimeout(s.timeoutId);this._timeoutInfo.clear();for(const s of this._requestHandlerAbortControllers.values())s.abort();this._requestHandlerAbortControllers.clear();const e=y.fromError(k.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)==null||t.call(this);for(const s of o.values())s(e)}_onerror(o){var e;(e=this.onerror)==null||e.call(this,o)}_onnotification(o){const e=this._notificationHandlers.get(o.method)??this.fallbackNotificationHandler;e!==void 0&&Promise.resolve().then(()=>e(o)).catch(t=>this._onerror(new Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(o,e){var w,_,b,P;const t=this._requestHandlers.get(o.method)??this.fallbackRequestHandler,s=this._transport,i=(b=(_=(w=o.params)==null?void 0:w._meta)==null?void 0:_[Y])==null?void 0:b.taskId;if(t===void 0){const R={jsonrpc:"2.0",id:o.id,error:{code:k.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:R,timestamp:Date.now()},s==null?void 0:s.sessionId).catch(C=>this._onerror(new Error(`Failed to enqueue error response: ${C}`))):s==null||s.send(R).catch(C=>this._onerror(new Error(`Failed to send an error response: ${C}`)));return}const c=new AbortController;this._requestHandlerAbortControllers.set(o.id,c);const u=Bt(o.params)?o.params.task:void 0,d=this._taskStore?this.requestTaskStore(o,s==null?void 0:s.sessionId):void 0,g={signal:c.signal,sessionId:s==null?void 0:s.sessionId,_meta:(P=o.params)==null?void 0:P._meta,sendNotification:async R=>{if(c.signal.aborted)return;const C={relatedRequestId:o.id};i&&(C.relatedTask={taskId:i}),await this.notification(R,C)},sendRequest:async(R,C,Q)=>{var D;if(c.signal.aborted)throw new y(k.ConnectionClosed,"Request was cancelled");const O={...Q,relatedRequestId:o.id};i&&!O.relatedTask&&(O.relatedTask={taskId:i});const V=((D=O.relatedTask)==null?void 0:D.taskId)??i;return V&&d&&await d.updateTaskStatus(V,"input_required"),await this.request(R,C,O)},authInfo:e==null?void 0:e.authInfo,requestId:o.id,requestInfo:e==null?void 0:e.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u==null?void 0:u.ttl,closeSSEStream:e==null?void 0:e.closeSSEStream,closeStandaloneSSEStream:e==null?void 0:e.closeStandaloneSSEStream};Promise.resolve().then(()=>{u&&this.assertTaskHandlerCapability(o.method)}).then(()=>t(o,g)).then(async R=>{if(c.signal.aborted)return;const C={result:R,jsonrpc:"2.0",id:o.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:C,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(C))},async R=>{if(c.signal.aborted)return;const C={jsonrpc:"2.0",id:o.id,error:{code:Number.isSafeInteger(R.code)?R.code:k.InternalError,message:R.message??"Internal error",...R.data!==void 0&&{data:R.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:C,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(C))}).catch(R=>this._onerror(new Error(`Failed to send response: ${R}`))).finally(()=>{this._requestHandlerAbortControllers.get(o.id)===c&&this._requestHandlerAbortControllers.delete(o.id)})}_onprogress(o){const{progressToken:e,...t}=o.params,s=Number(e),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(o)}`));return}const c=this._responseHandlers.get(s),u=this._timeoutInfo.get(s);if(u&&c&&u.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(d){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),c(d);return}i(t)}_onresponse(o){const e=Number(o.id),t=this._requestResolvers.get(e);if(t){if(this._requestResolvers.delete(e),fe(o))t(o);else{const c=new y(o.error.code,o.error.message,o.error.data);t(c)}return}const s=this._responseHandlers.get(e);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(o)}`));return}this._responseHandlers.delete(e),this._cleanupTimeout(e);let i=!1;if(fe(o)&&o.result&&typeof o.result=="object"){const c=o.result;if(c.task&&typeof c.task=="object"){const u=c.task;typeof u.taskId=="string"&&(i=!0,this._taskProgressTokens.set(u.taskId,e))}}if(i||this._progressHandlers.delete(e),fe(o))s(o);else{const c=y.fromError(o.error.code,o.error.message,o.error.data);s(c)}}get transport(){return this._transport}async close(){var o;await((o=this._transport)==null?void 0:o.close())}async*requestStream(o,e,t){var c,u;const{task:s}=t??{};if(!s){try{yield{type:"result",result:await this.request(o,e,t)}}catch(d){yield{type:"error",error:d instanceof y?d:new y(k.InternalError,String(d))}}return}let i;try{const d=await this.request(o,Ce,t);if(d.task)i=d.task.taskId,yield{type:"taskCreated",task:d.task};else throw new y(k.InternalError,"Task creation did not return a task");for(;;){const g=await this.getTask({taskId:i},t);if(yield{type:"taskStatus",task:g},G(g.status)){g.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},e,t)}:g.status==="failed"?yield{type:"error",error:new y(k.InternalError,`Task ${i} failed`)}:g.status==="cancelled"&&(yield{type:"error",error:new y(k.InternalError,`Task ${i} was cancelled`)});return}if(g.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},e,t)};return}const w=g.pollInterval??((c=this._options)==null?void 0:c.defaultTaskPollInterval)??1e3;await new Promise(_=>setTimeout(_,w)),(u=t==null?void 0:t.signal)==null||u.throwIfAborted()}}catch(d){yield{type:"error",error:d instanceof y?d:new y(k.InternalError,String(d))}}}request(o,e,t){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c,task:u,relatedTask:d}=t??{};return new Promise((g,w)=>{var V,D,pe,me,I;const _=T=>{w(T)};if(!this._transport){_(new Error("Not connected"));return}if(((V=this._options)==null?void 0:V.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(o.method),u&&this.assertTaskCapability(o.method)}catch(T){_(T);return}(D=t==null?void 0:t.signal)==null||D.throwIfAborted();const b=this._requestMessageId++,P={...o,jsonrpc:"2.0",id:b};t!=null&&t.onprogress&&(this._progressHandlers.set(b,t.onprogress),P.params={...o.params,_meta:{...((pe=o.params)==null?void 0:pe._meta)||{},progressToken:b}}),u&&(P.params={...P.params,task:u}),d&&(P.params={...P.params,_meta:{...((me=P.params)==null?void 0:me._meta)||{},[Y]:d}});const R=T=>{var A;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(A=this._transport)==null||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(T)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c}).catch(ee=>this._onerror(new Error(`Failed to send cancellation: ${ee}`)));const B=T instanceof y?T:new y(k.RequestTimeout,String(T));w(B)};this._responseHandlers.set(b,T=>{var B;if(!((B=t==null?void 0:t.signal)!=null&&B.aborted)){if(T instanceof Error)return w(T);try{const A=It(e,T.result);A.success?g(A.data):w(A.error)}catch(A){w(A)}}}),(I=t==null?void 0:t.signal)==null||I.addEventListener("abort",()=>{var T;R((T=t==null?void 0:t.signal)==null?void 0:T.reason)});const C=(t==null?void 0:t.timeout)??_o,Q=()=>R(y.fromError(k.RequestTimeout,"Request timed out",{timeout:C}));this._setupTimeout(b,C,t==null?void 0:t.maxTotalTimeout,Q,(t==null?void 0:t.resetTimeoutOnProgress)??!1);const O=d==null?void 0:d.taskId;if(O){const T=B=>{const A=this._responseHandlers.get(b);A?A(B):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,T),this._enqueueTaskMessage(O,{type:"request",message:P,timestamp:Date.now()}).catch(B=>{this._cleanupTimeout(b),w(B)})}else this._transport.send(P,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:c}).catch(T=>{this._cleanupTimeout(b),w(T)})})}async getTask(o,e){return this.request({method:"tasks/get",params:o},Pe,e)}async getTaskResult(o,e,t){return this.request({method:"tasks/result",params:o},e,t)}async listTasks(o,e){return this.request({method:"tasks/list",params:o},Me,e)}async cancelTask(o,e){return this.request({method:"tasks/cancel",params:o},us,e)}async notification(o,e){var u,d,g,w;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(o.method);const t=(u=e==null?void 0:e.relatedTask)==null?void 0:u.taskId;if(t){const _={...o,jsonrpc:"2.0",params:{...o.params,_meta:{...((d=o.params)==null?void 0:d._meta)||{},[Y]:e.relatedTask}}};await this._enqueueTaskMessage(t,{type:"notification",message:_,timestamp:Date.now()});return}if((((g=this._options)==null?void 0:g.debouncedNotificationMethods)??[]).includes(o.method)&&!o.params&&!(e!=null&&e.relatedRequestId)&&!(e!=null&&e.relatedTask)){if(this._pendingDebouncedNotifications.has(o.method))return;this._pendingDebouncedNotifications.add(o.method),Promise.resolve().then(()=>{var b,P;if(this._pendingDebouncedNotifications.delete(o.method),!this._transport)return;let _={...o,jsonrpc:"2.0"};e!=null&&e.relatedTask&&(_={..._,params:{..._.params,_meta:{...((b=_.params)==null?void 0:b._meta)||{},[Y]:e.relatedTask}}}),(P=this._transport)==null||P.send(_,e).catch(R=>this._onerror(R))});return}let c={...o,jsonrpc:"2.0"};e!=null&&e.relatedTask&&(c={...c,params:{...c.params,_meta:{...((w=c.params)==null?void 0:w._meta)||{},[Y]:e.relatedTask}}}),await this._transport.send(c,e)}setRequestHandler(o,e){const t=We(o);this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(s,i)=>{const c=Ke(o,s);return Promise.resolve(e(c,i))})}removeRequestHandler(o){this._requestHandlers.delete(o)}assertCanSetRequestHandler(o){if(this._requestHandlers.has(o))throw new Error(`A request handler for ${o} already exists, which would be overridden`)}setNotificationHandler(o,e){const t=We(o);this._notificationHandlers.set(t,s=>{const i=Ke(o,s);return Promise.resolve(e(i))})}removeNotificationHandler(o){this._notificationHandlers.delete(o)}_cleanupTaskProgressHandler(o){const e=this._taskProgressTokens.get(o);e!==void 0&&(this._progressHandlers.delete(e),this._taskProgressTokens.delete(o))}async _enqueueTaskMessage(o,e,t){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(i=this._options)==null?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(o,e,t,s)}async _clearTaskQueue(o,e){if(this._taskMessageQueue){const t=await this._taskMessageQueue.dequeueAll(o,e);for(const s of t)if(s.type==="request"&&Ve(s.message)){const i=s.message.id,c=this._requestResolvers.get(i);c?(c(new y(k.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${o} cleanup`))}}}async _waitForTaskUpdate(o,e){var s,i;let t=((s=this._options)==null?void 0:s.defaultTaskPollInterval)??1e3;try{const c=await((i=this._taskStore)==null?void 0:i.getTask(o));c!=null&&c.pollInterval&&(t=c.pollInterval)}catch{}return new Promise((c,u)=>{if(e.aborted){u(new y(k.InvalidRequest,"Request cancelled"));return}const d=setTimeout(c,t);e.addEventListener("abort",()=>{clearTimeout(d),u(new y(k.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(o,e){const t=this._taskStore;if(!t)throw new Error("No task store configured");return{createTask:async s=>{if(!o)throw new Error("No request provided");return await t.createTask(s,o.id,{method:o.method,params:o.params},e)},getTask:async s=>{const i=await t.getTask(s,e);if(!i)throw new y(k.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,c)=>{await t.storeTaskResult(s,i,c,e);const u=await t.getTask(s,e);if(u){const d=ge.parse({method:"notifications/tasks/status",params:u});await this.notification(d),G(u.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>t.getTaskResult(s,e),updateTaskStatus:async(s,i,c)=>{const u=await t.getTask(s,e);if(!u)throw new y(k.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(G(u.status))throw new y(k.InvalidParams,`Cannot update task "${s}" from terminal status "${u.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await t.updateTaskStatus(s,i,c,e);const d=await t.getTask(s,e);if(d){const g=ge.parse({method:"notifications/tasks/status",params:d});await this.notification(g),G(d.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>t.listTasks(s,e)}}}(l=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(l,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):l)(function(l){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+l+'" is not supported')});class xo extends wo{constructor(){super(...arguments);m(this,"_registeredMethods",new Set);m(this,"_eventSlots",new Map);m(this,"setRequestHandler",(e,t)=>{this._assertMethodNotRegistered(e,"setRequestHandler"),super.setRequestHandler(e,t)});m(this,"setNotificationHandler",(e,t)=>{this._assertMethodNotRegistered(e,"setNotificationHandler"),super.setNotificationHandler(e,t)});m(this,"replaceRequestHandler",(e,t)=>{let s=e.shape.method.value;this._registeredMethods.add(s),super.setRequestHandler(e,t)})}onEventDispatch(e,t){}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t){let s=this.eventSchemas[e];if(!s)throw Error(`Unknown event: ${String(e)}`);t={listeners:[]},this._eventSlots.set(e,t);let i=s.shape.method.value;this._registeredMethods.add(i);let c=t;super.setNotificationHandler(s,u=>{var g;let d=u.params;this.onEventDispatch(e,d),(g=c.onHandler)==null||g.call(c,d);for(let w of[...c.listeners])w(d)})}return t}setEventHandler(e,t){let s=this._ensureEventSlot(e);s.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),s.onHandler=t}getEventHandler(e){var t;return(t=this._eventSlots.get(e))==null?void 0:t.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let s=this._eventSlots.get(e);if(!s)return;let i=s.listeners.indexOf(t);i!==-1&&s.listeners.splice(i,1)}warnIfRequestHandlerReplaced(e,t,s){t&&s&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(e,t){let s=e.shape.method.value;if(this._registeredMethods.has(s))throw Error(`Handler for "${s}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(s)}}var Pt="2026-01-26",Ro="ui/notifications/tool-input-partial",vo=f([a("light"),a("dark")]).describe("Color theme preference for the host environment."),ae=f([a("inline"),a("fullscreen"),a("pip")]).describe("Display mode for UI presentation."),To=f([a("--color-background-primary"),a("--color-background-secondary"),a("--color-background-tertiary"),a("--color-background-inverse"),a("--color-background-ghost"),a("--color-background-info"),a("--color-background-danger"),a("--color-background-success"),a("--color-background-warning"),a("--color-background-disabled"),a("--color-text-primary"),a("--color-text-secondary"),a("--color-text-tertiary"),a("--color-text-inverse"),a("--color-text-ghost"),a("--color-text-info"),a("--color-text-danger"),a("--color-text-success"),a("--color-text-warning"),a("--color-text-disabled"),a("--color-border-primary"),a("--color-border-secondary"),a("--color-border-tertiary"),a("--color-border-inverse"),a("--color-border-ghost"),a("--color-border-info"),a("--color-border-danger"),a("--color-border-success"),a("--color-border-warning"),a("--color-border-disabled"),a("--color-ring-primary"),a("--color-ring-secondary"),a("--color-ring-inverse"),a("--color-ring-info"),a("--color-ring-danger"),a("--color-ring-success"),a("--color-ring-warning"),a("--font-sans"),a("--font-mono"),a("--font-weight-normal"),a("--font-weight-medium"),a("--font-weight-semibold"),a("--font-weight-bold"),a("--font-text-xs-size"),a("--font-text-sm-size"),a("--font-text-md-size"),a("--font-text-lg-size"),a("--font-heading-xs-size"),a("--font-heading-sm-size"),a("--font-heading-md-size"),a("--font-heading-lg-size"),a("--font-heading-xl-size"),a("--font-heading-2xl-size"),a("--font-heading-3xl-size"),a("--font-text-xs-line-height"),a("--font-text-sm-line-height"),a("--font-text-md-line-height"),a("--font-text-lg-line-height"),a("--font-heading-xs-line-height"),a("--font-heading-sm-line-height"),a("--font-heading-md-line-height"),a("--font-heading-lg-line-height"),a("--font-heading-xl-line-height"),a("--font-heading-2xl-line-height"),a("--font-heading-3xl-line-height"),a("--border-radius-xs"),a("--border-radius-sm"),a("--border-radius-md"),a("--border-radius-lg"),a("--border-radius-xl"),a("--border-radius-full"),a("--border-width-regular"),a("--shadow-hairline"),a("--shadow-sm"),a("--shadow-md"),a("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),qo=S(To.describe(`Style variables for theming MCP apps.
2
2
 
3
3
  Individual style keys are optional - hosts may provide any subset of these values.
4
4
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -36,4 +36,5 @@ Boolean requesting whether a visible border and background is provided by the ho
36
36
  - omitted: host decides border`)});var Ye=r({method:a("ui/request-display-mode"),params:r({mode:ae.describe("The display mode being requested.")})});r({mode:ae.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var Uo=f([a("model"),a("app")]).describe("Tool visibility scope - who can access the tool.");r({resourceUri:n().optional(),visibility:h(Uo).optional().describe(`Who can access this tool. Default: ["model", "app"]
37
37
  - "model": Tool visible to and callable by the agent
38
38
  - "app": Tool callable by the app from this server only`),csp:Je().optional(),permissions:Je().optional()});r({mimeTypes:h(n()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var Oo=r({method:a("ui/download-file"),params:r({contents:h(f([kt,_t])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Do=r({method:a("ui/message"),params:r({role:a("user").describe('Message role, currently only "user" is supported.'),content:h(he).describe("Message content blocks (text, image, etc.).")})});r({method:a("ui/notifications/sandbox-resource-ready"),params:r({html:n().describe("HTML content to load into the inner iframe."),sandbox:n().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Fe.optional().describe("CSP configuration from resource metadata."),permissions:je.optional().describe("Sandbox permissions from resource metadata.")})});r({method:a("ui/notifications/tool-result"),params:oe.describe("Standard MCP tool execution result.")});var Ht=r({toolInfo:r({id:re.optional().describe("JSON-RPC id of the tools/call request."),tool:De.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:vo.optional().describe("Current color theme preference."),styles:Eo.optional().describe("Style configuration for theming the app."),displayMode:ae.optional().describe("How the UI is currently displayed."),availableDisplayModes:h(ae).optional().describe("Display modes the host supports."),containerDimensions:f([r({height:p().describe("Fixed container height in pixels.")}),r({maxHeight:f([p(),we()]).optional().describe("Maximum container height in pixels.")})]).and(f([r({width:p().describe("Fixed container width in pixels.")}),r({maxWidth:f([p(),we()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
39
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:n().optional().describe("User's language and region preference in BCP 47 format."),timeZone:n().optional().describe("User's timezone in IANA format."),userAgent:n().optional().describe("Host application identifier."),platform:f([a("web"),a("desktop"),a("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:r({touch:x().optional().describe("Whether the device supports touch input."),hover:x().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:r({top:p().describe("Top safe area inset in pixels."),right:p().describe("Right safe area inset in pixels."),bottom:p().describe("Bottom safe area inset in pixels."),left:p().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();r({method:a("ui/notifications/host-context-changed"),params:Ht.describe("Partial context update containing only changed fields.")});var $o=r({method:a("ui/update-model-context"),params:r({content:h(he).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:S(n(),v().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),Fo=r({method:a("ui/initialize"),params:r({appInfo:Se.describe("App identification (name and version)."),appCapabilities:Ao.describe("Features and capabilities this app provides."),protocolVersion:n().describe("Protocol version this app supports.")})});r({protocolVersion:n().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Se.describe("Host application identification and version."),hostCapabilities:Lo.describe("Features and capabilities provided by the host."),hostContext:Ht.describe("Rich context about the host environment.")}).passthrough();class jo{constructor(o=window.parent,e){m(this,"eventTarget");m(this,"eventSource");m(this,"messageListener");m(this,"onclose");m(this,"onerror");m(this,"onmessage");m(this,"sessionId");m(this,"setProtocolVersion");this.eventTarget=o,this.eventSource=e,this.messageListener=t=>{var i,c,u;if(e&&t.source!==this.eventSource){console.debug("Ignoring message from unknown source",t);return}let s=Qt.safeParse(t.data);s.success?(console.debug("Parsed message",s.data),(i=this.onmessage)==null||i.call(this,s.data)):((c=t.data)==null?void 0:c.jsonrpc)!=="2.0"?console.debug("Ignoring non-JSON-RPC message",s.error.message,t):(console.error("Failed to parse message",s.error.message,t),(u=this.onerror)==null||u.call(this,Error("Invalid JSON-RPC message received: "+s.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(o,e){o.method!==Ro&&console.debug("Sending message",o),this.eventTarget.postMessage(o,"*")}async close(){var o;window.removeEventListener("message",this.messageListener),(o=this.onclose)==null||o.call(this)}}function Bo(l){if(!l)return"";let o=[];return l.camera&&o.push("camera"),l.microphone&&o.push("microphone"),l.geolocation&&o.push("geolocation"),l.clipboardWrite&&o.push("clipboard-write"),o.join("; ")}var Jo=[Pt];class Vo extends xo{constructor(e,t,s,i){super(i);m(this,"_client");m(this,"_hostInfo");m(this,"_capabilities");m(this,"_appCapabilities");m(this,"_hostContext",{});m(this,"_appInfo");m(this,"_initializedReceived",!1);m(this,"_baseReplaceRequestHandler",this.replaceRequestHandler);m(this,"replaceRequestHandler",(e,t)=>{this._baseReplaceRequestHandler(e,(s,i)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${s.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),t(s,i)))});m(this,"eventSchemas",{sizechange:Po,sandboxready:Io,initialized:zo,requestteardown:No,loggingmessage:qt});m(this,"onping");m(this,"_onmessage");m(this,"_onopenlink");m(this,"_ondownloadfile");m(this,"_onrequestdisplaymode");m(this,"_onupdatemodelcontext");m(this,"_oncalltool");m(this,"_onlistresources");m(this,"_onlistresourcetemplates");m(this,"_onreadresource");m(this,"_onlistprompts");m(this,"sendResourceTeardown",this.teardownResource);this._client=e,this._hostInfo=t,this._capabilities=s,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=(i==null?void 0:i.hostContext)||{},this.setRequestHandler(Fo,c=>this._oninitialize(c)),this.setRequestHandler(ke,(c,u)=>{var d;return(d=this.onping)==null||d.call(this,c.params,u),{}}),this.replaceRequestHandler(Ye,c=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}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)}get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler(Do,async(t,s)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t.params,s)})}get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(Co,async(t,s)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t.params,s)})}get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(Oo,async(t,s)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t.params,s)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler(Ye,async(t,s)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t.params,s)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler($o,async(t,s)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t.params,s)})}get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rt,async(t,s)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,s)})}set oncreatesamplingmessage(e){this.setRequestHandler(Ct,async(t,s)=>e(t.params,s))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler(ut,async(t,s)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,s)})}get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(pt,async(t,s)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,s)})}get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(ft,async(t,s)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,s)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler(yt,async(t,s)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,s)})}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:Jo.includes(t)?t:Pt,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},s=!1;for(let i of Object.keys(e)){let c=this._hostContext[i],u=e[i];Qo(c,u)||(t[i]=u,s=!0)}s&&(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},Mo,t)}callTool(e,t){return this.request({method:"tools/call",params:e},oe,t)}listTools(e,t){return this.request({method:"tools/list",params:e},xt,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 t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");t.tools&&(this.oncalltool=async(s,i)=>this._client.request({method:"tools/call",params:s},oe,{signal:i.signal}),t.tools.listChanged&&this._client.setNotificationHandler(vt,s=>this.sendToolListChanged(s.params))),t.resources&&(this.onlistresources=async(s,i)=>this._client.request({method:"resources/list",params:s},ht,{signal:i.signal}),this.onlistresourcetemplates=async(s,i)=>this._client.request({method:"resources/templates/list",params:s},mt,{signal:i.signal}),this.onreadresource=async(s,i)=>this._client.request({method:"resources/read",params:s},gt,{signal:i.signal}),t.resources.listChanged&&this._client.setNotificationHandler(bt,s=>this.sendResourceListChanged(s.params))),t.prompts&&(this.onlistprompts=async(s,i)=>this._client.request({method:"prompts/list",params:s},St,{signal:i.signal}),t.prompts.listChanged&&this._client.setNotificationHandler(wt,s=>this.sendPromptListChanged(s.params)))}return super.connect(e)}}function Qo(l,o){return JSON.stringify(l)===JSON.stringify(o)}const Wo="ui/notifications/sandbox-proxy-ready",Ko={name:"Grackle",version:"0.0.0"},Go=new Set(["http:","https:"]);function Yo(l){try{return Go.has(new URL(l).protocol)}catch{return!1}}function Ze(l){return l||(typeof document<"u"&&document.documentElement.getAttribute("data-theme")==="dark"?"dark":"light")}function Zo(l,o,e,t,s,i){if(l.src)return Promise.resolve(!1);l.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");const c=Bo(s);c&&l.setAttribute("allow",c);const u=new Promise(g=>{const w=_=>{const b=_.data;_.source===l.contentWindow&&_.origin===e&&(b==null?void 0:b.method)===Wo&&g(!0)};window.addEventListener("message",w,{signal:i}),i.addEventListener("abort",()=>g(!1),{once:!0})}),d=new URL(o,window.location.href);return t&&d.searchParams.set("csp",JSON.stringify(t)),l.src=d.href,u}function se(l){Promise.resolve(l).catch(()=>{})}function oa(l){const{widgetHtml:o,sandboxProxyUrl:e,csp:t,permissions:s,hostStyleVariables:i,theme:c,hostInfo:u,toolInput:d,toolResult:g,onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R}=l;if(typeof window<"u"&&new URL(e,window.location.href).origin===window.location.origin)throw new Error("McpAppWidget: sandboxProxyUrl must be served from a DIFFERENT origin than the host.");const C=K.useRef(null),V=K.useRef(void 0),[O,Q]=K.useState(!1),D=K.useRef({onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R});D.current={onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R};const pe=JSON.stringify(t??null),me=JSON.stringify(s??null);return K.useEffect(()=>{const I=C.current;if(!I)return;const T=new URL(e,window.location.href).origin,B=new AbortController,{signal:A}=B,ee=()=>A.aborted;let te;return(async()=>{if(!await Zo(I,e,T,t,s,A)||ee())return;const J=new Vo(null,u??Ko,{openLinks:{},updateModelContext:{text:{}}},{hostContext:{theme:Ze(c),platform:"web",styles:{variables:i??Ve()},containerDimensions:{maxHeight:6e3},displayMode:"inline",availableDisplayModes:["inline"]}});V.current=J,J.oncalltool=async E=>{const M=D.current.onCallTool;return M?M({name:E.name,arguments:E.arguments}):{isError:!0,content:[{type:"text",text:"No MCP client is connected to this host."}]}},J.onopenlink=async({url:E})=>{const M=D.current.onOpenLink;return M?M(E):Yo(E)&&window.open(E,"_blank","noopener,noreferrer"),{}},J.onmessage=async E=>{var M,W;return(W=(M=D.current).onSendMessage)==null||W.call(M,E),{}},J.onupdatemodelcontext=async E=>{var M,W;return(W=(M=D.current).onUpdateModelContext)==null||W.call(M,E),{}},J.onsizechange=({width:E,height:M})=>{var W,Be;E!==void 0&&(I.style.minWidth=`min(${E}px, 100%)`),M!==void 0&&(I.style.height=`${M}px`),(Be=(W=D.current).onSizeChange)==null||Be.call(W,{width:E,height:M})},J.onrequestdisplaymode=async()=>({mode:"inline"});const Et=new Promise(E=>{J.oninitialized=()=>E()});await J.connect(new jo(I.contentWindow,I.contentWindow)),!ee()&&(await J.sendSandboxResourceReady({html:o,csp:t,permissions:s}),await Et,!ee()&&(Q(!0),te=new ResizeObserver(([E])=>{const M=Math.round(E.contentRect.width);M>0&&se(J.sendHostContextChange({containerDimensions:{width:M,maxHeight:6e3}}))}),te.observe(I)))})().catch(()=>{}),()=>{B.abort(),Q(!1),te==null||te.disconnect();const _e=V.current;V.current=void 0,_e&&se(_e.teardownResource({})),I.removeAttribute("src")}},[o,e,pe,me]),K.useEffect(()=>{var I;O&&se((I=V.current)==null?void 0:I.sendToolInput({arguments:d??{}}))},[O,d]),K.useEffect(()=>{var I;!O||!g||se((I=V.current)==null?void 0:I.sendToolResult(g))},[O,g]),K.useEffect(()=>{var I;se((I=V.current)==null?void 0:I.sendHostContextChange({theme:Ze(c),styles:{variables:i??Ve()}}))},[c,i]),Lt.jsx("iframe",{ref:C,"data-testid":"mcp-app-widget",title:"MCP App widget",style:{width:"100%",border:"none",display:"block"}})}export{oa as McpAppWidget};
39
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:n().optional().describe("User's language and region preference in BCP 47 format."),timeZone:n().optional().describe("User's timezone in IANA format."),userAgent:n().optional().describe("Host application identifier."),platform:f([a("web"),a("desktop"),a("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:r({touch:x().optional().describe("Whether the device supports touch input."),hover:x().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:r({top:p().describe("Top safe area inset in pixels."),right:p().describe("Right safe area inset in pixels."),bottom:p().describe("Bottom safe area inset in pixels."),left:p().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();r({method:a("ui/notifications/host-context-changed"),params:Ht.describe("Partial context update containing only changed fields.")});var $o=r({method:a("ui/update-model-context"),params:r({content:h(he).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:S(n(),v().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),Fo=r({method:a("ui/initialize"),params:r({appInfo:Se.describe("App identification (name and version)."),appCapabilities:Ao.describe("Features and capabilities this app provides."),protocolVersion:n().describe("Protocol version this app supports.")})});r({protocolVersion:n().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Se.describe("Host application identification and version."),hostCapabilities:Lo.describe("Features and capabilities provided by the host."),hostContext:Ht.describe("Rich context about the host environment.")}).passthrough();class jo{constructor(o=window.parent,e){m(this,"eventTarget");m(this,"eventSource");m(this,"messageListener");m(this,"onclose");m(this,"onerror");m(this,"onmessage");m(this,"sessionId");m(this,"setProtocolVersion");this.eventTarget=o,this.eventSource=e,this.messageListener=t=>{var i,c,u;if(e&&t.source!==this.eventSource){console.debug("Ignoring message from unknown source",t);return}let s=Vt.safeParse(t.data);s.success?(console.debug("Parsed message",s.data),(i=this.onmessage)==null||i.call(this,s.data)):((c=t.data)==null?void 0:c.jsonrpc)!=="2.0"?console.debug("Ignoring non-JSON-RPC message",s.error.message,t):(console.error("Failed to parse message",s.error.message,t),(u=this.onerror)==null||u.call(this,Error("Invalid JSON-RPC message received: "+s.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(o,e){o.method!==Ro&&console.debug("Sending message",o),this.eventTarget.postMessage(o,"*")}async close(){var o;window.removeEventListener("message",this.messageListener),(o=this.onclose)==null||o.call(this)}}function Bo(l){if(!l)return"";let o=[];return l.camera&&o.push("camera"),l.microphone&&o.push("microphone"),l.geolocation&&o.push("geolocation"),l.clipboardWrite&&o.push("clipboard-write"),o.join("; ")}var Jo=[Pt];class Qo extends xo{constructor(e,t,s,i){super(i);m(this,"_client");m(this,"_hostInfo");m(this,"_capabilities");m(this,"_appCapabilities");m(this,"_hostContext",{});m(this,"_appInfo");m(this,"_initializedReceived",!1);m(this,"_baseReplaceRequestHandler",this.replaceRequestHandler);m(this,"replaceRequestHandler",(e,t)=>{this._baseReplaceRequestHandler(e,(s,i)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${s.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),t(s,i)))});m(this,"eventSchemas",{sizechange:Po,sandboxready:Io,initialized:zo,requestteardown:No,loggingmessage:qt});m(this,"onping");m(this,"_onmessage");m(this,"_onopenlink");m(this,"_ondownloadfile");m(this,"_onrequestdisplaymode");m(this,"_onupdatemodelcontext");m(this,"_oncalltool");m(this,"_onlistresources");m(this,"_onlistresourcetemplates");m(this,"_onreadresource");m(this,"_onlistprompts");m(this,"sendResourceTeardown",this.teardownResource);this._client=e,this._hostInfo=t,this._capabilities=s,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=(i==null?void 0:i.hostContext)||{},this.setRequestHandler(Fo,c=>this._oninitialize(c)),this.setRequestHandler(ke,(c,u)=>{var d;return(d=this.onping)==null||d.call(this,c.params,u),{}}),this.replaceRequestHandler(Ye,c=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}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)}get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler(Do,async(t,s)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t.params,s)})}get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(Co,async(t,s)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t.params,s)})}get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(Oo,async(t,s)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t.params,s)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler(Ye,async(t,s)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t.params,s)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler($o,async(t,s)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t.params,s)})}get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rt,async(t,s)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,s)})}set oncreatesamplingmessage(e){this.setRequestHandler(Ct,async(t,s)=>e(t.params,s))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler(ut,async(t,s)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,s)})}get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(pt,async(t,s)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,s)})}get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(ft,async(t,s)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,s)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler(yt,async(t,s)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,s)})}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:Jo.includes(t)?t:Pt,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},s=!1;for(let i of Object.keys(e)){let c=this._hostContext[i],u=e[i];Vo(c,u)||(t[i]=u,s=!0)}s&&(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},Mo,t)}callTool(e,t){return this.request({method:"tools/call",params:e},oe,t)}listTools(e,t){return this.request({method:"tools/list",params:e},xt,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 t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");t.tools&&(this.oncalltool=async(s,i)=>this._client.request({method:"tools/call",params:s},oe,{signal:i.signal}),t.tools.listChanged&&this._client.setNotificationHandler(vt,s=>this.sendToolListChanged(s.params))),t.resources&&(this.onlistresources=async(s,i)=>this._client.request({method:"resources/list",params:s},ht,{signal:i.signal}),this.onlistresourcetemplates=async(s,i)=>this._client.request({method:"resources/templates/list",params:s},mt,{signal:i.signal}),this.onreadresource=async(s,i)=>this._client.request({method:"resources/read",params:s},gt,{signal:i.signal}),t.resources.listChanged&&this._client.setNotificationHandler(bt,s=>this.sendResourceListChanged(s.params))),t.prompts&&(this.onlistprompts=async(s,i)=>this._client.request({method:"prompts/list",params:s},St,{signal:i.signal}),t.prompts.listChanged&&this._client.setNotificationHandler(wt,s=>this.sendPromptListChanged(s.params)))}return super.connect(e)}}function Vo(l,o){return JSON.stringify(l)===JSON.stringify(o)}const Wo="ui/notifications/sandbox-proxy-ready",Ko={name:"Grackle",version:"0.0.0"},Go=new Set(["http:","https:"]);function Yo(l){try{return Go.has(new URL(l).protocol)}catch{return!1}}function Ze(l){return l||(typeof document<"u"&&document.documentElement.getAttribute("data-theme")==="dark"?"dark":"light")}function Zo(l,o,e,t,s,i){if(l.src)return Promise.resolve(!1);l.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");const c=Bo(s);c&&l.setAttribute("allow",c);const u=new Promise(g=>{const w=_=>{const b=_.data;_.source===l.contentWindow&&_.origin===e&&(b==null?void 0:b.method)===Wo&&g(!0)};window.addEventListener("message",w,{signal:i}),i.addEventListener("abort",()=>g(!1),{once:!0})}),d=new URL(o,window.location.href);return t&&d.searchParams.set("csp",JSON.stringify(t)),l.src=d.href,u}function se(l){Promise.resolve(l).catch(()=>{})}function oa(l){const{widgetHtml:o,sandboxProxyUrl:e,csp:t,permissions:s,hostStyleVariables:i,theme:c,hostInfo:u,toolInput:d,toolResult:g,onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R}=l;if(typeof window<"u"&&new URL(e,window.location.href).origin===window.location.origin)throw new Error("McpAppWidget: sandboxProxyUrl must be served from a DIFFERENT origin than the host.");const C=K.useRef(null),Q=K.useRef(void 0),[O,V]=K.useState(!1),D=K.useRef({onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R});D.current={onCallTool:w,onOpenLink:_,onSendMessage:b,onUpdateModelContext:P,onSizeChange:R};const pe=JSON.stringify(t??null),me=JSON.stringify(s??null);return K.useEffect(()=>{const I=C.current;if(!I)return;const T=new URL(e,window.location.href).origin,B=new AbortController,{signal:A}=B,ee=()=>A.aborted;let te;return(async()=>{if(!await Zo(I,e,T,t,s,A)||ee())return;const J=new Qo(null,u??Ko,{openLinks:{},updateModelContext:{text:{}}},{hostContext:{theme:Ze(c),platform:"web",styles:{variables:i??Qe()},containerDimensions:{maxHeight:6e3},displayMode:"inline",availableDisplayModes:["inline"]}});Q.current=J,J.oncalltool=async E=>{const M=D.current.onCallTool;return M?M({name:E.name,arguments:E.arguments}):{isError:!0,content:[{type:"text",text:"No MCP client is connected to this host."}]}},J.onopenlink=async({url:E})=>{const M=D.current.onOpenLink;return M?M(E):Yo(E)&&window.open(E,"_blank","noopener,noreferrer"),{}},J.onmessage=async E=>{var M,W;return(W=(M=D.current).onSendMessage)==null||W.call(M,E),{}},J.onupdatemodelcontext=async E=>{var M,W;return(W=(M=D.current).onUpdateModelContext)==null||W.call(M,E),{}},J.onsizechange=({width:E,height:M})=>{var W,Be;E!==void 0&&(I.style.minWidth=`min(${E}px, 100%)`),M!==void 0&&(I.style.height=`${M}px`),(Be=(W=D.current).onSizeChange)==null||Be.call(W,{width:E,height:M})},J.onrequestdisplaymode=async()=>({mode:"inline"});const Et=new Promise(E=>{J.oninitialized=()=>E()});await J.connect(new jo(I.contentWindow,I.contentWindow)),!ee()&&(await J.sendSandboxResourceReady({html:o,csp:t,permissions:s}),await Et,!ee()&&(V(!0),te=new ResizeObserver(([E])=>{const M=Math.round(E.contentRect.width);M>0&&se(J.sendHostContextChange({containerDimensions:{width:M,maxHeight:6e3}}))}),te.observe(I)))})().catch(()=>{}),()=>{B.abort(),V(!1),te==null||te.disconnect();const _e=Q.current;Q.current=void 0,_e&&se(_e.teardownResource({})),I.removeAttribute("src")}},[o,e,pe,me]),K.useEffect(()=>{var I;O&&se((I=Q.current)==null?void 0:I.sendToolInput({arguments:d??{}}))},[O,d]),K.useEffect(()=>{var I;!O||!g||se((I=Q.current)==null?void 0:I.sendToolResult(g))},[O,g]),K.useEffect(()=>{var I;se((I=Q.current)==null?void 0:I.sendHostContextChange({theme:Ze(c),styles:{variables:i??Qe()}}))},[c,i]),Lt.jsx("iframe",{ref:C,"data-testid":"mcp-app-widget",title:"MCP App widget",style:{width:"100%",border:"none",display:"block"}})}export{oa as McpAppWidget};
40
+ //# sourceMappingURL=McpAppWidget-DsHebvaE.js.map