@zuplo/runtime 7.14.2 → 7.14.5

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.
@@ -22,25 +22,25 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as Wi,$a as Wu,$b as ea,$c as Np,$f as Kw,$g as Bm,Aa as Xi,Ab as bl,Ac as mp,Ad as tm,Af as Rm,Ag as Mm,Ah as Xw,Ba as Cu,Bb as vl,Bc as aa,Bd as xs,Bf as Dr,Bg as oe,C as ou,Ca as Iu,Cb as Cl,Cc as ks,Cd as Os,Cf as O,Cg as Um,Da as Tu,Db as Il,Dc as As,Dd as sr,Df as Lr,Dg as Ot,E as Cs,Ea as Eu,Eb as Tl,Ec as hp,Ed as rm,Ef as $r,Eg as la,Fa as ku,Fb as El,Fc as fp,Fd as nm,Ff as dt,Fg as $s,Ga as Au,Gb as kl,Gc as gp,Gd as um,Gf as ut,Gg as pa,H as Ki,Ha as Pu,Hb as Al,Hc as yp,Hd as lm,Hf as qs,Hg as Hs,Ia as xu,Ib as Pl,Ic as Sp,Id as pm,If as Hr,Ig as bo,Ja as Ou,Jb as xl,Jc as _p,Jd as mm,Jf as Br,Jg as Vr,Ka as Mu,Kb as Ol,Kc as wp,Kd as hm,Kf as Fr,Kg as qm,La as Uu,Lb as Ml,Lc as Rp,Ld as da,Lf as zs,Lg as mt,Ma as qu,Mb as Ul,Mc as bp,Mf as bm,Mg as ma,N as su,Na as zu,Nb as ql,Nc as vp,Nf as et,Ng as Bs,Oa as Nu,Ob as zl,Oc as Cp,Of as vm,Og as zm,Pa as ju,Pb as Nl,Pc as Ip,Pf as lt,Pg as Fs,Q as iu,Qa as Du,Qb as jl,Qc as Tp,Qf as z,Qg as ha,Ra as Lu,Rb as Dl,Rc as Ep,Rf as Ns,Rg as Js,Sa as Qi,Sb as Ll,Sc as kp,Sd as fm,Sf as Ee,Sg as Nm,T as au,Ta as $u,Tb as $l,Tc as Ap,Tf as Pt,Tg as pe,Ua as Hu,Ub as Hl,Uc as Pp,Uf as $w,Ug as jm,Va as Bu,Vb as Bl,Vc as xp,Vf as Hw,Vg as Dm,Wa as Fu,Wb as Fl,Wc as Op,Wf as Bw,Wg as Lm,Xa as Ju,Xb as Jl,Xc as Mp,Xf as Fw,Xg as fa,Ya as Vu,Yb as Vl,Yc as Up,Yf as Jw,Yg as $m,Za as Gu,Zb as Gl,Zc as qp,Zf as Vw,Zg as Hm,_ as Is,_a as Ku,_b as Kl,_c as zp,_f as Gw,_g as ga,aa as Pr,ab as Zu,ac as Wl,ad as jp,ag as Ww,ah as ar,b as vs,ba as mo,bb as Yu,bc as Zl,bd as Dp,bg as Zw,bh as Fm,ca as xr,cb as Xu,cc as Yl,cd as Lp,cg as Cm,ch as vo,da as Or,db as Qu,dc as Xl,dd as $p,dg as Im,dh as Jm,ea as ho,eb as el,ec as Ql,ed as Hp,eg as js,eh as Vs,fa as rr,fb as tl,fc as ep,fd as Bp,fg as _o,fh as Co,ga as cu,gb as rl,gc as tp,gd as Fp,gg as wo,gh as Vm,ha as du,hb as nl,hc as rp,hd as Jp,hg as Jr,hh as Gm,ia as uu,ib as ol,ic as np,id as Vp,ig as Tm,ih as Km,ja as lu,jb as sl,jc as op,jd as Gp,jg as ua,jh as Wm,ka as pu,kb as il,kc as sp,kd as Mr,kg as Em,kh as Zm,la as mu,lb as al,lc as ip,ld as Ur,lg as Ro,lh as Ym,ma as hu,mb as cl,mc as ap,md as Kp,mg as Ds,mh as Xm,n as ot,na as fu,nb as dl,nc as cp,nd as qr,ng as km,nh as Qm,oa as gu,ob as ul,oc as dp,od as At,og as Am,oh as Gs,pa as yu,pb as ll,pc as up,pd as ca,pg as Pm,ph as eh,qa as Su,qb as pl,qc as ta,qd as Ps,qg as xm,qh as th,ra as _u,rb as ml,rc as Ts,rd as Wp,rg as Ce,rh as H,sa as wu,sb as hl,sc as Es,sd as go,sf as gm,sg as ge,sh as te,ta as Ru,tb as fl,tc as ra,td as or,tf as je,tg as Om,th as ya,u as Ne,ua as bu,ub as gl,uc as na,ud as Zp,uf as ym,ug as Ls,uh as ye,v as nu,va as vu,vb as yl,vc as oa,vd as Yp,vf as Sm,vg as J,vh as ht,wa as nr,wb as Sl,wc as lp,wd as Xp,wf as _m,wg as pt,wh as ae,x as V,xa as Zi,xb as _l,xc as sa,xd as Qp,xf as ie,xg as xt,xh as Ks,ya as Yi,yb as wl,yc as ia,yd as em,yf as wm,yg as ke,yh as rh,za as fo,zb as Rl,zc as pp,zd as yo,zf as jr,zg as ue,zh as Yw}from"../chunk-MUDGPSWL.js";import"../chunk-VP5Q3DEN.js";import"../chunk-AENEWA54.js";import{a as kt,b as fe,c as So,d as Ms,e as om,f as sm,g as ir,h as Us,i as im,j as am,k as zr,l as Nr,s as cm,t as dm}from"../chunk-7RNZS3GX.js";import"../chunk-A3QGJZO7.js";import{A as p,b as Ji,c as eu,d as l,e as tu,f as ru,g as E,h as N,i as Rs,k as D,l as C,m as g,n as $,o as q,p as Vi,q as lo,r as M,s as F,t as w,u as L,v as Gi,w as bs,y as po}from"../chunk-C32OTSKW.js";import"../chunk-UKQQD2JN.js";import{$ as ws,a as Te,aa as Qd,c as k,d as ee}from"../chunk-UFTMOJ7K.js";import{a as o}from"../chunk-TYV53J3B.js";var Qw=Object.create,Ws=Object.defineProperty,eR=Object.getOwnPropertyDescriptor,tR=Object.getOwnPropertyNames,rR=Object.getPrototypeOf,nR=Object.prototype.hasOwnProperty,nh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),oh=o((e,t)=>{let r={};for(var n in e)Ws(r,n,{get:e[n],enumerable:!0});return t&&Ws(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),oR=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=tR(t),i=0,a=s.length,c;i<a;i++)c=s[i],!nR.call(e,c)&&c!==r&&Ws(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=eR(t,c))||n.enumerable});return e},"__copyProps"),sh=o((e,t,r)=>(r=e!=null?Qw(rR(e)):{},oR(t||!e||!e.__esModule?Ws(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var sR=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function ih(e){return typeof e=="string"&&sR.has(e.replace(/#$/,""))}o(ih,"declares2019Dialect");var va=Symbol.for("mcp.sdk.errorBrands");function cr(e,t){let r=new Set,n=t;for(;typeof n=="function";){let s=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof s=="string"&&r.add(s),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,va,{value:r,enumerable:!1,configurable:!0})}o(cr,"stampErrorBrands");function De(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,va)){let r=t[va];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}o(De,"brandedHasInstance");var me=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Mt=class yh extends Error{static{o(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",cr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new yh(t.error,t.error_description??t.error,t.error_uri)}},Se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),le=class extends Error{static{o(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",cr(this,new.target)}},yR=class extends le{static{o(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,n){super(e,t,r,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Sh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Sh,"resourceUrlFromServerUrl");function Aa(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}o(Aa,"withoutIssuer");function ei({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(i)}o(ei,"checkResourceAllowed");var SR="2026-07-28";function _h(e){return e>=SR}o(_h,"isModernProtocolVersion");function wh(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}o(wh,"appendTextFallbackForNonObject");var Rh=["task","inputRequests","requestState"];function _R(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Rh.some(t=>t in e)?e:{...e,content:[]}}o(_R,"normalizeContentlessToolResult");function wR(){let e=Gi(()=>q([l(),E(),N(),Rs(),M(l(),e),C(e)])),t=M(l(),e),r=q([l(),E().int()]),n=l(),s=g({ttl:E().optional()}),i=g({taskId:l()}),a=$({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),m=g({_meta:a.optional()}),h=g({method:l(),params:m.loose().optional()}),f=$({_meta:a.optional()}),S=q([l(),E().int()]),R=f.strict(),_=m.extend({requestId:S.optional(),reason:l().optional()}),y=h.extend({method:w("notifications/cancelled"),params:_}),b=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),I=g({icons:C(b).optional()}),U=g({name:l(),title:l().optional()}),v=U.extend({...U.shape,...I.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),Y=lo(g({applyDefaults:N().optional()}),t),x=bs(ve=>ve&&typeof ve=="object"&&!Array.isArray(ve)&&Object.keys(ve).length===0?{form:{}}:ve,lo(g({form:Y.optional(),url:t.optional()}),t.optional())),Z=$({list:t.optional(),cancel:t.optional(),requests:$({sampling:$({createMessage:t.optional()}).optional(),elicitation:$({create:t.optional()}).optional()}).optional()}),re=$({list:t.optional(),cancel:t.optional(),requests:$({tools:$({call:t.optional()}).optional()}).optional()}),P=g({experimental:M(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:x.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Z.optional(),extensions:M(l(),t).optional()}),B=c.extend({protocolVersion:l(),capabilities:P,clientInfo:v}),j=u.extend({method:w("initialize"),params:B}),X=g({experimental:M(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:re.optional(),extensions:M(l(),t).optional()}),Q=f.extend({protocolVersion:l(),capabilities:X,serverInfo:v,instructions:l().optional()}),He=h.extend({method:w("notifications/initialized"),params:m.optional()}),Ue=u.extend({method:w("ping"),params:c.optional()}),Be=g({progress:E(),total:L(E()),message:L(l())}),K=g({...m.shape,...Be.shape,progressToken:r}),de=h.extend({method:w("notifications/progress"),params:K}),xe=c.extend({cursor:n.optional()}),ne=u.extend({params:xe.optional()}),Ye=f.extend({nextCursor:n.optional()}),fr=g({uri:l(),mimeType:L(l()),_meta:M(l(),D()).optional()}),gr=fr.extend({text:l()}),Ft=l().refine(ve=>{try{return atob(ve),!0}catch{return!1}},{message:"Invalid Base64 string"}),yr=fr.extend({blob:Ft}),nt=F(["user","assistant"]),Xe=g({audience:C(nt).optional(),priority:E().min(0).max(1).optional(),lastModified:po.datetime({offset:!0}).optional()}),Jt=g({...U.shape,...I.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(E()),annotations:Xe.optional(),_meta:L($({}))}),yn=g({...U.shape,...I.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:Xe.optional(),_meta:L($({}))}),Sn=ne.extend({method:w("resources/list")}),_n=Ye.extend({resources:C(Jt)}),Ct=ne.extend({method:w("resources/templates/list")}),Sr=Ye.extend({resourceTemplates:C(yn)}),Vt=c.extend({uri:l()}),wn=Vt,Rn=u.extend({method:w("resources/read"),params:wn}),bn=f.extend({contents:C(q([gr,yr]))}),vn=h.extend({method:w("notifications/resources/list_changed"),params:m.optional()}),Cn=Vt,In=u.extend({method:w("resources/subscribe"),params:Cn}),Tn=Vt,En=u.extend({method:w("resources/unsubscribe"),params:Tn}),kn=m.extend({uri:l()}),An=h.extend({method:w("notifications/resources/updated"),params:kn}),Pn=g({name:l(),description:L(l()),required:L(N())}),xn=g({...U.shape,...I.shape,description:L(l()),arguments:L(C(Pn)),_meta:L($({}))}),On=ne.extend({method:w("prompts/list")}),Mn=Ye.extend({prompts:C(xn)}),Un=c.extend({name:l(),arguments:M(l(),l()).optional()}),qn=u.extend({method:w("prompts/get"),params:Un}),Gt=g({type:w("text"),text:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Kt=g({type:w("image"),data:Ft,mimeType:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Wt=g({type:w("audio"),data:Ft,mimeType:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),zn=g({type:w("tool_use"),name:l(),id:l(),input:M(l(),D()),_meta:M(l(),D()).optional()}),It=g({type:w("resource"),resource:q([gr,yr]),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Nn=Jt.extend({type:w("resource_link")}),Fe=q([Gt,Kt,Wt,Nn,It]),_r=g({role:nt,content:Fe}),wr=f.extend({description:l().optional(),messages:C(_r)}),Zt=h.extend({method:w("notifications/prompts/list_changed"),params:m.optional()}),jn=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Rr=g({taskSupport:F(["required","optional","forbidden"]).optional()}),Yt=g({...U.shape,...I.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:M(l(),e).optional(),required:C(l()).optional()}).catchall(D()),outputSchema:g({type:w("object"),properties:M(l(),e).optional(),required:C(l()).optional()}).catchall(D()).optional(),annotations:jn.optional(),execution:Rr.optional(),_meta:M(l(),D()).optional()}),br=ne.extend({method:w("tools/list")}),vr=Ye.extend({tools:C(Yt)}),Cr=f.extend({content:C(Fe),structuredContent:M(l(),D()).optional(),isError:N().optional()}),be=d.extend({name:l(),arguments:M(l(),D()).optional()}),Dn=u.extend({method:w("tools/call"),params:be}),os=h.extend({method:w("notifications/tools/list_changed"),params:m.optional()}),Ir=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Ln=c.extend({level:Ir}),$n=u.extend({method:w("logging/setLevel"),params:Ln}),Hn=m.extend({level:Ir,logger:l().optional(),data:D()}),Bn=h.extend({method:w("notifications/message"),params:Hn}),Fn=g({name:l().optional()}),Jn=g({hints:C(Fn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Vn=g({mode:F(["auto","required","none"]).optional()}),ss=g({type:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Fe),structuredContent:g({}).loose().optional(),isError:N().optional(),_meta:M(l(),D()).optional()}),Gn=Vi("type",[Gt,Kt,Wt]),Tt=Vi("type",[Gt,Kt,Wt,zn,ss]),Kn=g({role:nt,content:q([Tt,C(Tt)]),_meta:M(l(),D()).optional()}),Wn=d.extend({messages:C(Kn),modelPreferences:Jn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Yt).optional(),toolChoice:Vn.optional()}),Zn=u.extend({method:w("sampling/createMessage"),params:Wn}),Yn=f.extend({model:l(),stopReason:L(F(["endTurn","stopSequence","maxTokens"]).or(l())),role:nt,content:Gn}),Xn=f.extend({model:l(),stopReason:L(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:nt,content:q([Tt,C(Tt)])}),Qn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),eo=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),to=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),ro=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),no=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),oo=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),so=q([ro,no]),Xt=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),Qt=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),is=q([Xt,Qt]),as=q([oo,so,is]),qe=q([as,Qn,eo,to]),ze=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:M(l(),qe),required:C(l()).optional()}).catchall(D())}),io=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),Qe=q([ze,io]),cs=u.extend({method:w("elicitation/create"),params:Qe}),ds=m.extend({elicitationId:l()}),us=h.extend({method:w("notifications/elicitation/complete"),params:ds}),ls=f.extend({action:F(["accept","decline","cancel"]),content:bs(ve=>ve===null?void 0:ve,M(l(),q([l(),E(),N(),C(l())])).optional())}),ps=g({type:w("ref/resource"),uri:l()}),ms=g({type:w("ref/prompt"),name:l()}),hs=c.extend({ref:q([ms,ps]),argument:g({name:l(),value:l()}),context:g({arguments:M(l(),l()).optional()}).optional()}),ao=u.extend({method:w("completion/complete"),params:hs}),fs=f.extend({completion:$({values:C(l()).max(100),total:L(E().int()),hasMore:L(N())})}),gs=g({uri:l().startsWith("file://"),name:l().optional(),_meta:M(l(),D()).optional()}),Tr=u.extend({method:w("roots/list"),params:c.optional()}),co=f.extend({roots:C(gs)}),ys=h.extend({method:w("notifications/roots/list_changed"),params:m.optional()}),Ss=$({ttl:E().optional(),pollInterval:E().optional()}),uo=F(["working","input_required","completed","failed","cancelled"]),Et=g({taskId:l(),status:uo,ttl:q([E(),Rs()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:L(E()),statusMessage:L(l())}),Oe=f.extend({task:Et}),_s=m.merge(Et),er=h.extend({method:w("notifications/tasks/status"),params:_s}),Er=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),kr=f.merge(Et),Ar=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),Fi=f.loose(),Ie=ne.extend({method:w("tasks/list")}),se=Ye.extend({tasks:C(Et)}),tr=u.extend({method:w("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:R,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:y,IconSchema:b,IconsSchema:I,BaseMetadataSchema:U,ImplementationSchema:v,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:P,InitializeRequestParamsSchema:B,InitializeRequestSchema:j,ServerCapabilitiesSchema:X,InitializeResultSchema:Q,InitializedNotificationSchema:He,PingRequestSchema:Ue,ProgressSchema:Be,ProgressNotificationParamsSchema:K,ProgressNotificationSchema:de,PaginatedRequestParamsSchema:xe,PaginatedRequestSchema:ne,PaginatedResultSchema:Ye,ResourceContentsSchema:fr,TextResourceContentsSchema:gr,BlobResourceContentsSchema:yr,RoleSchema:nt,AnnotationsSchema:Xe,ResourceSchema:Jt,ResourceTemplateSchema:yn,ListResourcesRequestSchema:Sn,ListResourcesResultSchema:_n,ListResourceTemplatesRequestSchema:Ct,ListResourceTemplatesResultSchema:Sr,ResourceRequestParamsSchema:Vt,ReadResourceRequestParamsSchema:wn,ReadResourceRequestSchema:Rn,ReadResourceResultSchema:bn,ResourceListChangedNotificationSchema:vn,SubscribeRequestParamsSchema:Cn,SubscribeRequestSchema:In,UnsubscribeRequestParamsSchema:Tn,UnsubscribeRequestSchema:En,ResourceUpdatedNotificationParamsSchema:kn,ResourceUpdatedNotificationSchema:An,PromptArgumentSchema:Pn,PromptSchema:xn,ListPromptsRequestSchema:On,ListPromptsResultSchema:Mn,GetPromptRequestParamsSchema:Un,GetPromptRequestSchema:qn,TextContentSchema:Gt,ImageContentSchema:Kt,AudioContentSchema:Wt,ToolUseContentSchema:zn,EmbeddedResourceSchema:It,ResourceLinkSchema:Nn,ContentBlockSchema:Fe,PromptMessageSchema:_r,GetPromptResultSchema:wr,PromptListChangedNotificationSchema:Zt,ToolAnnotationsSchema:jn,ToolExecutionSchema:Rr,ToolSchema:Yt,ListToolsRequestSchema:br,ListToolsResultSchema:vr,CallToolResultSchema:Cr,CallToolRequestParamsSchema:be,CallToolRequestSchema:Dn,ToolListChangedNotificationSchema:os,LoggingLevelSchema:Ir,SetLevelRequestParamsSchema:Ln,SetLevelRequestSchema:$n,LoggingMessageNotificationParamsSchema:Hn,LoggingMessageNotificationSchema:Bn,ModelHintSchema:Fn,ModelPreferencesSchema:Jn,ToolChoiceSchema:Vn,ToolResultContentSchema:ss,SamplingContentSchema:Gn,SamplingMessageContentBlockSchema:Tt,SamplingMessageSchema:Kn,CreateMessageRequestParamsSchema:Wn,CreateMessageRequestSchema:Zn,CreateMessageResultSchema:Yn,CreateMessageResultWithToolsSchema:Xn,BooleanSchemaSchema:Qn,StringSchemaSchema:eo,NumberSchemaSchema:to,UntitledSingleSelectEnumSchemaSchema:ro,TitledSingleSelectEnumSchemaSchema:no,LegacyTitledEnumSchemaSchema:oo,SingleSelectEnumSchemaSchema:so,UntitledMultiSelectEnumSchemaSchema:Xt,TitledMultiSelectEnumSchemaSchema:Qt,MultiSelectEnumSchemaSchema:is,EnumSchemaSchema:as,PrimitiveSchemaDefinitionSchema:qe,ElicitRequestFormParamsSchema:ze,ElicitRequestURLParamsSchema:io,ElicitRequestParamsSchema:Qe,ElicitRequestSchema:cs,ElicitationCompleteNotificationParamsSchema:ds,ElicitationCompleteNotificationSchema:us,ElicitResultSchema:ls,ResourceTemplateReferenceSchema:ps,PromptReferenceSchema:ms,CompleteRequestParamsSchema:hs,CompleteRequestSchema:ao,CompleteResultSchema:fs,RootSchema:gs,ListRootsRequestSchema:Tr,ListRootsResultSchema:co,RootsListChangedNotificationSchema:ys,TaskCreationParamsSchema:Ss,TaskStatusSchema:uo,TaskSchema:Et,CreateTaskResultSchema:Oe,TaskStatusNotificationParamsSchema:_s,TaskStatusNotificationSchema:er,GetTaskRequestSchema:Er,GetTaskResultSchema:kr,GetTaskPayloadRequestSchema:Ar,GetTaskPayloadResultSchema:Fi,ListTasksRequestSchema:Ie,ListTasksResultSchema:se,CancelTaskRequestSchema:tr,CancelTaskResultSchema:f.merge(Et),ClientRequestSchema:q([Ue,j,ao,$n,qn,On,Sn,Ct,Rn,In,En,Dn,br,Er,Ar,Ie,tr]),ClientNotificationSchema:q([y,de,He,ys,er]),ClientResultSchema:q([R,Yn,Xn,ls,co,kr,se,Oe]),ServerRequestSchema:q([Ue,Zn,cs,Tr,Er,Ar,Ie,tr]),ServerNotificationSchema:q([y,de,Bn,An,vn,os,Zt,er,us]),ServerResultSchema:q([R,Q,fs,wr,Mn,_n,Sr,bn,Cr,vr,kr,se,Oe]),CallToolResultWireSchema:D().superRefine((ve,Lw)=>{if(!(typeof ve!="object"||ve===null||Array.isArray(ve)||ve.content!==void 0)){for(let Xd of Rh)if(Xd in ve){Lw.addIssue({code:"custom",message:`content is required when the body carries '${Xd}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(_R).pipe(Cr)}}o(wR,"build$1");var RR;function Pa(){return RR??=wR()}o(Pa,"buildSchemas2025");function bh(e){return e.type!=="object"}o(bh,"isNonObjectJsonSchemaRoot");var bR=new Set(["const","enum","default","examples"]),vR=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ah(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(ah,"establishesNewBase");function CR(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ah(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=ih(e.$schema)&&e.$recursiveAnchor!==!0,n=o((s,i)=>{if(Array.isArray(s))return s.map(d=>n(d,!1));if(s===null||typeof s!="object"||!i&&ah(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=n(u,!1):(d==="$ref"||d==="$dynamicRef")&&typeof u=="string"?a[d]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:d==="$recursiveRef"&&u==="#"&&r?c=!0:bR.has(d)?a[d]=u:vR.has(d)?a[d]=n(u,!0):a[d]=n(u,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}o(CR,"wrapOutputSchemaForLegacy");var vh={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ch={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},IR={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Zs;function ti(){if(Zs)return Zs;let e=Pa();return Zs={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Zs}o(ti,"registryMaps");function TR(){ti()}o(TR,"warmRegistryMaps2025");function Ih(e){return Object.prototype.hasOwnProperty.call(vh,e)}o(Ih,"hasRequestMethod2025");function Th(e){return Object.prototype.hasOwnProperty.call(Ch,e)}o(Th,"hasNotificationMethod2025");function ER(e){return Object.prototype.hasOwnProperty.call(IR,e)}o(ER,"hasResultMethod");function kR(e){return ER(e)?ti().resultSchemas[e]:void 0}o(kR,"getResultSchema");function AR(e){return Ih(e)?ti().requestSchemas[e]:void 0}o(AR,"getRequestSchema");function PR(e){return Th(e)?ti().notificationSchemas[e]:void 0}o(PR,"getNotificationSchema");var GM=Object.keys(vh),KM=Object.keys(Ch);function Ca(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ca,"isPlainObject$5");function Ys(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Ys,"triState$1");var ch={ok:!1,reason:"not-in-era"};function dh(e){return Ca(e)&&Ca(e.outputSchema)&&bh(e.outputSchema)}o(dh,"toolNeedsLegacyWrap");var xa={era:"2025-11-25",hasRequestMethod:Ih,hasNotificationMethod:Th,validateRequest:o((e,t)=>Ys(AR(e),t),"validateRequest"),validateResult:o((e,t)=>Ys(kR(e),t),"validateResult"),validateNotification:o((e,t)=>Ys(PR(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>ch,"validateInputRequest"),validateInputResponse:o(()=>ch,"validateInputResponse"),samplingResultVariant:o(((e,t)=>{let r=Pa();return Ys(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:o(e=>{},"outboundEnvelope"),validateEnvelopeMeta:o(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=wh(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&bh(t);return!s&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ca(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>dh(n))?t:{...t,tools:r.map(n=>dh(n)?{...n,outputSchema:CR(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function xR(){let e=Gi(()=>q([l(),E(),N(),Rs(),M(l(),e),C(e)])),t=M(l(),e),r=q([l(),E().int()]),n=l(),s=q([l(),E().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(se=>{try{return atob(se),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:E().optional()}),u=g({taskId:l()}),m=$({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:m.optional()}),f=h.extend({task:d.optional()}),S=g({_meta:m.optional()}),R=g({method:l(),params:S.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),y=g({icons:C(_).optional()}),b=g({name:l(),title:l().optional()}),I=b.extend({...b.shape,...y.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),U=lo(g({applyDefaults:N().optional()}),t),v=bs(se=>se&&typeof se=="object"&&!Array.isArray(se)&&Object.keys(se).length===0?{form:{}}:se,lo(g({form:U.optional(),url:t.optional()}),t.optional())),Y=$({list:t.optional(),cancel:t.optional(),requests:$({sampling:$({createMessage:t.optional()}).optional(),elicitation:$({create:t.optional()}).optional()}).optional()}),x=$({list:t.optional(),cancel:t.optional(),requests:$({tools:$({call:t.optional()}).optional()}).optional()}),Z=g({experimental:M(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:v.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Y.optional(),extensions:M(l(),t).optional()}),re=g({experimental:M(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:x.optional(),extensions:M(l(),t).optional()}),P=g({progress:E(),total:L(E()),message:L(l())}),B=g({...S.shape,...P.shape,progressToken:r}),j=R.extend({method:w("notifications/progress"),params:B}),X=S.extend({level:a,logger:l().optional(),data:D()}),Q=R.extend({method:w("notifications/message"),params:X}),He=g({uri:l(),mimeType:L(l()),_meta:M(l(),D()).optional()}),Ue=He.extend({text:l()}),Be=He.extend({blob:c}),K=g({audience:C(i).optional(),priority:E().min(0).max(1).optional(),lastModified:po.datetime({offset:!0}).optional()}),de=g({...b.shape,...y.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(E()),annotations:K.optional(),_meta:L($({}))}),xe=g({...b.shape,...y.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:K.optional(),_meta:L($({}))}),ne=R.extend({method:w("notifications/resources/list_changed"),params:S.optional()}),Ye=S.extend({uri:l()}),fr=R.extend({method:w("notifications/resources/updated"),params:Ye}),gr=g({name:l(),description:L(l()),required:L(N())}),Ft=g({...b.shape,...y.shape,description:L(l()),arguments:L(C(gr)),_meta:L($({}))}),yr=R.extend({method:w("notifications/prompts/list_changed"),params:S.optional()}),nt=g({type:w("text"),text:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),Xe=g({type:w("image"),data:c,mimeType:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),Jt=g({type:w("audio"),data:c,mimeType:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),yn=g({type:w("tool_use"),name:l(),id:l(),input:M(l(),D()),_meta:M(l(),D()).optional()}),Sn=g({type:w("resource"),resource:q([Ue,Be]),annotations:K.optional(),_meta:M(l(),D()).optional()}),_n=de.extend({type:w("resource_link")}),Ct=q([nt,Xe,Jt,_n,Sn]),Sr=g({role:i,content:Ct}),Vt=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),wn=R.extend({method:w("notifications/tools/list_changed"),params:S.optional()}),Rn=g({name:l().optional()}),bn=g({hints:C(Rn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),vn=g({mode:F(["auto","required","none"]).optional()}),Cn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),In=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),Tn=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),En=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),kn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),An=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),Pn=q([En,kn]),xn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),On=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),Mn=q([xn,On]),Un=q([An,Pn,Mn]),qn=q([Un,Cn,In,Tn]),Gt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:M(l(),qn),required:C(l()).optional()}).catchall(D())}),Kt=g({type:w("ref/resource"),uri:l()}),Wt=g({type:w("ref/prompt"),name:l()}),zn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:M(l(),D()).optional()}),It=Z.shape,Nn=g({experimental:It.experimental,sampling:It.sampling,elicitation:It.elicitation,roots:It.roots,extensions:It.extensions}),Fe=re.shape,_r=g({experimental:Fe.experimental,logging:Fe.logging,completions:Fe.completions,prompts:Fe.prompts,resources:Fe.resources,tools:Fe.tools,extensions:Fe.extensions}),wr=$({progressToken:r.optional(),[Pr]:l(),[mo]:I.optional(),[Or]:Nn,[ho]:a.optional()}),Zt=g({...b.shape,...y.shape,description:l().optional(),inputSchema:$({$schema:l().optional(),type:w("object")}),outputSchema:$({$schema:l().optional()}).optional(),annotations:Vt.optional(),_meta:M(l(),D()).optional()}),jn=g({type:w("tool_result"),toolUseId:l(),content:C(Ct),structuredContent:D().optional(),isError:N().optional(),_meta:M(l(),D()).optional()}),Rr=q([nt,Xe,Jt,yn,jn]),Yt=g({role:i,content:q([Rr,C(Rr)]),_meta:M(l(),D()).optional()}),br=l(),vr=$({[xr]:I.optional().catch(void 0)}),Cr=vr.optional();function be(se){return $({_meta:Cr,resultType:br.default("complete"),...se})}o(be,"wireResult");let Dn=be({}),os=be({nextCursor:n.optional()}),Ir=be({content:C(Ct),structuredContent:D().optional(),isError:N().optional()}),Ln=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Zt),nextCursor:n.optional()}),$n=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Ft),nextCursor:n.optional()}),Hn=be({description:l().optional(),messages:C(Sr)}),Bn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(de),nextCursor:n.optional()}),Fn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),Jn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),Vn=be({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),ss=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"])}),Gn=be({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:_r,instructions:l().optional()}),Tt=g({messages:C(Yt),modelPreferences:bn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Zt).optional(),toolChoice:vn.optional()}),Kn=g({method:w("sampling/createMessage"),params:Tt}),Wn=g({method:w("roots/list"),params:g({_meta:M(l(),D()).optional()}).optional()}),Zn=g({...Yt.shape,model:l(),stopReason:l().optional()}),Yn=g({roots:C(zn)}),Xn=g({action:F(["accept","decline","cancel"]),content:M(l(),q([l(),E(),N(),C(l())])).optional()}),Qn=g({mode:w("url"),message:l(),url:l().url()}),eo=q([Gt,Qn]),to=g({method:w("elicitation/create"),params:eo}),ro=q([Kn,Wn,to]),no=q([Zn,Yn,Xn]),oo=M(l(),ro),so=M(l(),no),Xt=be({inputRequests:oo.optional(),requestState:l().optional()}),Qt={inputResponses:so.optional(),requestState:l().optional()},is=g({_meta:wr,...Qt}),as=$({progressToken:r.optional()});function qe(se,tr){return g({method:w(se),params:g({_meta:wr,...tr})})}o(qe,"wireRequest");function ze(se,tr){return g({method:w(se),params:g({_meta:as.optional(),...tr}).optional()})}o(ze,"dispatchRequest");let io={name:l(),arguments:M(l(),D()).optional(),...Qt},Qe={cursor:n.optional()},cs=qe("tools/call",io),ds=qe("tools/list",Qe),us=qe("prompts/list",Qe),ls=qe("prompts/get",{name:l(),arguments:M(l(),l()).optional(),...Qt}),ps=qe("resources/list",Qe),ms=qe("resources/templates/list",Qe),hs=qe("resources/read",{uri:l(),...Qt}),ao={ref:q([Wt,Kt]),argument:g({name:l(),value:l()}),context:g({arguments:M(l(),l()).optional()}).optional()},fs=qe("completion/complete",ao),gs=qe("server/discover",{}),Tr=g({toolsListChanged:N().optional(),promptsListChanged:N().optional(),resourcesListChanged:N().optional(),resourceSubscriptions:C(l()).optional()}),co={notifications:Tr},ys=qe("subscriptions/listen",co),Ss=vr.extend({"io.modelcontextprotocol/subscriptionId":s}),uo=$({_meta:Ss,resultType:br.default("complete")}),Et={"tools/call":ze("tools/call",io),"tools/list":ze("tools/list",Qe),"prompts/get":ze("prompts/get",{name:l(),arguments:M(l(),l()).optional()}),"prompts/list":ze("prompts/list",Qe),"resources/list":ze("resources/list",Qe),"resources/templates/list":ze("resources/templates/list",Qe),"resources/read":ze("resources/read",{uri:l()}),"completion/complete":ze("completion/complete",ao),"server/discover":ze("server/discover",{}),"subscriptions/listen":ze("subscriptions/listen",co)};function Oe(se){return $({_meta:Cr,...se})}o(Oe,"liftedResult");let _s={"tools/call":Oe({content:C(Ct),structuredContent:D().optional(),isError:N().optional()}),"tools/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Zt),nextCursor:n.optional()}),"prompts/get":Oe({description:l().optional(),messages:C(Sr)}),"prompts/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Ft),nextCursor:n.optional()}),"resources/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(de),nextCursor:n.optional()}),"resources/templates/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),"resources/read":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),"completion/complete":Oe({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),"server/discover":Oe({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:_r,instructions:l().optional()}),"subscriptions/listen":Oe({})},er=$({"io.modelcontextprotocol/subscriptionId":s.optional()}),Er=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:er.optional(),notifications:Tr})}),kr=g({_meta:er.optional(),requestId:s,reason:l().optional()}),Ar=g({method:w("notifications/cancelled"),params:kr}),Fi={"notifications/cancelled":Ar,"notifications/progress":j,"notifications/message":Q,"notifications/resources/updated":fr,"notifications/resources/list_changed":ne,"notifications/tools/list_changed":wn,"notifications/prompts/list_changed":yr,"notifications/subscriptions/acknowledged":Er},Ie=o(se=>g({jsonrpc:w("2.0"),id:q([l(),E().int()]),result:se}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:R,IconSchema:_,IconsSchema:y,BaseMetadataSchema:b,ImplementationSchema:I,ClientTasksCapabilitySchema:Y,ServerTasksCapabilitySchema:x,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:re,ProgressSchema:P,ProgressNotificationParamsSchema:B,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:X,LoggingMessageNotificationSchema:Q,ResourceContentsSchema:He,TextResourceContentsSchema:Ue,BlobResourceContentsSchema:Be,AnnotationsSchema:K,ResourceSchema:de,ResourceTemplateSchema:xe,ResourceListChangedNotificationSchema:ne,ResourceUpdatedNotificationParamsSchema:Ye,ResourceUpdatedNotificationSchema:fr,PromptArgumentSchema:gr,PromptSchema:Ft,PromptListChangedNotificationSchema:yr,TextContentSchema:nt,ImageContentSchema:Xe,AudioContentSchema:Jt,ToolUseContentSchema:yn,EmbeddedResourceSchema:Sn,ResourceLinkSchema:_n,ContentBlockSchema:Ct,PromptMessageSchema:Sr,ToolAnnotationsSchema:Vt,ToolListChangedNotificationSchema:wn,ModelHintSchema:Rn,ModelPreferencesSchema:bn,ToolChoiceSchema:vn,BooleanSchemaSchema:Cn,StringSchemaSchema:In,NumberSchemaSchema:Tn,UntitledSingleSelectEnumSchemaSchema:En,TitledSingleSelectEnumSchemaSchema:kn,LegacyTitledEnumSchemaSchema:An,SingleSelectEnumSchemaSchema:Pn,UntitledMultiSelectEnumSchemaSchema:xn,TitledMultiSelectEnumSchemaSchema:On,MultiSelectEnumSchemaSchema:Mn,EnumSchemaSchema:Un,PrimitiveSchemaDefinitionSchema:qn,ElicitRequestFormParamsSchema:Gt,ResourceTemplateReferenceSchema:Kt,PromptReferenceSchema:Wt,RootSchema:zn,ClientCapabilities2026Schema:Nn,ServerCapabilities2026Schema:_r,RequestMetaEnvelopeSchema:wr,ToolSchema:Zt,ToolResultContentSchema:jn,SamplingMessageContentBlockSchema:Rr,SamplingMessageSchema:Yt,ResultTypeSchema:br,ResultMetaSchema:vr,ResultSchema:Dn,PaginatedResultSchema:os,CallToolResultSchema:Ir,ListToolsResultSchema:Ln,ListPromptsResultSchema:$n,GetPromptResultSchema:Hn,ListResourcesResultSchema:Bn,ListResourceTemplatesResultSchema:Fn,ReadResourceResultSchema:Jn,CompleteResultSchema:Vn,CacheableResultSchema:ss,DiscoverResultSchema:Gn,CreateMessageRequestParamsSchema:Tt,CreateMessageRequestSchema:Kn,ListRootsRequestSchema:Wn,CreateMessageResultSchema:Zn,ListRootsResultSchema:Yn,ElicitResultSchema:Xn,ElicitRequestURLParamsSchema:Qn,ElicitRequestParamsSchema:eo,ElicitRequestSchema:to,InputRequestSchema:ro,InputResponseSchema:no,InputRequestsSchema:oo,InputResponsesSchema:so,InputRequiredResultSchema:Xt,InputResponseRequestParamsSchema:is,CallToolRequestSchema:cs,ListToolsRequestSchema:ds,ListPromptsRequestSchema:us,GetPromptRequestSchema:ls,ListResourcesRequestSchema:ps,ListResourceTemplatesRequestSchema:ms,ReadResourceRequestSchema:hs,CompleteRequestSchema:fs,DiscoverRequestSchema:gs,SubscriptionFilterSchema:Tr,SubscriptionsListenRequestSchema:ys,SubscriptionsListenResultMetaSchema:Ss,SubscriptionsListenResultSchema:uo,dispatchRequestSchemas:Et,dispatchResultSchemas:_s,NotificationMetaSchema:er,SubscriptionsAcknowledgedNotificationSchema:Er,CancelledNotificationParamsSchema:kr,CancelledNotificationSchema:Ar,notificationSchemas2026:Fi,JSONRPCResultResponseSchema:Ie(Dn),CallToolResultResponseSchema:Ie(q([Ir,Xt])),ListToolsResultResponseSchema:Ie(Ln),ListPromptsResultResponseSchema:Ie($n),GetPromptResultResponseSchema:Ie(q([Hn,Xt])),ListResourcesResultResponseSchema:Ie(Bn),ListResourceTemplatesResultResponseSchema:Ie(Fn),ReadResourceResultResponseSchema:Ie(q([Jn,Xt])),CompleteResultResponseSchema:Ie(Vn),DiscoverResultResponseSchema:Ie(Gn),SubscriptionsListenResultResponseSchema:Ie(uo)}}o(xR,"build");var OR;function ft(){return OR??=xR()}o(ft,"buildSchemas2026");var MR=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function UR(e){return MR.includes(e)}o(UR,"isCacheableResultMethod");var Oa=Symbol("modelcontextprotocol.resultCacheHintFallback");function qR(e){return e[Oa]}o(qR,"cacheHintFallbackOf");function Eh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(Eh,"isValidCacheTtlMs");function kh(e){return e==="public"||e==="private"}o(kh,"isValidCacheScope");var A=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),_e=class Ah extends Error{static{o(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",cr(this,new.target)}static fromError(t,r,n){if(t===A.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ri(s.elicitations,r)}if(t===A.UnsupportedProtocolVersion&&n){let s=n;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new xh({supported:s.supported,requested:s.requested},r)}if(t===A.InvalidParams||t===A.ResourceNotFound){let s=n;if(typeof s?.uri=="string"&&(t===A.ResourceNotFound||Object.keys(s).length===1))return new Ph(s.uri,r)}if(t===A.MissingRequiredClientCapability&&n){let s=n;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new Oh({requiredCapabilities:s.requiredCapabilities},r)}return new Ah(t,r,n)}},Ph=class extends _e{static{o(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(A.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ri=class extends _e{static{o(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},xh=class extends _e{static{o(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(A.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Oh=class extends _e{static{o(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(A.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},zR=0,NR="private",jR=["tools/call","prompts/get","resources/read"];function DR(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||jR.includes(e))return t;throw new _e(A.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}o(DR,"stampResultType");function LR(e,t){let r=qR(t);if(t.resultType!=="complete"||!UR(e))return r===void 0?t:JR(t);let n=t,s=Eh(n.ttlMs)?n.ttlMs:BR(r),i=kh(n.cacheScope)?n.cacheScope:FR(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Oa],a}o(LR,"fillCacheFields");function $R(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o($R,"isPlainObject$4");function HR(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[xr]:t}}:!$R(r)||r[xr]!==void 0?e:{...e,_meta:{...r,[xr]:t}}}o(HR,"stampServerInfoMeta");function BR(e){return e!==void 0&&Eh(e.ttlMs)?e.ttlMs:zR}o(BR,"resolveTtlMs");function FR(e){return e!==void 0&&kh(e.cacheScope)?e.cacheScope:NR}o(FR,"resolveCacheScope");function JR(e){let t={...e};return delete t[Oa],t}o(JR,"stripCacheHintFallback");var VR=["elicitation/create","sampling/createMessage","roots/list"],Xs;function Ma(){if(Xs)return Xs;let e=ft();return Xs={request:{"elicitation/create":g({method:w("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:w("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:w("roots/list"),params:$({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Xs}o(Ma,"inputSchemaMaps");function GR(){Ma()}o(GR,"warmInputSchemaMaps2026");function Mh(e){return VR.includes(e)}o(Mh,"isInputRequestMethod2026");function Sa(e){return Mh(e)?Ma().request[e]:void 0}o(Sa,"getInputRequestSchema2026");function KR(e){return Mh(e)?Ma().response[e]:void 0}o(KR,"getInputResponseSchema2026");var Ua={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Uh={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function qh(e){return Object.prototype.hasOwnProperty.call(Ua,e)}o(qh,"hasRequestMethod2026");function zh(e){return Object.prototype.hasOwnProperty.call(Uh,e)}o(zh,"hasNotificationMethod2026");function WR(e){return Object.prototype.hasOwnProperty.call(Ua,e)}o(WR,"hasResultMethod2026");function ZR(e){return qh(e)?ft().dispatchRequestSchemas[e]:void 0}o(ZR,"getRequestSchema2026");function YR(e){return WR(e)?ft().dispatchResultSchemas[e]:void 0}o(YR,"getResultSchema2026");function XR(e){return zh(e)?ft().notificationSchemas2026[e]:void 0}o(XR,"getNotificationSchema2026");var WM=Object.keys(Ua),ZM=Object.keys(Uh);function Eo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Eo,"isPlainObject$3");function Io(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Io,"triState");var QR={ok:!1,reason:"not-in-era"},eb=[Pr,Or];function tb(e,t){let r=t,n=!1,s=o(()=>(n||(r={...r},n=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>Eo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!Eo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(Eo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}o(tb,"enforceDeletedFields");var qa={era:"2026-07-28",hasRequestMethod:qh,hasNotificationMethod:zh,hasInputRequestMethod:o(e=>Sa(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>Io(ZR(e),t),"validateRequest"),validateResult:o((e,t)=>Io(YR(e),t),"validateResult"),validateNotification:o((e,t)=>Io(XR(e),t),"validateNotification"),validateInputRequest:o((e,t)=>Io(Sa(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>Io(KR(e),t),"validateInputResponse"),samplingResultVariant:o(()=>QR,"samplingResultVariant"),outboundEnvelope(e){return{[Pr]:e.protocolVersion,[mo]:e.clientInfo,[Or]:e.clientCapabilities,...e.logLevel!==void 0&&{[ho]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of eb)n in e||t.push({key:n,problem:"missing"});let r=ft().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let s=n.path.map(String),i=s.length>0?s.join("."):"_meta";s.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:o(e=>wh(e),"projectCallToolResult"),inputRequestSchema:Sa,decodeResult(e,t){if(!Eo(t))return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Eo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:ft().ResultMetaSchema.safeParse(t._meta),m=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new le(Se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=Nh(),s=Object.hasOwn(n,e)?n[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return HR(LR(e,DR(e,tb(e,t))),r)},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=ft().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Qs;function Nh(){if(Qs)return Qs;let e=ft();return Qs={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Qs}o(Nh,"getWireResultSchemas");function rb(){Nh()}o(rb,"warmWireResultSchemas2026");var za="2026-07-28";function Ao(e){return e!==void 0&&_h(e)?qa:xa}o(Ao,"codecForVersion");function uh(e){return e.revision!==void 0?Ao(e.revision).era:e.era==="modern"?qa.era:xa.era}o(uh,"classifiedWireEra");function _a(e){return jh.some(t=>t.hasRequestMethod(e))}o(_a,"isSpecRequestMethod");function wa(e){return jh.some(t=>t.hasNotificationMethod(e))}o(wa,"isSpecNotificationMethod");function lh(e){return e==="tasks/get"||e==="tasks/cancel"}o(lh,"isExtensionReusedRequestMethod");var jh=[xa,qa],nb=oh({AnnotationsSchema:o(()=>Xu,"AnnotationsSchema"),AudioContentSchema:o(()=>xl,"AudioContentSchema"),BaseMetadataSchema:o(()=>Pu,"BaseMetadataSchema"),BaseRequestParamsSchema:o(()=>gu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:o(()=>Zu,"BlobResourceContentsSchema"),BooleanSchemaSchema:o(()=>ta,"BooleanSchemaSchema"),CallToolRequestParamsSchema:o(()=>Vl,"CallToolRequestParamsSchema"),CallToolRequestSchema:o(()=>Gl,"CallToolRequestSchema"),CallToolResultSchema:o(()=>Fl,"CallToolResultSchema"),CancelTaskRequestSchema:o(()=>Lp,"CancelTaskRequestSchema"),CancelTaskResultSchema:o(()=>$p,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:o(()=>Tu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:o(()=>Eu,"CancelledNotificationSchema"),ClientCapabilitiesSchema:o(()=>Uu,"ClientCapabilitiesSchema"),ClientNotificationSchema:o(()=>Bp,"ClientNotificationSchema"),ClientRequestSchema:o(()=>Hp,"ClientRequestSchema"),ClientResultSchema:o(()=>Fp,"ClientResultSchema"),ClientTasksCapabilitySchema:o(()=>Ou,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:o(()=>Jl,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:o(()=>Rp,"CompleteRequestParamsSchema"),CompleteRequestSchema:o(()=>bp,"CompleteRequestSchema"),CompleteResultSchema:o(()=>vp,"CompleteResultSchema"),ContentBlockSchema:o(()=>ql,"ContentBlockSchema"),CreateMessageRequestParamsSchema:o(()=>ap,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:o(()=>cp,"CreateMessageRequestSchema"),CreateMessageResultSchema:o(()=>dp,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:o(()=>up,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:o(()=>xp,"CreateTaskResultSchema"),CursorSchema:o(()=>pu,"CursorSchema"),DiscoverRequestSchema:o(()=>Lu,"DiscoverRequestSchema"),DiscoverResultSchema:o(()=>Qi,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:o(()=>ks,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:o(()=>hp,"ElicitRequestParamsSchema"),ElicitRequestSchema:o(()=>fp,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:o(()=>As,"ElicitRequestURLParamsSchema"),ElicitResultSchema:o(()=>Sp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:o(()=>gp,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:o(()=>yp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:o(()=>Ml,"EmbeddedResourceSchema"),EmptyResultSchema:o(()=>Iu,"EmptyResultSchema"),EnumSchemaSchema:o(()=>mp,"EnumSchemaSchema"),GetPromptRequestParamsSchema:o(()=>El,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:o(()=>kl,"GetPromptRequestSchema"),GetPromptResultSchema:o(()=>Nl,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:o(()=>zp,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:o(()=>Np,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:o(()=>Up,"GetTaskRequestSchema"),GetTaskResultSchema:o(()=>qp,"GetTaskResultSchema"),IconSchema:o(()=>ku,"IconSchema"),IconsSchema:o(()=>Au,"IconsSchema"),ImageContentSchema:o(()=>Pl,"ImageContentSchema"),ImplementationSchema:o(()=>xu,"ImplementationSchema"),InitializeRequestParamsSchema:o(()=>qu,"InitializeRequestParamsSchema"),InitializeRequestSchema:o(()=>zu,"InitializeRequestSchema"),InitializeResultSchema:o(()=>ju,"InitializeResultSchema"),InitializedNotificationSchema:o(()=>Du,"InitializedNotificationSchema"),JSONArraySchema:o(()=>uu,"JSONArraySchema"),JSONObjectSchema:o(()=>du,"JSONObjectSchema"),JSONRPCErrorResponseSchema:o(()=>fo,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:o(()=>Xi,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:o(()=>Zi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:o(()=>nr,"JSONRPCRequestSchema"),JSONRPCResponseSchema:o(()=>Cu,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:o(()=>Yi,"JSONRPCResultResponseSchema"),JSONValueSchema:o(()=>cu,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:o(()=>oa,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:o(()=>ea,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:o(()=>Il,"ListPromptsRequestSchema"),ListPromptsResultSchema:o(()=>Tl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:o(()=>nl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:o(()=>ol,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:o(()=>tl,"ListResourcesRequestSchema"),ListResourcesResultSchema:o(()=>rl,"ListResourcesResultSchema"),ListRootsRequestSchema:o(()=>Ip,"ListRootsRequestSchema"),ListRootsResultSchema:o(()=>Tp,"ListRootsResultSchema"),ListTasksRequestSchema:o(()=>jp,"ListTasksRequestSchema"),ListTasksResultSchema:o(()=>Dp,"ListTasksResultSchema"),ListToolsRequestSchema:o(()=>Hl,"ListToolsRequestSchema"),ListToolsResultSchema:o(()=>Bl,"ListToolsResultSchema"),LoggingLevelSchema:o(()=>Wl,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:o(()=>Xl,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:o(()=>Ql,"LoggingMessageNotificationSchema"),ModelHintSchema:o(()=>ep,"ModelHintSchema"),ModelPreferencesSchema:o(()=>tp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:o(()=>pp,"MultiSelectEnumSchemaSchema"),NotificationSchema:o(()=>wu,"NotificationSchema"),NotificationsParamsSchema:o(()=>_u,"NotificationsParamsSchema"),NumberSchemaSchema:o(()=>Es,"NumberSchemaSchema"),PaginatedRequestParamsSchema:o(()=>Ju,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:o(()=>Vu,"PaginatedRequestSchema"),PaginatedResultSchema:o(()=>Gu,"PaginatedResultSchema"),PingRequestSchema:o(()=>$u,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:o(()=>aa,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:o(()=>Bu,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:o(()=>Fu,"ProgressNotificationSchema"),ProgressSchema:o(()=>Hu,"ProgressSchema"),ProgressTokenSchema:o(()=>lu,"ProgressTokenSchema"),PromptArgumentSchema:o(()=>vl,"PromptArgumentSchema"),PromptListChangedNotificationSchema:o(()=>jl,"PromptListChangedNotificationSchema"),PromptMessageSchema:o(()=>zl,"PromptMessageSchema"),PromptReferenceSchema:o(()=>wp,"PromptReferenceSchema"),PromptSchema:o(()=>Cl,"PromptSchema"),ReadResourceRequestParamsSchema:o(()=>il,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:o(()=>al,"ReadResourceRequestSchema"),ReadResourceResultSchema:o(()=>cl,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:o(()=>hu,"RelatedTaskMetadataSchema"),RequestIdSchema:o(()=>vu,"RequestIdSchema"),RequestMetaSchema:o(()=>fu,"RequestMetaSchema"),RequestSchema:o(()=>Su,"RequestSchema"),ResourceContentsSchema:o(()=>Ku,"ResourceContentsSchema"),ResourceLinkSchema:o(()=>Ul,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:o(()=>dl,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:o(()=>sl,"ResourceRequestParamsSchema"),ResourceSchema:o(()=>Qu,"ResourceSchema"),ResourceTemplateReferenceSchema:o(()=>_p,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:o(()=>el,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:o(()=>Rl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:o(()=>bl,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:o(()=>Ru,"ResultMetaObjectSchema"),ResultSchema:o(()=>bu,"ResultSchema"),RoleSchema:o(()=>Yu,"RoleSchema"),RootSchema:o(()=>Cp,"RootSchema"),RootsListChangedNotificationSchema:o(()=>Ep,"RootsListChangedNotificationSchema"),SamplingContentSchema:o(()=>op,"SamplingContentSchema"),SamplingMessageContentBlockSchema:o(()=>sp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:o(()=>ip,"SamplingMessageSchema"),ServerCapabilitiesSchema:o(()=>Nu,"ServerCapabilitiesSchema"),ServerNotificationSchema:o(()=>Vp,"ServerNotificationSchema"),ServerRequestSchema:o(()=>Jp,"ServerRequestSchema"),ServerResultSchema:o(()=>Gp,"ServerResultSchema"),ServerTasksCapabilitySchema:o(()=>Mu,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:o(()=>Zl,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:o(()=>Yl,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:o(()=>lp,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:o(()=>Ts,"StringSchemaSchema"),SubscribeRequestParamsSchema:o(()=>ul,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:o(()=>ll,"SubscribeRequestSchema"),SubscriptionFilterSchema:o(()=>hl,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:o(()=>yl,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:o(()=>Sl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:o(()=>fl,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:o(()=>gl,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:o(()=>_l,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:o(()=>wl,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:o(()=>yu,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:o(()=>kp,"TaskCreationParamsSchema"),TaskMetadataSchema:o(()=>mu,"TaskMetadataSchema"),TaskSchema:o(()=>Pp,"TaskSchema"),TaskStatusNotificationParamsSchema:o(()=>Op,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:o(()=>Mp,"TaskStatusNotificationSchema"),TaskStatusSchema:o(()=>Ap,"TaskStatusSchema"),TextContentSchema:o(()=>Al,"TextContentSchema"),TextResourceContentsSchema:o(()=>Wu,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:o(()=>ia,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:o(()=>na,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:o(()=>Dl,"ToolAnnotationsSchema"),ToolChoiceSchema:o(()=>rp,"ToolChoiceSchema"),ToolExecutionSchema:o(()=>Ll,"ToolExecutionSchema"),ToolListChangedNotificationSchema:o(()=>Kl,"ToolListChangedNotificationSchema"),ToolResultContentSchema:o(()=>np,"ToolResultContentSchema"),ToolSchema:o(()=>$l,"ToolSchema"),ToolUseContentSchema:o(()=>Ol,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:o(()=>pl,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:o(()=>ml,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:o(()=>sa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:o(()=>ra,"UntitledSingleSelectEnumSchemaSchema")});var Dh=o(e=>nr.safeParse(e).success,"isJSONRPCRequest"),Lh=o(e=>Zi.safeParse(e).success,"isJSONRPCNotification"),Ia=o(e=>Yi.safeParse(e).success,"isJSONRPCResultResponse"),$h=o(e=>fo.safeParse(e).success,"isJSONRPCErrorResponse");var ko=-32020,YM=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[A.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[ko,A.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[A.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[A.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[A.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[ko],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[A.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[ko],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],XM={[A.ParseError]:400,[A.InvalidRequest]:400,[A.MethodNotFound]:404,[A.UnsupportedProtocolVersion]:400,[A.MissingRequiredClientCapability]:400,[ko]:400};function Na(e,t){return eu(e,t)}o(Na,"parseSchema");function To(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}o(To,"shapeKeys");function Ta(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}o(Ta,"isStandardSchema");var ph=!1,Ea="draft-2020-12";function ob(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Ea});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");ph||(ph=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=Ji(e,{target:Ea,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Hh(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}o(ob,"standardSchemaToJsonSchema");function Hh(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Hh(n)))}return!1}o(Hh,"isProvablyObjectShapedRoot");function sb(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(sb,"formatIssue");async function Ra(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>sb(n)).join(", ")}:{success:!0,data:r.value}}o(Ra,"validateStandardSchema");function ib(e){let t=Ji(e,{target:Ea,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(ib,"zodEmittedPattern");var ab=/\\\.\\d\{(\d+)\}/;function cb(e){let t=ab.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(s=>r.map(i=>po.datetime({local:n,offset:s,precision:i}))))}o(cb,"datetimeReferenceSchemas");function db(e,t){let r;switch(e){case"email":r=[tu()];break;case"uri":r=[ru()];break;case"date":r=[po.date()];break;case"date-time":r=cb(t);break}return new Set(r.map(n=>ib(n)).filter(n=>n!==void 0))}o(db,"referencePatternsForFormat");function ub(e,t,r){return r!=="zod"?!0:db(e,t).has(t)}o(ub,"isLibraryFormatPattern");function Po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Po,"isJsonObject");function lb(e){try{return ob(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new _e(A.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}o(lb,"convertStandardElicitationSchema");var pb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function ja(e){return pb.has(e)||e.startsWith("x-")}o(ja,"isAnnotationOnlyJsonSchemaKeyword");var mb=new Set(["$schema",...Object.keys(ks.shape.requestedSchema.shape)]),mh={string:To([Ts,ra,na,oa]),number:To([Es]),integer:To([Es]),boolean:To([ta]),array:To([sa,ia])},hb=new Set(Ts.shape.format.unwrap().options);function fb(e,t,r,n){if(!Po(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(mh,e.type)?mh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||ja(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?hb.has(e.format)?(typeof c!="string"||!ub(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(fb,"walkProperty");function gb(e,t){let r={},n=[];for(let[s,i]of Object.entries(e))s==="properties"&&Po(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,fb(c,`properties.${a}`,t,n)])):mb.has(s)?r[s]=i:ja(s)||n.push(s);if(n.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}o(gb,"walkRequestedSchema");function yb(e,t){if(!Po(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!Na(aa,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}o(yb,"describeUnsupportedProperties");function ka(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,s)=>ka(n,t[s],`${r}[${s}]`)):!Po(e)||!Po(t)?[]:Object.entries(e).flatMap(([n,s])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?ka(s,t[n],i):ja(n)?[]:[i]})}o(ka,"findDroppedConstraintPaths");function Sb(e){if(!Ta(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=gb(lb(e.requestedSchema),t),n=Na(ks.shape.requestedSchema,r);if(!n.success)throw new _e(A.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${yb(r,n.error.message)}`);let s=ka(r,n.data);if(s.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}o(Sb,"normalizeElicitInputParams");function _b(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}o(_b,"buildInputRequired");var QM=Object.assign(_b,{elicit(e){try{return{method:"elicitation/create",params:Sb(e)}}catch(t){throw t instanceof _e?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var wb=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Rb={IdJagTokenExchangeResponseSchema:ca,OAuthClientInformationFullSchema:or,OAuthClientInformationSchema:go,OAuthClientMetadataSchema:Wp,OAuthClientRegistrationErrorSchema:Zp,OAuthErrorResponseSchema:Ps,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Mr,OAuthTokenRevocationRequestSchema:Yp,OAuthTokensSchema:At,OpenIdProviderDiscoveryMetadataSchema:qr,OpenIdProviderMetadataSchema:Kp},Bh={},Fh={};function Jh(e,t){let r=e.slice(0,-6);Bh[r]=t,Fh[r]=n=>t.safeParse(n).success}o(Jh,"register");for(let e of wb)Jh(e,nb[e]);for(let[e,t]of Object.entries(Rb))Jh(e,t);var bb=Object.freeze(Bh),vb=Object.freeze(Fh);function Cb(e){switch(e){case"initialize":case"notifications/initialized":return Ao(void 0);case"server/discover":return Ao(za);default:return}}o(Cb,"bootstrapOutboundCodec");var Vh=6e4,Ib=[Pr,mo,Or,ho],Tb=["inputResponses","requestState"];function hh(e,t){let r=e.params;if(!ba(r))return{message:e,lifted:{}};let n=r._meta,s=ba(n)?Ib.filter(d=>d in n):[],i=t==="request"?Tb.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&ba(n)){let d={},u={...n};for(let m of s)d[m]=n[m],delete u[m];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}o(hh,"liftWireOnlyMaterial");function fh(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let s=e.validateResult(t,n);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}o(fh,"codecResultValidator");function Gh(e){return()=>e}o(Gh,"requestStateAccessor");var Eb=Gh(void 0),kb,Ab=class{static{o(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{kb=o((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Wi,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(Se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Ia(s)||$h(s)?this._onresponse(s):Dh(s)?this._onrequest(s,i):Lh(s)?this._onnotification(s,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(Se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=hh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=uh(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(wa(r.method)&&!n.hasNotificationMethod(r.method))return;let s=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;s===void 0&&i===void 0||Promise.resolve().then(()=>s===void 0?i(r):s(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=hh(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=o((_,y,b)=>{let I={jsonrpc:"2.0",id:r.id,error:{code:_,message:y,...b!==void 0&&{data:b}}};i?.send(I).catch(U=>this._onerror(new Error(`Failed to send an error response: ${U}`)))},"sendErrorResponse");if(t?.classification!==void 0){let _=uh(t.classification);if(_!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${_} but this instance serves ${s.era}`));let y=t.classification.revision??_;a(A.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(_a(r.method)&&!s.hasRequestMethod(r.method)&&!(lh(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(A.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(A.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(n);if(d!==void 0){a(A.InvalidParams,d);return}let u=o((_,y)=>this._notificationViaCodec(this._resolveOutboundCodec(_.method),_,{...y,relatedRequestId:r.id}),"sendNotification"),m=o((_,y,b)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(_.method),_,y,{...b,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:Pb(n.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:n.requestState===void 0?Eb:Gh(n.requestState),signal:h.signal,send:o(((_,y,b)=>{let I=this._resolveOutboundCodec(_.method);if(this._assertOutboundRequestInEra(I,_.method),Ta(y))return m(_,y,b);let U=fh(I,_.method);if(U===void 0)throw new TypeError(`'${_.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(_,U,y)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},R=this.buildContext(S,t);Promise.resolve().then(()=>c(r,R)).then(async _=>{if(h.signal.aborted)return;let y;try{y=s.encodeResult(r.method,_,this._outboundServerInfo())}catch(I){this._onerror(new Error(`Failed to encode result for ${r.method}: ${I}`)),a(A.InternalError,"Internal error");return}let b={result:y,jsonrpc:"2.0",id:r.id};await i?.send(b)},async _=>{if(h.signal.aborted)return;let y=Number.isSafeInteger(_.code)?_.code:A.InternalError,b={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(y),message:_.message??"Internal error",..._.data!==void 0&&{data:_.data}}};await i?.send(b)}).catch(_=>this._onerror(new Error(`Failed to send response: ${_}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Ia(e)?r(e):r(_e.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(Ta(t))return lh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=fh(n,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,s,t)}_negotiatedWireCodec(){return Ao(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Cb(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(_a(t)&&!e.hasRequestMethod(t))throw new le(Se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},d=Date.now(),u,m;return new Promise((h,f)=>{let S=o(x=>{f(x)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(x){S(x);return}if(n?.signal?.aborted){let x=n.signal.reason;throw x instanceof le?x:new le(Se.RequestTimeout,String(x))}let R=e.era===za&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;m=_;let y={...t,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:_}});let b=this._envelopeOutbound(y),I=!1,U=o(x=>{I||(this._progressHandlers.delete(_),R===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(x)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`))):R.abort(),f(x instanceof le?x:new le(Se.RequestTimeout,String(x))))},"cancel");this._responseHandlers.set(_,x=>{if(n?.signal?.aborted)return;if(I=!0,x instanceof Error)return f(x);let Z;try{Z=e.decodeResult(t.method,x.result)}catch(P){return f(P instanceof Error?P:new Error(String(P)))}if(Z.kind==="invalid")return f(Z.error);if(Z.kind==="input_required"){if(n?.allowInputRequired===!0)return h(xb(Z));let P={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:d,retry:o((B,j)=>this._requestWithSchemaViaCodec(e,B===void 0?{method:t.method}:{method:t.method,params:B},r,j),"retry")};return h(this._resolveNonCompleteResult(Z,P))}let re=Z.result;Ra(r,re).then(P=>{P.success?h(P.data):f(new le(Se.InvalidResult,`Invalid result for ${t.method}: ${P.error}`))},f)}),u=o(()=>U(n?.signal?.reason),"onAbort"),n?.signal?.addEventListener("abort",u,{once:!0});let v=n?.timeout??Vh,Y=o(()=>U(new le(Se.RequestTimeout,"Request timed out",{timeout:v})),"timeoutHandler");this._setupTimeout(_,v,n?.maxTotalTimeout,Y,n?.resetTimeoutOnProgress??!1),this._transport.send(b,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:R?.signal}).catch(x=>{this._progressHandlers.delete(_),f(x)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(Se.NotConnected,"Not connected");if(wa(t.method)&&!e.hasNotificationMethod(t.method))throw new le(Se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(s=>this._onerror(s))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!_a(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=o((s,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,s);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,s)),!c.ok)throw c.reason==="not-in-era"?new _e(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)n=o(async(s,i)=>{let a=await Ra(t.params,{...s.params});if(!a.success)throw new _e(A.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!wa(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,s)=>{let i=s.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new _e(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let s=await Ra(t.params,{...n.params});if(!s.success)throw new _e(A.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ba(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(ba,"isPlainObject$1");function gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(gh,"isPlainObject");function Pb(e){let t={},r=[];if(!gh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!gh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(Pb,"partitionInputResponses");function xb(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(xb,"manualInputRequiredValue");var Ob=nh((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(c){if(!c)throw new TypeError("argument string is required");var d=typeof c=="object"?i(c):c;if(typeof d!="string")throw new TypeError("argument string is required to be a string");var u=d.indexOf(";"),m=u!==-1?d.slice(0,u).trim():d.trim();if(!n.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(u!==-1){var f,S,R;for(t.lastIndex=u;S=t.exec(d);){if(S.index!==u)throw new TypeError("invalid parameter format");u+=S[0].length,f=S[1].toLowerCase(),R=S[2],R.charCodeAt(0)===34&&(R=R.slice(1,-1),R.indexOf("\\")!==-1&&(R=R.replace(r,"$1"))),h.parameters[f]=R}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}o(s,"parse");function i(c){var d;if(typeof c.getHeader=="function"?d=c.getHeader("content-type"):typeof c.headers=="object"&&(d=c.headers&&c.headers["content-type"]),typeof d!="string")throw new TypeError("content-type header is missing from object");return d}o(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}o(a,"ContentType")})),e0=sh(Ob(),1);var Mb=10*1024*1024;var Ub=new Set([301,302,303,307,308]),qb=5;function zb(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}o(zb,"isWithinOrigin");function Nb(e,t){let r=Ub.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Nb,"redirectTarget");var jb=new WeakSet;function ni(e){return jb.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let n=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Nb(s,a);if(!c||i===qb)return a;let d=new URL(s),u=n==="GET"||a.status===307||a.status===308,m=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!m||!zb(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(ni,"fetchWithinOrigin");function Da(){Pa(),ft(),TR(),GR(),rb()}o(Da,"preloadSchemas");var p0=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var Db=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Lb=[0,31,28,31,30,31,30,31,31,30,31,30,31],$b=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Hb=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Bb=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Fb=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Jb=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Vb=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Gb=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Kb=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Wb=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Zb=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),Yb=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xb=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Qb=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function st(e){return e.test.bind(e)}o(st,"bind");var m0={date:Kh,time:Wh.bind(void 0,!1),"date-time":rv,duration:Qb,uri:sv,"uri-reference":st(Bb),"uri-template":st(Fb),url:st(Jb),email:Zb,hostname:st(Hb),ipv4:st(Yb),ipv6:st(Xb),regex:av,uuid:st(Vb),"json-pointer":st(Gb),"json-pointer-uri-fragment":st(Kb),"relative-json-pointer":st(Wb)};function ev(e){return e%4===0&&(e%100!==0||e%400===0)}o(ev,"isLeapYear");function Kh(e){let t=e.match(Db);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&ev(r)?29:Lb[n])}o(Kh,"date");function Wh(e,t){let r=t.match($b);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!e||a)}o(Wh,"time");var tv=/t|\s/i;function rv(e){let t=e.split(tv);return t.length==2&&Kh(t[0])&&Wh(!0,t[1])}o(rv,"date_time");var nv=/\/|:/,ov=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function sv(e){return nv.test(e)&&ov.test(e)}o(sv,"uri");var iv=/[^\\]\\Z/;function av(e){if(iv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(av,"regex");Da();var Zh=!1;var La;La=globalThis.crypto;async function dv(e){return(await La).getRandomValues(new Uint8Array(e))}o(dv,"getRandomValues");async function uv(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await dv(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(uv,"random");async function lv(e){return await uv(e)}o(lv,"generateVerifier");async function pv(e){let t=await(await La).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(pv,"generateChallenge");async function $a(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await lv(e),r=await pv(t);return{code_verifier:t,code_challenge:r}}o($a,"pkceChallenge");var Oo=class extends Error{static{o(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e),this.name=new.target.name,cr(this,new.target)}},xo=class extends Oo{static{o(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},Va=class extends Oo{static{o(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},ii=class extends Oo{static{o(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},si=class extends Oo{static{o(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},rU=class extends Oo{static{o(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Ja(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):ef(e.issuer,t)?e:void 0}o(Ja,"discardIfIssuerMismatch");function ef(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(ef,"issuersMatch");var nU=class extends Error{static{o(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",cr(this,new.target)}};function tf(e){return e?.authorization_response_iss_parameter_supported===!0}o(tf,"isIssParameterSupported");function rf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new xo("authorization_response",t,void 0);return}if(e!==t)throw new xo("authorization_response",t,e)}}o(rf,"validateAuthorizationResponseIssuer");function mv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(mv,"isClientAuthMethod");var Ha="code",Ba="S256";function hv(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&mv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(hv,"selectClientAuthMethod");function fv(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":gv(s,i,r);return;case"client_secret_post":yv(s,i,n);return;case"none":Sv(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(fv,"applyClientAuthentication");function gv(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(gv,"applyBasicAuth");function yv(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(yv,"applyPostAuth");function Sv(e,t){t.set("client_id",e)}o(Sv,"applyPublicAuth");function nf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(nf,"isLoopbackHost");function _v(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!nf(t.hostname))throw new ii(t.href);return t}o(_v,"assertSecureTokenEndpoint");function wv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||nf(r.hostname))return"native"}return"web"}o(wv,"deriveApplicationType");function Rv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??wv(t.redirect_uris)}}o(Rv,"resolveClientMetadata");async function Yh(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Ps.parse(JSON.parse(r));return Mt.fromResponse(n)}catch(n){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Mt(me.ServerError,s)}}o(Yh,"parseErrorResponse");function Xh(e,t,r){let n=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${n}. Cause: ${JSON.stringify(t.message)}`)}o(Xh,"warnCredentialInvalidation");async function Ga(e,t){try{return await Fa(e,t)}catch(r){if(r instanceof Mt){if(r.code===me.InvalidClient||r.code===me.UnauthorizedClient)return Xh(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Fa(e,t);if(r.code===me.InvalidGrant||r.code===me.InvalidDpopProof)return Xh(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Fa(e,t)}throw r}}o(Ga,"auth");function bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}o(bv,"determineScope");async function Fa(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=Rv(e),m=await e.discoveryState?.(),h,f,S,R,_=i;if(!_&&m?.resourceMetadataUrl&&(_=new URL(m.resourceMetadataUrl)),m?.authorizationServerUrl){if(f=m.authorizationServerUrl,h=m.resourceMetadata,S=m.authorizationServerMetadata??await cf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await sf(t,{resourceMetadataUrl:_},a)}catch(X){if(X instanceof TypeError)throw X}(S!==m.authorizationServerMetadata||h!==m.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S})}else{let X=await Av(t,{resourceMetadataUrl:_,fetchFn:a,skipIssuerMetadataValidation:c});f=X.authorizationServerUrl,S=X.authorizationServerMetadata,h=X.resourceMetadata,R={authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S}}let y=S?.issuer??String(f),b={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),r!==void 0){let X=m?.authorizationServerMetadata?.issuer??m?.authorizationServerUrl;if(X===void 0){if(e.saveDiscoveryState!==void 0)throw new si("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!ef(X,y))throw new si(X,y)}R&&await e.saveDiscoveryState?.(R);let I=await vv(t,e,h),U=I&&h&&!e.validateResourceURL?h.resource:I;U&&await e.saveResourceUrl?.(Wa(U));let v=bv({requestedScope:s,resourceMetadata:h,authServerMetadata:S,clientMetadata:e.clientMetadata}),Y=await Promise.resolve(e.clientInformation(b)),x=Ja(Y,y,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&Y?.issuer&&e.saveClientInformation===void 0)throw new si(Y.issuer,y);if(x&&x.issuer===void 0&&(x={...x,issuer:y},await e.saveClientInformation?.(x,b)),!x){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let X=S?.client_id_metadata_document_supported===!0,Q=e.clientMetadataUrl;if(Q&&!Ka(Q))throw new Mt(me.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Q}`);if(X&&Q)x={client_id:Q,issuer:y},await e.saveClientInformation?.(x,b);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");x={...await Uv(f,{metadata:S,clientMetadata:u,scope:v,fetchFn:a}),issuer:y},await e.saveClientInformation(x,b)}}let Z=!e.redirectUrl;if(r!==void 0||Z){r!==void 0&&rf({iss:n,expectedIssuer:S?.issuer,issParameterSupported:tf(S)});let X=await Mv(e,f,{metadata:S,resource:U,authorizationCode:r,iss:n,scope:v,fetchFn:a});return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let re=Ja(await e.tokens(b),y);if(re&&re.issuer===void 0&&(re={...re,issuer:y},await e.saveTokens(re,b)),re?.refresh_token&&!d){let X;try{X=await Ov(f,{metadata:S,clientInformation:x,refreshToken:re.refresh_token,resource:U,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(Q){if(Q instanceof ii)throw Q;if(!(Q instanceof Mt)||Q.code===me.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(Q instanceof Error?Q.message:String(Q))}`);else throw Q}if(X)return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let P=e.state?await e.state():void 0,{authorizationUrl:B,codeVerifier:j}=await Pv(f,{metadata:S,clientInformation:x,state:P,redirectUrl:e.redirectUrl,scope:v,resource:U});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(B),"REDIRECT"}o(Fa,"authInternal");function Ka(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Ka,"isHttpsUrl");async function vv(e,t,r){let n=Sh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ei({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(vv,"selectResourceURL");var Cv=new Set(["bearer","dpop"]);function of(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!Cv.has(r.toLowerCase())||!n)return{};let s=oi(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=oi(e,"scope")||void 0,c=oi(e,"error")||void 0,d=oi(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}o(of,"extractWWWAuthenticateParams");function oi(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(n);if(s){let i=s[1]||s[2];if(i)return i}return null}o(oi,"extractFieldFromWwwAuth");async function sf(e,t,r=fetch){let n=await Ev(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Mr.parse(await n.json())}o(sf,"discoverOAuthProtectedResourceMetadata");async function af(e,t,r=fetch){let n=ni(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Zh)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(af,"fetchWithCorsRetry");function Iv(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(Iv,"buildWellKnownPath");async function Qh(e,t,r=fetch){return await af(e,{"MCP-Protocol-Version":t},r)}o(Qh,"tryMetadataDiscovery");function Tv(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(Tv,"shouldAttemptFallback");async function Ev(e,t,r,n){let s=new URL(e),i=n?.protocolVersion??Is,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let d=Iv(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await Qh(a,i,r);return!n?.metadataUrl&&Tv(c,s.pathname)&&(c=await Qh(new URL(`/.well-known/${t}`,s),i,r)),c}o(Ev,"discoverMetadataWithFallback");function kv(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"},{url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(kv,"buildDiscoveryUrls");async function cf(e,{fetchFn:t=fetch,protocolVersion:r=Is,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=kv(e);for(let{url:a,type:c}of i){let d=await af(a,s,t);if(!d)continue;if(!d.ok){if(await d.text?.().catch(()=>{}),d.status<500||d.status===502)continue;throw new Error(`HTTP ${d.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=c==="oauth"?Ur.parse(await d.json()):qr.parse(await d.json());if(!n){let m=typeof e=="string"?e:e.href;if(!(u.issuer===m||m.endsWith("/")&&u.issuer===m.slice(0,-1)))throw new xo("metadata",m,u.issuer)}return u}}o(cf,"discoverAuthorizationServerMetadata");async function Av(e,t){let r,n;try{r=await sf(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let s=await cf(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(Av,"discoverOAuthServerInfo");function Wa(e){return typeof e=="string"?e:e.href}o(Wa,"resourceIndicatorToString");async function Pv(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ha))throw new Error(`Incompatible auth server: does not support response type ${Ha}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ba))throw new Error(`Incompatible auth server: does not support code challenge method ${Ba}`)}else c=new URL("/authorize",e);let d=await $a(),u=d.code_verifier,m=d.code_challenge;return c.searchParams.set("response_type",Ha),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Ba),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),s&&c.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",Wa(a)),{authorizationUrl:c,codeVerifier:u}}o(Pv,"startAuthorization");function xv(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(xv,"prepareAuthorizationCodeRequest");async function df(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=_v(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",Wa(i)),!s&&n&&fv(hv(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let m=o(async()=>{let S=new Headers(u);return s&&await s(S,r,d,t),a&&S.set("DPoP",await a.buildProof({htm:"POST",htu:d})),ni(c??fetch)(d,{method:"POST",headers:S,body:r})},"requestOnce"),h=await m();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===me.UseDpopNonce&&(a.observeNonce(h,d),h=await m()),a?.observeNonce(h,d),!h.ok)throw await Yh(h);let f=await h.json();try{return At.parse(Aa(f))}catch(S){throw typeof f=="object"&&f!==null&&"error"in f?await Yh(JSON.stringify(f)):S}}o(df,"executeTokenRequest");async function Ov(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await df(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(Ov,"refreshAuthorization");async function Mv(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&rf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:tf(r)});let d=r?.issuer??String(t),u=o(async()=>{let S=await e.clientInformation({issuer:d}),R=Ja(S,d,{canPersistStamp:!1});if(S&&R===void 0)throw new si(String(S.issuer),d);return R},"readClientInformation"),m=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=xv(s,await e.codeVerifier(),e.redirectUrl)}return m??=await u(),df(t,{metadata:r,tokenRequestParams:f,clientInformation:m,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(Mv,"fetchToken");async function Uv(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:s}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},c=await ni(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new Va({status:c.status,body:await c.text(),submittedMetadata:a});return or.parse(Aa(await c.json()))}o(Uv,"registerClient");var oU=class extends Error{static{o(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,cr(this,new.target)}};function Me(e){let t=nr.safeParse(e);return t.success?t.data.id:void 0}o(Me,"parseJsonRpcRequestId");function Za(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Me(t)}catch{return}}o(Za,"readJsonRpcRequestIdFromBody");function gt(e){return fo.parse({jsonrpc:rr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}o(gt,"jsonRpcErrorResponse");function uf(e){return new ri([As.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o(uf,"urlElicitationRequiredError");function it(e){return(e??"").split(";")[0].trim().toLowerCase()}o(it,"mediaTypeEssence");var qv=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function yt(e){for(let t of qv)e.delete(t);return e}o(yt,"deleteEncodedBodyHeaders");function lf(){let e=ws.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(lf,"currentRuntime");var zv=new Set(["gzip","x-gzip","deflate","br","zstd"]);function at(e,t=lf()){let r=e.get("content-encoding")?.trim();if(!r||r.toLowerCase()==="identity")return!1;switch(t){case"deno":return!0;case"workerd":return r!=="gzip"&&r!=="br";default:return!r.toLowerCase().split(",").every(n=>zv.has(n.trim()))}}o(at,"isBodyStillEncoded");function pf(e){return at(e)?e:yt(e)}o(pf,"deleteEncodedBodyHeadersIfDecoded");function mf(e,t=lf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?at(e,t):e.has("content-length"))?e:yt(e)}o(mf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var ff=10*1024*1024,Nv=1024,jv=32,Dv=64,dr=class extends Error{constructor(r,n=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=n;this.name="SseEventTooLargeError"}maxEventChars;comment;static{o(this,"SseEventTooLargeError")}},Lv=10;function $v(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o($v,"handleRejection");function gf(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(gf,"fieldName");var Mo=class{static{o(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#l=!1;#p=/\r\n|\r|\n/g;#m="";#d=[];#o=[];#i=0;#a=!1;#u=!1;#h=!1;#s=!1;#f=!1;#S=0;#C=0;#c=[];#g=0;#y=[];#_;#w;#R;#b=[];constructor(t={}){let r=t.maxEventChars??ff;if(!Number.isInteger(r)||r<=0)throw new RangeError(`maxEventChars must be a positive integer, got ${r}`);this.#e=r,this.#r=t.onOversize==="discard",this.#t=t.emitLoneComments===!0}get discardedEvents(){return this.#S}get discardedComments(){return this.#C}get discarding(){return this.#s||this.#f}get idle(){return this.#i===0&&!this.#a&&!this.#s&&this.#c.length===0}push(t){let r=[];return this.#T(this.#I(this.#n.decode(t,{stream:!0})),r),r}end(){let t=[];return this.#T(this.#I(this.#n.decode()),t),(this.#i>0||this.#a)&&this.#A(t,!1),this.#s||this.#P(t,!1),this.#s=!1,t}#I(t){return this.#l||t===""?t:(this.#l=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let n=0;this.#h&&(this.#h=!1,t.charCodeAt(0)===Lv&&(n=1));let s=this.#p;s.lastIndex=n;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(n,i.index)),this.#A(r),n=i.index+i[0].length,i[0]==="\r"&&n===t.length&&(this.#h=!0),i=s.exec(t);this.#E(t.slice(n))}#E(t){if(t!==""){if(this.#s||this.#f){this.#a=!0;return}if(this.#i===0?this.#m=t:(this.#o.push(t),this.#o.length>=Dv&&(this.#d.push(this.#o.join("")),this.#o=[])),this.#i+=t.length,this.#g+this.#i>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#f=!0,this.#S++,this.#C++):this.#k(r),this.#a=!0}}}#O(){return this.#t&&this.#c.length===0&&this.#m.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new dr(this.#e,t);this.#x(),this.#u=!1,this.#v(),this.#s=!0,this.#S++}#v(){this.#m="",this.#d.length>0&&(this.#d=[]),this.#o.length>0&&(this.#o=[]),this.#i=0}#A(t,r=!0){let n=this.#d.length===0&&this.#o.length===0?this.#m:this.#m+this.#d.join("")+this.#o.join(""),s=n===""&&!this.#a;if(this.#v(),this.#a=!1,this.#f){this.#f=!1,this.#u=!0;return}if(s){this.#s?this.#s=!1:this.#u&&this.#c.length===0?(this.#u=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#u=!1,this.#P(t,!0));return}if(this.#s)return;if(this.#t&&r&&this.#c.length===0&&n.charCodeAt(0)===58){t.push({lines:[n],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[n.slice(1)],terminated:!0,lone:!0}),this.#u=!0;return}if(this.#g+=n.length,this.#c.push(n),this.#c.length>Nv&&(this.#g+=Math.max(0,jv-n.length),this.#g>this.#e)){this.#k();return}if(n.charCodeAt(0)===58){this.#b.push(n.slice(1));return}let i=n.indexOf(":"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#y.push(c);break;case"event":this.#_=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#R=Number(c));break;default:break}}#P(t,r){this.#c.length>0&&t.push({lines:this.#c,data:this.#y.length>0?this.#y.join(`
26
- `):void 0,event:this.#_,id:this.#w,retry:this.#R,comments:this.#b,terminated:r}),this.#x()}#x(){this.#c=[],this.#g=0,this.#y=[],this.#_=void 0,this.#w=void 0,this.#R=void 0,this.#b=[]}};function Ya(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}o(Ya,"assertSingleLine");function Xa(e){if("lines"in e){for(let n of e.lines){if(/[\r\n]/.test(n))throw new TypeError("SSE event line must not contain a line break");if(n==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(n=>`${n}
25
+ import{$ as Ji,$a as Ju,$b as Zi,$c as Mp,$f as zw,$g as Dm,Aa as Ki,Ab as Sl,Ac as dp,Ad as Yp,Af as ym,Ag as Am,Ah as eh,Ba as wu,Bb as _l,Bc as na,Bd as ks,Bf as $r,Bg as oe,Bh as th,C as eu,Ca as Ru,Cb as wl,Cc as Is,Cd as As,Cf as M,Cg as Pm,Ch as Dw,Da as bu,Db as Rl,Dc as Ts,Dd as ir,Df as Lr,Dg as Mt,Dh as $w,E as ws,Ea as vu,Eb as bl,Ec as up,Ed as Xp,Ef as Hr,Eg as da,Fa as Cu,Fb as vl,Fc as lp,Fd as sa,Ff as ut,Fg as zs,Ga as Iu,Gb as Cl,Gc as pp,Gd as am,Gf as lt,Gg as ua,H as Rs,Ha as Tu,Hb as Il,Hc as mp,Hd as cm,Hf as Ps,Hg as Ns,Ia as Eu,Ib as Tl,Ic as hp,Id as dm,If as Br,Ig as wo,Ja as ku,Jb as El,Jc as fp,Jd as ia,Jf as Fr,Jg as Vr,Ka as Au,Kb as kl,Kc as gp,Kd as um,Kf as Jr,Kg as xm,La as Pu,Lb as Al,Lc as yp,Ld as aa,Lf as xs,Lg as ht,Ma as xu,Mb as Pl,Mc as Sp,Mf as Sm,Mg as la,N as tu,Na as Ou,Nb as xl,Nc as _p,Nf as et,Ng as js,Oa as Mu,Ob as Ol,Oc as wp,Of as _m,Og as Om,Pa as Uu,Pb as Ml,Pc as Rp,Pf as pt,Pg as Ds,Q as ru,Qa as qu,Qb as Ul,Qc as bp,Qf as z,Qg as pa,Ra as zu,Rb as ql,Rc as vp,Rf as Os,Rg as $s,Sa as Wi,Sb as zl,Sc as Cp,Sd as lm,Sf as Ee,Sg as Mm,T as nu,Ta as Nu,Tb as Nl,Tc as Ip,Tf as xt,Tg as pe,Ua as ju,Ub as jl,Uc as Tp,Uf as Aw,Ug as Um,Va as Du,Vb as Dl,Vc as Ep,Vf as Pw,Vg as qm,Wa as $u,Wb as $l,Wc as kp,Wf as xw,Wg as zm,Xa as Lu,Xb as Ll,Xc as Ap,Xf as Ow,Xg as ma,Ya as Hu,Yb as Hl,Yc as Pp,Yf as Mw,Yg as Nm,Za as Bu,Zb as Bl,Zc as xp,Zf as Uw,Zg as jm,_ as bs,_a as Fu,_b as Fl,_c as Op,_f as qw,_g as ha,aa as xr,ab as Gu,ac as Jl,ad as Up,ag as Nw,ah as cr,b as _s,ba as lo,bb as Vu,bc as Gl,bd as qp,bg as jw,bh as $m,ca as Or,cb as Ku,cc as Vl,cd as zp,cg as wm,ch as Ro,da as Mr,db as Wu,dc as Kl,dd as Np,dg as Rm,dh as Lm,ea as po,eb as Zu,ec as Wl,ed as jp,eg as Ms,eh as Ls,fa as nr,fb as Yu,fc as Zl,fd as Dp,fg as yo,fh as bo,ga as ou,gb as Xu,gc as Yl,gd as $p,gg as So,gh as Hm,ha as su,hb as Qu,hc as Xl,hd as Lp,hg as Gr,hh as Bm,ia as iu,ib as el,ic as Ql,id as Hp,ig as bm,ih as Fm,ja as au,jb as tl,jc as ep,jd as Bp,jg as ca,jh as Jm,ka as cu,kb as rl,kc as tp,kd as Ur,kg as vm,kh as Gm,la as du,lb as nl,lc as rp,ld as qr,lg as _o,lh as Vm,ma as uu,mb as ol,mc as np,md as Fp,mg as Us,mh as Km,n as ot,na as lu,nb as sl,nc as op,nd as zr,ng as Cm,nh as Wm,oa as pu,ob as il,oc as sp,od as Pt,og as Im,oh as Hs,pa as mu,pb as al,pc as ip,pd as oa,pg as Tm,ph as Zm,qa as hu,qb as cl,qc as Yi,qd as Es,qg as Em,qh as Ym,ra as fu,rb as dl,rc as vs,rd as Jp,rg as Ce,rh as H,sa as gu,sb as ul,sc as Cs,sd as ho,sf as pm,sg as ge,sh as ee,ta as yu,tb as ll,tc as Xi,td as sr,tf as je,tg as km,th as fa,u as Ne,ua as Su,ub as pl,uc as Qi,ud as Gp,uf as mm,ug as qs,uh as ye,v as Qd,va as _u,vb as ml,vc as ea,vd as Vp,vf as hm,vg as J,vh as ft,wa as or,wb as hl,wc as ap,wd as Kp,wf as fm,wg as mt,wh as ce,x as G,xa as Gi,xb as fl,xc as ta,xd as Wp,xf as ie,xg as Ot,xh as Bs,ya as Vi,yb as gl,yc as ra,yd as Zp,yf as gm,yg as ke,yh as Xm,za as mo,zb as yl,zc as cp,zd as fo,zf as Dr,zg as ae,zh as Qm}from"../chunk-UGZSO3CK.js";import"../chunk-VP5Q3DEN.js";import"../chunk-AENEWA54.js";import{a as At,b as fe,c as go,d as Qp,e as em,f as tm,g as ar,h as rm,i as nm,j as om,k as Nr,l as jr,s as sm,t as im}from"../chunk-7RNZS3GX.js";import"../chunk-A3QGJZO7.js";import{A as p,b as Hi,c as Zd,d as l,e as Yd,f as Xd,g as E,h as N,i as ys,k as D,l as C,m as g,n as L,o as q,p as Bi,q as co,r as U,s as F,t as w,u as $,v as Fi,w as Ss,y as uo}from"../chunk-C32OTSKW.js";import"../chunk-UKQQD2JN.js";import{$ as gs,a as Te,aa as Wd,c as k,d as Q}from"../chunk-UFTMOJ7K.js";import{a as o}from"../chunk-TYV53J3B.js";var Lw=Object.create,Fs=Object.defineProperty,Hw=Object.getOwnPropertyDescriptor,Bw=Object.getOwnPropertyNames,Fw=Object.getPrototypeOf,Jw=Object.prototype.hasOwnProperty,rh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),nh=o((e,t)=>{let r={};for(var n in e)Fs(r,n,{get:e[n],enumerable:!0});return t&&Fs(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Gw=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=Bw(t),i=0,a=s.length,c;i<a;i++)c=s[i],!Jw.call(e,c)&&c!==r&&Fs(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=Hw(t,c))||n.enumerable});return e},"__copyProps"),oh=o((e,t,r)=>(r=e!=null?Lw(Fw(e)):{},Gw(t||!e||!e.__esModule?Fs(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Vw=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function sh(e){return typeof e=="string"&&Vw.has(e.replace(/#$/,""))}o(sh,"declares2019Dialect");var Ra=Symbol.for("mcp.sdk.errorBrands");function dr(e,t){let r=new Set,n=t;for(;typeof n=="function";){let s=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof s=="string"&&r.add(s),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,Ra,{value:r,enumerable:!1,configurable:!0})}o(dr,"stampErrorBrands");function De(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Ra)){let r=t[Ra];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}o(De,"brandedHasInstance");var me=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Ut=class gh extends Error{static{o(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",dr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new gh(t.error,t.error_description??t.error,t.error_uri)}},Se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),le=class extends Error{static{o(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",dr(this,new.target)}},sR=class extends le{static{o(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,n){super(e,t,r,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function yh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(yh,"resourceUrlFromServerUrl");function Ea(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}o(Ea,"withoutIssuer");function Ws({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(i)}o(Ws,"checkResourceAllowed");var iR="2026-07-28";function Sh(e){return e>=iR}o(Sh,"isModernProtocolVersion");function _h(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}o(_h,"appendTextFallbackForNonObject");var wh=["task","inputRequests","requestState"];function aR(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||wh.some(t=>t in e)?e:{...e,content:[]}}o(aR,"normalizeContentlessToolResult");function cR(){let e=Fi(()=>q([l(),E(),N(),ys(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),E().int()]),n=l(),s=g({ttl:E().optional()}),i=g({taskId:l()}),a=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),m=g({_meta:a.optional()}),h=g({method:l(),params:m.loose().optional()}),f=L({_meta:a.optional()}),S=q([l(),E().int()]),R=f.strict(),_=m.extend({requestId:S.optional(),reason:l().optional()}),y=h.extend({method:w("notifications/cancelled"),params:_}),b=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),I=g({icons:C(b).optional()}),A=g({name:l(),title:l().optional()}),v=A.extend({...A.shape,...I.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),Y=co(g({applyDefaults:N().optional()}),t),O=Ss(ve=>ve&&typeof ve=="object"&&!Array.isArray(ve)&&Object.keys(ve).length===0?{form:{}}:ve,co(g({form:Y.optional(),url:t.optional()}),t.optional())),Z=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),re=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),x=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:O.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Z.optional(),extensions:U(l(),t).optional()}),B=c.extend({protocolVersion:l(),capabilities:x,clientInfo:v}),j=u.extend({method:w("initialize"),params:B}),X=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:re.optional(),extensions:U(l(),t).optional()}),te=f.extend({protocolVersion:l(),capabilities:X,serverInfo:v,instructions:l().optional()}),He=h.extend({method:w("notifications/initialized"),params:m.optional()}),Ue=u.extend({method:w("ping"),params:c.optional()}),Be=g({progress:E(),total:$(E()),message:$(l())}),K=g({...m.shape,...Be.shape,progressToken:r}),ue=h.extend({method:w("notifications/progress"),params:K}),xe=c.extend({cursor:n.optional()}),ne=u.extend({params:xe.optional()}),Ye=f.extend({nextCursor:n.optional()}),gr=g({uri:l(),mimeType:$(l()),_meta:U(l(),D()).optional()}),yr=gr.extend({text:l()}),Jt=l().refine(ve=>{try{return atob(ve),!0}catch{return!1}},{message:"Invalid Base64 string"}),Sr=gr.extend({blob:Jt}),nt=F(["user","assistant"]),Xe=g({audience:C(nt).optional(),priority:E().min(0).max(1).optional(),lastModified:uo.datetime({offset:!0}).optional()}),Gt=g({...A.shape,...I.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(E()),annotations:Xe.optional(),_meta:$(L({}))}),fn=g({...A.shape,...I.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:Xe.optional(),_meta:$(L({}))}),gn=ne.extend({method:w("resources/list")}),yn=Ye.extend({resources:C(Gt)}),It=ne.extend({method:w("resources/templates/list")}),_r=Ye.extend({resourceTemplates:C(fn)}),Vt=c.extend({uri:l()}),Sn=Vt,_n=u.extend({method:w("resources/read"),params:Sn}),wn=f.extend({contents:C(q([yr,Sr]))}),Rn=h.extend({method:w("notifications/resources/list_changed"),params:m.optional()}),bn=Vt,vn=u.extend({method:w("resources/subscribe"),params:bn}),Cn=Vt,In=u.extend({method:w("resources/unsubscribe"),params:Cn}),Tn=m.extend({uri:l()}),En=h.extend({method:w("notifications/resources/updated"),params:Tn}),kn=g({name:l(),description:$(l()),required:$(N())}),An=g({...A.shape,...I.shape,description:$(l()),arguments:$(C(kn)),_meta:$(L({}))}),Pn=ne.extend({method:w("prompts/list")}),xn=Ye.extend({prompts:C(An)}),On=c.extend({name:l(),arguments:U(l(),l()).optional()}),Mn=u.extend({method:w("prompts/get"),params:On}),Kt=g({type:w("text"),text:l(),annotations:Xe.optional(),_meta:U(l(),D()).optional()}),Wt=g({type:w("image"),data:Jt,mimeType:l(),annotations:Xe.optional(),_meta:U(l(),D()).optional()}),Zt=g({type:w("audio"),data:Jt,mimeType:l(),annotations:Xe.optional(),_meta:U(l(),D()).optional()}),Un=g({type:w("tool_use"),name:l(),id:l(),input:U(l(),D()),_meta:U(l(),D()).optional()}),Tt=g({type:w("resource"),resource:q([yr,Sr]),annotations:Xe.optional(),_meta:U(l(),D()).optional()}),qn=Gt.extend({type:w("resource_link")}),Fe=q([Kt,Wt,Zt,qn,Tt]),wr=g({role:nt,content:Fe}),Rr=f.extend({description:l().optional(),messages:C(wr)}),Yt=h.extend({method:w("notifications/prompts/list_changed"),params:m.optional()}),zn=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),br=g({taskSupport:F(["required","optional","forbidden"]).optional()}),Xt=g({...A.shape,...I.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(D()),outputSchema:g({type:w("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(D()).optional(),annotations:zn.optional(),execution:br.optional(),_meta:U(l(),D()).optional()}),vr=ne.extend({method:w("tools/list")}),Cr=Ye.extend({tools:C(Xt)}),Ir=f.extend({content:C(Fe),structuredContent:U(l(),D()).optional(),isError:N().optional()}),be=d.extend({name:l(),arguments:U(l(),D()).optional()}),Nn=u.extend({method:w("tools/call"),params:be}),es=h.extend({method:w("notifications/tools/list_changed"),params:m.optional()}),Tr=F(["debug","info","notice","warning","error","critical","alert","emergency"]),jn=c.extend({level:Tr}),Dn=u.extend({method:w("logging/setLevel"),params:jn}),$n=m.extend({level:Tr,logger:l().optional(),data:D()}),Ln=h.extend({method:w("notifications/message"),params:$n}),Hn=g({name:l().optional()}),Bn=g({hints:C(Hn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Fn=g({mode:F(["auto","required","none"]).optional()}),ts=g({type:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Fe),structuredContent:g({}).loose().optional(),isError:N().optional(),_meta:U(l(),D()).optional()}),Jn=Bi("type",[Kt,Wt,Zt]),Et=Bi("type",[Kt,Wt,Zt,Un,ts]),Gn=g({role:nt,content:q([Et,C(Et)]),_meta:U(l(),D()).optional()}),Vn=d.extend({messages:C(Gn),modelPreferences:Bn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Xt).optional(),toolChoice:Fn.optional()}),Kn=u.extend({method:w("sampling/createMessage"),params:Vn}),Wn=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens"]).or(l())),role:nt,content:Jn}),Zn=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:nt,content:q([Et,C(Et)])}),Yn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),Xn=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),Qn=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),eo=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),to=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),ro=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),no=q([eo,to]),Qt=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),er=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),rs=q([Qt,er]),ns=q([ro,no,rs]),qe=q([ns,Yn,Xn,Qn]),ze=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:U(l(),qe),required:C(l()).optional()}).catchall(D())}),oo=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),Qe=q([ze,oo]),os=u.extend({method:w("elicitation/create"),params:Qe}),ss=m.extend({elicitationId:l()}),is=h.extend({method:w("notifications/elicitation/complete"),params:ss}),as=f.extend({action:F(["accept","decline","cancel"]),content:Ss(ve=>ve===null?void 0:ve,U(l(),q([l(),E(),N(),C(l())])).optional())}),cs=g({type:w("ref/resource"),uri:l()}),ds=g({type:w("ref/prompt"),name:l()}),us=c.extend({ref:q([ds,cs]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()}),so=u.extend({method:w("completion/complete"),params:us}),ls=f.extend({completion:L({values:C(l()).max(100),total:$(E().int()),hasMore:$(N())})}),ps=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),D()).optional()}),Er=u.extend({method:w("roots/list"),params:c.optional()}),io=f.extend({roots:C(ps)}),ms=h.extend({method:w("notifications/roots/list_changed"),params:m.optional()}),hs=L({ttl:E().optional(),pollInterval:E().optional()}),ao=F(["working","input_required","completed","failed","cancelled"]),kt=g({taskId:l(),status:ao,ttl:q([E(),ys()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:$(E()),statusMessage:$(l())}),Oe=f.extend({task:kt}),fs=m.merge(kt),tr=h.extend({method:w("notifications/tasks/status"),params:fs}),kr=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),Ar=f.merge(kt),Pr=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),Li=f.loose(),Ie=ne.extend({method:w("tasks/list")}),se=Ye.extend({tasks:C(kt)}),rr=u.extend({method:w("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:R,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:y,IconSchema:b,IconsSchema:I,BaseMetadataSchema:A,ImplementationSchema:v,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:x,InitializeRequestParamsSchema:B,InitializeRequestSchema:j,ServerCapabilitiesSchema:X,InitializeResultSchema:te,InitializedNotificationSchema:He,PingRequestSchema:Ue,ProgressSchema:Be,ProgressNotificationParamsSchema:K,ProgressNotificationSchema:ue,PaginatedRequestParamsSchema:xe,PaginatedRequestSchema:ne,PaginatedResultSchema:Ye,ResourceContentsSchema:gr,TextResourceContentsSchema:yr,BlobResourceContentsSchema:Sr,RoleSchema:nt,AnnotationsSchema:Xe,ResourceSchema:Gt,ResourceTemplateSchema:fn,ListResourcesRequestSchema:gn,ListResourcesResultSchema:yn,ListResourceTemplatesRequestSchema:It,ListResourceTemplatesResultSchema:_r,ResourceRequestParamsSchema:Vt,ReadResourceRequestParamsSchema:Sn,ReadResourceRequestSchema:_n,ReadResourceResultSchema:wn,ResourceListChangedNotificationSchema:Rn,SubscribeRequestParamsSchema:bn,SubscribeRequestSchema:vn,UnsubscribeRequestParamsSchema:Cn,UnsubscribeRequestSchema:In,ResourceUpdatedNotificationParamsSchema:Tn,ResourceUpdatedNotificationSchema:En,PromptArgumentSchema:kn,PromptSchema:An,ListPromptsRequestSchema:Pn,ListPromptsResultSchema:xn,GetPromptRequestParamsSchema:On,GetPromptRequestSchema:Mn,TextContentSchema:Kt,ImageContentSchema:Wt,AudioContentSchema:Zt,ToolUseContentSchema:Un,EmbeddedResourceSchema:Tt,ResourceLinkSchema:qn,ContentBlockSchema:Fe,PromptMessageSchema:wr,GetPromptResultSchema:Rr,PromptListChangedNotificationSchema:Yt,ToolAnnotationsSchema:zn,ToolExecutionSchema:br,ToolSchema:Xt,ListToolsRequestSchema:vr,ListToolsResultSchema:Cr,CallToolResultSchema:Ir,CallToolRequestParamsSchema:be,CallToolRequestSchema:Nn,ToolListChangedNotificationSchema:es,LoggingLevelSchema:Tr,SetLevelRequestParamsSchema:jn,SetLevelRequestSchema:Dn,LoggingMessageNotificationParamsSchema:$n,LoggingMessageNotificationSchema:Ln,ModelHintSchema:Hn,ModelPreferencesSchema:Bn,ToolChoiceSchema:Fn,ToolResultContentSchema:ts,SamplingContentSchema:Jn,SamplingMessageContentBlockSchema:Et,SamplingMessageSchema:Gn,CreateMessageRequestParamsSchema:Vn,CreateMessageRequestSchema:Kn,CreateMessageResultSchema:Wn,CreateMessageResultWithToolsSchema:Zn,BooleanSchemaSchema:Yn,StringSchemaSchema:Xn,NumberSchemaSchema:Qn,UntitledSingleSelectEnumSchemaSchema:eo,TitledSingleSelectEnumSchemaSchema:to,LegacyTitledEnumSchemaSchema:ro,SingleSelectEnumSchemaSchema:no,UntitledMultiSelectEnumSchemaSchema:Qt,TitledMultiSelectEnumSchemaSchema:er,MultiSelectEnumSchemaSchema:rs,EnumSchemaSchema:ns,PrimitiveSchemaDefinitionSchema:qe,ElicitRequestFormParamsSchema:ze,ElicitRequestURLParamsSchema:oo,ElicitRequestParamsSchema:Qe,ElicitRequestSchema:os,ElicitationCompleteNotificationParamsSchema:ss,ElicitationCompleteNotificationSchema:is,ElicitResultSchema:as,ResourceTemplateReferenceSchema:cs,PromptReferenceSchema:ds,CompleteRequestParamsSchema:us,CompleteRequestSchema:so,CompleteResultSchema:ls,RootSchema:ps,ListRootsRequestSchema:Er,ListRootsResultSchema:io,RootsListChangedNotificationSchema:ms,TaskCreationParamsSchema:hs,TaskStatusSchema:ao,TaskSchema:kt,CreateTaskResultSchema:Oe,TaskStatusNotificationParamsSchema:fs,TaskStatusNotificationSchema:tr,GetTaskRequestSchema:kr,GetTaskResultSchema:Ar,GetTaskPayloadRequestSchema:Pr,GetTaskPayloadResultSchema:Li,ListTasksRequestSchema:Ie,ListTasksResultSchema:se,CancelTaskRequestSchema:rr,CancelTaskResultSchema:f.merge(kt),ClientRequestSchema:q([Ue,j,so,Dn,Mn,Pn,gn,It,_n,vn,In,Nn,vr,kr,Pr,Ie,rr]),ClientNotificationSchema:q([y,ue,He,ms,tr]),ClientResultSchema:q([R,Wn,Zn,as,io,Ar,se,Oe]),ServerRequestSchema:q([Ue,Kn,os,Er,kr,Pr,Ie,rr]),ServerNotificationSchema:q([y,ue,Ln,En,Rn,es,Yt,tr,is]),ServerResultSchema:q([R,te,ls,Rr,xn,yn,_r,wn,Ir,Cr,Ar,se,Oe]),CallToolResultWireSchema:D().superRefine((ve,kw)=>{if(!(typeof ve!="object"||ve===null||Array.isArray(ve)||ve.content!==void 0)){for(let Kd of wh)if(Kd in ve){kw.addIssue({code:"custom",message:`content is required when the body carries '${Kd}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(aR).pipe(Ir)}}o(cR,"build$1");var dR;function ka(){return dR??=cR()}o(ka,"buildSchemas2025");function Rh(e){return e.type!=="object"}o(Rh,"isNonObjectJsonSchemaRoot");var uR=new Set(["const","enum","default","examples"]),lR=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ih(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(ih,"establishesNewBase");function pR(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ih(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=sh(e.$schema)&&e.$recursiveAnchor!==!0,n=o((s,i)=>{if(Array.isArray(s))return s.map(d=>n(d,!1));if(s===null||typeof s!="object"||!i&&ih(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=n(u,!1):(d==="$ref"||d==="$dynamicRef")&&typeof u=="string"?a[d]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:d==="$recursiveRef"&&u==="#"&&r?c=!0:uR.has(d)?a[d]=u:lR.has(d)?a[d]=n(u,!0):a[d]=n(u,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}o(pR,"wrapOutputSchemaForLegacy");var bh={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},vh={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},mR={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Js;function Zs(){if(Js)return Js;let e=ka();return Js={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Js}o(Zs,"registryMaps");function hR(){Zs()}o(hR,"warmRegistryMaps2025");function Ch(e){return Object.prototype.hasOwnProperty.call(bh,e)}o(Ch,"hasRequestMethod2025");function Ih(e){return Object.prototype.hasOwnProperty.call(vh,e)}o(Ih,"hasNotificationMethod2025");function fR(e){return Object.prototype.hasOwnProperty.call(mR,e)}o(fR,"hasResultMethod");function gR(e){return fR(e)?Zs().resultSchemas[e]:void 0}o(gR,"getResultSchema");function yR(e){return Ch(e)?Zs().requestSchemas[e]:void 0}o(yR,"getRequestSchema");function SR(e){return Ih(e)?Zs().notificationSchemas[e]:void 0}o(SR,"getNotificationSchema");var qM=Object.keys(bh),zM=Object.keys(vh);function ba(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(ba,"isPlainObject$5");function Gs(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Gs,"triState$1");var ah={ok:!1,reason:"not-in-era"};function ch(e){return ba(e)&&ba(e.outputSchema)&&Rh(e.outputSchema)}o(ch,"toolNeedsLegacyWrap");var Aa={era:"2025-11-25",hasRequestMethod:Ch,hasNotificationMethod:Ih,validateRequest:o((e,t)=>Gs(yR(e),t),"validateRequest"),validateResult:o((e,t)=>Gs(gR(e),t),"validateResult"),validateNotification:o((e,t)=>Gs(SR(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>ah,"validateInputRequest"),validateInputResponse:o(()=>ah,"validateInputResponse"),samplingResultVariant:o(((e,t)=>{let r=ka();return Gs(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:o(e=>{},"outboundEnvelope"),validateEnvelopeMeta:o(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=_h(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&Rh(t);return!s&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(ba(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>ch(n))?t:{...t,tools:r.map(n=>ch(n)?{...n,outputSchema:pR(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function _R(){let e=Fi(()=>q([l(),E(),N(),ys(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),E().int()]),n=l(),s=q([l(),E().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(se=>{try{return atob(se),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:E().optional()}),u=g({taskId:l()}),m=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:m.optional()}),f=h.extend({task:d.optional()}),S=g({_meta:m.optional()}),R=g({method:l(),params:S.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),y=g({icons:C(_).optional()}),b=g({name:l(),title:l().optional()}),I=b.extend({...b.shape,...y.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),A=co(g({applyDefaults:N().optional()}),t),v=Ss(se=>se&&typeof se=="object"&&!Array.isArray(se)&&Object.keys(se).length===0?{form:{}}:se,co(g({form:A.optional(),url:t.optional()}),t.optional())),Y=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),O=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),Z=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:v.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Y.optional(),extensions:U(l(),t).optional()}),re=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:O.optional(),extensions:U(l(),t).optional()}),x=g({progress:E(),total:$(E()),message:$(l())}),B=g({...S.shape,...x.shape,progressToken:r}),j=R.extend({method:w("notifications/progress"),params:B}),X=S.extend({level:a,logger:l().optional(),data:D()}),te=R.extend({method:w("notifications/message"),params:X}),He=g({uri:l(),mimeType:$(l()),_meta:U(l(),D()).optional()}),Ue=He.extend({text:l()}),Be=He.extend({blob:c}),K=g({audience:C(i).optional(),priority:E().min(0).max(1).optional(),lastModified:uo.datetime({offset:!0}).optional()}),ue=g({...b.shape,...y.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(E()),annotations:K.optional(),_meta:$(L({}))}),xe=g({...b.shape,...y.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:K.optional(),_meta:$(L({}))}),ne=R.extend({method:w("notifications/resources/list_changed"),params:S.optional()}),Ye=S.extend({uri:l()}),gr=R.extend({method:w("notifications/resources/updated"),params:Ye}),yr=g({name:l(),description:$(l()),required:$(N())}),Jt=g({...b.shape,...y.shape,description:$(l()),arguments:$(C(yr)),_meta:$(L({}))}),Sr=R.extend({method:w("notifications/prompts/list_changed"),params:S.optional()}),nt=g({type:w("text"),text:l(),annotations:K.optional(),_meta:U(l(),D()).optional()}),Xe=g({type:w("image"),data:c,mimeType:l(),annotations:K.optional(),_meta:U(l(),D()).optional()}),Gt=g({type:w("audio"),data:c,mimeType:l(),annotations:K.optional(),_meta:U(l(),D()).optional()}),fn=g({type:w("tool_use"),name:l(),id:l(),input:U(l(),D()),_meta:U(l(),D()).optional()}),gn=g({type:w("resource"),resource:q([Ue,Be]),annotations:K.optional(),_meta:U(l(),D()).optional()}),yn=ue.extend({type:w("resource_link")}),It=q([nt,Xe,Gt,yn,gn]),_r=g({role:i,content:It}),Vt=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Sn=R.extend({method:w("notifications/tools/list_changed"),params:S.optional()}),_n=g({name:l().optional()}),wn=g({hints:C(_n).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Rn=g({mode:F(["auto","required","none"]).optional()}),bn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),vn=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),Cn=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),In=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),Tn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),En=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),kn=q([In,Tn]),An=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),Pn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),xn=q([An,Pn]),On=q([En,kn,xn]),Mn=q([On,bn,vn,Cn]),Kt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:U(l(),Mn),required:C(l()).optional()}).catchall(D())}),Wt=g({type:w("ref/resource"),uri:l()}),Zt=g({type:w("ref/prompt"),name:l()}),Un=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),D()).optional()}),Tt=Z.shape,qn=g({experimental:Tt.experimental,sampling:Tt.sampling,elicitation:Tt.elicitation,roots:Tt.roots,extensions:Tt.extensions}),Fe=re.shape,wr=g({experimental:Fe.experimental,logging:Fe.logging,completions:Fe.completions,prompts:Fe.prompts,resources:Fe.resources,tools:Fe.tools,extensions:Fe.extensions}),Rr=L({progressToken:r.optional(),[xr]:l(),[lo]:I.optional(),[Mr]:qn,[po]:a.optional()}),Yt=g({...b.shape,...y.shape,description:l().optional(),inputSchema:L({$schema:l().optional(),type:w("object")}),outputSchema:L({$schema:l().optional()}).optional(),annotations:Vt.optional(),_meta:U(l(),D()).optional()}),zn=g({type:w("tool_result"),toolUseId:l(),content:C(It),structuredContent:D().optional(),isError:N().optional(),_meta:U(l(),D()).optional()}),br=q([nt,Xe,Gt,fn,zn]),Xt=g({role:i,content:q([br,C(br)]),_meta:U(l(),D()).optional()}),vr=l(),Cr=L({[Or]:I.optional().catch(void 0)}),Ir=Cr.optional();function be(se){return L({_meta:Ir,resultType:vr.default("complete"),...se})}o(be,"wireResult");let Nn=be({}),es=be({nextCursor:n.optional()}),Tr=be({content:C(It),structuredContent:D().optional(),isError:N().optional()}),jn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Yt),nextCursor:n.optional()}),Dn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Jt),nextCursor:n.optional()}),$n=be({description:l().optional(),messages:C(_r)}),Ln=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(ue),nextCursor:n.optional()}),Hn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),Bn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),Fn=be({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),ts=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"])}),Jn=be({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:wr,instructions:l().optional()}),Et=g({messages:C(Xt),modelPreferences:wn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Yt).optional(),toolChoice:Rn.optional()}),Gn=g({method:w("sampling/createMessage"),params:Et}),Vn=g({method:w("roots/list"),params:g({_meta:U(l(),D()).optional()}).optional()}),Kn=g({...Xt.shape,model:l(),stopReason:l().optional()}),Wn=g({roots:C(Un)}),Zn=g({action:F(["accept","decline","cancel"]),content:U(l(),q([l(),E(),N(),C(l())])).optional()}),Yn=g({mode:w("url"),message:l(),url:l().url()}),Xn=q([Kt,Yn]),Qn=g({method:w("elicitation/create"),params:Xn}),eo=q([Gn,Vn,Qn]),to=q([Kn,Wn,Zn]),ro=U(l(),eo),no=U(l(),to),Qt=be({inputRequests:ro.optional(),requestState:l().optional()}),er={inputResponses:no.optional(),requestState:l().optional()},rs=g({_meta:Rr,...er}),ns=L({progressToken:r.optional()});function qe(se,rr){return g({method:w(se),params:g({_meta:Rr,...rr})})}o(qe,"wireRequest");function ze(se,rr){return g({method:w(se),params:g({_meta:ns.optional(),...rr}).optional()})}o(ze,"dispatchRequest");let oo={name:l(),arguments:U(l(),D()).optional(),...er},Qe={cursor:n.optional()},os=qe("tools/call",oo),ss=qe("tools/list",Qe),is=qe("prompts/list",Qe),as=qe("prompts/get",{name:l(),arguments:U(l(),l()).optional(),...er}),cs=qe("resources/list",Qe),ds=qe("resources/templates/list",Qe),us=qe("resources/read",{uri:l(),...er}),so={ref:q([Zt,Wt]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()},ls=qe("completion/complete",so),ps=qe("server/discover",{}),Er=g({toolsListChanged:N().optional(),promptsListChanged:N().optional(),resourcesListChanged:N().optional(),resourceSubscriptions:C(l()).optional()}),io={notifications:Er},ms=qe("subscriptions/listen",io),hs=Cr.extend({"io.modelcontextprotocol/subscriptionId":s}),ao=L({_meta:hs,resultType:vr.default("complete")}),kt={"tools/call":ze("tools/call",oo),"tools/list":ze("tools/list",Qe),"prompts/get":ze("prompts/get",{name:l(),arguments:U(l(),l()).optional()}),"prompts/list":ze("prompts/list",Qe),"resources/list":ze("resources/list",Qe),"resources/templates/list":ze("resources/templates/list",Qe),"resources/read":ze("resources/read",{uri:l()}),"completion/complete":ze("completion/complete",so),"server/discover":ze("server/discover",{}),"subscriptions/listen":ze("subscriptions/listen",io)};function Oe(se){return L({_meta:Ir,...se})}o(Oe,"liftedResult");let fs={"tools/call":Oe({content:C(It),structuredContent:D().optional(),isError:N().optional()}),"tools/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Yt),nextCursor:n.optional()}),"prompts/get":Oe({description:l().optional(),messages:C(_r)}),"prompts/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Jt),nextCursor:n.optional()}),"resources/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(ue),nextCursor:n.optional()}),"resources/templates/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),"resources/read":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),"completion/complete":Oe({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),"server/discover":Oe({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:wr,instructions:l().optional()}),"subscriptions/listen":Oe({})},tr=L({"io.modelcontextprotocol/subscriptionId":s.optional()}),kr=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:tr.optional(),notifications:Er})}),Ar=g({_meta:tr.optional(),requestId:s,reason:l().optional()}),Pr=g({method:w("notifications/cancelled"),params:Ar}),Li={"notifications/cancelled":Pr,"notifications/progress":j,"notifications/message":te,"notifications/resources/updated":gr,"notifications/resources/list_changed":ne,"notifications/tools/list_changed":Sn,"notifications/prompts/list_changed":Sr,"notifications/subscriptions/acknowledged":kr},Ie=o(se=>g({jsonrpc:w("2.0"),id:q([l(),E().int()]),result:se}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:R,IconSchema:_,IconsSchema:y,BaseMetadataSchema:b,ImplementationSchema:I,ClientTasksCapabilitySchema:Y,ServerTasksCapabilitySchema:O,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:re,ProgressSchema:x,ProgressNotificationParamsSchema:B,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:X,LoggingMessageNotificationSchema:te,ResourceContentsSchema:He,TextResourceContentsSchema:Ue,BlobResourceContentsSchema:Be,AnnotationsSchema:K,ResourceSchema:ue,ResourceTemplateSchema:xe,ResourceListChangedNotificationSchema:ne,ResourceUpdatedNotificationParamsSchema:Ye,ResourceUpdatedNotificationSchema:gr,PromptArgumentSchema:yr,PromptSchema:Jt,PromptListChangedNotificationSchema:Sr,TextContentSchema:nt,ImageContentSchema:Xe,AudioContentSchema:Gt,ToolUseContentSchema:fn,EmbeddedResourceSchema:gn,ResourceLinkSchema:yn,ContentBlockSchema:It,PromptMessageSchema:_r,ToolAnnotationsSchema:Vt,ToolListChangedNotificationSchema:Sn,ModelHintSchema:_n,ModelPreferencesSchema:wn,ToolChoiceSchema:Rn,BooleanSchemaSchema:bn,StringSchemaSchema:vn,NumberSchemaSchema:Cn,UntitledSingleSelectEnumSchemaSchema:In,TitledSingleSelectEnumSchemaSchema:Tn,LegacyTitledEnumSchemaSchema:En,SingleSelectEnumSchemaSchema:kn,UntitledMultiSelectEnumSchemaSchema:An,TitledMultiSelectEnumSchemaSchema:Pn,MultiSelectEnumSchemaSchema:xn,EnumSchemaSchema:On,PrimitiveSchemaDefinitionSchema:Mn,ElicitRequestFormParamsSchema:Kt,ResourceTemplateReferenceSchema:Wt,PromptReferenceSchema:Zt,RootSchema:Un,ClientCapabilities2026Schema:qn,ServerCapabilities2026Schema:wr,RequestMetaEnvelopeSchema:Rr,ToolSchema:Yt,ToolResultContentSchema:zn,SamplingMessageContentBlockSchema:br,SamplingMessageSchema:Xt,ResultTypeSchema:vr,ResultMetaSchema:Cr,ResultSchema:Nn,PaginatedResultSchema:es,CallToolResultSchema:Tr,ListToolsResultSchema:jn,ListPromptsResultSchema:Dn,GetPromptResultSchema:$n,ListResourcesResultSchema:Ln,ListResourceTemplatesResultSchema:Hn,ReadResourceResultSchema:Bn,CompleteResultSchema:Fn,CacheableResultSchema:ts,DiscoverResultSchema:Jn,CreateMessageRequestParamsSchema:Et,CreateMessageRequestSchema:Gn,ListRootsRequestSchema:Vn,CreateMessageResultSchema:Kn,ListRootsResultSchema:Wn,ElicitResultSchema:Zn,ElicitRequestURLParamsSchema:Yn,ElicitRequestParamsSchema:Xn,ElicitRequestSchema:Qn,InputRequestSchema:eo,InputResponseSchema:to,InputRequestsSchema:ro,InputResponsesSchema:no,InputRequiredResultSchema:Qt,InputResponseRequestParamsSchema:rs,CallToolRequestSchema:os,ListToolsRequestSchema:ss,ListPromptsRequestSchema:is,GetPromptRequestSchema:as,ListResourcesRequestSchema:cs,ListResourceTemplatesRequestSchema:ds,ReadResourceRequestSchema:us,CompleteRequestSchema:ls,DiscoverRequestSchema:ps,SubscriptionFilterSchema:Er,SubscriptionsListenRequestSchema:ms,SubscriptionsListenResultMetaSchema:hs,SubscriptionsListenResultSchema:ao,dispatchRequestSchemas:kt,dispatchResultSchemas:fs,NotificationMetaSchema:tr,SubscriptionsAcknowledgedNotificationSchema:kr,CancelledNotificationParamsSchema:Ar,CancelledNotificationSchema:Pr,notificationSchemas2026:Li,JSONRPCResultResponseSchema:Ie(Nn),CallToolResultResponseSchema:Ie(q([Tr,Qt])),ListToolsResultResponseSchema:Ie(jn),ListPromptsResultResponseSchema:Ie(Dn),GetPromptResultResponseSchema:Ie(q([$n,Qt])),ListResourcesResultResponseSchema:Ie(Ln),ListResourceTemplatesResultResponseSchema:Ie(Hn),ReadResourceResultResponseSchema:Ie(q([Bn,Qt])),CompleteResultResponseSchema:Ie(Fn),DiscoverResultResponseSchema:Ie(Jn),SubscriptionsListenResultResponseSchema:Ie(ao)}}o(_R,"build");var wR;function gt(){return wR??=_R()}o(gt,"buildSchemas2026");var RR=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function bR(e){return RR.includes(e)}o(bR,"isCacheableResultMethod");var Pa=Symbol("modelcontextprotocol.resultCacheHintFallback");function vR(e){return e[Pa]}o(vR,"cacheHintFallbackOf");function Th(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(Th,"isValidCacheTtlMs");function Eh(e){return e==="public"||e==="private"}o(Eh,"isValidCacheScope");var P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),_e=class kh extends Error{static{o(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",dr(this,new.target)}static fromError(t,r,n){if(t===P.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Ys(s.elicitations,r)}if(t===P.UnsupportedProtocolVersion&&n){let s=n;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Ph({supported:s.supported,requested:s.requested},r)}if(t===P.InvalidParams||t===P.ResourceNotFound){let s=n;if(typeof s?.uri=="string"&&(t===P.ResourceNotFound||Object.keys(s).length===1))return new Ah(s.uri,r)}if(t===P.MissingRequiredClientCapability&&n){let s=n;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new xh({requiredCapabilities:s.requiredCapabilities},r)}return new kh(t,r,n)}},Ah=class extends _e{static{o(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(P.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Ys=class extends _e{static{o(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(P.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Ph=class extends _e{static{o(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(P.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},xh=class extends _e{static{o(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(P.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},CR=0,IR="private",TR=["tools/call","prompts/get","resources/read"];function ER(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||TR.includes(e))return t;throw new _e(P.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}o(ER,"stampResultType");function kR(e,t){let r=vR(t);if(t.resultType!=="complete"||!bR(e))return r===void 0?t:MR(t);let n=t,s=Th(n.ttlMs)?n.ttlMs:xR(r),i=Eh(n.cacheScope)?n.cacheScope:OR(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Pa],a}o(kR,"fillCacheFields");function AR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(AR,"isPlainObject$4");function PR(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Or]:t}}:!AR(r)||r[Or]!==void 0?e:{...e,_meta:{...r,[Or]:t}}}o(PR,"stampServerInfoMeta");function xR(e){return e!==void 0&&Th(e.ttlMs)?e.ttlMs:CR}o(xR,"resolveTtlMs");function OR(e){return e!==void 0&&Eh(e.cacheScope)?e.cacheScope:IR}o(OR,"resolveCacheScope");function MR(e){let t={...e};return delete t[Pa],t}o(MR,"stripCacheHintFallback");var UR=["elicitation/create","sampling/createMessage","roots/list"],Vs;function xa(){if(Vs)return Vs;let e=gt();return Vs={request:{"elicitation/create":g({method:w("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:w("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:w("roots/list"),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Vs}o(xa,"inputSchemaMaps");function qR(){xa()}o(qR,"warmInputSchemaMaps2026");function Oh(e){return UR.includes(e)}o(Oh,"isInputRequestMethod2026");function ga(e){return Oh(e)?xa().request[e]:void 0}o(ga,"getInputRequestSchema2026");function zR(e){return Oh(e)?xa().response[e]:void 0}o(zR,"getInputResponseSchema2026");var Oa={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Mh={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Uh(e){return Object.prototype.hasOwnProperty.call(Oa,e)}o(Uh,"hasRequestMethod2026");function qh(e){return Object.prototype.hasOwnProperty.call(Mh,e)}o(qh,"hasNotificationMethod2026");function NR(e){return Object.prototype.hasOwnProperty.call(Oa,e)}o(NR,"hasResultMethod2026");function jR(e){return Uh(e)?gt().dispatchRequestSchemas[e]:void 0}o(jR,"getRequestSchema2026");function DR(e){return NR(e)?gt().dispatchResultSchemas[e]:void 0}o(DR,"getResultSchema2026");function $R(e){return qh(e)?gt().notificationSchemas2026[e]:void 0}o($R,"getNotificationSchema2026");var NM=Object.keys(Oa),jM=Object.keys(Mh);function Io(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Io,"isPlainObject$3");function vo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(vo,"triState");var LR={ok:!1,reason:"not-in-era"},HR=[xr,Mr];function BR(e,t){let r=t,n=!1,s=o(()=>(n||(r={...r},n=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>Io(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!Io(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(Io(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}o(BR,"enforceDeletedFields");var Ma={era:"2026-07-28",hasRequestMethod:Uh,hasNotificationMethod:qh,hasInputRequestMethod:o(e=>ga(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>vo(jR(e),t),"validateRequest"),validateResult:o((e,t)=>vo(DR(e),t),"validateResult"),validateNotification:o((e,t)=>vo($R(e),t),"validateNotification"),validateInputRequest:o((e,t)=>vo(ga(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>vo(zR(e),t),"validateInputResponse"),samplingResultVariant:o(()=>LR,"samplingResultVariant"),outboundEnvelope(e){return{[xr]:e.protocolVersion,[lo]:e.clientInfo,[Mr]:e.clientCapabilities,...e.logLevel!==void 0&&{[po]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of HR)n in e||t.push({key:n,problem:"missing"});let r=gt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let s=n.path.map(String),i=s.length>0?s.join("."):"_meta";s.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:o(e=>_h(e),"projectCallToolResult"),inputRequestSchema:ga,decodeResult(e,t){if(!Io(t))return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Io(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:gt().ResultMetaSchema.safeParse(t._meta),m=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new le(Se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=zh(),s=Object.hasOwn(n,e)?n[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return PR(kR(e,ER(e,BR(e,t))),r)},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=gt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Ks;function zh(){if(Ks)return Ks;let e=gt();return Ks={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Ks}o(zh,"getWireResultSchemas");function FR(){zh()}o(FR,"warmWireResultSchemas2026");var Ua="2026-07-28";function Eo(e){return e!==void 0&&Sh(e)?Ma:Aa}o(Eo,"codecForVersion");function dh(e){return e.revision!==void 0?Eo(e.revision).era:e.era==="modern"?Ma.era:Aa.era}o(dh,"classifiedWireEra");function ya(e){return Nh.some(t=>t.hasRequestMethod(e))}o(ya,"isSpecRequestMethod");function Sa(e){return Nh.some(t=>t.hasNotificationMethod(e))}o(Sa,"isSpecNotificationMethod");function uh(e){return e==="tasks/get"||e==="tasks/cancel"}o(uh,"isExtensionReusedRequestMethod");var Nh=[Aa,Ma],JR=nh({AnnotationsSchema:o(()=>Ku,"AnnotationsSchema"),AudioContentSchema:o(()=>El,"AudioContentSchema"),BaseMetadataSchema:o(()=>Tu,"BaseMetadataSchema"),BaseRequestParamsSchema:o(()=>pu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:o(()=>Gu,"BlobResourceContentsSchema"),BooleanSchemaSchema:o(()=>Yi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:o(()=>Hl,"CallToolRequestParamsSchema"),CallToolRequestSchema:o(()=>Bl,"CallToolRequestSchema"),CallToolResultSchema:o(()=>$l,"CallToolResultSchema"),CancelTaskRequestSchema:o(()=>zp,"CancelTaskRequestSchema"),CancelTaskResultSchema:o(()=>Np,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:o(()=>bu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:o(()=>vu,"CancelledNotificationSchema"),ClientCapabilitiesSchema:o(()=>Pu,"ClientCapabilitiesSchema"),ClientNotificationSchema:o(()=>Dp,"ClientNotificationSchema"),ClientRequestSchema:o(()=>jp,"ClientRequestSchema"),ClientResultSchema:o(()=>$p,"ClientResultSchema"),ClientTasksCapabilitySchema:o(()=>ku,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:o(()=>Ll,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:o(()=>yp,"CompleteRequestParamsSchema"),CompleteRequestSchema:o(()=>Sp,"CompleteRequestSchema"),CompleteResultSchema:o(()=>_p,"CompleteResultSchema"),ContentBlockSchema:o(()=>xl,"ContentBlockSchema"),CreateMessageRequestParamsSchema:o(()=>np,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:o(()=>op,"CreateMessageRequestSchema"),CreateMessageResultSchema:o(()=>sp,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:o(()=>ip,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:o(()=>Ep,"CreateTaskResultSchema"),CursorSchema:o(()=>cu,"CursorSchema"),DiscoverRequestSchema:o(()=>zu,"DiscoverRequestSchema"),DiscoverResultSchema:o(()=>Wi,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:o(()=>Is,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:o(()=>up,"ElicitRequestParamsSchema"),ElicitRequestSchema:o(()=>lp,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:o(()=>Ts,"ElicitRequestURLParamsSchema"),ElicitResultSchema:o(()=>hp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:o(()=>pp,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:o(()=>mp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:o(()=>Al,"EmbeddedResourceSchema"),EmptyResultSchema:o(()=>Ru,"EmptyResultSchema"),EnumSchemaSchema:o(()=>dp,"EnumSchemaSchema"),GetPromptRequestParamsSchema:o(()=>vl,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:o(()=>Cl,"GetPromptRequestSchema"),GetPromptResultSchema:o(()=>Ml,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:o(()=>Op,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:o(()=>Mp,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:o(()=>Pp,"GetTaskRequestSchema"),GetTaskResultSchema:o(()=>xp,"GetTaskResultSchema"),IconSchema:o(()=>Cu,"IconSchema"),IconsSchema:o(()=>Iu,"IconsSchema"),ImageContentSchema:o(()=>Tl,"ImageContentSchema"),ImplementationSchema:o(()=>Eu,"ImplementationSchema"),InitializeRequestParamsSchema:o(()=>xu,"InitializeRequestParamsSchema"),InitializeRequestSchema:o(()=>Ou,"InitializeRequestSchema"),InitializeResultSchema:o(()=>Uu,"InitializeResultSchema"),InitializedNotificationSchema:o(()=>qu,"InitializedNotificationSchema"),JSONArraySchema:o(()=>iu,"JSONArraySchema"),JSONObjectSchema:o(()=>su,"JSONObjectSchema"),JSONRPCErrorResponseSchema:o(()=>mo,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:o(()=>Ki,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:o(()=>Gi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:o(()=>or,"JSONRPCRequestSchema"),JSONRPCResponseSchema:o(()=>wu,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:o(()=>Vi,"JSONRPCResultResponseSchema"),JSONValueSchema:o(()=>ou,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:o(()=>ea,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:o(()=>Zi,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:o(()=>Rl,"ListPromptsRequestSchema"),ListPromptsResultSchema:o(()=>bl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:o(()=>Qu,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:o(()=>el,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:o(()=>Yu,"ListResourcesRequestSchema"),ListResourcesResultSchema:o(()=>Xu,"ListResourcesResultSchema"),ListRootsRequestSchema:o(()=>Rp,"ListRootsRequestSchema"),ListRootsResultSchema:o(()=>bp,"ListRootsResultSchema"),ListTasksRequestSchema:o(()=>Up,"ListTasksRequestSchema"),ListTasksResultSchema:o(()=>qp,"ListTasksResultSchema"),ListToolsRequestSchema:o(()=>jl,"ListToolsRequestSchema"),ListToolsResultSchema:o(()=>Dl,"ListToolsResultSchema"),LoggingLevelSchema:o(()=>Jl,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:o(()=>Kl,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:o(()=>Wl,"LoggingMessageNotificationSchema"),ModelHintSchema:o(()=>Zl,"ModelHintSchema"),ModelPreferencesSchema:o(()=>Yl,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:o(()=>cp,"MultiSelectEnumSchemaSchema"),NotificationSchema:o(()=>gu,"NotificationSchema"),NotificationsParamsSchema:o(()=>fu,"NotificationsParamsSchema"),NumberSchemaSchema:o(()=>Cs,"NumberSchemaSchema"),PaginatedRequestParamsSchema:o(()=>Lu,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:o(()=>Hu,"PaginatedRequestSchema"),PaginatedResultSchema:o(()=>Bu,"PaginatedResultSchema"),PingRequestSchema:o(()=>Nu,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:o(()=>na,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:o(()=>Du,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:o(()=>$u,"ProgressNotificationSchema"),ProgressSchema:o(()=>ju,"ProgressSchema"),ProgressTokenSchema:o(()=>au,"ProgressTokenSchema"),PromptArgumentSchema:o(()=>_l,"PromptArgumentSchema"),PromptListChangedNotificationSchema:o(()=>Ul,"PromptListChangedNotificationSchema"),PromptMessageSchema:o(()=>Ol,"PromptMessageSchema"),PromptReferenceSchema:o(()=>gp,"PromptReferenceSchema"),PromptSchema:o(()=>wl,"PromptSchema"),ReadResourceRequestParamsSchema:o(()=>rl,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:o(()=>nl,"ReadResourceRequestSchema"),ReadResourceResultSchema:o(()=>ol,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:o(()=>uu,"RelatedTaskMetadataSchema"),RequestIdSchema:o(()=>_u,"RequestIdSchema"),RequestMetaSchema:o(()=>lu,"RequestMetaSchema"),RequestSchema:o(()=>hu,"RequestSchema"),ResourceContentsSchema:o(()=>Fu,"ResourceContentsSchema"),ResourceLinkSchema:o(()=>Pl,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:o(()=>sl,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:o(()=>tl,"ResourceRequestParamsSchema"),ResourceSchema:o(()=>Wu,"ResourceSchema"),ResourceTemplateReferenceSchema:o(()=>fp,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:o(()=>Zu,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:o(()=>yl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:o(()=>Sl,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:o(()=>yu,"ResultMetaObjectSchema"),ResultSchema:o(()=>Su,"ResultSchema"),RoleSchema:o(()=>Vu,"RoleSchema"),RootSchema:o(()=>wp,"RootSchema"),RootsListChangedNotificationSchema:o(()=>vp,"RootsListChangedNotificationSchema"),SamplingContentSchema:o(()=>ep,"SamplingContentSchema"),SamplingMessageContentBlockSchema:o(()=>tp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:o(()=>rp,"SamplingMessageSchema"),ServerCapabilitiesSchema:o(()=>Mu,"ServerCapabilitiesSchema"),ServerNotificationSchema:o(()=>Hp,"ServerNotificationSchema"),ServerRequestSchema:o(()=>Lp,"ServerRequestSchema"),ServerResultSchema:o(()=>Bp,"ServerResultSchema"),ServerTasksCapabilitySchema:o(()=>Au,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:o(()=>Gl,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:o(()=>Vl,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:o(()=>ap,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:o(()=>vs,"StringSchemaSchema"),SubscribeRequestParamsSchema:o(()=>il,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:o(()=>al,"SubscribeRequestSchema"),SubscriptionFilterSchema:o(()=>ul,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:o(()=>ml,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:o(()=>hl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:o(()=>ll,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:o(()=>pl,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:o(()=>fl,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:o(()=>gl,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:o(()=>mu,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:o(()=>Cp,"TaskCreationParamsSchema"),TaskMetadataSchema:o(()=>du,"TaskMetadataSchema"),TaskSchema:o(()=>Tp,"TaskSchema"),TaskStatusNotificationParamsSchema:o(()=>kp,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:o(()=>Ap,"TaskStatusNotificationSchema"),TaskStatusSchema:o(()=>Ip,"TaskStatusSchema"),TextContentSchema:o(()=>Il,"TextContentSchema"),TextResourceContentsSchema:o(()=>Ju,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:o(()=>ra,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:o(()=>Qi,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:o(()=>ql,"ToolAnnotationsSchema"),ToolChoiceSchema:o(()=>Xl,"ToolChoiceSchema"),ToolExecutionSchema:o(()=>zl,"ToolExecutionSchema"),ToolListChangedNotificationSchema:o(()=>Fl,"ToolListChangedNotificationSchema"),ToolResultContentSchema:o(()=>Ql,"ToolResultContentSchema"),ToolSchema:o(()=>Nl,"ToolSchema"),ToolUseContentSchema:o(()=>kl,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:o(()=>cl,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:o(()=>dl,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:o(()=>ta,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:o(()=>Xi,"UntitledSingleSelectEnumSchemaSchema")});var jh=o(e=>or.safeParse(e).success,"isJSONRPCRequest"),Dh=o(e=>Gi.safeParse(e).success,"isJSONRPCNotification"),va=o(e=>Vi.safeParse(e).success,"isJSONRPCResultResponse"),$h=o(e=>mo.safeParse(e).success,"isJSONRPCErrorResponse");var To=-32020,DM=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[P.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[To,P.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[P.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[P.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[P.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[To],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[P.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[To],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],$M={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[To]:400};function qa(e,t){return Zd(e,t)}o(qa,"parseSchema");function Co(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}o(Co,"shapeKeys");function Ca(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}o(Ca,"isStandardSchema");var lh=!1,Ia="draft-2020-12";function GR(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Ia});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");lh||(lh=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=Hi(e,{target:Ia,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Lh(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}o(GR,"standardSchemaToJsonSchema");function Lh(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Lh(n)))}return!1}o(Lh,"isProvablyObjectShapedRoot");function VR(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(VR,"formatIssue");async function _a(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>VR(n)).join(", ")}:{success:!0,data:r.value}}o(_a,"validateStandardSchema");function KR(e){let t=Hi(e,{target:Ia,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(KR,"zodEmittedPattern");var WR=/\\\.\\d\{(\d+)\}/;function ZR(e){let t=WR.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(s=>r.map(i=>uo.datetime({local:n,offset:s,precision:i}))))}o(ZR,"datetimeReferenceSchemas");function YR(e,t){let r;switch(e){case"email":r=[Yd()];break;case"uri":r=[Xd()];break;case"date":r=[uo.date()];break;case"date-time":r=ZR(t);break}return new Set(r.map(n=>KR(n)).filter(n=>n!==void 0))}o(YR,"referencePatternsForFormat");function XR(e,t,r){return r!=="zod"?!0:YR(e,t).has(t)}o(XR,"isLibraryFormatPattern");function ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(ko,"isJsonObject");function QR(e){try{return GR(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new _e(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}o(QR,"convertStandardElicitationSchema");var eb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function za(e){return eb.has(e)||e.startsWith("x-")}o(za,"isAnnotationOnlyJsonSchemaKeyword");var tb=new Set(["$schema",...Object.keys(Is.shape.requestedSchema.shape)]),ph={string:Co([vs,Xi,Qi,ea]),number:Co([Cs]),integer:Co([Cs]),boolean:Co([Yi]),array:Co([ta,ra])},rb=new Set(vs.shape.format.unwrap().options);function nb(e,t,r,n){if(!ko(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(ph,e.type)?ph[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||za(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?rb.has(e.format)?(typeof c!="string"||!XR(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(nb,"walkProperty");function ob(e,t){let r={},n=[];for(let[s,i]of Object.entries(e))s==="properties"&&ko(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,nb(c,`properties.${a}`,t,n)])):tb.has(s)?r[s]=i:za(s)||n.push(s);if(n.length>0)throw new _e(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}o(ob,"walkRequestedSchema");function sb(e,t){if(!ko(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!qa(na,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}o(sb,"describeUnsupportedProperties");function Ta(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,s)=>Ta(n,t[s],`${r}[${s}]`)):!ko(e)||!ko(t)?[]:Object.entries(e).flatMap(([n,s])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Ta(s,t[n],i):za(n)?[]:[i]})}o(Ta,"findDroppedConstraintPaths");function ib(e){if(!Ca(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=ob(QR(e.requestedSchema),t),n=qa(Is.shape.requestedSchema,r);if(!n.success)throw new _e(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${sb(r,n.error.message)}`);let s=Ta(r,n.data);if(s.length>0)throw new _e(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new _e(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}o(ib,"normalizeElicitInputParams");function ab(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}o(ab,"buildInputRequired");var LM=Object.assign(ab,{elicit(e){try{return{method:"elicitation/create",params:ib(e)}}catch(t){throw t instanceof _e?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var cb=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],db={IdJagTokenExchangeResponseSchema:oa,OAuthClientInformationFullSchema:sr,OAuthClientInformationSchema:ho,OAuthClientMetadataSchema:Jp,OAuthClientRegistrationErrorSchema:Gp,OAuthErrorResponseSchema:Es,OAuthMetadataSchema:qr,OAuthProtectedResourceMetadataSchema:Ur,OAuthTokenRevocationRequestSchema:Vp,OAuthTokensSchema:Pt,OpenIdProviderDiscoveryMetadataSchema:zr,OpenIdProviderMetadataSchema:Fp},Hh={},Bh={};function Fh(e,t){let r=e.slice(0,-6);Hh[r]=t,Bh[r]=n=>t.safeParse(n).success}o(Fh,"register");for(let e of cb)Fh(e,JR[e]);for(let[e,t]of Object.entries(db))Fh(e,t);var ub=Object.freeze(Hh),lb=Object.freeze(Bh);function pb(e){switch(e){case"initialize":case"notifications/initialized":return Eo(void 0);case"server/discover":return Eo(Ua);default:return}}o(pb,"bootstrapOutboundCodec");var Jh=6e4,mb=[xr,lo,Mr,po],hb=["inputResponses","requestState"];function mh(e,t){let r=e.params;if(!wa(r))return{message:e,lifted:{}};let n=r._meta,s=wa(n)?mb.filter(d=>d in n):[],i=t==="request"?hb.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&wa(n)){let d={},u={...n};for(let m of s)d[m]=n[m],delete u[m];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}o(mh,"liftWireOnlyMaterial");function hh(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let s=e.validateResult(t,n);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}o(hh,"codecResultValidator");function Gh(e){return()=>e}o(Gh,"requestStateAccessor");var fb=Gh(void 0),gb,yb=class{static{o(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{gb=o((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ji,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(Se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),va(s)||$h(s)?this._onresponse(s):jh(s)?this._onrequest(s,i):Dh(s)?this._onnotification(s,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(Se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=mh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=dh(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(Sa(r.method)&&!n.hasNotificationMethod(r.method))return;let s=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;s===void 0&&i===void 0||Promise.resolve().then(()=>s===void 0?i(r):s(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=mh(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=o((_,y,b)=>{let I={jsonrpc:"2.0",id:r.id,error:{code:_,message:y,...b!==void 0&&{data:b}}};i?.send(I).catch(A=>this._onerror(new Error(`Failed to send an error response: ${A}`)))},"sendErrorResponse");if(t?.classification!==void 0){let _=dh(t.classification);if(_!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${_} but this instance serves ${s.era}`));let y=t.classification.revision??_;a(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(ya(r.method)&&!s.hasRequestMethod(r.method)&&!(uh(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(P.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(P.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(n);if(d!==void 0){a(P.InvalidParams,d);return}let u=o((_,y)=>this._notificationViaCodec(this._resolveOutboundCodec(_.method),_,{...y,relatedRequestId:r.id}),"sendNotification"),m=o((_,y,b)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(_.method),_,y,{...b,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:Sb(n.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:n.requestState===void 0?fb:Gh(n.requestState),signal:h.signal,send:o(((_,y,b)=>{let I=this._resolveOutboundCodec(_.method);if(this._assertOutboundRequestInEra(I,_.method),Ca(y))return m(_,y,b);let A=hh(I,_.method);if(A===void 0)throw new TypeError(`'${_.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(_,A,y)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},R=this.buildContext(S,t);Promise.resolve().then(()=>c(r,R)).then(async _=>{if(h.signal.aborted)return;let y;try{y=s.encodeResult(r.method,_,this._outboundServerInfo())}catch(I){this._onerror(new Error(`Failed to encode result for ${r.method}: ${I}`)),a(P.InternalError,"Internal error");return}let b={result:y,jsonrpc:"2.0",id:r.id};await i?.send(b)},async _=>{if(h.signal.aborted)return;let y=Number.isSafeInteger(_.code)?_.code:P.InternalError,b={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(y),message:_.message??"Internal error",..._.data!==void 0&&{data:_.data}}};await i?.send(b)}).catch(_=>this._onerror(new Error(`Failed to send response: ${_}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),va(e)?r(e):r(_e.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(Ca(t))return uh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=hh(n,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,s,t)}_negotiatedWireCodec(){return Eo(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=pb(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(ya(t)&&!e.hasRequestMethod(t))throw new le(Se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},d=Date.now(),u,m;return new Promise((h,f)=>{let S=o(O=>{f(O)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(O){S(O);return}if(n?.signal?.aborted){let O=n.signal.reason;throw O instanceof le?O:new le(Se.RequestTimeout,String(O))}let R=e.era===Ua&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;m=_;let y={...t,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:_}});let b=this._envelopeOutbound(y),I=!1,A=o(O=>{I||(this._progressHandlers.delete(_),R===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(O)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`))):R.abort(),f(O instanceof le?O:new le(Se.RequestTimeout,String(O))))},"cancel");this._responseHandlers.set(_,O=>{if(n?.signal?.aborted)return;if(I=!0,O instanceof Error)return f(O);let Z;try{Z=e.decodeResult(t.method,O.result)}catch(x){return f(x instanceof Error?x:new Error(String(x)))}if(Z.kind==="invalid")return f(Z.error);if(Z.kind==="input_required"){if(n?.allowInputRequired===!0)return h(_b(Z));let x={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:d,retry:o((B,j)=>this._requestWithSchemaViaCodec(e,B===void 0?{method:t.method}:{method:t.method,params:B},r,j),"retry")};return h(this._resolveNonCompleteResult(Z,x))}let re=Z.result;_a(r,re).then(x=>{x.success?h(x.data):f(new le(Se.InvalidResult,`Invalid result for ${t.method}: ${x.error}`))},f)}),u=o(()=>A(n?.signal?.reason),"onAbort"),n?.signal?.addEventListener("abort",u,{once:!0});let v=n?.timeout??Jh,Y=o(()=>A(new le(Se.RequestTimeout,"Request timed out",{timeout:v})),"timeoutHandler");this._setupTimeout(_,v,n?.maxTotalTimeout,Y,n?.resetTimeoutOnProgress??!1),this._transport.send(b,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:R?.signal}).catch(O=>{this._progressHandlers.delete(_),f(O)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(Se.NotConnected,"Not connected");if(Sa(t.method)&&!e.hasNotificationMethod(t.method))throw new le(Se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(s=>this._onerror(s))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!ya(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=o((s,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,s);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,s)),!c.ok)throw c.reason==="not-in-era"?new _e(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)n=o(async(s,i)=>{let a=await _a(t.params,{...s.params});if(!a.success)throw new _e(P.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!Sa(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,s)=>{let i=s.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new _e(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let s=await _a(t.params,{...n.params});if(!s.success)throw new _e(P.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function wa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(wa,"isPlainObject$1");function fh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(fh,"isPlainObject");function Sb(e){let t={},r=[];if(!fh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!fh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(Sb,"partitionInputResponses");function _b(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(_b,"manualInputRequiredValue");var wb=rh((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(c){if(!c)throw new TypeError("argument string is required");var d=typeof c=="object"?i(c):c;if(typeof d!="string")throw new TypeError("argument string is required to be a string");var u=d.indexOf(";"),m=u!==-1?d.slice(0,u).trim():d.trim();if(!n.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(u!==-1){var f,S,R;for(t.lastIndex=u;S=t.exec(d);){if(S.index!==u)throw new TypeError("invalid parameter format");u+=S[0].length,f=S[1].toLowerCase(),R=S[2],R.charCodeAt(0)===34&&(R=R.slice(1,-1),R.indexOf("\\")!==-1&&(R=R.replace(r,"$1"))),h.parameters[f]=R}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}o(s,"parse");function i(c){var d;if(typeof c.getHeader=="function"?d=c.getHeader("content-type"):typeof c.headers=="object"&&(d=c.headers&&c.headers["content-type"]),typeof d!="string")throw new TypeError("content-type header is missing from object");return d}o(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}o(a,"ContentType")})),HM=oh(wb(),1);var Rb=10*1024*1024;var bb=new Set([301,302,303,307,308]),vb=5;function Cb(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}o(Cb,"isWithinOrigin");function Ib(e,t){let r=bb.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Ib,"redirectTarget");var Tb=new WeakSet;function Xs(e){return Tb.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let n=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Ib(s,a);if(!c||i===vb)return a;let d=new URL(s),u=n==="GET"||a.status===307||a.status===308,m=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!m||!Cb(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(Xs,"fetchWithinOrigin");function Na(){ka(),gt(),hR(),qR(),FR()}o(Na,"preloadSchemas");var e0=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var Eb=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,kb=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ab=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Pb=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,xb=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Ob=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Mb=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Ub=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,qb=/^(?:\/(?:[^~/]|~0|~1)*)*$/,zb=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Nb=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,jb=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),Db=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,$b=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Lb=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function st(e){return e.test.bind(e)}o(st,"bind");var t0={date:Vh,time:Kh.bind(void 0,!1),"date-time":Fb,duration:Lb,uri:Vb,"uri-reference":st(xb),"uri-template":st(Ob),url:st(Mb),email:jb,hostname:st(Pb),ipv4:st(Db),ipv6:st($b),regex:Wb,uuid:st(Ub),"json-pointer":st(qb),"json-pointer-uri-fragment":st(zb),"relative-json-pointer":st(Nb)};function Hb(e){return e%4===0&&(e%100!==0||e%400===0)}o(Hb,"isLeapYear");function Vh(e){let t=e.match(Eb);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&Hb(r)?29:kb[n])}o(Vh,"date");function Kh(e,t){let r=t.match(Ab);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!e||a)}o(Kh,"time");var Bb=/t|\s/i;function Fb(e){let t=e.split(Bb);return t.length==2&&Vh(t[0])&&Kh(!0,t[1])}o(Fb,"date_time");var Jb=/\/|:/,Gb=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Vb(e){return Jb.test(e)&&Gb.test(e)}o(Vb,"uri");var Kb=/[^\\]\\Z/;function Wb(e){if(Kb.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(Wb,"regex");Na();var Wh=!1;var ja;ja=globalThis.crypto;async function Yb(e){return(await ja).getRandomValues(new Uint8Array(e))}o(Yb,"getRandomValues");async function Xb(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await Yb(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(Xb,"random");async function Qb(e){return await Xb(e)}o(Qb,"generateVerifier");async function ev(e){let t=await(await ja).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(ev,"generateChallenge");async function Da(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Qb(e),r=await ev(t);return{code_verifier:t,code_challenge:r}}o(Da,"pkceChallenge");var Po=class extends Error{static{o(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e),this.name=new.target.name,dr(this,new.target)}},Ao=class extends Po{static{o(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},Fa=class extends Po{static{o(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},ti=class extends Po{static{o(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},ei=class extends Po{static{o(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},F0=class extends Po{static{o(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Ba(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Qh(e.issuer,t)?e:void 0}o(Ba,"discardIfIssuerMismatch");function Qh(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(Qh,"issuersMatch");var J0=class extends Error{static{o(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",dr(this,new.target)}};function ef(e){return e?.authorization_response_iss_parameter_supported===!0}o(ef,"isIssParameterSupported");function tf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Ao("authorization_response",t,void 0);return}if(e!==t)throw new Ao("authorization_response",t,e)}}o(tf,"validateAuthorizationResponseIssuer");function tv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(tv,"isClientAuthMethod");var $a="code",La="S256";function rv(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&tv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(rv,"selectClientAuthMethod");function nv(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":ov(s,i,r);return;case"client_secret_post":sv(s,i,n);return;case"none":iv(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(nv,"applyClientAuthentication");function ov(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(ov,"applyBasicAuth");function sv(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(sv,"applyPostAuth");function iv(e,t){t.set("client_id",e)}o(iv,"applyPublicAuth");function rf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(rf,"isLoopbackHost");function av(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!rf(t.hostname))throw new ti(t.href);return t}o(av,"assertSecureTokenEndpoint");function cv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||rf(r.hostname))return"native"}return"web"}o(cv,"deriveApplicationType");function dv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??cv(t.redirect_uris)}}o(dv,"resolveClientMetadata");async function Zh(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Es.parse(JSON.parse(r));return Ut.fromResponse(n)}catch(n){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Ut(me.ServerError,s)}}o(Zh,"parseErrorResponse");function Yh(e,t,r){let n=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`}o(Yh,"warnCredentialInvalidation");async function Ja(e,t){try{return await Ha(e,t)}catch(r){if(r instanceof Ut){if(r.code===me.InvalidClient||r.code===me.UnauthorizedClient)return Yh(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Ha(e,t);if(r.code===me.InvalidGrant||r.code===me.InvalidDpopProof)return Yh(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Ha(e,t)}throw r}}o(Ja,"auth");function uv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}o(uv,"determineScope");async function Ha(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=dv(e),m=await e.discoveryState?.(),h,f,S,R,_=i;if(!_&&m?.resourceMetadataUrl&&(_=new URL(m.resourceMetadataUrl)),m?.authorizationServerUrl){if(f=m.authorizationServerUrl,h=m.resourceMetadata,S=m.authorizationServerMetadata??await af(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await of(t,{resourceMetadataUrl:_},a)}catch(X){if(X instanceof TypeError)throw X}(S!==m.authorizationServerMetadata||h!==m.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S})}else{let X=await yv(t,{resourceMetadataUrl:_,fetchFn:a,skipIssuerMetadataValidation:c});f=X.authorizationServerUrl,S=X.authorizationServerMetadata,h=X.resourceMetadata,R={authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S}}let y=S?.issuer??String(f),b={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),r!==void 0){let X=m?.authorizationServerMetadata?.issuer??m?.authorizationServerUrl;if(X===void 0){if(e.saveDiscoveryState!==void 0)throw new ei("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Qh(X,y))throw new ei(X,y)}R&&await e.saveDiscoveryState?.(R);let I=await lv(t,e,h),A=I&&h&&!e.validateResourceURL?h.resource:I;A&&await e.saveResourceUrl?.(Va(A));let v=uv({requestedScope:s,resourceMetadata:h,authServerMetadata:S,clientMetadata:e.clientMetadata}),Y=await Promise.resolve(e.clientInformation(b)),O=Ba(Y,y,{canPersistStamp:e.saveClientInformation!==void 0});if(O===void 0&&Y?.issuer&&e.saveClientInformation===void 0)throw new ei(Y.issuer,y);if(O&&O.issuer===void 0&&(O={...O,issuer:y},await e.saveClientInformation?.(O,b)),!O){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let X=S?.client_id_metadata_document_supported===!0,te=e.clientMetadataUrl;if(te&&!Ga(te))throw new Ut(me.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${te}`);if(X&&te)O={client_id:te,issuer:y},await e.saveClientInformation?.(O,b);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");O={...await bv(f,{metadata:S,clientMetadata:u,scope:v,fetchFn:a}),issuer:y},await e.saveClientInformation(O,b)}}let Z=!e.redirectUrl;if(r!==void 0||Z){r!==void 0&&tf({iss:n,expectedIssuer:S?.issuer,issParameterSupported:ef(S)});let X=await Rv(e,f,{metadata:S,resource:A,authorizationCode:r,iss:n,scope:v,fetchFn:a});return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let re=Ba(await e.tokens(b),y);if(re&&re.issuer===void 0&&(re={...re,issuer:y},await e.saveTokens(re,b)),re?.refresh_token&&!d){let X;try{X=await wv(f,{metadata:S,clientInformation:O,refreshToken:re.refresh_token,resource:A,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(te){if(te instanceof ti||!(!(te instanceof Ut)||te.code===me.ServerError))throw te}if(X)return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let x=e.state?await e.state():void 0,{authorizationUrl:B,codeVerifier:j}=await Sv(f,{metadata:S,clientInformation:O,state:x,redirectUrl:e.redirectUrl,scope:v,resource:A});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(B),"REDIRECT"}o(Ha,"authInternal");function Ga(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Ga,"isHttpsUrl");async function lv(e,t,r){let n=yh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Ws({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(lv,"selectResourceURL");var pv=new Set(["bearer","dpop"]);function nf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!pv.has(r.toLowerCase())||!n)return{};let s=Qs(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=Qs(e,"scope")||void 0,c=Qs(e,"error")||void 0,d=Qs(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}o(nf,"extractWWWAuthenticateParams");function Qs(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(n);if(s){let i=s[1]||s[2];if(i)return i}return null}o(Qs,"extractFieldFromWwwAuth");async function of(e,t,r=fetch){let n=await fv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Ur.parse(await n.json())}o(of,"discoverOAuthProtectedResourceMetadata");async function sf(e,t,r=fetch){let n=Xs(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Wh)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(sf,"fetchWithCorsRetry");function mv(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(mv,"buildWellKnownPath");async function Xh(e,t,r=fetch){return await sf(e,{"MCP-Protocol-Version":t},r)}o(Xh,"tryMetadataDiscovery");function hv(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(hv,"shouldAttemptFallback");async function fv(e,t,r,n){let s=new URL(e),i=n?.protocolVersion??bs,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let d=mv(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await Xh(a,i,r);return!n?.metadataUrl&&hv(c,s.pathname)&&(c=await Xh(new URL(`/.well-known/${t}`,s),i,r)),c}o(fv,"discoverMetadataWithFallback");function gv(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"},{url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(gv,"buildDiscoveryUrls");async function af(e,{fetchFn:t=fetch,protocolVersion:r=bs,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=gv(e);for(let{url:a,type:c}of i){let d=await sf(a,s,t);if(!d)continue;if(!d.ok){if(await d.text?.().catch(()=>{}),d.status<500||d.status===502)continue;throw new Error(`HTTP ${d.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=c==="oauth"?qr.parse(await d.json()):zr.parse(await d.json());if(!n){let m=typeof e=="string"?e:e.href;if(!(u.issuer===m||m.endsWith("/")&&u.issuer===m.slice(0,-1)))throw new Ao("metadata",m,u.issuer)}return u}}o(af,"discoverAuthorizationServerMetadata");async function yv(e,t){let r,n;try{r=await of(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let s=await af(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(yv,"discoverOAuthServerInfo");function Va(e){return typeof e=="string"?e:e.href}o(Va,"resourceIndicatorToString");async function Sv(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes($a))throw new Error(`Incompatible auth server: does not support response type ${$a}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(La))throw new Error(`Incompatible auth server: does not support code challenge method ${La}`)}else c=new URL("/authorize",e);let d=await Da(),u=d.code_verifier,m=d.code_challenge;return c.searchParams.set("response_type",$a),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",La),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),s&&c.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",Va(a)),{authorizationUrl:c,codeVerifier:u}}o(Sv,"startAuthorization");function _v(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(_v,"prepareAuthorizationCodeRequest");async function cf(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=av(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",Va(i)),!s&&n&&nv(rv(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let m=o(async()=>{let S=new Headers(u);return s&&await s(S,r,d,t),a&&S.set("DPoP",await a.buildProof({htm:"POST",htu:d})),Xs(c??fetch)(d,{method:"POST",headers:S,body:r})},"requestOnce"),h=await m();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===me.UseDpopNonce&&(a.observeNonce(h,d),h=await m()),a?.observeNonce(h,d),!h.ok)throw await Zh(h);let f=await h.json();try{return Pt.parse(Ea(f))}catch(S){throw typeof f=="object"&&f!==null&&"error"in f?await Zh(JSON.stringify(f)):S}}o(cf,"executeTokenRequest");async function wv(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await cf(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(wv,"refreshAuthorization");async function Rv(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&tf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:ef(r)});let d=r?.issuer??String(t),u=o(async()=>{let S=await e.clientInformation({issuer:d}),R=Ba(S,d,{canPersistStamp:!1});if(S&&R===void 0)throw new ei(String(S.issuer),d);return R},"readClientInformation"),m=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=_v(s,await e.codeVerifier(),e.redirectUrl)}return m??=await u(),cf(t,{metadata:r,tokenRequestParams:f,clientInformation:m,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(Rv,"fetchToken");async function bv(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:s}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},c=await Xs(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new Fa({status:c.status,body:await c.text(),submittedMetadata:a});return sr.parse(Ea(await c.json()))}o(bv,"registerClient");var G0=class extends Error{static{o(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,dr(this,new.target)}};function Me(e){let t=or.safeParse(e);return t.success?t.data.id:void 0}o(Me,"parseJsonRpcRequestId");function Ka(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Me(t)}catch{return}}o(Ka,"readJsonRpcRequestIdFromBody");function yt(e){return mo.parse({jsonrpc:nr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}o(yt,"jsonRpcErrorResponse");function df(e){return new Ys([Ts.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o(df,"urlElicitationRequiredError");function it(e){return(e??"").split(";")[0].trim().toLowerCase()}o(it,"mediaTypeEssence");var vv=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function St(e){for(let t of vv)e.delete(t);return e}o(St,"deleteEncodedBodyHeaders");function uf(){let e=gs.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(uf,"currentRuntime");var Cv=new Set(["gzip","x-gzip","deflate","br","zstd"]);function at(e,t=uf()){let r=e.get("content-encoding")?.trim();if(!r||r.toLowerCase()==="identity")return!1;switch(t){case"deno":return!0;case"workerd":return r!=="gzip"&&r!=="br";default:return!r.toLowerCase().split(",").every(n=>Cv.has(n.trim()))}}o(at,"isBodyStillEncoded");function lf(e){return at(e)?e:St(e)}o(lf,"deleteEncodedBodyHeadersIfDecoded");function pf(e,t=uf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?at(e,t):e.has("content-length"))?e:St(e)}o(pf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var hf=10*1024*1024,Iv=1024,Tv=32,Ev=64,ur=class extends Error{constructor(r,n=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=n;this.name="SseEventTooLargeError"}maxEventChars;comment;static{o(this,"SseEventTooLargeError")}},kv=10;function Av(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o(Av,"handleRejection");function ff(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(ff,"fieldName");var xo=class{static{o(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#l=!1;#p=/\r\n|\r|\n/g;#m="";#d=[];#o=[];#i=0;#a=!1;#u=!1;#h=!1;#s=!1;#f=!1;#S=0;#C=0;#c=[];#g=0;#y=[];#_;#w;#R;#b=[];constructor(t={}){let r=t.maxEventChars??hf;if(!Number.isInteger(r)||r<=0)throw new RangeError(`maxEventChars must be a positive integer, got ${r}`);this.#e=r,this.#r=t.onOversize==="discard",this.#t=t.emitLoneComments===!0}get discardedEvents(){return this.#S}get discardedComments(){return this.#C}get discarding(){return this.#s||this.#f}get idle(){return this.#i===0&&!this.#a&&!this.#s&&this.#c.length===0}push(t){let r=[];return this.#T(this.#I(this.#n.decode(t,{stream:!0})),r),r}end(){let t=[];return this.#T(this.#I(this.#n.decode()),t),(this.#i>0||this.#a)&&this.#A(t,!1),this.#s||this.#P(t,!1),this.#s=!1,t}#I(t){return this.#l||t===""?t:(this.#l=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let n=0;this.#h&&(this.#h=!1,t.charCodeAt(0)===kv&&(n=1));let s=this.#p;s.lastIndex=n;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(n,i.index)),this.#A(r),n=i.index+i[0].length,i[0]==="\r"&&n===t.length&&(this.#h=!0),i=s.exec(t);this.#E(t.slice(n))}#E(t){if(t!==""){if(this.#s||this.#f){this.#a=!0;return}if(this.#i===0?this.#m=t:(this.#o.push(t),this.#o.length>=Ev&&(this.#d.push(this.#o.join("")),this.#o=[])),this.#i+=t.length,this.#g+this.#i>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#f=!0,this.#S++,this.#C++):this.#k(r),this.#a=!0}}}#O(){return this.#t&&this.#c.length===0&&this.#m.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new ur(this.#e,t);this.#x(),this.#u=!1,this.#v(),this.#s=!0,this.#S++}#v(){this.#m="",this.#d.length>0&&(this.#d=[]),this.#o.length>0&&(this.#o=[]),this.#i=0}#A(t,r=!0){let n=this.#d.length===0&&this.#o.length===0?this.#m:this.#m+this.#d.join("")+this.#o.join(""),s=n===""&&!this.#a;if(this.#v(),this.#a=!1,this.#f){this.#f=!1,this.#u=!0;return}if(s){this.#s?this.#s=!1:this.#u&&this.#c.length===0?(this.#u=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#u=!1,this.#P(t,!0));return}if(this.#s)return;if(this.#t&&r&&this.#c.length===0&&n.charCodeAt(0)===58){t.push({lines:[n],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[n.slice(1)],terminated:!0,lone:!0}),this.#u=!0;return}if(this.#g+=n.length,this.#c.push(n),this.#c.length>Iv&&(this.#g+=Math.max(0,Tv-n.length),this.#g>this.#e)){this.#k();return}if(n.charCodeAt(0)===58){this.#b.push(n.slice(1));return}let i=n.indexOf(":"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#y.push(c);break;case"event":this.#_=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#R=Number(c));break;default:break}}#P(t,r){this.#c.length>0&&t.push({lines:this.#c,data:this.#y.length>0?this.#y.join(`
26
+ `):void 0,event:this.#_,id:this.#w,retry:this.#R,comments:this.#b,terminated:r}),this.#x()}#x(){this.#c=[],this.#g=0,this.#y=[],this.#_=void 0,this.#w=void 0,this.#R=void 0,this.#b=[]}};function Wa(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}o(Wa,"assertSingleLine");function Za(e){if("lines"in e){for(let n of e.lines){if(/[\r\n]/.test(n))throw new TypeError("SSE event line must not contain a line break");if(n==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(n=>`${n}
27
27
  `).join("");return e.lines[0]?.charCodeAt(0)===65279&&(r=`
28
28
  ${r}`),e.terminated?`${r}
29
- `:r}let t="";for(let r of e.comments??[])Ya("comment",r),t+=`:${r}
30
- `;if(e.event!==void 0&&(Ya("event",e.event),t+=`event: ${e.event}
31
- `),e.id!==void 0){if(Ya("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
29
+ `:r}let t="";for(let r of e.comments??[])Wa("comment",r),t+=`:${r}
30
+ `;if(e.event!==void 0&&(Wa("event",e.event),t+=`event: ${e.event}
31
+ `),e.id!==void 0){if(Wa("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
32
32
  `}if(e.retry!==void 0){if(!Number.isSafeInteger(e.retry)||e.retry<0)throw new TypeError("SSE retry must be a non-negative integer");t+=`retry: ${e.retry}
33
33
  `}if(e.data!==void 0)for(let r of e.data.split(/\r\n|\r|\n/))t+=`data: ${r}
34
34
  `;return t===""?"":`${t}
35
- `}o(Xa,"serializeSseEvent");var Hv=new Set(["data","event","id","retry"]);function yf(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!Hv.has(gf(t)))}o(yf,"hasUnknownSseFields");function qo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>gf(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
36
- `)}}o(qo,"replaceSseData");var Sf=Symbol("sse.terminate");function ec(...e){return{[Sf]:!0,events:e}}o(ec,"terminateSse");function Bv(e){return typeof e=="object"&&e!==null&&Sf in e}o(Bv,"isTerminate");var Fv=64,hf=new Uint8Array(0),Qa=class{static{o(this,"SseRawEventBytes")}#e=hf;#r=0;#t=[];#n=0;get length(){return this.#r+this.#n}get views(){return this.#t.length}push(t){t.length!==0&&(this.#t.push(t),this.#n+=t.length,this.#t.length>=Fv&&this.#l())}take(){let t;return this.#r===0?t=Kv(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=hf,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#l(){let t=this.#r+this.#n;if(t>this.#e.length){let r=new Uint8Array(Math.max(t,this.#e.length*2));r.set(this.#e.subarray(0,this.#r)),this.#e=r}for(let r of this.#t)this.#e.set(r,this.#r),this.#r+=r.length;this.#t=[],this.#n=0}},Uo=10,ai=13,Jv=[239,187,191];function Vv(e){let t=[],r=0;for(let n=0;n<e.length;n++){let s=e[n];(s===Uo||s===ai&&e[n+1]!==Uo)&&(t.push(e.subarray(r,n+1)),r=n+1)}return r<e.length&&t.push(e.subarray(r)),t}o(Vv,"splitLines");function Gv(e){let t=e[e.length-1];return t===Uo||t===ai}o(Gv,"endsLine");function tc(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??ff,a=new Mo(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,u={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},m=e.getReader(),h=!1,f=!1,S=0,R=new Qa,_=0,y=!1,b,I,U=o(P=>{h=!0,d.abort(P),m.cancel(P).catch(()=>{})},"stop"),v=o((P,B)=>{try{$v(r.onFailure?.(P,B),()=>{})}catch{}},"report"),Y=o(P=>{v(P,{mode:n,kind:"oversize",...P.comment?{comment:!0}:{}})},"reportOversize"),x=o(P=>{if(!("lines"in P))return Xa(P);if(P.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return P.lone===!0&&P.lines.length>0&&P.lines.every(B=>B.charCodeAt(0)===58)?Xa({...P,terminated:!1}):Xa(P)},"write"),Z=o((P,B)=>Bv(P)?{text:P.events.map(x).join(""),terminate:!0}:P===void 0?{text:B===void 0?"":x(B),terminate:!1}:P===null?{text:"",terminate:!1}:{text:(Array.isArray(P)?P:[P]).map(x).join(""),terminate:!1},"render"),re=o(P=>{if(!s)try{return a.push(P).map(j=>({event:j}))}catch(j){throw j instanceof dr&&Y(j),j}let B=[];for(let j of Vv(P)){if(y&&(y=!1,j[0]===Uo)){a.push(j),S+=j.length,B.push({raw:j,atStart:!1});continue}let X=a.discardedEvents,Q=a.discardedComments,He=a.discarding;!He&&R.length===0&&(_=S),S+=j.length;for(let Ue of a.push(j))B.push({event:Ue});He?(B.push({raw:j,atStart:!1}),y=!a.discarding&&j[j.length-1]===ai):a.discardedEvents>X?(Y(new dr(i,a.discardedComments>Q)),R.push(j),B.push({raw:R.take(),atStart:_===0}),y=!a.discarding&&j[j.length-1]===ai):Gv(j)&&a.idle?R.clear():R.push(j)}return B},"parse");return new ReadableStream({async pull(P){if(I!==void 0){P.error(I.error);return}try{for(;;){let B=await m.read();if(h)return;let j,X=!1,Q=!1;if(B.done){j=[],Q=s&&a.discarding;let K=a.discardedEvents,de=a.discardedComments,xe;try{xe=a.end()}catch(ne){throw ne instanceof dr&&Y(ne),ne}for(let ne of xe)ne.terminated?j.push({event:ne}):X=!0;a.discardedEvents>K&&R.length>0&&(Y(new dr(i,a.discardedComments>de)),j.push({raw:R.take(),atStart:_===0}),Q=!0),R.clear(),X||=Q}else j=re(B.value);let He=!1,Ue=o(K=>{K.length>0&&(P.enqueue(K),He=!0,f=!0)},"enqueue"),Be=o(K=>{K!==""&&Ue(c.encode(K))},"emit");for(let K of j){if("raw"in K){!f&&!K.atStart&&Jv.every((ne,Ye)=>K.raw[Ye]===ne)&&Be(`
37
- `),Ue(K.raw.slice()),b=K.raw[K.raw.length-1];continue}let{event:de}=K,xe;try{let ne=await t(de,u);if(h)return;xe=Z(ne,de)}catch(ne){if(h)return;if(v(ne,{mode:n,kind:"transform",event:de}),n==="closed")throw ne;xe={text:x(de),terminate:!1}}if(Be(xe.text),xe.terminate){U("SSE stream terminated by its rewriter"),P.close();return}}if(B.done){if(r.end!==void 0){let K;try{let de=await r.end({...u,unterminated:X});if(h)return;K=Z(de,void 0)}catch(de){if(h)return;if(v(de,{mode:n,kind:"end"}),n==="closed")throw de;K={text:"",terminate:!1}}if(Q&&K.text!==""&&Be(b===Uo?`
35
+ `}o(Za,"serializeSseEvent");var Pv=new Set(["data","event","id","retry"]);function gf(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!Pv.has(ff(t)))}o(gf,"hasUnknownSseFields");function Mo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>ff(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
36
+ `)}}o(Mo,"replaceSseData");var yf=Symbol("sse.terminate");function Xa(...e){return{[yf]:!0,events:e}}o(Xa,"terminateSse");function xv(e){return typeof e=="object"&&e!==null&&yf in e}o(xv,"isTerminate");var Ov=64,mf=new Uint8Array(0),Ya=class{static{o(this,"SseRawEventBytes")}#e=mf;#r=0;#t=[];#n=0;get length(){return this.#r+this.#n}get views(){return this.#t.length}push(t){t.length!==0&&(this.#t.push(t),this.#n+=t.length,this.#t.length>=Ov&&this.#l())}take(){let t;return this.#r===0?t=zv(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=mf,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#l(){let t=this.#r+this.#n;if(t>this.#e.length){let r=new Uint8Array(Math.max(t,this.#e.length*2));r.set(this.#e.subarray(0,this.#r)),this.#e=r}for(let r of this.#t)this.#e.set(r,this.#r),this.#r+=r.length;this.#t=[],this.#n=0}},Oo=10,ri=13,Mv=[239,187,191];function Uv(e){let t=[],r=0;for(let n=0;n<e.length;n++){let s=e[n];(s===Oo||s===ri&&e[n+1]!==Oo)&&(t.push(e.subarray(r,n+1)),r=n+1)}return r<e.length&&t.push(e.subarray(r)),t}o(Uv,"splitLines");function qv(e){let t=e[e.length-1];return t===Oo||t===ri}o(qv,"endsLine");function Qa(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??hf,a=new xo(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,u={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},m=e.getReader(),h=!1,f=!1,S=0,R=new Ya,_=0,y=!1,b,I,A=o(x=>{h=!0,d.abort(x),m.cancel(x).catch(()=>{})},"stop"),v=o((x,B)=>{try{Av(r.onFailure?.(x,B),()=>{})}catch{}},"report"),Y=o(x=>{v(x,{mode:n,kind:"oversize",...x.comment?{comment:!0}:{}})},"reportOversize"),O=o(x=>{if(!("lines"in x))return Za(x);if(x.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return x.lone===!0&&x.lines.length>0&&x.lines.every(B=>B.charCodeAt(0)===58)?Za({...x,terminated:!1}):Za(x)},"write"),Z=o((x,B)=>xv(x)?{text:x.events.map(O).join(""),terminate:!0}:x===void 0?{text:B===void 0?"":O(B),terminate:!1}:x===null?{text:"",terminate:!1}:{text:(Array.isArray(x)?x:[x]).map(O).join(""),terminate:!1},"render"),re=o(x=>{if(!s)try{return a.push(x).map(j=>({event:j}))}catch(j){throw j instanceof ur&&Y(j),j}let B=[];for(let j of Uv(x)){if(y&&(y=!1,j[0]===Oo)){a.push(j),S+=j.length,B.push({raw:j,atStart:!1});continue}let X=a.discardedEvents,te=a.discardedComments,He=a.discarding;!He&&R.length===0&&(_=S),S+=j.length;for(let Ue of a.push(j))B.push({event:Ue});He?(B.push({raw:j,atStart:!1}),y=!a.discarding&&j[j.length-1]===ri):a.discardedEvents>X?(Y(new ur(i,a.discardedComments>te)),R.push(j),B.push({raw:R.take(),atStart:_===0}),y=!a.discarding&&j[j.length-1]===ri):qv(j)&&a.idle?R.clear():R.push(j)}return B},"parse");return new ReadableStream({async pull(x){if(I!==void 0){x.error(I.error);return}try{for(;;){let B=await m.read();if(h)return;let j,X=!1,te=!1;if(B.done){j=[],te=s&&a.discarding;let K=a.discardedEvents,ue=a.discardedComments,xe;try{xe=a.end()}catch(ne){throw ne instanceof ur&&Y(ne),ne}for(let ne of xe)ne.terminated?j.push({event:ne}):X=!0;a.discardedEvents>K&&R.length>0&&(Y(new ur(i,a.discardedComments>ue)),j.push({raw:R.take(),atStart:_===0}),te=!0),R.clear(),X||=te}else j=re(B.value);let He=!1,Ue=o(K=>{K.length>0&&(x.enqueue(K),He=!0,f=!0)},"enqueue"),Be=o(K=>{K!==""&&Ue(c.encode(K))},"emit");for(let K of j){if("raw"in K){!f&&!K.atStart&&Mv.every((ne,Ye)=>K.raw[Ye]===ne)&&Be(`
37
+ `),Ue(K.raw.slice()),b=K.raw[K.raw.length-1];continue}let{event:ue}=K,xe;try{let ne=await t(ue,u);if(h)return;xe=Z(ne,ue)}catch(ne){if(h)return;if(v(ne,{mode:n,kind:"transform",event:ue}),n==="closed")throw ne;xe={text:O(ue),terminate:!1}}if(Be(xe.text),xe.terminate){A("SSE stream terminated by its rewriter"),x.close();return}}if(B.done){if(r.end!==void 0){let K;try{let ue=await r.end({...u,unterminated:X});if(h)return;K=Z(ue,void 0)}catch(ue){if(h)return;if(v(ue,{mode:n,kind:"end"}),n==="closed")throw ue;K={text:"",terminate:!1}}if(te&&K.text!==""&&Be(b===Oo?`
38
38
  `:`
39
39
 
40
- `),Be(K.text),K.terminate){U("SSE stream terminated by its rewriter"),P.close();return}}h=!0,P.close();return}if(He)return}}catch(B){h||(U(B),(P.desiredSize??0)<0?I={error:B}:P.error(B))}},cancel(P){if(!h)return h=!0,d.abort(P),m.cancel(P)}},{highWaterMark:0})}o(tc,"rewriteSseStream");function Kv(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(Kv,"concatBytes");function ci(e,t,r){if(e.body===null)return e;let n=yt(new Headers(e.headers));return n.set("content-type","text/event-stream"),new Response(tc(e.body,t,r),{status:e.status,statusText:e.statusText,headers:n})}o(ci,"rewriteSseResponse");var Rf=new Set(["jsonrpc","method","id","params"]),oc=new Set(["name","uri","ref"]),bf=new Set(["type","name","uri"]),Wv="subscriptions/listen",sc="notifications",vf="resourceSubscriptions",Zv=new Set([...oc,St(sc)]),Yv=new Set([St(vf)]),Xv=/[^\u0000-\u007f]/,Qv=34,eC=92,_f=123,tC=125,rC=91,nC=93,oC=58,rc=44;function zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(zo,"isRecord");function St(e){return e.toUpperCase().toLowerCase()}o(St,"foldCase");function nc(e,t){return Object.keys(e).some(r=>{let n=St(r);return n!==r&&t.has(n)})}o(nc,"hasCaseVariant");function wf(e,t){let r=St(t);return Object.keys(e).some(n=>n!==t&&St(n)===r)}o(wf,"hasCaseVariantOf");function sC(e,t){let r=o(a=>{switch(a.role){case"member":return Rf;case"params":return t.has(a.member)?Zv:oc;case"ref":return bf;case"notifications":return Yv;default:return}},"watchedFor"),n=[],s=0,i=o(a=>{let c=n.at(-1);if(c===void 0)return a?"member":"batch";if(a){if(c.role==="batch")return"member";if(c.role==="member"&&c.key==="params")return"params";if(c.role==="params"&&c.key==="ref")return"ref";if(c.role==="params"&&c.key===sc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===Qv){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let m=0;for(;e.charCodeAt(d-1-m)===eC;)m++;if(m%2===0)break}let u=s>0?void 0:n.at(-1);if(u?.isObject&&u.expectKey){let m=e.slice(a,d+1),h=m.includes("\\")?JSON.parse(m):m.slice(1,-1);if(Xv.test(h))return!0;u.key=h;let f=St(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===_f||c===rC){let d=c===_f,u=s>0?void 0:i(d);if(u===void 0)s++;else{let m=n.at(-1)?.member??0;n.push({role:u,isObject:d,seen:new Set,member:m,expectKey:d})}}else if(c===tC||c===nC)s>0?s--:n.pop();else if(s===0&&(c===oC||c===rc)){let d=n.at(-1);d?.isObject?d.expectKey=c===rc:d?.role==="batch"&&c===rc&&d.member++}}return!1}o(sC,"hasUnsafeKeyInText");function Cf(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(zo(s)){if(nc(s,Rf)||e.checksListen===!0&&s.method===Wv&&(t.add(r),zo(s.params)&&(wf(s.params,sc)||zo(s.params.notifications)&&wf(s.params.notifications,vf))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!zo(s.params))&&(nc(s.params,oc)||zo(s.params.ref)&&nc(s.params.ref,bf)))return!0}}return sC(e.text,t)}o(Cf,"hasAmbiguousIdentifyingKeys");var iC=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),aC=47,If=44,cC=38,ic=o(e=>e!==aC&&e!==If,"VALUE"),dC=o(e=>!iC(e),"ANY"),uC=o(e=>e!==cC,"QUERY_VALUE"),lC=["+","#",".","/","?","&"],ac=class{static{o(this,"Builder")}edges=[[]];current=0;#e(){return this.edges.push([]),this.edges.length-1}literal(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:o(i=>i===n,"test"),to:s}),this.current=s}}plus(t){let r=this.#e();this.edges[this.current].push({test:t,to:r}),this.edges[r].push({test:t,to:r}),this.current=r}value(t){if(this.plus(ic),!t)return;let r=this.current,n=this.#e();this.edges[r].push({test:o(s=>s===If,"test"),to:n}),this.edges[n].push({test:ic,to:r})}};function Tf(e){let t=new ac,r="",n=0;for(;n<e.length;){if(e[n]!=="{"){r+=e[n],n++;continue}let s=e.indexOf("}",n);if(s===-1)return;t.literal(r),r="";let i=e.slice(n+1,s),a=lC.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,m)=>{t.literal(`${m===0?a:"&"}${u}=`),t.plus(uC)});break;case"+":case"#":t.plus(dC);break;case".":t.literal("."),t.plus(ic);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}n=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}o(Tf,"compileUriTemplate");function Ef(e,t){if(t.length>1e6)return!1;let{edges:r,accept:n}=e,s=new Array(r.length).fill(-1),i=[0];for(let a=0;a<t.length;a++){let c=t.charCodeAt(a),d=[];for(let u of i)for(let m of r[u])s[m.to]!==a&&m.test(c)&&(s[m.to]=a,d.push(m.to));if(d.length===0)return!1;i=d}return i.includes(n)}o(Ef,"matchesUriTemplate");var mi=p.record(p.string(),p.unknown()),pC=p.record(p.string(),p.unknown()),Ut=p.array(p.string().min(1)).min(1).optional(),mC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),annotations:pC.optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),hC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),fC=p.object({uri:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),gC=p.object({uriTemplate:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),yC=p.array(p.union([p.string(),mC])),SC=p.array(p.union([p.string(),hC])),_C=p.array(p.union([p.string(),fC])),wC=p.array(p.union([p.string(),gC])),RC=p.object({module:p.unknown(),export:p.string().min(1)}).strict(),bC=p.object({mode:p.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:p.string().min(1).optional(),groupClaim:p.string().min(1).optional(),identifier:RC.optional()}).strict(),vC=p.object({tools:yC.optional(),prompts:SC.optional(),resources:_C.optional(),resourceTemplates:wC.optional(),accessControl:bC.optional()}).strict(),_t=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read","resources/subscribe","resources/unsubscribe"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function CC(e,t){return ym(vC,e,`MCP capability filter policy "${t}"`)}o(CC,"parseMcpCapabilityFilterOptions");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(G,"isRecord");function Je(e){return typeof e.method=="string"?e.method:void 0}o(Je,"messageMethod");function jo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}o(jo,"correlationKey");function qf(e){let t=new Set,r=new Map;for(let n of e){let s=jo(n);if(s===void 0)continue;t.add(s);let i=String(n),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return n=>{let s=jo(n);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(n));return i?.size===1?[...i][0]:void 0}}o(qf,"createReplyIdMatcher");function kf(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(kf,"asStringArray");function Af(e,t){if(!G(e))return[];let r=t in e?e[t]:t.split(".").reduce((n,s)=>G(n)?n[s]:void 0,e);return Array.isArray(r)?r.filter(n=>typeof n=="string"):typeof r=="string"?r.split(/\s+/).filter(n=>n.length>0):[]}o(Af,"readClaimValues");function fc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!G(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:kf(e.roles),groups:kf(e.groups),public:e.public===!0}}o(fc,"normalizeEntry");function IC(e,t,r){if(e.public)return!0;let n=e.roles??[],s=e.groups??[];return n.length===0&&s.length===0?!1:n.some(i=>t.has(i))||s.some(i=>r.has(i))}o(IC,"isCallerAllowed");function di(e,t,r,n){if(e===void 0)return;let s=[];for(let i of e){let a=fc(i,t);a!==void 0&&IC(a,r,n)&&s.push(a.key)}return s}o(di,"allowedKeys");var zf=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(Af(e.user?.data,n)),a=new Set(Af(e.user?.data,s));return{tools:di(r.tools,"name",i,a),prompts:di(r.prompts,"name",i,a),resources:di(r.resources,"uri",i,a),resourceTemplates:di(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function TC(e,t){let r=[];for(let n of _t){let s=e[n.option];if(s!==void 0)for(let i of s){let a=fc(i,n.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new ee(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}o(TC,"assertNoConflictingMarkup");function EC(e,t){let r=[];for(let n of _t){let s=e[n.option];if(s!==void 0)for(let i of s){let a=fc(i,n.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}o(EC,"assertNoMarkup");function kC(e,t){let r=e.identifier;if(r===void 0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let n=r.module[r.export];if(typeof n!="function")throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=n;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new k(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof d!="object"||Array.isArray(d))throw new k(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}o(kC,"buildCustomResolver");function AC(e,t){let r=e.accessControl,n=r?.mode??"allPublic";if(n==="function"){if(r===void 0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return kC(r,t)}if(n==="rolesAndGroups")return TC(e,t),zf;EC(e,t)}o(AC,"buildCapabilityResolver");function PC(e){let t={};for(let r of _t){let n=e[r.option];if(n===void 0)continue;let s=new Map;for(let i of n){let a=QC(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o(PC,"buildProjectionMaps");function Nf(e){return e===void 0?void 0:_t.find(t=>t.listMethod===e)}o(Nf,"findListRule");function gc(e){return e===void 0?void 0:_t.find(t=>t.directMethods.includes(e))}o(gc,"findDirectRule");var hi="completion/complete",jf=["prompts","resources","resourceTemplates"];function Df(e){return e===hi||gc(e)!==void 0}o(Df,"isCapabilityMethod");var pi="subscriptions/listen",xC=[..._t.flatMap(e=>[e.listMethod,...e.directMethods]),hi,pi];function OC(e){let t=St(e.trim()),r=xC.find(n=>St(n)===t);return r!==void 0&&r!==e?r:void 0}o(OC,"methodVariantOf");function MC(e,[t,r]){return{code:A.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(MC,"invalidParams");function yc(e){return t=>({code:A.InvalidParams,message:`${e} "${Os(t)}" not found`})}o(yc,"namedNotFound");function UC(e,t){return{code:em(t),message:"Resource not found",data:{uri:xs(e,tm)}}}o(UC,"resourceNotFound");var qC={legacy:yc("Tool"),modern:yo.tool},cc={legacy:yc("Prompt"),modern:yo.prompt},zC={legacy:UC,modern:yo.resource},NC={legacy:yc("Resource template"),modern:yo.resourceTemplate};function jC(e){let t=Je(e);if(t===void 0||!Df(t))return[];let r=G(e.raw)?e.raw.params:void 0,n=o((d,u)=>G(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=o(d=>G(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==hi){let d=gc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:n(r,"uri"),issue:s("params.uri"),notFound:zC}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?qC:cc}]}let i=G(r)?r.ref:void 0,a=G(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:n(i,"name"),issue:["params.ref.name","a string"],notFound:cc}];if(a==="ref/resource"){let d=n(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&DC(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:NC}]}let c=G(r)?G(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:jf,target:void 0,issue:c,notFound:cc}]}o(jC,"capabilityAccesses");function DC(e){let t=!1,r=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else LC(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(DC,"hasTemplateExpression");function LC(e){return e>32&&e<127?!1:$C.test(String.fromCharCode(e))}o(LC,"isWhitespaceCode");var $C=/\s/;function HC(e){return e.type==="invalid"&&(!G(e.raw)||e.raw.jsonrpc!=="2.0")}o(HC,"isNonJsonRpcMember");function BC(e){return G(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(BC,"hasNonStringMethod");function Lf(e){return e.type==="request"||e.type==="invalid"&&Je(e)!==void 0}o(Lf,"awaitsReply");function FC(e){return G(e.raw)&&G(e.raw.params)?e.raw.params:void 0}o(FC,"rawParams");function JC(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:fe()&&zr(e.headers,r.raw)}o(JC,"isModernRequest");var Pf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},dc="=?base64?",uc="?=",VC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function GC(e){if(!e.startsWith(dc)||!e.endsWith(uc)||e.length<dc.length+uc.length)return e;let t=e.slice(dc.length,e.length-uc.length);if(VC.test(t))try{let r=atob(t),n=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}o(GC,"decodeMcpHeaderValue");var KC=-32020;function WC(e,t){let r=Je(t);if(r===void 0)return;let n=G(t.raw)?t.raw.id:void 0,s=Sc(n)?n:void 0,i=e.headers.get("mcp-protocol-version"),a=im(t.raw);if(i!==null&&a!==void 0&&i!==a)return ui(s,i,`the body envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let c=e.headers.get("mcp-method");if(c!==null&&c!==r)return ui(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(Pf,r)?Pf[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let m=GC(d);if(m===void 0)return ui(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=FC(t)?.[u];if(typeof h=="string"&&m!==h)return ui(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${m}"`)}o(WC,"headerMismatchResponse");function ui(e,t,r){return Gr(400,{code:KC,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(ui,"mismatchResponse");var ZC={code:A.MethodNotFound,message:"Method not found"},xf={code:A.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},YC={code:A.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},XC="2025-06-18";function Sc(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(Sc,"isValidRequestId");function $f(e){return G(e.raw)&&!Object.hasOwn(e.raw,"id")}o($f,"isSentAsNotification");function No(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}o(No,"jsonRpcError");function Gr(e,t,r){return Response.json(No(t,r),{status:e})}o(Gr,"jsonRpcErrorResponse");function li(e){return Gr(400,{code:A.InvalidRequest,message:`Invalid Request: ${e}`})}o(li,"invalidRequestResponse");function lc(e,t,r=!1){if($f(e))return{status:400,body:No({code:A.InvalidRequest,message:`Invalid Request: a notification cannot use ${Os(Je(e)??"this method")}; send it as a request with an id`})};let n=G(e.raw)?e.raw.id:void 0;return Sc(n)?{status:r&&t.code===A.MethodNotFound?404:200,body:No(t,n)}:{status:400,body:No({code:A.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}o(lc,"refusalOf");function Of(e,t,r=!1){let[n]=[...t];if(e.shape!=="batch"){let{status:a,body:c}=lc(n[0],n[1],r);return Response.json(c,{status:a})}let s=e.protocolVersion;if(s!==void 0&&s>=XC)return li(`protocol version ${Os(s)} does not support JSON-RPC batches`);let i=e.messages.flatMap(a=>a.type==="result"||a.type==="error"||$f(a)?[]:[lc(a,t.get(a)??YC).body]);if(i.length===0){let{status:a,body:c}=lc(n[0],n[1]);return Response.json(c,{status:a})}return Response.json(i)}o(Of,"refusalResponse");function QC(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!G(e))return;let r=e[t];if(typeof r!="string")return;let n={...e};return delete n.roles,delete n.groups,delete n.public,{key:r,overlay:n}}o(QC,"buildProjection");function Mf(e){let t=e.base[e.property],r=e.overlay[e.property];return G(r)?G(t)?{...t,...r}:r:t}o(Mf,"mergeRecordProperty");function eI(e,t){let r={...e,...t.overlay},n=Mf({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=Mf({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(eI,"applyProjection");var Ae=Symbol("unreadable"),Kr=Symbol("dropped");function tI(e,t,r,n,s){let i=e.result;if(!G(i))return Ae;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?Ae:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!G(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(n!==void 0&&!n.has(u))return[];let m=r.get(u);return m===void 0?[]:[eI(d,m)]})}}}o(tI,"filterAndProjectItems");var Hf="resources/read";function rI(e){let t=e.result;return!G(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}o(rI,"withPrivateReadScope");function Bf(e,t){let r=Nf(Je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(Bf,"listTargetOf");function nI(e,t,r){return G(e)&&_t.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(nI,"carriesUnfilteredList");function oI(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(y=>Bf(y,r),"listTarget"),d=t.messages.filter(Lf),u=new Map;for(let y of d){let b=jo(y.id);b!==void 0&&!u.get(b)&&u.set(b,c(y))}let m=qf(d.map(y=>y.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&Je(h)===Hf,S=o(y=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let b=m(y);return b===void 0?void 0:u.get(b)},"targetForReply"),R=o(y=>{if(!G(y))return Ae;if(!("result"in y))return"method"in y&&!("error"in y)?_(y):"error"in y||"method"in y?y:Ae;let b=S(y.id);return b===void 0||nI(y.result,b,r)?Ae:b===null?f?rI(y):y:tI(y,b.rule,b.projections,n?.[b.rule.option],s)},"filterMessage"),_=o(y=>{if(a===void 0)return y;if(y.method==="notifications/resources/updated"){let b=G(y.params)?y.params.uri:void 0;return typeof b=="string"&&!a(b)?Kr:y}if(y.method==="notifications/subscriptions/acknowledged"){let b=Vf(y.params,a);return b===void 0?y:{...y,params:b}}return y},"filterServerMessage");return y=>{if(!Array.isArray(y))return R(y);if(t.shape!=="batch")return Ae;let b=y.map(R);if(b.includes(Ae))return Ae;let I=b.filter(U=>U!==Kr);return I.length===b.length?b:I.length===0?Kr:I}}o(oI,"createReplyFilter");function sI(e){return it(e.headers.get("content-type")).includes("json")}o(sI,"isJsonResponse");function iI(e){return it(e.headers.get("content-type"))==="text/event-stream"}o(iI,"isEventStreamResponse");var aI=10*1024*1024,cI=/^[\w.~:/+=-]{0,256}$/;function dI(e){if(yf(e))return null;let t=!1;for(let n of e.lines){let s=n.indexOf(":"),i=s===-1?n:n.slice(0,s),a=s===-1?"":n.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&cI.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=o(n=>n.trim()===""?n:"","blank");return{...e,lines:e.lines.map(n=>n.startsWith(":")?`:${r(n.slice(1))}`:n),comments:e.comments.map(r)}}o(dI,"inspectSseLines");var Ff="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",uI="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function mc(e,t){let r=e.messages.filter(Lf),n=new Map,s=new Set;for(let u of r){let m=u.id,h=jo(m);m==null||h===void 0||(n.set(h,m),Bf(u,t)!==null&&s.add(h))}let i=qf(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:jo(a.id),d=new Set;return{keyOf(u){if(!(!G(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:o(u=>u!==void 0&&n.has(u),"isPending"),hasFailed:o(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&n.delete(u)},fail(u){return[...u].flatMap(m=>{let h=n.get(m);return h===void 0?[]:(n.delete(m),d.add(m),[{jsonrpc:"2.0",id:h,error:{code:A.InternalError,message:s.has(m)?Ff:uI}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(mc,"createReplyTracker");function Jf(e,t,r){let n=[],s=0;for(let i of e){let a=r.keyOf(i);if(a!==void 0&&r.hasFailed(a))continue;let c=Array.isArray(i)?Ae:t(i);c!==Kr&&(c!==Ae?(n.push(c),r.answer(a)):r.isPending(a)?n.push(...r.fail([a])):s++)}return{replies:n,dropped:s}}o(Jf,"filterBatchMembers");function lI(e){let{response:t,envelope:r,projectionMaps:n,filterReply:s,warn:i}=e,a=mc(r,n),c=!1,d=o(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=o(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),m=o(()=>a.pendingKeys().length===0,"isDone");return ci(t,h=>{let f=dI(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let S;try{S=JSON.parse(f.data)}catch{return d("its data is not JSON")}let R=a.keyOf(S);if(R!==void 0&&a.hasFailed(R))return null;let _=s(S);if(_===Kr)return null;if(_===Ae&&r.shape==="batch"&&Array.isArray(S)){let{replies:y,dropped:b}=Jf(S,s,a);if(b>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),y.length===0)return null;let I=qo(f,JSON.stringify(y));return m()?ec(I):I}if(_===Ae){if(!a.isPending(R))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let y=u(a.fail([R]));return m()?ec(...y):y}for(let y of Array.isArray(_)?_:[_])a.answer(a.keyOf(y));return _===S?f:qo(f,JSON.stringify(_))},{maxEventChars:aI,onOversize:"discard",end:o(({unterminated:h,discardedEvents:f})=>((h||f>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||f>0?u(a.fail(a.pendingKeys())):null),"end"),onFailure:o((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}o(lI,"filterEventStream");function _c(e){return Je(e)===pi}o(_c,"isListenRequest");function pI(e){return fe()&&e.messages.some(_c)}o(pI,"filtersListen");function Vf(e,t){if(!G(e)||!G(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let n=r.filter(s=>typeof s=="string"&&t(s));if(n.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:n}}}o(Vf,"narrowSubscriptionParams");function mI(e,t,r){let n=!1,s=t.messages.map(a=>{if(!_c(a)||!G(a.raw))return a.raw;let c=Vf(a.raw.params,r);return c===void 0?a.raw:(n=!0,{...a.raw,params:c})});if(!n)return e;let i=new Headers(e.headers);return i.delete("content-length"),new kt(e,{headers:i,body:JSON.stringify(t.shape==="batch"?s:s[0])})}o(mI,"narrowListenSubscriptions");var pc=Symbol("access unresolved"),Uf=10*1024*1024,Gf="the request body could not be read";async function hI(e,t,r){let n=e.clone().body;if(n===null)return{blank:!0,overLimit:!1};let s=n.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:u}=await s.read(),m=d?i.decode():i.decode(u,{stream:!0});if(a+=m.length,c&&=!/\S/.test(m),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}o(hI,"scanBody");function wc(e){return Array.isArray(e)?`batch member 0: ${wc(e[0])}`:G(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}o(wc,"invalidMessageReason");async function fI(e,t){if(e.body===null)return;let r=o(()=>Ne.contentTooLarge(e,t,{detail:"The request body is larger than the MCP capability filter can inspect."}),"tooLarge");if(Number(e.headers.get("content-length")??Number.NaN)>Uf)return r();let s=it(e.headers.get("content-type")).includes("json"),i=o(()=>Ne.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=o(()=>Gr(400,{code:A.ParseError,message:`Parse error: ${Gf}`}),"unreadable"),c;try{c=await hI(e,Uf,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(m){return m instanceof SyntaxError?Gr(400,{code:A.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=G(d)?d.id:void 0;return Gr(400,{code:A.InvalidRequest,message:`Invalid Request: ${wc(d)}`},Sc(u)?u:void 0)}o(fI,"refuseUninspectable");var hc=class extends Cs{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=CC(t,r);super(n,r),this.#r=r,this.#e=PC(n),this.#t=AC(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,Tf(i)]))}async handler(t,r){let n=await dm(t);if(n===null)return await fI(t,r)??t;let s=JC(t,n);if(s){let v=n.messages[0],Y=v===void 0?void 0:WC(t,v);if(Y!==void 0)return Y}let i=n.messages.findIndex(HC);if(i!==-1)return li(`batch member ${i}: ${wc(n.messages[i].raw)}`);let a=n.messages.findIndex(BC);if(a!==-1)return li(n.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=cm(n);if(c===void 0)try{c=await t.clone().text()}catch{return Gr(400,{code:A.ParseError,message:`Parse error: ${Gf}`})}if(Cf({envelope:n,text:c,isCapabilityMethod:Df,checksListen:this.#a()}))return li("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let d=new Map;for(let v of n.messages){let Y=Je(v),x=Y===void 0?void 0:OC(Y);x!==void 0&&this.#u(x)&&d.set(v,ZC)}let u=pI(n),m=d.size===0&&this.#t!==void 0&&n.messages.some(v=>this.#i(v,u))?await this.#s(t,r):void 0,h=s&&Us(t.headers.get("mcp-protocol-version"));if(d.size===0)for(let v of n.messages){let Y=m===pc?this.#i(v,u)?xf:void 0:this.#m(v,m,h,n.protocolVersion);Y!==void 0&&d.set(v,Y)}if(d.size>0)return Of(n,d,s);if(m===pc)return Of(n,new Map(n.messages.map(v=>[v,xf])),s);let f=u||s?this.#l(m):void 0,S=f===void 0?t:mI(t,n,f),R=s&&this.#t!==void 0,_=R&&this.#p();if(!this.#h(n,u,_))return S;let y=oI({envelope:n,projectionMaps:this.#e,allowedSets:m,privateScope:R,privateReadScope:_,isResourceVisible:f}),b=o(v=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${v}`),"warn"),I=o((v,Y)=>{b(`did not forward an upstream reply (${v}); answered -32603`);let x=mc(n,this.#e),Z=x.fail(x.pendingKeys()),re=yt(new Headers(Y.headers));return re.set("content-type","application/json"),Z.length===0?new Response(JSON.stringify(No({code:A.InternalError,message:Ff})),{status:502,headers:re}):new Response(JSON.stringify(n.shape==="batch"?Z:Z[0]),{status:200,headers:re})},"unreadable");r.addResponseSendingHook(async v=>{let Y=!v.ok;if(v.body!==null&&at(v.headers))return Y?v:I("its body is still content-encoded",v);if(iI(v))return lI({response:v,envelope:n,projectionMaps:this.#e,filterReply:y,warn:b});if(!sI(v))return v.ok&&v.status!==202&&v.status!==204&&v.body!==null?I("no or an unknown media type",v):v;let x;try{x=await v.clone().json()}catch{return Y?v:I("its body is not JSON",v)}if(Y&&!Array.isArray(x)&&!(G(x)&&"result"in x))return v;let Z=y(x);if(Z===Ae&&n.shape==="batch"&&Array.isArray(x)){let P=mc(n,this.#e),{replies:B,dropped:j}=Jf(x,y,P);j>0&&B.push(...P.fail(P.pendingKeys())),B.length>0&&(b("did not forward a batch reply member it could not read; sent the rest"),Z=B)}if(Z===Ae||Z===Kr)return I("the filter could not read the reply",v);if(Z===x)return v;let re=yt(new Headers(v.headers));return new Response(JSON.stringify(Z),{status:v.status,statusText:v.statusText,headers:re})});let U=new kt(S);return U.headers.set("accept-encoding","gzip, br"),U}#l(t){if(!this.#p())return;let r=o((n,s)=>{let i=t?.[n];return this.#e[n]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return n=>this.#d(n,r)}#p(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#m(t,r,n,s){let i=o(c=>this.#e[c]!==void 0,"isConfigured"),a=o((c,d)=>{let u=r?.[c];return this.#e[c]?.has(d)===!0&&(u===void 0||u.has(d))},"isAllowed");for(let c of jC(t)){if(!(c.refusedBy??c.options).some(i))continue;let{target:d}=c;if(d===void 0)return MC(Je(t)??"",c.issue);if(!(c.resource?this.#d(d,a):c.options.filter(i).some(m=>a(m,d))))return n?c.notFound.modern(d):c.notFound.legacy(d,s??null)}}#d(t,r){let n=this.#e.resources!==void 0;if(n&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!Ef(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!n&&!s}#o(t){let r=o(n=>this.#e[n]!==void 0,"isConfigured");return t===hi?jf.some(r):gc(t)?.option==="resources"&&r("resourceTemplates")?!0:_t.some(n=>r(n.option)&&(n.listMethod===t||n.directMethods.includes(t)))}#i(t,r){let n=Je(t);return r&&n===pi&&this.#p()?!0:n!==void 0&&this.#o(n)}#a(){return fe()&&this.#p()}#u(t){return t===pi?this.#a():this.#o(t)}#h(t,r,n){return t.messages.some(s=>{if(r&&_c(s))return this.#p();if(n&&t.shape==="single"&&Je(s)===Hf)return!0;let i=Nf(Je(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#s(t,r){let n=this.#t;if(n===void 0)return{};let s;try{s=await n(t,r,this.options)}catch(a){return r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; refused the requests that needed it`,a),pc}let i={};for(let a of _t){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let m of d)typeof m=="string"&&c.has(m)&&u.add(m);i[a.option]=u}return i}};var Rc="zuplo.com",gI=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),yI=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Kf(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(Kf,"s2FaviconHref");function SI(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}o(SI,"strictFaviconHref");var Wf=Kf(Rc);function bc(e){let t=e.toLowerCase();return t===Rc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Kf(Rc):SI(e)}o(bc,"resolveIconHref");function _I(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(_I,"hostnameFromHost");function wI(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(wI,"isLocalOrAddressHost");function RI(e){let t=_I(e).toLowerCase().replace(/\.$/,"");if(wI(t)||yI.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let n=r.slice(-2).join("."),s=gI.has(n)?3:2;return r.slice(-s).join(".")}o(RI,"inferFaviconDomain");function vc(e){return{src:bc(RI(e)),mimeType:"image/png",sizes:["128x128"]}}o(vc,"resolveMcpFaviconIcon");function fi(e){try{return vc(new URL(e).host)}catch{return}}o(fi,"resolveMcpFaviconIconFromUrl");var bI=-32020,vI=new Set(["envelope-invalid","modern-header-without-claim","header-body-version-mismatch","method-header-mismatch","notification-envelope-invalid","notification-header-body-version-mismatch","notification-method-header-mismatch"]),Zf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Yf="=?base64?",Xf="?=",CI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function II(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(II,"isRecord");function Qf(e){return e===" "||e===" "}o(Qf,"isHttpOws");function TI(e){let t=0,r=e.length;for(;t<r&&Qf(e[t]);)t++;for(;r>t&&Qf(e[r-1]);)r--;return e.slice(t,r)}o(TI,"stripHttpOws");function gi(e,t){return e.get(t)??void 0}o(gi,"readHeader");function EI(e){if(!e.startsWith(Yf)||!e.endsWith(Xf))return e;let t=e.slice(Yf.length,e.length-Xf.length);if(CI.test(t))try{let r=Uint8Array.from(atob(t),n=>n.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}o(EI,"decodeMcpHeaderValue");function Ic(e,t,r){let n=Me(e);return Response.json(gt({...n===void 0?{}:{id:n},error:r}),{status:t})}o(Ic,"errorResponse");function eg(e,t,r){return Ic(e,400,{code:bI,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(eg,"headerMismatchResponse");function kI(e,t){let r=t.method,n=gi(e,"mcp-name");if(n===void 0||typeof r!="string"||!Object.hasOwn(Zf,r))return;let s=Zf[r],i=TI(n),a=EI(i);if(a===void 0)return eg(t,i,"the Mcp-Name header carries an invalid Base64 sentinel value");let c=II(t.params)?t.params[s]:void 0,d=typeof c=="string"?c:void 0;if(d!==void 0&&a!==d)return eg(t,i,`the body carries params.${s}="${d}" but the Mcp-Name header names "${a}"`)}o(kI,"mcpNameMismatchResponse");function tg(e){let{headers:t,message:r}=e,n=Qp({httpMethod:"POST",...Cc("protocolVersionHeader",gi(t,"mcp-protocol-version")),...Cc("mcpMethodHeader",gi(t,"mcp-method")),...Cc("mcpNameHeader",gi(t,"mcp-name")),body:r});if(n.kind==="reject")return vI.has(n.cell)?Ic(r,n.httpStatus,{code:n.code,message:n.message,...n.data===void 0?{}:{data:n.data}}):void 0;if(n.kind!=="modern")return;let s=n.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new Xp({supported:[...e.supportedVersions],requested:s??"unknown"});return Ic(r,400,{code:i.code,message:i.message,data:i.data})}return n.messageKind==="request"?kI(t,r):void 0}o(tg,"validateModernGatewayRequest");function Cc(e,t){return t===void 0?{}:{[e]:t}}o(Cc,"optionalHeader");function qt(e){let t=Ce().connectionsById.get(e);if(!t)throw new ee(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}o(qt,"getUpstreamServerConfig");function yi(e){let t=Ce().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new ee(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}o(yi,"getUpstreamAuthConfig");function Wr(e,t){let r=yi({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new ee(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}o(Wr,"requireUpstreamOAuthConfig");function rg(e,t){let r=yi({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new ee(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}o(rg,"requireUpstreamIdJagConfig");import{base64url as Si}from"jose";var AI="__Host-",PI=16,xI=32,og=".",OI=!1;function zt(){return OI}o(zt,"isBrowserBindingEnforced");var Do=p.object({id:p.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:p.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function _i(e,t){return new URL(ie(e,t)).protocol==="https:"}o(_i,"isSecureGatewayOrigin");function Tc(e,t){return t?`${AI}${e}`:e}o(Tc,"gatewayCookieName");function Lo(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}o(Lo,"serializeGatewayCookie");function Ec(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let s=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}o(Ec,"parseCookieHeader");function ng(e){return Si.encode(crypto.getRandomValues(new Uint8Array(e)))}o(ng,"randomBase64url");async function sg(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Si.encode(new Uint8Array(t))}o(sg,"hashNonce");function MI(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}o(MI,"constantTimeEqual");function ig(e,t,r){return Tc(`zuplo_mcp_${e}_${t}`,r)}o(ig,"bindingCookieName");async function $o(e){let t=ng(PI),r=ng(xI),n=_i(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${og}${Si.encode(e.payload)}`;return{claim:{id:t,hash:await sg(r)},setCookie:Lo({name:ig(e.purpose,t,n),value:s,maxAgeSeconds:e.ttlSeconds,secure:n})}}o($o,"startBrowserBinding");async function wi(e){let t=_i(e.request.url,e.request.headers),r=ig(e.purpose,e.claim.id,t),n=Lo({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Ec(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:n};let i=s.indexOf(og),a=i<0?s:s.slice(0,i);if(!MI(await sg(a),e.claim.hash))return{matched:!1,clearCookie:n};if(i<0)return{matched:!0,clearCookie:n};try{return{matched:!0,payload:new TextDecoder().decode(Si.decode(s.slice(i+1))),clearCookie:n}}catch{return{matched:!1,clearCookie:n}}}o(wi,"verifyBrowserBinding");function ag(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(ag,"mergeAbortSignals");async function UI(e){try{await e.cancel()}catch{}}o(UI,"cancelReader");async function Ri(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await UI(r),t.createLimitError();n.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of n)a.set(d,c),c+=d.byteLength;return a}o(Ri,"readBoundedByteStream");var qI=2,zI=1024*1024,NI=1e4,jI=new Set([301,302,303,307,308]),DI=["authorization","proxy-authorization","cookie","cookie2"];function kc(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(kc,"readRequestUrl");function Zr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Zr,"readRequestMethod");function LI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[O]:r}})}o(LI,"assertContentLengthWithinLimit");async function $I(e,t,r){return LI(e,t,r),Ri(e.body,{maxBytes:t,createLimitError:o(()=>new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[O]:r}}),"createLimitError")})}o($I,"readBoundedResponseBody");function HI(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(HI,"responseFromBufferedBody");function BI(e,t){if(!jI.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(BI,"resolveRedirectUrl");function cg(e,t){try{return t.validateUrl(e)}catch(r){throw new k({message:"Outbound URL was not allowed.",extensionMembers:{[O]:t.problemCode}},{cause:r})}}o(cg,"validateOutboundUrl");function FI(e,t){throw e instanceof k&&zs(e.extensionMembers?.[O])?e:new k({message:"Outbound fetch failed.",extensionMembers:{[O]:t}},{cause:e})}o(FI,"normalizeFetchError");function Ho(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,s]of Object.entries(t.extra))s!==void 0&&(r[n]=s);t.error!==void 0&&ke(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Ho,"logOutboundFailure");async function JI(e,t,r,n,s,i,a){let c=Zr(r,n);try{return await t(r,n)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Ho(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ue(i),error:d,extra:{abortReason:a()}}),FI(d,s)}}o(JI,"fetchWithNormalizedError");function VI(e){if(e.redirects>=e.maxRedirects)throw new k({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[O]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new k({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[O]:e.problemCode}})}o(VI,"assertRedirectAllowed");function GI(e,t){let r=new Headers(e);for(let n of DI)r.delete(n);for(let n of t)r.delete(n);return r}o(GI,"stripCrossOriginHeaders");function KI(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=GI(e.headers,s)),i}o(KI,"buildRedirectInit");function WI(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(WI,"buildInitialRequestInit");function ZI(e){let t=Zr(e.currentInput,e.currentInit);VI({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=cg(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),s=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:KI(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(ZI,"followRedirect");async function Ac(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??qI,i=r.maxResponseBytes??zI,a=r.timeoutMs??NI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,m=new AbortController,h=ag(m,t.signal),f=!1,S=setTimeout(()=>{f=!0,m.abort()},a),R=e,_=WI(e,t,m.signal),y;try{y=cg(kc(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(I){throw Ho(u,{event:"outbound_url_blocked",problemCode:n,method:Zr(e,t),host:ue(kc(e)),error:I}),clearTimeout(S),h?.(),I}let b=0;try{for(;;){let I=await JI(u,c,R,_,n,y,()=>f?`timeout_after_${a}ms`:void 0),U=BI(I,y);if(U!==void 0)try{let v=ZI({currentInput:R,currentInit:_,currentUrl:y,redirectUrl:U,redirects:b,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:d});R=v.currentInput,_=v.currentInit,y=v.currentUrl,b=v.redirects;continue}catch(v){throw Ho(u,{event:"outbound_redirect_blocked",problemCode:n,method:Zr(R,_),host:ue(y),error:v,extra:{redirects:b,maxRedirects:s,redirectTargetHost:ue(U)}}),v}try{return HI(I,await $I(I,i,n))}catch(v){throw Ho(u,{event:"outbound_response_size_exceeded",problemCode:n,method:Zr(R,_),host:ue(y),error:v,extra:{maxResponseBytes:i,status:I.status}}),v}}}finally{clearTimeout(S),h?.()}}o(Ac,"runSafeOutboundExchange");async function Bo(e,t,r){let n=await Ac(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(s){throw Ho(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Zr(e,t),host:ue(kc(e)),error:s,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new k({message:"Outbound JSON response could not be parsed.",extensionMembers:{[O]:r.problemCode??"invalid_request"}},{cause:s})}}o(Bo,"runSafeOutboundJsonExchange");function dg(e,t={},r={}){return Ac(e,t,{...r,validateUrl:vo})}o(dg,"fetchConfiguredOutbound");function ug(e,t={},r={}){return Bo(e,t,{...r,validateUrl:vo})}o(ug,"fetchConfiguredOutboundJson");function bi(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Jm})}o(bi,"fetchIdentityProviderJson");function lg(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Vs})}o(lg,"fetchCimdClientMetadataJson");function pg(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Co})}o(pg,"fetchCimdClientJwksJson");import{errors as Sg,jwtVerify as _g,SignJWT as wg}from"jose";var he="zuplo-mcp-gateway",we=he,Re="HS256";import{base64url as YI}from"jose";var XI=new TextEncoder,QI="MCP gateway could not initialize secure key material.",eT=32,mg=new Map,hg=new Map,tT;function rT(){return tT??ws.instance.authPrivateKey}o(rT,"readAuthPrivateKey");function fg(e){return new Te(QI,e===void 0?void 0:{cause:e})}o(fg,"createGeneratedKeyMaterialError");function gg(e,t){let r=YI.decode(t);if(r.byteLength!==eT)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(gg,"decodeJwkKeyField");function nT(e){let t=rT();if(!t)throw fg();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=gg("d",r.d);gg("x",r.x);let s=XI.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+n.byteLength);return i.set(s),i.set(n,s.byteLength),i}catch(r){throw fg(r)}}o(nT,"decodeGeneratedKeyMaterial");function oT(e){let t=mg.get(e);return t||(t=nT(e),mg.set(e,t)),t}o(oT,"getMasterKeyMaterial");async function Ve(e){let t=hg.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(oT(e.keyMaterialPurpose));return hg.set(e.purpose,r),r}o(Ve,"readCachedDerivedKey");var sT="SHA-256",iT=32,aT="zuplo-mcp-gateway:",cT=new TextEncoder,yg=new WeakMap;async function ct(e,t){let r=yg.get(e);r||(r=new Map,yg.set(e,r));let n=r.get(t);if(n)return n;let s=await dT(e,t);return r.set(t,s),s}o(ct,"deriveGatewaySigningKey");async function dT(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=cT.encode(`${aT}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:sT,salt:new Uint8Array,info:ye(s)},n,iT*8);return new Uint8Array(i)}o(dT,"hkdfExpand");var Rg=900,uT=900,lT=Em.extend({id:Zm,browserBinding:Do.optional()}),pT=lT.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),bg=ua.extend({id:Ym,purpose:p.literal("browser_connect")}),mT=ua.extend({purpose:p.literal("browser_connect")}),hT=bg.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),vi=Rg*1e3;async function vg(){return Ve({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"oauth-state"),"derive")})}o(vg,"getOAuthStateKey");async function Cg(){return Ve({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-connect"),"derive")})}o(Cg,"getBrowserConnectKey");async function Ig(e){let t=Math.floor(Date.now()/1e3)+Rg;return new wg(e).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await vg())}o(Ig,"signOAuthState");async function Ci(e){try{let{payload:t}=await _g(e,await vg(),{algorithms:[Re],issuer:he,audience:we});return pT.parse(t)}catch(t){throw t instanceof Sg.JWTExpired?new k({message:"OAuth state has expired",extensionMembers:{[O]:"oauth_state_expired"}},{cause:t}):new k({message:"OAuth state could not be verified",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:t})}}o(Ci,"verifyOAuthState");async function Tg(e){let t=Math.floor(Date.now()/1e3)+uT,r=mT.parse(e),n=bg.parse({...r,id:th()});return new wg(n).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await Cg())}o(Tg,"signBrowserConnectTicket");async function Eg(e){try{let{payload:t}=await _g(e,await Cg(),{algorithms:[Re],issuer:he,audience:we});return hT.parse(t)}catch(t){throw t instanceof Sg.JWTExpired?new k({message:"Browser connect ticket has expired",extensionMembers:{[O]:"oauth_state_expired"}},{cause:t}):new k({message:"Browser connect ticket could not be verified",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:t})}}o(Eg,"verifyBrowserConnectTicket");async function kg(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new k({message:"Browser connect ticket has already been used",extensionMembers:{[O]:"oauth_state_reused"}})}o(kg,"consumeBrowserConnectTicket");function fT(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(fT,"buildConnectRequiredMessage");async function gT(e){let t=ie(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Tg({...Ro(e),purpose:"browser_connect"})),r.toString()}o(gT,"buildGatewayBrowserTicketUrl");function yT(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(yT,"buildGatewayConnectPath");async function Pc(e){return gT({...e,path:yT(e.upstreamServerId),redirect:!0})}o(Pc,"buildGatewayConnectUrl");async function Ii(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Pc(t),message:fT(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ii,"buildRedirectConnectRequiredResponse");function Ag(e){return Pg({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(Ag,"buildAdminConnectRequiredResponse");function Pg(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(Pg,"buildAdminSetupRequiredResponse");function xg(e){return Ce().byOperationId.get(e)?.downstreamOAuth!==void 0}o(xg,"routeSupportsBrowserConnect");function Og(e){return Pg({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o(Og,"buildBrowserConnectUnavailableResponse");var Mg=12;async function Ug(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}o(Ug,"sha256Hex");async function ur(e){if(e)return(await Ug(e)).slice(0,Mg)}o(ur,"fingerprintSecret");async function Yr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Ug(t)).slice(0,Mg)}o(Yr,"fingerprintConnectionIdentity");var ST=6e4;function Xr(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,n)=>t.scopes[n]!==r)}o(Xr,"credentialGenerationChanged");function Pe(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+ST)return"near_expiry"}return"usable"}o(Pe,"describeAccessTokenState");var qg=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _T(e,t){return e&&e.length>0?e.join(t):void 0}o(_T,"joinOAuthScopes");function wT(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of qg)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o(wT,"sanitizeAuthorizationServerMetadata");function zg(e){let t=wT(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(zg,"sanitizeOAuthDiscoveryState");function Ng(e){let t=new URL(e);for(let r of qg){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(Ng,"dedupeSingletonAuthorizationRequestParams");function Ti(e){let t=new URL(e);return je(t)&&gm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(Ti,"normalizeLoopbackOAuthRedirectUri");function jg(e){return _T(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(jg,"readProtectedResourceMetadataScope");function RT(e){return`Zuplo MCP Gateway - ${e}`}o(RT,"buildGatewayOAuthClientName");function bT(e,t){return e&&e.length>0?e.join(t):void 0}o(bT,"joinOAuthScopeList");function vT(e){if(e.clientRegistration.mode!=="auto")return bT(e.scopes,e.scopeDelimiter)}o(vT,"readPublicClientMetadataScope");function xc(e){return new URL(ge().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}o(xc,"buildOAuthClientMetadataDocumentUrl");function Oc(e){let t=qt(e.upstreamServerId);return{client_name:RT(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}o(Oc,"buildGatewayOAuthClientMetadata");function Dg(e,t,r){let n=Wr(t,r),s=vT(n);return{client_id:xc({origin:e,upstreamServerId:t}),...Oc({origin:e,upstreamServerId:t,redirectUri:Ti(new URL(n.redirectPath,e)).toString(),scope:s})}}o(Dg,"buildOAuthClientMetadataDocument");import{base64url as Nt}from"jose";var CT="SHA-256",Qr="AES-GCM",IT=12,Uc="zuplo-secret",qc=1,Lg="generated:auth_private_key:token-encryption",TT=p.object({version:p.literal(qc),keyId:p.literal(Lg),algorithm:p.literal(Qr),iv:p.string().min(1),ciphertext:p.string().min(1)}).strict();async function Mc(){return Ve({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(CT,ye(e));return crypto.subtle.importKey("raw",t,{name:Qr},!1,["encrypt","decrypt"])},"derive")})}o(Mc,"getEncryptionKey");function $g(e){return ye(new TextEncoder().encode(`${Uc}:v${e.version}:${e.keyId}`))}o($g,"getAssociatedData");function ET(e){return`${Uc}:v${e.version}:${Nt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(ET,"encodeEnvelope");function kT(e){let t=`${Uc}:v${qc}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Nt.decode(r));return TT.parse(JSON.parse(n))}o(kT,"decodeEnvelope");async function wt(e){let t=await Mc(),r=crypto.getRandomValues(new Uint8Array(IT)),n={version:qc,keyId:Lg},s=await crypto.subtle.encrypt({name:Qr,iv:r,additionalData:$g(n)},t,new TextEncoder().encode(e));return ET({...n,algorithm:Qr,iv:Nt.encode(r),ciphertext:Nt.encode(new Uint8Array(s))})}o(wt,"encryptSecret");async function Rt(e){let t=kT(e);if(t){let a=await Mc(),c=await crypto.subtle.decrypt({name:Qr,iv:ye(Nt.decode(t.iv)),additionalData:$g(t)},a,ye(Nt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new Te("Encrypted payload is malformed");let s=await Mc(),i=await crypto.subtle.decrypt({name:Qr,iv:ye(Nt.decode(r))},s,ye(Nt.decode(n)));return new TextDecoder().decode(i)}o(Rt,"decryptSecret");var Hg={issuer:p.string().min(1).optional()},AT=p.union([or.extend(Hg),go.extend(Hg)]),Bg=p.object({authorizationServerUrl:p.url(),resourceMetadataUrl:p.url().optional(),resourceMetadata:Mr.optional(),authorizationServerMetadata:p.union([Ur,qr]).optional()}).passthrough(),PT="Bearer",xT="__zuplo_refresh_only_upstream_access_token__";function zc(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(zc,"splitScopes");function Nc(e,t){let r=new Set(e);return t.every(n=>r.has(n))}o(Nc,"scopesCover");function OT(e){return Dr.parse(e)}o(OT,"parsePkceCodeVerifier");function MT(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}o(MT,"readTokenExpiry");async function Fg(e){if(e!==void 0)return wt(JSON.stringify(e))}o(Fg,"encryptJson");async function Jg(e,t){if(!e)return;let r=await Rt(e);try{return t.parse(JSON.parse(r))}catch(n){throw new k({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:n})}}o(Jg,"decryptJson");function UT(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(UT,"clientInformationAllowsRedirectUri");function qT(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(qT,"clientInformationMatchesCurrentClientMetadataUrl");function zT(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(zT,"isUrlBasedClientInformation");function NT(e,t){return t===void 0?e:{...e,scope:t}}o(NT,"applyOAuthClientMetadataScope");function jT(e,t){return jg({state:e,delimiter:t})}o(jT,"readResourceMetadataScope");function DT(e,t){return e&&e.length>0?e.join(t):void 0}o(DT,"joinOAuthScopeList");function LT(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new ee(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return or.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(LT,"buildManualOAuthClientInformation");function $T(e,t){let r=xc({origin:new URL(t).origin,upstreamServerId:e});return Ka(r)?r:void 0}o($T,"buildClientMetadataUrl");function HT(e){for(let t of e)if(t!==void 0)return t}o(HT,"firstDefined");function BT(e){let t=Wr(e.target.upstreamServerId,e.target.authProfileId),r=DT(t.scopes,t.scopeDelimiter),n=Oc({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:LT({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=$T(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}o(BT,"buildInitialOAuthClientSetup");function FT(e,t){if(t===void 0)return HT([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(FT,"readEncryptedClientInformation");function JT(e){return e.pendingState?.encryptedDiscoveryState}o(JT,"readEncryptedDiscoveryState");function jc(e,t){return t===void 0?e:{...e,issuer:t}}o(jc,"applyIssuerStamp");var jt=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;skipIssuerMetadataValidationValue;skipResourceIndicatorValidationValue;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=BT({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.browserBinding=t.browserBinding,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.skipIssuerMetadataValidationValue=r.skipIssuerMetadataValidation,this.skipResourceIndicatorValidationValue=r.skipResourceIndicatorValidation,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=FT(t,this.configuredClientInformation),this.encryptedDiscoveryState=JT(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get skipIssuerMetadataValidation(){return this.skipIssuerMetadataValidationValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let n=zc(this.configuredScope??r??this.readEffectiveScope());return Nc(t.scopes,n)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Pe(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let n=oe();n&&n.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Yr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await ur(await Rt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(n){let s=oe();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:n}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});s.error(i,"Upstream OAuth conditional storage write failed")}throw n}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return NT(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ig({id:t.id,...Ro({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId}),...this.browserBinding===void 0?{}:{browserBinding:this.browserBinding}})}async clientInformation(t){return this.configuredClientInformation?jc(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,oe()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!zT({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Fg(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ei({requestedResource:t,configuredResource:r}))throw new Error(`Protected resource ${r} does not match expected ${t} (or origin)`);return new URL(r)}}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=zg(Bg.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Fg(r),await this.syncPendingState(!1),oe()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ue(r.authorizationServerUrl),resourceMetadataHost:ue(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=jT(r,this.scopeDelimiter);let n=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&n!==void 0){let s=zc(this.configuredScope).filter(i=>!n.includes(i));s.length>0&&oe()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:n},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return jc(r,t?.issuer)}async saveTokens(t){let r=At.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,a=r.refresh_token?await wt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:At.parse({...r,refresh_token:await Rt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Gs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await wt(r.access_token),encryptedRefreshToken:a,scopes:zc(r.scope??this.readEffectiveScope()),expiresAt:MT(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),m=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Pe(u.connection)!=="usable"||!Nc(u.connection.scopes,c.scopes)||!Xr(s,u.connection))){m=!0;let f=u.connection,S={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};oe()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,Xr(s,u.connection)&&Pe(u.connection)==="usable"&&Nc(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),m){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";oe()?.info({event:`upstream_oauth_bounded_rebase_${f}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${f}`)}let h=u.kind==="persisted"?u.connection:void 0;oe()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await ur(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:m,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Ng(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:OT(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new k({message:"OAuth code verifier is missing",extensionMembers:{[O]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),s&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:eh(),...Ro({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:J(new Date(Date.now()+vi)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await Jg(this.encryptedClientInformation,AT)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!UT(r,this.redirectUriValue)||!qT({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=jc(go.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await Jg(this.encryptedDiscoveryState,Bg)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){oe()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await Rt(t.encryptedAccessToken):void 0,n=t.encryptedRefreshToken?await Rt(t.encryptedRefreshToken):void 0;if(!r&&!n)return;let s=oe();this.usedRefreshTokenFingerprintValue=s?await ur(n):void 0,s?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!n,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=At.parse({access_token:r??xT,token_type:PT,refresh_token:n,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=i,i}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let n=r.status,s=r.updatedAt,i={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let a=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,Xr(r,a.connection)&&Pe(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=oe();if(c){let d=a.kind==="missing"?void 0:a.connection,u={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:n,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...u,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(u,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(u,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var VT=3e4,GT=256*1024,KT=2,WT="does not support dynamic client registration",ZT=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],YT=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],XT=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],QT="Protected resource ",eE=" does not match expected ",tE=["HTTP 403 Forbidden","Access Denied","permission to access"],rE=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function nE(e){return e instanceof Error&&e.message.includes(WT)}o(nE,"isDynamicClientRegistrationUnsupported");function oE(e){return e instanceof Error&&ZT.some(t=>e.message.includes(t))}o(oE,"isProtectedResourceMetadataUnavailable");function sE(e){return e instanceof Error&&YT.some(t=>e.message.includes(t))}o(sE,"isAuthorizationServerMetadataUnavailable");function iE(e){return e instanceof Error&&XT.some(t=>e.message.includes(t))}o(iE,"isAuthorizationServerIncompatible");function aE(e){return e instanceof Error&&e.message.includes(QT)&&e.message.includes(eE)}o(aE,"isProtectedResourceMismatch");function cE(e){return e instanceof Error&&tE.some(t=>e.message.includes(t))}o(cE,"isUpstreamProviderAccessDenied");function dE(e){return e instanceof Mt&&rE.has(e.code)}o(dE,"isStoredConnectionReconsentError");function bt(e){let t=e.diagnostics??{};return new k({message:e.message,extensionMembers:{[O]:e.code,[qs]:e.upstreamServerId,[Hr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[ut]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[dt]:t.httpStatus},...t.providerError===void 0?{}:{[Br]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Fr]:t.providerErrorDescription}}},{cause:e.cause})}o(bt,"buildUpstreamSetupProblem");function uE(e,t){return`The authorization server for ${e} failed RFC 8414 \xA73.3 issuer validation: the gateway discovered it at "${t.expected}", but its metadata document declares issuer "${t.received}". Providers that publish a path-scoped authorization server whose metadata reports the root origin hit this; if that is the case here, set skipIssuerMetadataValidation on this upstream's OAuth config to accept it \u2014 that weakens the authorization-server mix-up defense, so scope it to this upstream. Otherwise correct the authorization server URL this upstream points at, or ask the provider to fix the published issuer.`}o(uE,"describeIssuerMetadataMismatch");var lE=128,pE=256;function Vg(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}o(Vg,"truncateProviderDetail");function mE(e){let{error:t,errorDescription:r}=Kg(e.body),n=Vg(t,lE),s=Vg(r,pE);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(mE,"readRegistrationRejectionDiagnostics");function hE(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}o(hE,"describeRegistrationRejection");function fE(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(fE,"readDiscoveryEndpointUrl");function gE(e){if(e.error instanceof k&&e.error.extensionMembers?.[O]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(nE(e.error))return bt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`});if(e.error instanceof Va){let r=mE(e.error);return bt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${hE(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof xo&&e.error.kind==="metadata")return bt({...t,code:"upstream_oauth_issuer_mismatch",message:uE(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ii)return bt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} publishes the non-HTTPS token endpoint "${e.error.tokenEndpoint}". The gateway will not send credentials to it. Ask the provider to serve the token endpoint over TLS before retrying.`,diagnostics:{upstreamUrl:e.error.tokenEndpoint}});if(iE(e.error))return bt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} cannot run the OAuth flow the gateway requires: ${e.error.message}. Ask the provider to support the authorization code flow with PKCE (S256), or configure this upstream to use an authorization server that does.`});if(sE(e.error)){let r=fE(e.error.message);return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The gateway could not load OAuth authorization server metadata for the upstream MCP server "${e.upstreamServerId}": ${e.error.message}. Confirm the authorization server advertised by "${e.resourceMetadataUrl}" publishes RFC 8414 or OpenID Connect discovery metadata and is reachable from the gateway, then retry.`,diagnostics:r===void 0?{}:{upstreamUrl:r}})}if(aE(e.error))return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The protected resource metadata at "${e.resourceMetadataUrl}" names a resource that does not match the configured MCP URL for ${e.upstreamServerId}: ${e.error.message}. Point this upstream's MCP URL at the resource the provider publishes, or ask the provider to correct the advertised resource.`});if(oE(e.error))return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`});if(cE(e.error))return bt({...t,code:"upstream_provider_access_denied",message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`})}o(gE,"mapUpstreamOAuthSetupError");function yE(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(yE,"readOAuthFetchRequest");function SE(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(SE,"readOAuthFetchMethod");function _E(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(_E,"responseLooksJson");function wE(e,t){let r=e.headers.get("content-type")??"",n=t.trimStart().toLowerCase();return r.includes("html")||n.startsWith("<!doctype html")||n.startsWith("<html")}o(wE,"responseLooksHtml");var RE=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function bE(e){return RE.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o(bE,"isMetadataDiscoveryRequest");function vE(e,t,r){return e!=="GET"||!bE(t)?!1:r>=400&&r<500||r===502}o(vE,"sdkRetriesDiscoveryCandidate");function CE(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new k({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[O]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[dt]:e.response.status,[Lr]:r,[ut]:e.request.url.toString(),[$r]:e.body}})}o(CE,"throwUpstreamHtmlError");function Kg(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}o(Kg,"readUpstreamOAuthErrorBody");function IE(e){let{error:t,errorDescription:r}=Kg(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ue(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}o(IE,"logUpstreamOAuthHttpError");function Wg(e){return async(t,r)=>{let n=yE(t),s=SE(t,r),i=oe(),a=Date.now(),c=await dg(t,r,{maxRedirects:KT,maxResponseBytes:GT,problemCode:"upstream_token_exchange_failed",timeoutMs:VT}),d=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:ue(n.url),path:n.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:d.length},"Upstream OAuth HTTP request completed"),c.ok||IE({log:i,upstreamServerId:e,method:s,request:n,response:c,body:d}),vE(s,n.url,c.status)||(!c.ok&&wE(c,d)&&CE({upstreamServerId:e,request:n,response:c,body:d}),!_E(c,d)))return c;try{JSON.parse(d)}catch(u){throw new k({message:`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[O]:"upstream_token_exchange_failed"}},{cause:u})}return c}}o(Wg,"createUpstreamOAuthFetch");function Zg(e){oe()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ue(e.serverUrl),resourceMetadataHost:ue(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}o(Zg,"logUpstreamOAuthFlowStarted");function Yg(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ue(e.serverUrl);r!==void 0&&(t.serverHost=r);let n=e.error instanceof k?e.error.extensionMembers?.[O]:void 0;typeof n=="string"&&(t.code=n),ke(t,"error",e.error),oe()?.warn(t,"Upstream OAuth flow failed before a connection was established")}o(Yg,"logUpstreamOAuthFlowFailed");function Xg(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(Xg,"readAuthorizationRequestScope");async function Qg(e,t){e.applyChallengeScope(t.requestedScope),Zg({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Wg(t.upstreamServerId)},n=Xg(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await Ga(e,r)}catch(r){Yg({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=gE({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(Qg,"runUpstreamOAuth");async function TE(e,t){e.applyChallengeScope(t.requestedScope),Zg({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Wg(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=Xg(e,t);n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await Ga(e,r)}catch(s){throw Yg({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(TE,"exchangeUpstreamAuthorizationCode");async function Gg(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await H().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Pe(r)!=="usable"||!Xr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}o(Gg,"adoptPeerCredentialAtResolutionBoundary");async function ey(e,t){let r=await Qg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new k({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}}):new k({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}})}o(ey,"requireUpstreamAuthorizationRedirect");async function ty(e){let t=Pe(e.connection),r=!!e.forceRefresh,n=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=oe(),i=s?await Yr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(s?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:i,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!n,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},n?"Reusing stored upstream access token":"Refreshing upstream credential"),n)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a;try{a=await Qg(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!dE(c))throw c;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await Gg({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new k({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new k({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});return await Gg({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(ty,"authorizeUpstreamOAuthSession");async function EE(e){let t=await Ci(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),n=kE(r);return AE({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),PE(n),n}o(EE,"consumeStoredCallbackState");function kE(e){switch(e.kind){case"consumed":throw new k({message:"OAuth state has already been used",extensionMembers:{[O]:"oauth_state_reused"}});case"missing":throw new k({message:"OAuth state is missing or expired",extensionMembers:{[O]:"oauth_state_expired"}});case"available":return e.record}}o(kE,"readConsumedCallbackState");function AE(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new k({message:"OAuth callback did not match the initiating request",extensionMembers:{[O]:"oauth_callback_mismatch"}})}o(AE,"assertStoredCallbackStateMatches");function PE(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[O]:"oauth_state_expired"}})}o(PE,"assertStoredCallbackStateFresh");async function Dc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Ag(r)}if(zt()&&!xg(e.operationId))return oe()?.warn({event:"upstream_connect_link_unavailable",upstreamServerId:e.upstreamServerId,operationId:e.operationId},"User-owned upstream needs a connection, but this MCP route has no gateway MCP OAuth sign-in to bind a connect link to; returning an administrator answer instead of a link"),Og({upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,...e.connection===void 0?{}:{connectionId:e.connection.id},requiresReconsent:!!e.connection});let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Ii(t)}o(Dc,"buildOAuthConnectRequiredResponse");async function ry(e){let t=await EE({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ds(t),[n]=await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(s.connection=n);let i=new jt(s),a=await TE(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(a==="AUTHORIZED"){let c=i.readUsablePeerAdoption();if(c!==void 0&&await i.adoptConnectionForDirectResolution(c,"cas_loss"),!i.tokenWriteWasPersisted&&c===void 0)throw new k({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new k({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}}):new k({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}})}o(ry,"finishUpstreamOAuthCallback");import{importPKCS8 as xE,SignJWT as OE}from"jose";var oy=1e4,sy=64*1024,iy=2,ME=300,tt=p.string().min(1),UE=p.object({access_token:tt,issued_token_type:p.literal(pa),token_type:p.string().optional(),expires_in:p.number().int().positive().optional(),scope:tt.optional()}).passthrough(),qE=p.object({id_token:tt,token_type:tt.optional(),expires_in:p.number().int().positive().optional(),refresh_token:tt.optional(),scope:tt.optional()}).passthrough(),zE=p.object({access_token:tt,token_type:tt,expires_in:p.number().int().positive().optional(),scope:tt.optional(),resource:tt.optional(),refresh_token:tt.optional()}).passthrough();function ny(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(ny,"formEncodeClientCredential");function NE(e){return e.replaceAll("\\n",`
41
- `)}o(NE,"normalizePem");async function jE(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??ME,n=await xE(NE(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new OE({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(n)}o(jE,"createPrivateKeyJwtClientAssertion");async function DE(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=ny(e.clientAuth.clientId),r=ny(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Hs),e.form.set("client_assertion",await jE({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(DE,"appendClientAuthentication");async function Lc(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await DE({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(Lc,"buildFormRequest");function ay(e){return(t,r)=>bi(t,r,{context:e,maxRedirects:iy,maxResponseBytes:sy,problemCode:"upstream_token_exchange_failed",timeoutMs:oy})}o(ay,"defaultIdpFetchJson");function LE(e){return(t,r)=>ug(t,r,{context:e,maxRedirects:iy,maxResponseBytes:sy,problemCode:"upstream_token_exchange_failed",timeoutMs:oy})}o(LE,"defaultResourceAsFetchJson");function Ei(e){let t={[O]:e.code,[ut]:e.tokenUrl};return e.response!==void 0&&(t[dt]=e.response.status),new k({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}o(Ei,"runtimeError");function $c(e){if(!e.response.ok)throw Ei({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}o($c,"assertTokenEndpointSucceeded");function $E(e){let t=qE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o($E,"parseIdpRefreshTokenResponse");function HE(e){let t=UE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(HE,"parseIdJagTokenExchangeResponse");function BE(e){let t=zE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}o(BE,"parseAccessTokenResponse");async function cy(e){let t=new URLSearchParams({grant_type:$s,requested_token_type:pa,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??ay(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return $c({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),HE({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(cy,"requestIdJag");async function dy(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??ay(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return $c({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),$E({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(dy,"refreshIdpSubjectToken");async function uy(e){let t=new URLSearchParams({grant_type:Ot,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??LE(e.context),{response:n,json:s}=await r(e.resourceAs.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return $c({response:n,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),BE({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(uy,"exchangeIdJagForAccessToken");function FE(e){return Pe(e)==="usable"}o(FE,"hasUsableAccessToken");function JE(e){if(e.tokenType.toLowerCase()!=="bearer")throw new k({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[O]:"upstream_token_response_invalid"}})}o(JE,"assertBearerToken");function ly(e,t){if(t===Vr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(ly,"hasExpiredSubjectToken");async function VE(e){let t=await Rt(e.encryptedSubjectToken);if(e.subjectTokenType!==Vr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await dy({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:bo};let n=await H().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await wt(r.refreshToken),idpSubjectTokenType:Vr,idpSubjectTokenExpiresAt:void 0}});return oe()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:n.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await ur(t),newSubjectRefreshTokenFingerprint:await ur(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:n,subjectToken:r.idToken,subjectTokenType:bo}}o(VE,"resolveIdJagSubjectToken");async function py(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Pe(t),n=!!e.forceRefresh,s=!n&&r==="usable",i=oe(),a=i?await Yr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(i?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:a,connectionId:t?.id,accessTokenState:r,forceRefresh:n,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&FE(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Rt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||ly(t,d))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:d,subjectTokenExpired:d!==void 0&&ly(t,d)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let u=qt(e.upstreamServerId),m=rg(e.upstreamServerId,e.authProfileId),h=m.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),S=await VE({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),R=await cy({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:m.resourceAs.audience,resource:h,scope:f,clientAuth:m.idp.clientAuth,context:e.context}),_=R.scope??f,y=await uy({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:R.assertion,resource:h,scope:_,clientAuth:m.resourceAs.clientAuth,context:e.context});if(JE(y),t!==void 0){let I=(y.scope??_)?.split(/[,\s]+/).filter(Boolean)??[],U=y.expiresIn===void 0?void 0:J(new Date(Date.now()+y.expiresIn*1e3)),v=await H().upsertUpstreamConnection({id:S.connection.id,ownerMode:S.connection.ownerMode,subjectId:S.connection.subjectId,upstreamServerId:S.connection.upstreamServerId,authProfileId:S.connection.authProfileId,status:"active",encryptedAccessToken:await wt(y.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:I,expiresAt:U,metadata:S.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:v.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:I.length,expiresAt:U},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}o(py,"authorizeUpstreamIdJagRequest");var ki=new Map;function GE(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(GE,"normalizeRefreshFlightScope");function KE(e){return Ti(new URL(e.callbackPath,ie(e.requestUrl,e.requestHeaders))).toString()}o(KE,"buildGatewayOAuthRedirectUri");async function Hc(e){let t=qt(e.upstreamServerId),r=Wr(e.upstreamServerId,e.authProfileId),n=KE({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:n,returnOrigin:ie(e.request.url,e.request.headers)}}}o(Hc,"prepareUpstreamOAuthRequest");async function my(e){let t=await Hc(e),r=new jt({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return ey(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(my,"startUpstreamConnect");async function hy(e){let t=await Hc(e),r=new jt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>ty({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n();let s=Xm({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,GE(r.configuredAuthorizationScope??e.requestedScope)]),a=ki.get(i);if(a!==void 0){oe()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let u=await a;if(u.kind==="usable"&&r.connectionSatisfiesRequestedScope(u.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(u.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:m,...h}=e;if(t=await Hc(h),r=new jt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n()}let c=n(),d;return d=c.then(()=>{let u=r.currentConnection;return u!==void 0&&Pe(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{ki.get(i)===d&&ki.delete(i)}),ki.set(i,d),c}o(hy,"authorizeUpstreamRequest");async function en(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return hy({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return py({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Te(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(en,"resolveUpstreamCredentialForRoute");async function fy(e){if(e.connectRequest.authMode==="id-jag")throw new Te(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await my({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding}});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}o(fy,"startUpstreamConnectForRequest");async function WE(e,t){if(t===void 0)throw new k({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[O]:"oauth_callback_mismatch"}});let r=await wi({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new k({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[O]:"oauth_callback_mismatch"}})}o(WE,"requireCallbackBrowser");async function gy(e){let t=await Ci(e.callbackRequest.state);zt()&&await WE(e,t.browserBinding);let r=t.authProfileId;if(yi({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Te(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return ry({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:qt(e.callbackRequest.upstreamServerId)})}o(gy,"finishUpstreamCallbackForRequest");function ZE(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(ZE,"buildRouteAuthBaseFromConnection");function yy(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:km(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(yy,"buildRouteAuthBaseFromPolicyOptions");function Ai(e,t){let n=Ce().byOperationId.get(t);if(!n)throw new ee(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(n.connection===void 0)throw new ee(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(n.connection.upstreamServerId!==e)throw new ee(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return ZE({connection:n.connection,operationId:t})}o(Ai,"resolveRouteAuthBase");function Bc(e,t){switch(e){case"user":return Jr(t);case"shared":return Tm()}}o(Bc,"buildOwnerForSubject");function tn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:Bc("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:Bc("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:Bc("user",t),initiatedBySubjectId:t}}}o(tn,"resolveRouteAuthForSubject");import{base64url as YE,errors as XE,jwtVerify as QE,SignJWT as ek}from"jose";var Fc="zuplo-connect.",tk=600,Sy="mcp_connect_request_state",rk=p.object({purpose:p.literal(Sy),binding:p.string().min(1),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),nk=new TextEncoder;async function _y(){return Ve({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"connect-request-state"),"derive")})}o(_y,"getConnectRequestStateKey");async function wy(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",nk.encode(t));return YE.encode(new Uint8Array(r))}o(wy,"digestBinding");function Jc(e){return typeof e=="string"&&e.startsWith(Fc)}o(Jc,"isConnectRequestState");async function Ry(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new ek({purpose:Sy,binding:await wy(e)}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt(r).setExpirationTime(r+tk).sign(await _y());return`${Fc}${n}`}o(Ry,"signConnectRequestState");async function by(e,t,r=new Date){if(!Jc(e))return"invalid";let n;try{let{payload:s}=await QE(e.slice(Fc.length),await _y(),{algorithms:[Re],issuer:he,audience:we,currentDate:r,clockTolerance:0});n=rk.parse(s)}catch(s){return s instanceof XE.JWTExpired?"expired":"invalid"}return n.binding===await wy(t)?void 0:"mismatch"}o(by,"verifyConnectRequestState");var ok=new Set(["tools/call","prompts/get","resources/read"]);var sk=-32021,ik="Invalid or expired requestState";function rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(rn,"isRecord");function vy(e,t){if(!(!fe()||!rn(t)||typeof t.method!="string"||!zr(e,t)))return{message:t,method:t.method}}o(vy,"readModernMcpRequest");function Vc(e){return!Object.hasOwn(e.message,"id")}o(Vc,"isModernNotification");function Gc(){return new Response(null,{status:202})}o(Gc,"acceptedNotificationResponse");function Kc(e){let t=e.message.params;return rn(t)?t:void 0}o(Kc,"readParams");function Cy(e){if(!ok.has(e.method))return;let t=Kc(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}o(Cy,"readInputRequiredTarget");function Iy(e,t,r){return{...e,method:t.method,target:r}}o(Iy,"buildBinding");function ak(e){let t=Me(e.message);return Response.json(gt({...t===void 0?{}:{id:t},error:{code:A.InvalidParams,message:ik,data:{reason:"invalid_request_state"}}}))}o(ak,"invalidRequestStateResponse");function ck(e){if(!rn(e))return;let t=e[Nr],r=rn(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}o(ck,"readElicitationAction");function dk(e){let t={...Kc(e)};if(delete t.requestState,rn(t.inputResponses)){let r={...t.inputResponses};delete r[Nr],Object.keys(r).length===0?delete t.inputResponses:t.inputResponses=r}return{...e.message,params:t}}o(dk,"stripConnectState");async function Ty(e){let t=Kc(e.request),r=t?.requestState;if(!Jc(r))return{kind:"none"};let n=Cy(e.request),s=n===void 0?"mismatch":await by(r,Iy(e.binding,e.request,n),e.now);if(s!==void 0)return{kind:"rejected",reason:s,response:ak(e.request)};let i=dk(e.request),a=new TextEncoder().encode(JSON.stringify(i));return{kind:"accepted",body:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),request:{message:i,method:e.request.method},action:ck(t?.inputResponses)}}o(Ty,"readModernConnectRetry");function uk(e){let t=am(e.message)?.elicitation;return rn(t)&&t.url!==void 0}o(uk,"declaresUrlElicitation");function lk(e,t){return Response.json(gt({...e===void 0?{}:{id:e},error:{code:A.InvalidRequest,message:t.message,data:{connectRequired:t}}}))}o(lk,"connectRequiredErrorResponse");async function Ey(e){if(Vc(e.request))return Gc();let t=Me(e.request.message),r=Cy(e.request),n=e.payload.authUrl;if(r===void 0||n===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return lk(t,e.payload);if(!uk(e.request))return Response.json(gt({...t===void 0?{}:{id:t},error:{code:sk,message:`${e.payload.message} The client must declare URL elicitation (clientCapabilities.elicitation.url) to be sent the connect link.`,data:{requiredCapabilities:{elicitation:{url:{}}},connectRequired:e.payload}}}),{status:400});let s=await Ry(Iy(e.binding,e.request,r),e.now);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"input_required",inputRequests:{[Nr]:{method:"elicitation/create",params:{mode:"url",message:e.payload.message,url:n}}},requestState:s,_meta:{[ir]:e.serverInfo}}})}o(Ey,"modernConnectRequiredResponse");var Wc=[So],pk=0,mk="private",hk="0.0.0";function fk(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(fk,"buildGatewayDiscoverCapabilities");function Zc(e){let{connection:t}=e,r=t.serverInfo,n=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...n===void 0?{}:{title:n},version:r?.version??hk,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}o(Zc,"buildGatewayDiscoverServerInfo");function ky(e){let t=Me(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...Wc],capabilities:fk(e.capabilityFilter),_meta:{[ir]:Zc({connection:e.connection,icons:e.icons})},ttlMs:pk,cacheScope:mk}})}o(ky,"gatewayDiscoverResponse");var Yc=new WeakMap;function Ay(e,t){Yc.set(e,t)}o(Ay,"setUpstreamAuthRetry");function Py(e){let t=Yc.get(e);return Yc.delete(e),t}o(Py,"takeUpstreamAuthRetry");var gk=A.InvalidRequest,yk="The upstream connection returned no OAuth tokens.";function xy(e){let t=Za(e);return Response.json(gt({id:t,error:{code:A.InternalError,message:yk}}),{status:t===void 0?500:200})}o(xy,"noUpstreamTokensJsonRpcResponse");function Sk(e,t){return{credentialType:e.type,forceRefresh:t}}o(Sk,"buildCredentialResolvedAttributes");function _k(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(_k,"connectRequiredReasonCode");function Oy(e){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:Sk(e.credential,e.forceRefresh===!0)})}o(Oy,"emitCredentialResolvedAnalyticsEvent");function My(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:_k(e.payload.state),reasonClass:"auth",attributes:t})}o(My,"emitCredentialMissingAnalyticsEvents");function wk(e){let t=e.route.raw();return js.parse(t?.operationId)}o(wk,"readOperationId");async function Rk(e,t,r,n,s){let i=await en({request:e,context:n,routeAuth:t});if(i.kind==="connect_required")return My({context:n,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),n.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(Oy({context:n,credential:a,routeBinding:t,mcpProtocolVersion:s}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(n.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}o(Rk,"buildCredentialHeaders");var bk=new Set(["authorization","cookie","cookie2"]);function vk(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(vk,"parseJsonRequestBody");function Ck(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(Ck,"readJsonRequestMethod");function Ik(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Ik,"isJsonResponse");function Dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Dt,"isRecord");function Uy(e){return Array.isArray(e)&&e.length>0}o(Uy,"hasIconList");function qy(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=fi(Cm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(qy,"readFallbackServerIcons");function Tk(e){if(!Dt(e.body))return e.body;let t=e.body.result;if(!Dt(t))return e.body;let r=t.serverInfo;return!Dt(r)||Uy(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(Tk,"addMissingServerIcons");function Ek(e){if(!Dt(e.body))return e.body;let t=e.body.result;if(!Dt(t))return e.body;let r=t._meta;if(!Dt(r))return e.body;let n=r[ir];return!Dt(n)||Uy(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[ir]:{...n,icons:e.icons}}}}}o(Ek,"addMissingDiscoverServerIcons");function kk(e,t){let r=zy(e.headers);for(let n of bk)r.delete(n);for(let[n,s]of t)r.set(n,s);return new kt(e,{headers:r})}o(kk,"applyUpstreamHeaders");function zy(e){let t=new Headers(e);return au(t),t}o(zy,"buildProxyHeaders");async function Ak(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(Ak,"readRetryBody");function Pk(e,t){let r=t.authUrl===void 0?void 0:uf({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(gt({id:Za(e),error:{code:r?.code??gk,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}o(Pk,"connectRequiredJsonRpcResponse");function xk(e){let t=e.modern;if(t===void 0)return{respond:o(async s=>Pk(e.requestBody,s),"respond")};let r=o(()=>qy({connection:e.connection,context:e.context}),"readIcons"),n=t.request.method==="server/discover"?async()=>ky({request:t.request,connection:e.connection,capabilityFilter:Ok(e.context),icons:r()}):s=>Ey({request:t.request,payload:s,binding:t.binding,previousAction:t.previousAction,serverInfo:Zc({connection:e.connection,icons:r()})});return{respond:o(async s=>{let i=tg({headers:e.headers,message:t.request.message,supportedVersions:Wc});return i!==void 0?i:Vc(t.request)?Gc():n(s)},"respond")}}o(xk,"createConnectRequiredResponder");function Ok(e){return Ls()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(Ok,"readRouteCapabilityFilter");async function Mk(e){let{scope:t}=of(e.upstreamResponse),r=await en({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return My({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let n=new Headers(e.headers),s=r.credential;if(Oy({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return n.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:n};let i=await s.provider.tokens();return i?(n.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:n}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"no_tokens"})}o(Mk,"applyRefreshedCredentialHeaders");function Uk(e){Ay(e.context,{refresh:o(async(t,r)=>{let n=await Mk({request:e.request,context:e.context,headers:zy(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return n.kind==="connect_required"?{kind:"response",response:await e.connectRequired.respond(n.payload)}:n.kind==="no_tokens"?{kind:"response",response:xy(e.requestBody)}:n},"refresh")})}o(Uk,"registerUpstreamAuthRetry");function qk(e){return e.body!==null&&e.status>=200&&e.status<=299&&it(e.headers.get("content-type"))==="text/event-stream"&&!at(e.headers)}o(qk,"isRewritableEventStream");function zk(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(zk,"answersRequestId");function Nk(e,t){if(e.data===void 0||e.data===""||e.event!==void 0&&e.event!=="message")return;let r;try{r=JSON.parse(e.data)}catch{return}if(!(!Dt(r)||"method"in r||!("result"in r||"error"in r)||!zk(r.id,t)))return r}o(Nk,"readResponseInEvent");function jk(e){let t=!1;return ci(e.response,r=>{if(t)return;let n=Nk(r,e.requestId);if(n===void 0)return;t=!0;let s=e.addMissingIcons({body:n,icons:e.icons});return s===n?void 0:qo(r,JSON.stringify(s))},{failureMode:"open"})}o(jk,"addMissingIconsToEventStream");function Dk(e){let t=Ck(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?Tk:Ek,n=qy({connection:e.connection,context:e.context});if(n===void 0||n.length===0)return;let s=fe()?Me(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!Ik(i))return s!==void 0&&qk(i)?jk({response:i,requestId:s,addMissingIcons:r,icons:n}):i;let a;try{a=await i.clone().json()}catch{return i}let c=r({body:a,icons:n});if(c===a)return i;let d=pf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(Dk,"installInitializeIconHook");function Lk(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new kt(e,{headers:r,body:t})}o(Lk,"withRequestBody");async function Xc(e,t,r){let n=wk(t),s=e,i=await Ak(s),a=vk(i),c=sr(s.headers,a),d=yy({connection:r,operationId:n}),u=ar(s.user,s.url,s.headers);t.log.setLogProperties?.({requestId:t.requestId}),Mm(t,u);let m=tn(d,u.subjectId),h=vy(s.headers,a),f={subjectId:u.subjectId,operationId:n,upstreamServerId:m.upstreamServerId,authProfileId:m.authProfileId},S;if(h!==void 0){let b=await Ty({request:h,binding:f});if(b.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:b.reason,upstreamServerId:m.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),b.response;b.kind==="accepted"&&(s=Lk(s,b.body),i=b.body,a=b.request.message,h=b.request,S=b.action)}let R=xk({requestBody:i,headers:s.headers,modern:h===void 0?void 0:{request:h,binding:f,previousAction:S},context:t,connection:r}),_=await Rk(s,m,r,t,c);if(_.kind==="connect_required")return R.respond(_.payload);if(_.kind==="no_tokens")return xy(i);let y=kk(s,_.headers);return Uk({request:y,context:t,requestBody:i,connectRequired:R,routeAuth:m,mcpProtocolVersion:c}),Dk({context:t,requestJson:a,connection:r,modern:h!==void 0}),y}o(Xc,"mcpTokenExchangePolicy");var Qc=class extends Cs{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=Am(t,r);super(n,r),this.#e=n}async handler(t,r){return Xc(t,r,this.#e)}};var Ny=Symbol("Html");function $k(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o($k,"escapeHtml");function Hk(e){return e===null||typeof e!="object"?!1:e[Ny]===!0}o(Hk,"isHtml");function Pi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Pi).join(""):Hk(e)?e.value:$k(String(e))}o(Pi,"renderValue");function Ge(e){return{[Ny]:!0,value:e}}o(Ge,"trustedHtml");var Ke=Ge("");function W(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Pi(t[n]),r+=e[n+1]??"";return Ge(r)}o(W,"html");function nn(e,t=Ke){let r=Pi(t),n="",s=!0;for(let i of e)s||(n+=r),n+=Pi(i),s=!1;return Ge(n)}o(nn,"joinHtml");function on(e){return e.value}o(on,"renderHtml");function jy(e){return W`<section class="page-section" aria-labelledby="error-next-steps"><h2 class="section-label" id="error-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol>${e.action}</section><section class="page-section" aria-labelledby="error-reference"><h2 class="section-label" id="error-reference">Reference</h2><dl class="kv kv--boxed">${e.reference}</dl></section><section class="page-section tech" aria-labelledby="error-technical"><h2 class="section-label" id="error-technical">Technical details <span class="section-label__count">for administrators</span></h2><dl class="kv">${e.diagnostics}</dl>${e.upstreamResponse}</section>`}o(jy,"renderBrowserErrorPage");var Dy=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><path d="m8.25 12.25 2.5 2.5 5-5.25"/></svg>'),Ly=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><line x1="12" y1="7.5" x2="12" y2="12.75"/><circle cx="12" cy="16.25" r=".9" fill="currentColor" stroke="none"/></svg>'),sn=Ge('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}.card__status{border:1px solid;border-radius:50%;justify-content:center;align-items:center;width:48px;height:48px;margin:0 auto 16px;display:flex}.card__status svg{width:24px;height:24px}.card__status--error{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger)}.card__status--success{background:var(--success-bg);border-color:var(--success-border);color:var(--success)}.card__status--neutral{background:var(--surface-2);border-color:var(--border);color:var(--text-3)}.page-section{flex-direction:column;gap:10px;display:flex}.steps{counter-reset:step;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.steps li{counter-increment:step;color:var(--text-2);align-items:flex-start;gap:10px;font-size:13.5px;line-height:1.5;display:flex}.steps li:before{content:counter(step);border:1px solid var(--border-strong);background:var(--surface);width:20px;height:20px;color:var(--text-2);border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;margin-top:1px;font-size:11.5px;font-weight:600;line-height:1;display:inline-flex}.kv{flex-direction:column;margin:0;display:flex}.kv__row{border-top:1px solid var(--border);grid-template-columns:124px minmax(0,1fr);gap:2px 12px;padding:7px 0;display:grid}.kv__row:first-child{border-top:0;padding-top:0}.kv__row:last-child{padding-bottom:0}.kv__row--block{grid-template-columns:minmax(0,1fr)}.kv__label{color:var(--text-3);margin:0;padding-top:1px;font-size:12px;font-weight:500}.kv__value{min-width:0;color:var(--text);overflow-wrap:anywhere;margin:0;font-size:13px;line-height:1.5}.kv__value code{font-family:var(--font-mono);color:var(--text);font-size:12px}.kv__row--fix .kv__value{color:var(--text);font-weight:500}.kv--boxed{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px}.kv--boxed .kv__row{grid-template-columns:92px minmax(0,1fr);padding:6px 0}.kv--boxed .kv__row:first-child{padding-top:0}.kv--boxed .kv__row:last-child{padding-bottom:0}.tech{border-top:1px solid var(--border);padding-top:18px}.provider-response{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2)}.provider-response__summary{cursor:pointer;user-select:none;color:var(--text-2);align-items:center;gap:8px;padding:9px 12px;font-size:12.5px;font-weight:500;list-style:none;display:flex}.provider-response__summary::-webkit-details-marker{display:none}.provider-response__summary:before{content:"";border-bottom:1.5px solid;border-right:1.5px solid;flex-shrink:0;width:6px;height:6px;margin-left:2px;transition:transform .15s;transform:rotate(-45deg)}.provider-response[open]>.provider-response__summary:before{transform:rotate(45deg)}.provider-response__summary:hover{color:var(--text)}.provider-response__summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--radius)}.provider-response__frame{border:0;border-top:1px solid var(--border);border-radius:0 0 var(--radius)var(--radius);background:#fff;width:100%;min-height:240px;display:block}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.kv__row{grid-template-columns:minmax(0,1fr)}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function an(e){return W`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
40
+ `),Be(K.text),K.terminate){A("SSE stream terminated by its rewriter"),x.close();return}}h=!0,x.close();return}if(He)return}}catch(B){h||(A(B),(x.desiredSize??0)<0?I={error:B}:x.error(B))}},cancel(x){if(!h)return h=!0,d.abort(x),m.cancel(x)}},{highWaterMark:0})}o(Qa,"rewriteSseStream");function zv(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(zv,"concatBytes");function ni(e,t,r){if(e.body===null)return e;let n=St(new Headers(e.headers));return n.set("content-type","text/event-stream"),new Response(Qa(e.body,t,r),{status:e.status,statusText:e.statusText,headers:n})}o(ni,"rewriteSseResponse");var wf=new Set(["jsonrpc","method","id","params"]),rc=new Set(["name","uri","ref"]),Rf=new Set(["type","name","uri"]),Nv="subscriptions/listen",nc="notifications",bf="resourceSubscriptions",jv=new Set([...rc,_t(nc)]),Dv=new Set([_t(bf)]),$v=/[^\u0000-\u007f]/,Lv=34,Hv=92,Sf=123,Bv=125,Fv=91,Jv=93,Gv=58,ec=44;function Uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Uo,"isRecord");function _t(e){return e.toUpperCase().toLowerCase()}o(_t,"foldCase");function tc(e,t){return Object.keys(e).some(r=>{let n=_t(r);return n!==r&&t.has(n)})}o(tc,"hasCaseVariant");function _f(e,t){let r=_t(t);return Object.keys(e).some(n=>n!==t&&_t(n)===r)}o(_f,"hasCaseVariantOf");function Vv(e,t){let r=o(a=>{switch(a.role){case"member":return wf;case"params":return t.has(a.member)?jv:rc;case"ref":return Rf;case"notifications":return Dv;default:return}},"watchedFor"),n=[],s=0,i=o(a=>{let c=n.at(-1);if(c===void 0)return a?"member":"batch";if(a){if(c.role==="batch")return"member";if(c.role==="member"&&c.key==="params")return"params";if(c.role==="params"&&c.key==="ref")return"ref";if(c.role==="params"&&c.key===nc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===Lv){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let m=0;for(;e.charCodeAt(d-1-m)===Hv;)m++;if(m%2===0)break}let u=s>0?void 0:n.at(-1);if(u?.isObject&&u.expectKey){let m=e.slice(a,d+1),h=m.includes("\\")?JSON.parse(m):m.slice(1,-1);if($v.test(h))return!0;u.key=h;let f=_t(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===Sf||c===Fv){let d=c===Sf,u=s>0?void 0:i(d);if(u===void 0)s++;else{let m=n.at(-1)?.member??0;n.push({role:u,isObject:d,seen:new Set,member:m,expectKey:d})}}else if(c===Bv||c===Jv)s>0?s--:n.pop();else if(s===0&&(c===Gv||c===ec)){let d=n.at(-1);d?.isObject?d.expectKey=c===ec:d?.role==="batch"&&c===ec&&d.member++}}return!1}o(Vv,"hasUnsafeKeyInText");function vf(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(Uo(s)){if(tc(s,wf)||e.checksListen===!0&&s.method===Nv&&(t.add(r),Uo(s.params)&&(_f(s.params,nc)||Uo(s.params.notifications)&&_f(s.params.notifications,bf))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!Uo(s.params))&&(tc(s.params,rc)||Uo(s.params.ref)&&tc(s.params.ref,Rf)))return!0}}return Vv(e.text,t)}o(vf,"hasAmbiguousIdentifyingKeys");var Kv=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),Wv=47,Cf=44,Zv=38,oc=o(e=>e!==Wv&&e!==Cf,"VALUE"),Yv=o(e=>!Kv(e),"ANY"),Xv=o(e=>e!==Zv,"QUERY_VALUE"),Qv=["+","#",".","/","?","&"],sc=class{static{o(this,"Builder")}edges=[[]];current=0;#e(){return this.edges.push([]),this.edges.length-1}literal(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:o(i=>i===n,"test"),to:s}),this.current=s}}plus(t){let r=this.#e();this.edges[this.current].push({test:t,to:r}),this.edges[r].push({test:t,to:r}),this.current=r}value(t){if(this.plus(oc),!t)return;let r=this.current,n=this.#e();this.edges[r].push({test:o(s=>s===Cf,"test"),to:n}),this.edges[n].push({test:oc,to:r})}};function If(e){let t=new sc,r="",n=0;for(;n<e.length;){if(e[n]!=="{"){r+=e[n],n++;continue}let s=e.indexOf("}",n);if(s===-1)return;t.literal(r),r="";let i=e.slice(n+1,s),a=Qv.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,m)=>{t.literal(`${m===0?a:"&"}${u}=`),t.plus(Xv)});break;case"+":case"#":t.plus(Yv);break;case".":t.literal("."),t.plus(oc);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}n=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}o(If,"compileUriTemplate");function Tf(e,t){if(t.length>1e6)return!1;let{edges:r,accept:n}=e,s=new Array(r.length).fill(-1),i=[0];for(let a=0;a<t.length;a++){let c=t.charCodeAt(a),d=[];for(let u of i)for(let m of r[u])s[m.to]!==a&&m.test(c)&&(s[m.to]=a,d.push(m.to));if(d.length===0)return!1;i=d}return i.includes(n)}o(Tf,"matchesUriTemplate");var ci=p.record(p.string(),p.unknown()),eC=p.record(p.string(),p.unknown()),qt=p.array(p.string().min(1)).min(1).optional(),tC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),annotations:eC.optional(),_meta:ci.optional(),roles:qt,groups:qt,public:p.boolean().optional()}).strict(),rC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),_meta:ci.optional(),roles:qt,groups:qt,public:p.boolean().optional()}).strict(),nC=p.object({uri:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:ci.optional(),roles:qt,groups:qt,public:p.boolean().optional()}).strict(),oC=p.object({uriTemplate:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:ci.optional(),roles:qt,groups:qt,public:p.boolean().optional()}).strict(),sC=p.array(p.union([p.string(),tC])),iC=p.array(p.union([p.string(),rC])),aC=p.array(p.union([p.string(),nC])),cC=p.array(p.union([p.string(),oC])),dC=p.object({module:p.unknown(),export:p.string().min(1)}).strict(),uC=p.object({mode:p.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:p.string().min(1).optional(),groupClaim:p.string().min(1).optional(),identifier:dC.optional()}).strict(),lC=p.object({tools:sC.optional(),prompts:iC.optional(),resources:aC.optional(),resourceTemplates:cC.optional(),accessControl:uC.optional()}).strict(),wt=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read","resources/subscribe","resources/unsubscribe"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function pC(e,t){return mm(lC,e,`MCP capability filter policy "${t}"`)}o(pC,"parseMcpCapabilityFilterOptions");function V(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(V,"isRecord");function Je(e){return typeof e.method=="string"?e.method:void 0}o(Je,"messageMethod");function zo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}o(zo,"correlationKey");function Uf(e){let t=new Set,r=new Map;for(let n of e){let s=zo(n);if(s===void 0)continue;t.add(s);let i=String(n),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return n=>{let s=zo(n);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(n));return i?.size===1?[...i][0]:void 0}}o(Uf,"createReplyIdMatcher");function Ef(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(Ef,"asStringArray");function kf(e,t){if(!V(e))return[];let r=t in e?e[t]:t.split(".").reduce((n,s)=>V(n)?n[s]:void 0,e);return Array.isArray(r)?r.filter(n=>typeof n=="string"):typeof r=="string"?r.split(/\s+/).filter(n=>n.length>0):[]}o(kf,"readClaimValues");function mc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!V(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Ef(e.roles),groups:Ef(e.groups),public:e.public===!0}}o(mc,"normalizeEntry");function mC(e,t,r){if(e.public)return!0;let n=e.roles??[],s=e.groups??[];return n.length===0&&s.length===0?!1:n.some(i=>t.has(i))||s.some(i=>r.has(i))}o(mC,"isCallerAllowed");function oi(e,t,r,n){if(e===void 0)return;let s=[];for(let i of e){let a=mc(i,t);a!==void 0&&mC(a,r,n)&&s.push(a.key)}return s}o(oi,"allowedKeys");var qf=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(kf(e.user?.data,n)),a=new Set(kf(e.user?.data,s));return{tools:oi(r.tools,"name",i,a),prompts:oi(r.prompts,"name",i,a),resources:oi(r.resources,"uri",i,a),resourceTemplates:oi(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function hC(e,t){let r=[];for(let n of wt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=mc(i,n.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new Q(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}o(hC,"assertNoConflictingMarkup");function fC(e,t){let r=[];for(let n of wt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=mc(i,n.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new Q(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}o(fC,"assertNoMarkup");function gC(e,t){let r=e.identifier;if(r===void 0)throw new Q(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new Q(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new Q(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let n=r.module[r.export];if(typeof n!="function")throw new Q(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=n;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new k(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof d!="object"||Array.isArray(d))throw new k(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}o(gC,"buildCustomResolver");function yC(e,t){let r=e.accessControl,n=r?.mode??"allPublic";if(n==="function"){if(r===void 0)throw new Q(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return gC(r,t)}if(n==="rolesAndGroups")return hC(e,t),qf;fC(e,t)}o(yC,"buildCapabilityResolver");function SC(e){let t={};for(let r of wt){let n=e[r.option];if(n===void 0)continue;let s=new Map;for(let i of n){let a=LC(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o(SC,"buildProjectionMaps");function zf(e){return e===void 0?void 0:wt.find(t=>t.listMethod===e)}o(zf,"findListRule");function hc(e){return e===void 0?void 0:wt.find(t=>t.directMethods.includes(e))}o(hc,"findDirectRule");var di="completion/complete",Nf=["prompts","resources","resourceTemplates"];function jf(e){return e===di||hc(e)!==void 0}o(jf,"isCapabilityMethod");var ai="subscriptions/listen",_C=[...wt.flatMap(e=>[e.listMethod,...e.directMethods]),di,ai];function wC(e){let t=_t(e.trim()),r=_C.find(n=>_t(n)===t);return r!==void 0&&r!==e?r:void 0}o(wC,"methodVariantOf");function RC(e,[t,r]){return{code:P.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(RC,"invalidParams");function fc(e){return t=>({code:P.InvalidParams,message:`${e} "${As(t)}" not found`})}o(fc,"namedNotFound");function bC(e,t){return{code:Zp(t),message:"Resource not found",data:{uri:ks(e,Yp)}}}o(bC,"resourceNotFound");var vC={legacy:fc("Tool"),modern:fo.tool},ic={legacy:fc("Prompt"),modern:fo.prompt},CC={legacy:bC,modern:fo.resource},IC={legacy:fc("Resource template"),modern:fo.resourceTemplate};function TC(e){let t=Je(e);if(t===void 0||!jf(t))return[];let r=V(e.raw)?e.raw.params:void 0,n=o((d,u)=>V(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=o(d=>V(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==di){let d=hc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:n(r,"uri"),issue:s("params.uri"),notFound:CC}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?vC:ic}]}let i=V(r)?r.ref:void 0,a=V(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:n(i,"name"),issue:["params.ref.name","a string"],notFound:ic}];if(a==="ref/resource"){let d=n(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&EC(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:IC}]}let c=V(r)?V(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Nf,target:void 0,issue:c,notFound:ic}]}o(TC,"capabilityAccesses");function EC(e){let t=!1,r=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else kC(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(EC,"hasTemplateExpression");function kC(e){return e>32&&e<127?!1:AC.test(String.fromCharCode(e))}o(kC,"isWhitespaceCode");var AC=/\s/;function PC(e){return e.type==="invalid"&&(!V(e.raw)||e.raw.jsonrpc!=="2.0")}o(PC,"isNonJsonRpcMember");function xC(e){return V(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(xC,"hasNonStringMethod");function Df(e){return e.type==="request"||e.type==="invalid"&&Je(e)!==void 0}o(Df,"awaitsReply");function OC(e){return V(e.raw)&&V(e.raw.params)?e.raw.params:void 0}o(OC,"rawParams");function MC(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:fe()&&Nr(e.headers,r.raw)}o(MC,"isModernRequest");var Af={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},ac="=?base64?",cc="?=",UC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function qC(e){if(!e.startsWith(ac)||!e.endsWith(cc)||e.length<ac.length+cc.length)return e;let t=e.slice(ac.length,e.length-cc.length);if(UC.test(t))try{let r=atob(t),n=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}o(qC,"decodeMcpHeaderValue");var zC=-32020;function NC(e,t){let r=Je(t);if(r===void 0)return;let n=V(t.raw)?t.raw.id:void 0,s=gc(n)?n:void 0,i=e.headers.get("mcp-protocol-version"),a=nm(t.raw);if(i!==null&&a!==void 0&&i!==a)return si(s,i,`the body envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let c=e.headers.get("mcp-method");if(c!==null&&c!==r)return si(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(Af,r)?Af[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let m=qC(d);if(m===void 0)return si(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=OC(t)?.[u];if(typeof h=="string"&&m!==h)return si(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${m}"`)}o(NC,"headerMismatchResponse");function si(e,t,r){return Kr(400,{code:zC,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(si,"mismatchResponse");var jC={code:P.MethodNotFound,message:"Method not found"},Pf={code:P.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},DC={code:P.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},$C="2025-06-18";function gc(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(gc,"isValidRequestId");function $f(e){return V(e.raw)&&!Object.hasOwn(e.raw,"id")}o($f,"isSentAsNotification");function qo(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}o(qo,"jsonRpcError");function Kr(e,t,r){return Response.json(qo(t,r),{status:e})}o(Kr,"jsonRpcErrorResponse");function ii(e){return Kr(400,{code:P.InvalidRequest,message:`Invalid Request: ${e}`})}o(ii,"invalidRequestResponse");function dc(e,t,r=!1){if($f(e))return{status:400,body:qo({code:P.InvalidRequest,message:`Invalid Request: a notification cannot use ${As(Je(e)??"this method")}; send it as a request with an id`})};let n=V(e.raw)?e.raw.id:void 0;return gc(n)?{status:r&&t.code===P.MethodNotFound?404:200,body:qo(t,n)}:{status:400,body:qo({code:P.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}o(dc,"refusalOf");function xf(e,t,r=!1){let[n]=[...t];if(e.shape!=="batch"){let{status:a,body:c}=dc(n[0],n[1],r);return Response.json(c,{status:a})}let s=e.protocolVersion;if(s!==void 0&&s>=$C)return ii(`protocol version ${As(s)} does not support JSON-RPC batches`);let i=e.messages.flatMap(a=>a.type==="result"||a.type==="error"||$f(a)?[]:[dc(a,t.get(a)??DC).body]);if(i.length===0){let{status:a,body:c}=dc(n[0],n[1]);return Response.json(c,{status:a})}return Response.json(i)}o(xf,"refusalResponse");function LC(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!V(e))return;let r=e[t];if(typeof r!="string")return;let n={...e};return delete n.roles,delete n.groups,delete n.public,{key:r,overlay:n}}o(LC,"buildProjection");function Of(e){let t=e.base[e.property],r=e.overlay[e.property];return V(r)?V(t)?{...t,...r}:r:t}o(Of,"mergeRecordProperty");function HC(e,t){let r={...e,...t.overlay},n=Of({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=Of({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(HC,"applyProjection");var Ae=Symbol("unreadable"),Wr=Symbol("dropped");function BC(e,t,r,n,s){let i=e.result;if(!V(i))return Ae;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?Ae:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!V(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(n!==void 0&&!n.has(u))return[];let m=r.get(u);return m===void 0?[]:[HC(d,m)]})}}}o(BC,"filterAndProjectItems");var Lf="resources/read";function FC(e){let t=e.result;return!V(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}o(FC,"withPrivateReadScope");function Hf(e,t){let r=zf(Je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(Hf,"listTargetOf");function JC(e,t,r){return V(e)&&wt.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(JC,"carriesUnfilteredList");function GC(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(y=>Hf(y,r),"listTarget"),d=t.messages.filter(Df),u=new Map;for(let y of d){let b=zo(y.id);b!==void 0&&!u.get(b)&&u.set(b,c(y))}let m=Uf(d.map(y=>y.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&Je(h)===Lf,S=o(y=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let b=m(y);return b===void 0?void 0:u.get(b)},"targetForReply"),R=o(y=>{if(!V(y))return Ae;if(!("result"in y))return"method"in y&&!("error"in y)?_(y):"error"in y||"method"in y?y:Ae;let b=S(y.id);return b===void 0||JC(y.result,b,r)?Ae:b===null?f?FC(y):y:BC(y,b.rule,b.projections,n?.[b.rule.option],s)},"filterMessage"),_=o(y=>{if(a===void 0)return y;if(y.method==="notifications/resources/updated"){let b=V(y.params)?y.params.uri:void 0;return typeof b=="string"&&!a(b)?Wr:y}if(y.method==="notifications/subscriptions/acknowledged"){let b=Jf(y.params,a);return b===void 0?y:{...y,params:b}}return y},"filterServerMessage");return y=>{if(!Array.isArray(y))return R(y);if(t.shape!=="batch")return Ae;let b=y.map(R);if(b.includes(Ae))return Ae;let I=b.filter(A=>A!==Wr);return I.length===b.length?b:I.length===0?Wr:I}}o(GC,"createReplyFilter");function VC(e){return it(e.headers.get("content-type")).includes("json")}o(VC,"isJsonResponse");function KC(e){return it(e.headers.get("content-type"))==="text/event-stream"}o(KC,"isEventStreamResponse");var WC=10*1024*1024,ZC=/^[\w.~:/+=-]{0,256}$/;function YC(e){if(gf(e))return null;let t=!1;for(let n of e.lines){let s=n.indexOf(":"),i=s===-1?n:n.slice(0,s),a=s===-1?"":n.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&ZC.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=o(n=>n.trim()===""?n:"","blank");return{...e,lines:e.lines.map(n=>n.startsWith(":")?`:${r(n.slice(1))}`:n),comments:e.comments.map(r)}}o(YC,"inspectSseLines");var Bf="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",XC="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function lc(e,t){let r=e.messages.filter(Df),n=new Map,s=new Set;for(let u of r){let m=u.id,h=zo(m);m==null||h===void 0||(n.set(h,m),Hf(u,t)!==null&&s.add(h))}let i=Uf(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:zo(a.id),d=new Set;return{keyOf(u){if(!(!V(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:o(u=>u!==void 0&&n.has(u),"isPending"),hasFailed:o(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&n.delete(u)},fail(u){return[...u].flatMap(m=>{let h=n.get(m);return h===void 0?[]:(n.delete(m),d.add(m),[{jsonrpc:"2.0",id:h,error:{code:P.InternalError,message:s.has(m)?Bf:XC}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(lc,"createReplyTracker");function Ff(e,t,r){let n=[],s=0;for(let i of e){let a=r.keyOf(i);if(a!==void 0&&r.hasFailed(a))continue;let c=Array.isArray(i)?Ae:t(i);c!==Wr&&(c!==Ae?(n.push(c),r.answer(a)):r.isPending(a)?n.push(...r.fail([a])):s++)}return{replies:n,dropped:s}}o(Ff,"filterBatchMembers");function QC(e){let{response:t,envelope:r,projectionMaps:n,filterReply:s,warn:i}=e,a=lc(r,n),c=!1,d=o(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=o(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),m=o(()=>a.pendingKeys().length===0,"isDone");return ni(t,h=>{let f=YC(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let S;try{S=JSON.parse(f.data)}catch{return d("its data is not JSON")}let R=a.keyOf(S);if(R!==void 0&&a.hasFailed(R))return null;let _=s(S);if(_===Wr)return null;if(_===Ae&&r.shape==="batch"&&Array.isArray(S)){let{replies:y,dropped:b}=Ff(S,s,a);if(b>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),y.length===0)return null;let I=Mo(f,JSON.stringify(y));return m()?Xa(I):I}if(_===Ae){if(!a.isPending(R))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let y=u(a.fail([R]));return m()?Xa(...y):y}for(let y of Array.isArray(_)?_:[_])a.answer(a.keyOf(y));return _===S?f:Mo(f,JSON.stringify(_))},{maxEventChars:WC,onOversize:"discard",end:o(({unterminated:h,discardedEvents:f})=>((h||f>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||f>0?u(a.fail(a.pendingKeys())):null),"end"),onFailure:o((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}o(QC,"filterEventStream");function yc(e){return Je(e)===ai}o(yc,"isListenRequest");function eI(e){return fe()&&e.messages.some(yc)}o(eI,"filtersListen");function Jf(e,t){if(!V(e)||!V(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let n=r.filter(s=>typeof s=="string"&&t(s));if(n.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:n}}}o(Jf,"narrowSubscriptionParams");function tI(e,t,r){let n=!1,s=t.messages.map(a=>{if(!yc(a)||!V(a.raw))return a.raw;let c=Jf(a.raw.params,r);return c===void 0?a.raw:(n=!0,{...a.raw,params:c})});if(!n)return e;let i=new Headers(e.headers);return i.delete("content-length"),new At(e,{headers:i,body:JSON.stringify(t.shape==="batch"?s:s[0])})}o(tI,"narrowListenSubscriptions");var uc=Symbol("access unresolved"),Mf=10*1024*1024,Gf="the request body could not be read";async function rI(e,t,r){let n=e.clone().body;if(n===null)return{blank:!0,overLimit:!1};let s=n.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:u}=await s.read(),m=d?i.decode():i.decode(u,{stream:!0});if(a+=m.length,c&&=!/\S/.test(m),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}o(rI,"scanBody");function Sc(e){return Array.isArray(e)?`batch member 0: ${Sc(e[0])}`:V(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}o(Sc,"invalidMessageReason");async function nI(e,t){if(e.body===null)return;let r=o(()=>Ne.contentTooLarge(e,t,{detail:"The request body is larger than the MCP capability filter can inspect."}),"tooLarge");if(Number(e.headers.get("content-length")??Number.NaN)>Mf)return r();let s=it(e.headers.get("content-type")).includes("json"),i=o(()=>Ne.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=o(()=>Kr(400,{code:P.ParseError,message:`Parse error: ${Gf}`}),"unreadable"),c;try{c=await rI(e,Mf,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(m){return m instanceof SyntaxError?Kr(400,{code:P.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=V(d)?d.id:void 0;return Kr(400,{code:P.InvalidRequest,message:`Invalid Request: ${Sc(d)}`},gc(u)?u:void 0)}o(nI,"refuseUninspectable");var pc=class extends ws{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=pC(t,r);super(n,r),this.#r=r,this.#e=SC(n),this.#t=yC(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,If(i)]))}async handler(t,r){let n=await im(t);if(n===null)return await nI(t,r)??t;let s=MC(t,n);if(s){let v=n.messages[0],Y=v===void 0?void 0:NC(t,v);if(Y!==void 0)return Y}let i=n.messages.findIndex(PC);if(i!==-1)return ii(`batch member ${i}: ${Sc(n.messages[i].raw)}`);let a=n.messages.findIndex(xC);if(a!==-1)return ii(n.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=sm(n);if(c===void 0)try{c=await t.clone().text()}catch{return Kr(400,{code:P.ParseError,message:`Parse error: ${Gf}`})}if(vf({envelope:n,text:c,isCapabilityMethod:jf,checksListen:this.#a()}))return ii("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let d=new Map;for(let v of n.messages){let Y=Je(v),O=Y===void 0?void 0:wC(Y);O!==void 0&&this.#u(O)&&d.set(v,jC)}let u=eI(n),m=d.size===0&&this.#t!==void 0&&n.messages.some(v=>this.#i(v,u))?await this.#s(t,r):void 0,h=s&&rm(t.headers.get("mcp-protocol-version"));if(d.size===0)for(let v of n.messages){let Y=m===uc?this.#i(v,u)?Pf:void 0:this.#m(v,m,h,n.protocolVersion);Y!==void 0&&d.set(v,Y)}if(d.size>0)return xf(n,d,s);if(m===uc)return xf(n,new Map(n.messages.map(v=>[v,Pf])),s);let f=u||s?this.#l(m):void 0,S=f===void 0?t:tI(t,n,f),R=s&&this.#t!==void 0,_=R&&this.#p();if(!this.#h(n,u,_))return S;let y=GC({envelope:n,projectionMaps:this.#e,allowedSets:m,privateScope:R,privateReadScope:_,isResourceVisible:f}),b=o(v=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${v}`),"warn"),I=o((v,Y)=>{b(`did not forward an upstream reply (${v}); answered -32603`);let O=lc(n,this.#e),Z=O.fail(O.pendingKeys()),re=St(new Headers(Y.headers));return re.set("content-type","application/json"),Z.length===0?new Response(JSON.stringify(qo({code:P.InternalError,message:Bf})),{status:502,headers:re}):new Response(JSON.stringify(n.shape==="batch"?Z:Z[0]),{status:200,headers:re})},"unreadable");r.addResponseSendingHook(async v=>{let Y=!v.ok;if(v.body!==null&&at(v.headers))return Y?v:I("its body is still content-encoded",v);if(KC(v))return QC({response:v,envelope:n,projectionMaps:this.#e,filterReply:y,warn:b});if(!VC(v))return v.ok&&v.status!==202&&v.status!==204&&v.body!==null?I("no or an unknown media type",v):v;let O;try{O=await v.clone().json()}catch{return Y?v:I("its body is not JSON",v)}if(Y&&!Array.isArray(O)&&!(V(O)&&"result"in O))return v;let Z=y(O);if(Z===Ae&&n.shape==="batch"&&Array.isArray(O)){let x=lc(n,this.#e),{replies:B,dropped:j}=Ff(O,y,x);j>0&&B.push(...x.fail(x.pendingKeys())),B.length>0&&(b("did not forward a batch reply member it could not read; sent the rest"),Z=B)}if(Z===Ae||Z===Wr)return I("the filter could not read the reply",v);if(Z===O)return v;let re=St(new Headers(v.headers));return new Response(JSON.stringify(Z),{status:v.status,statusText:v.statusText,headers:re})});let A=new At(S);return A.headers.set("accept-encoding","gzip, br"),A}#l(t){if(!this.#p())return;let r=o((n,s)=>{let i=t?.[n];return this.#e[n]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return n=>this.#d(n,r)}#p(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#m(t,r,n,s){let i=o(c=>this.#e[c]!==void 0,"isConfigured"),a=o((c,d)=>{let u=r?.[c];return this.#e[c]?.has(d)===!0&&(u===void 0||u.has(d))},"isAllowed");for(let c of TC(t)){if(!(c.refusedBy??c.options).some(i))continue;let{target:d}=c;if(d===void 0)return RC(Je(t)??"",c.issue);if(!(c.resource?this.#d(d,a):c.options.filter(i).some(m=>a(m,d))))return n?c.notFound.modern(d):c.notFound.legacy(d,s??null)}}#d(t,r){let n=this.#e.resources!==void 0;if(n&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!Tf(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!n&&!s}#o(t){let r=o(n=>this.#e[n]!==void 0,"isConfigured");return t===di?Nf.some(r):hc(t)?.option==="resources"&&r("resourceTemplates")?!0:wt.some(n=>r(n.option)&&(n.listMethod===t||n.directMethods.includes(t)))}#i(t,r){let n=Je(t);return r&&n===ai&&this.#p()?!0:n!==void 0&&this.#o(n)}#a(){return fe()&&this.#p()}#u(t){return t===ai?this.#a():this.#o(t)}#h(t,r,n){return t.messages.some(s=>{if(r&&yc(s))return this.#p();if(n&&t.shape==="single"&&Je(s)===Lf)return!0;let i=zf(Je(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#s(t,r){let n=this.#t;if(n===void 0)return{};let s;try{s=await n(t,r,this.options)}catch(a){return r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; refused the requests that needed it`,a),uc}let i={};for(let a of wt){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let m of d)typeof m=="string"&&c.has(m)&&u.add(m);i[a.option]=u}return i}};var _c="zuplo.com",oI=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),sI=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Vf(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(Vf,"s2FaviconHref");function iI(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}o(iI,"strictFaviconHref");var Kf=Vf(_c);function wc(e){let t=e.toLowerCase();return t===_c||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Vf(_c):iI(e)}o(wc,"resolveIconHref");function aI(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(aI,"hostnameFromHost");function cI(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(cI,"isLocalOrAddressHost");function dI(e){let t=aI(e).toLowerCase().replace(/\.$/,"");if(cI(t)||sI.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let n=r.slice(-2).join("."),s=oI.has(n)?3:2;return r.slice(-s).join(".")}o(dI,"inferFaviconDomain");function Rc(e){return{src:wc(dI(e)),mimeType:"image/png",sizes:["128x128"]}}o(Rc,"resolveMcpFaviconIcon");function ui(e){try{return Rc(new URL(e).host)}catch{return}}o(ui,"resolveMcpFaviconIconFromUrl");var uI=-32020,lI=new Set(["envelope-invalid","modern-header-without-claim","header-body-version-mismatch","method-header-mismatch","notification-envelope-invalid","notification-header-body-version-mismatch","notification-method-header-mismatch"]),Wf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Zf="=?base64?",Yf="?=",pI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function mI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(mI,"isRecord");function Xf(e){return e===" "||e===" "}o(Xf,"isHttpOws");function hI(e){let t=0,r=e.length;for(;t<r&&Xf(e[t]);)t++;for(;r>t&&Xf(e[r-1]);)r--;return e.slice(t,r)}o(hI,"stripHttpOws");function li(e,t){return e.get(t)??void 0}o(li,"readHeader");function fI(e){if(!e.startsWith(Zf)||!e.endsWith(Yf))return e;let t=e.slice(Zf.length,e.length-Yf.length);if(pI.test(t))try{let r=Uint8Array.from(atob(t),n=>n.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}o(fI,"decodeMcpHeaderValue");function vc(e,t,r){let n=Me(e);return Response.json(yt({...n===void 0?{}:{id:n},error:r}),{status:t})}o(vc,"errorResponse");function Qf(e,t,r){return vc(e,400,{code:uI,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(Qf,"headerMismatchResponse");function gI(e,t){let r=t.method,n=li(e,"mcp-name");if(n===void 0||typeof r!="string"||!Object.hasOwn(Wf,r))return;let s=Wf[r],i=hI(n),a=fI(i);if(a===void 0)return Qf(t,i,"the Mcp-Name header carries an invalid Base64 sentinel value");let c=mI(t.params)?t.params[s]:void 0,d=typeof c=="string"?c:void 0;if(d!==void 0&&a!==d)return Qf(t,i,`the body carries params.${s}="${d}" but the Mcp-Name header names "${a}"`)}o(gI,"mcpNameMismatchResponse");function eg(e){let{headers:t,message:r}=e,n=Wp({httpMethod:"POST",...bc("protocolVersionHeader",li(t,"mcp-protocol-version")),...bc("mcpMethodHeader",li(t,"mcp-method")),...bc("mcpNameHeader",li(t,"mcp-name")),body:r});if(n.kind==="reject")return lI.has(n.cell)?vc(r,n.httpStatus,{code:n.code,message:n.message,...n.data===void 0?{}:{data:n.data}}):void 0;if(n.kind!=="modern")return;let s=n.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new Kp({supported:[...e.supportedVersions],requested:s??"unknown"});return vc(r,400,{code:i.code,message:i.message,data:i.data})}return n.messageKind==="request"?gI(t,r):void 0}o(eg,"validateModernGatewayRequest");function bc(e,t){return t===void 0?{}:{[e]:t}}o(bc,"optionalHeader");import{context as yI,TraceFlags as SI,trace as _I}from"@opentelemetry/api";var tg="mcp-session-id",wI=256*1024;function ct(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(ct,"isPlainObject");function rg(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(rg,"isJsonContentType");function Ic(e,t,r){if(t===void 0||r===void 0||r.byteLength>Xm||!rg(e))return;let n=t.value;if(!ct(n)||typeof n.method!="string"||n.params!==void 0&&!ct(n.params))return;let s=n.id;return{message:n,method:n.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...n.params===void 0?{}:{params:n.params},...typeof n.jsonrpc=="string"?{jsonrpc:n.jsonrpc}:{}}}o(Ic,"parseMcpRequestMessage");function Cc(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}o(Cc,"readStringParam");function RI(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Cc(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Cc(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Cc(e.params,"uri")};default:return{}}}o(RI,"readCapability");function ng(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(ng,"readHeader");function bI(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let n=new URL(r.__rewriteFunction(e,tu(t))),s=n.port!==""?Number(n.port):n.protocol==="https:"?443:n.protocol==="http:"?80:void 0;return{serverAddress:n.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}o(bI,"readUpstreamServer");function og(e,t){let r=ir(e.headers,t.message),n=ng(e.headers,tg),s={methodName:t.method,...RI(t),...t.id===void 0?{}:{jsonRpcRequestId:t.id},...t.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:t.jsonrpc},...n===void 0?{}:{mcpSessionId:n}};return{common:s,server:{...s,mcpProtocolVersion:r??am,params:t.params},requestedProtocolVersion:r}}o(og,"readServerSpanInput");function sg(e){let{request:t,context:r,parsed:n}=e,{common:s,server:i,requestedProtocolVersion:a}=og(t,n),c=ia(i),d;try{Rs(c.span);let u=c.span.isRecording()||dm()?bI(t,r):{};return d=yI.with(c.ctx,()=>um({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Rs(d.span),sa(r,c.span.spanContext()),{server:c,client:d}}catch(u){throw pi(d===void 0?[c]:[d,c]),u}}o(sg,"startMcpProxySpans");var vI=["content-digest","repr-digest","digest","content-md5"];function CI(e){return vI.some(t=>e.has(t))}o(CI,"hasBodyIntegrityHeader");function ig(e,t,r,n){let s=_I.getSpanContext(t.client.ctx);if(r.byteLength>wI||n!==void 0&&CI(n)||s===void 0||(s.traceFlags&SI.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!ct(i))return r;try{let a=aa(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!Qm(r))return r;let c=aa(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}o(ig,"injectTraceContextIntoBody");function ag(e,t){if(e){if(ct(e.error)){let r=e.error.code,n=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof n=="string"?{message:ks(n,cm)}:{},httpStatusCode:t}}if(ct(e.result)&&e.result.isError===!0)return{isError:!0}}}o(ag,"readSpanResponse");function II(e,t,r){let n=ng(t.headers,tg),s=r?.result,i=Xp(ct(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);lr(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(II,"recordInitializeResult");function cg(e){let{spans:t}=e,r=[t.client,t.server];try{TI(r,e)}catch{}finally{pi(r)}}o(cg,"finishMcpProxySpans");function TI(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&II(e,n,s.message);let i=ag(s.message,n.status);i?lr(e,a=>a.setResponse(i)):s.ended==="errored"?lr(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?lr(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?lr(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?lr(e,a=>a.setErrorType("response_replaced","A different response was sent before the JSON-RPC response arrived.")):t.expectsResponse&&s.ended==="complete"&&!s.message&&!s.truncated&&!s.uninspected&&lr(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(TI,"recordOutcome");function lr(e,t){for(let r of e)try{t(r)}catch{}}o(lr,"forEachHandle");function pi(e){for(let t of e)try{t.end()}catch{}}o(pi,"endEach");function Tc(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}o(Tc,"failMcpProxySpans");function Ec(e){for(let t of[e.client,e.server])try{t.setErrorType("cancelled","The client cancelled the request before the upstream sent response headers.")}catch{}finally{pi([t])}}o(Ec,"cancelMcpProxySpans");function EI(e){switch(e){case"connect_required":return"The gateway asked the client to connect the upstream server; the request was not forwarded.";case"no_upstream_tokens":return"The upstream connection returned no OAuth tokens; the request was not forwarded."}}o(EI,"gatewayAnswerMessage");var kI=64*1024;async function AI(e){if(e.body===null||!rg(e))return;let t=await e.clone().text();if(t.length>kI)return;let r=JSON.parse(t);return ct(r)?r:void 0}o(AI,"readGatewayAnswer");function PI(e){return ct(e.error)?ct(e.error.data)&&e.error.data.connectRequired!==void 0:ct(e.result)&&e.result.resultType==="input_required"}o(PI,"isConnectRequiredAnswer");async function dg(e){let t;try{let r=Ic(e.request,e.requestJson===void 0?void 0:{value:e.requestJson},e.requestBody);if(r===void 0)return;let{server:n}=og(e.request,r);t=ia({...n,startTime:e.startTime}),Rs(t.span),sa(e.context,t.span.spanContext());let s;try{s=await AI(e.response)}catch{}let i=ag(s,e.response.status);i?t.setResponse(i):e.response.status>=400&&s===void 0&&t.setErrorType(String(e.response.status));let a=e.outcome??(s!==void 0&&PI(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,EI(a))}catch{}finally{t&&pi([t])}}o(dg,"recordGatewayAnsweredMcpSpan");function zt(e){let t=Ce().connectionsById.get(e);if(!t)throw new Q(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}o(zt,"getUpstreamServerConfig");function mi(e){let t=Ce().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new Q(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}o(mi,"getUpstreamAuthConfig");function Zr(e,t){let r=mi({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new Q(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}o(Zr,"requireUpstreamOAuthConfig");function ug(e,t){let r=mi({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new Q(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}o(ug,"requireUpstreamIdJagConfig");import{base64url as hi}from"jose";var xI="__Host-",OI=16,MI=32,pg=".",UI=!1;function Nt(){return UI}o(Nt,"isBrowserBindingEnforced");var No=p.object({id:p.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:p.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function fi(e,t){return new URL(ie(e,t)).protocol==="https:"}o(fi,"isSecureGatewayOrigin");function kc(e,t){return t?`${xI}${e}`:e}o(kc,"gatewayCookieName");function jo(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}o(jo,"serializeGatewayCookie");function Ac(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let s=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}o(Ac,"parseCookieHeader");function lg(e){return hi.encode(crypto.getRandomValues(new Uint8Array(e)))}o(lg,"randomBase64url");async function mg(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return hi.encode(new Uint8Array(t))}o(mg,"hashNonce");function qI(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}o(qI,"constantTimeEqual");function hg(e,t,r){return kc(`zuplo_mcp_${e}_${t}`,r)}o(hg,"bindingCookieName");async function Do(e){let t=lg(OI),r=lg(MI),n=fi(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${pg}${hi.encode(e.payload)}`;return{claim:{id:t,hash:await mg(r)},setCookie:jo({name:hg(e.purpose,t,n),value:s,maxAgeSeconds:e.ttlSeconds,secure:n})}}o(Do,"startBrowserBinding");async function gi(e){let t=fi(e.request.url,e.request.headers),r=hg(e.purpose,e.claim.id,t),n=jo({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Ac(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:n};let i=s.indexOf(pg),a=i<0?s:s.slice(0,i);if(!qI(await mg(a),e.claim.hash))return{matched:!1,clearCookie:n};if(i<0)return{matched:!0,clearCookie:n};try{return{matched:!0,payload:new TextDecoder().decode(hi.decode(s.slice(i+1))),clearCookie:n}}catch{return{matched:!1,clearCookie:n}}}o(gi,"verifyBrowserBinding");function fg(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(fg,"mergeAbortSignals");async function zI(e){try{await e.cancel()}catch{}}o(zI,"cancelReader");async function yi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await zI(r),t.createLimitError();n.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of n)a.set(d,c),c+=d.byteLength;return a}o(yi,"readBoundedByteStream");var NI=2,jI=1024*1024,DI=1e4,$I=new Set([301,302,303,307,308]),LI=["authorization","proxy-authorization","cookie","cookie2"];function Pc(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Pc,"readRequestUrl");function Yr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Yr,"readRequestMethod");function HI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[M]:r}})}o(HI,"assertContentLengthWithinLimit");async function BI(e,t,r){return HI(e,t,r),yi(e.body,{maxBytes:t,createLimitError:o(()=>new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[M]:r}}),"createLimitError")})}o(BI,"readBoundedResponseBody");function FI(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(FI,"responseFromBufferedBody");function JI(e,t){if(!$I.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(JI,"resolveRedirectUrl");function gg(e,t){try{return t.validateUrl(e)}catch(r){throw new k({message:"Outbound URL was not allowed.",extensionMembers:{[M]:t.problemCode}},{cause:r})}}o(gg,"validateOutboundUrl");function GI(e,t){throw e instanceof k&&xs(e.extensionMembers?.[M])?e:new k({message:"Outbound fetch failed.",extensionMembers:{[M]:t}},{cause:e})}o(GI,"normalizeFetchError");function $o(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,s]of Object.entries(t.extra))s!==void 0&&(r[n]=s);t.error!==void 0&&ke(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o($o,"logOutboundFailure");async function VI(e,t,r,n,s,i,a){let c=Yr(r,n);try{return await t(r,n)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";$o(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ae(i),error:d,extra:{abortReason:a()}}),GI(d,s)}}o(VI,"fetchWithNormalizedError");function KI(e){if(e.redirects>=e.maxRedirects)throw new k({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[M]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new k({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[M]:e.problemCode}})}o(KI,"assertRedirectAllowed");function WI(e,t){let r=new Headers(e);for(let n of LI)r.delete(n);for(let n of t)r.delete(n);return r}o(WI,"stripCrossOriginHeaders");function ZI(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=WI(e.headers,s)),i}o(ZI,"buildRedirectInit");function YI(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(YI,"buildInitialRequestInit");function XI(e){let t=Yr(e.currentInput,e.currentInit);KI({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=gg(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),s=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:ZI(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(XI,"followRedirect");async function xc(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??NI,i=r.maxResponseBytes??jI,a=r.timeoutMs??DI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,m=new AbortController,h=fg(m,t.signal),f=!1,S=setTimeout(()=>{f=!0,m.abort()},a),R=e,_=YI(e,t,m.signal),y;try{y=gg(Pc(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(I){throw $o(u,{event:"outbound_url_blocked",problemCode:n,method:Yr(e,t),host:ae(Pc(e)),error:I}),clearTimeout(S),h?.(),I}let b=0;try{for(;;){let I=await VI(u,c,R,_,n,y,()=>f?`timeout_after_${a}ms`:void 0),A=JI(I,y);if(A!==void 0)try{let v=XI({currentInput:R,currentInit:_,currentUrl:y,redirectUrl:A,redirects:b,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:d});R=v.currentInput,_=v.currentInit,y=v.currentUrl,b=v.redirects;continue}catch(v){throw $o(u,{event:"outbound_redirect_blocked",problemCode:n,method:Yr(R,_),host:ae(y),error:v,extra:{redirects:b,maxRedirects:s,redirectTargetHost:ae(A)}}),v}try{return FI(I,await BI(I,i,n))}catch(v){throw $o(u,{event:"outbound_response_size_exceeded",problemCode:n,method:Yr(R,_),host:ae(y),error:v,extra:{maxResponseBytes:i,status:I.status}}),v}}}finally{clearTimeout(S),h?.()}}o(xc,"runSafeOutboundExchange");async function Lo(e,t,r){let n=await xc(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(s){throw $o(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Yr(e,t),host:ae(Pc(e)),error:s,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new k({message:"Outbound JSON response could not be parsed.",extensionMembers:{[M]:r.problemCode??"invalid_request"}},{cause:s})}}o(Lo,"runSafeOutboundJsonExchange");function yg(e,t={},r={}){return xc(e,t,{...r,validateUrl:Ro})}o(yg,"fetchConfiguredOutbound");function Sg(e,t={},r={}){return Lo(e,t,{...r,validateUrl:Ro})}o(Sg,"fetchConfiguredOutboundJson");function Si(e,t={},r={}){return Lo(e,t,{...r,validateUrl:Lm})}o(Si,"fetchIdentityProviderJson");function _g(e,t={},r={}){return Lo(e,t,{...r,validateUrl:Ls})}o(_g,"fetchCimdClientMetadataJson");function wg(e,t={},r={}){return Lo(e,t,{...r,validateUrl:bo})}o(wg,"fetchCimdClientJwksJson");import{errors as Tg,jwtVerify as Eg,SignJWT as kg}from"jose";var he="zuplo-mcp-gateway",we=he,Re="HS256";import{base64url as QI}from"jose";var eT=new TextEncoder,tT="MCP gateway could not initialize secure key material.",rT=32,Rg=new Map,bg=new Map,nT;function oT(){return nT??gs.instance.authPrivateKey}o(oT,"readAuthPrivateKey");function vg(e){return new Te(tT,e===void 0?void 0:{cause:e})}o(vg,"createGeneratedKeyMaterialError");function Cg(e,t){let r=QI.decode(t);if(r.byteLength!==rT)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(Cg,"decodeJwkKeyField");function sT(e){let t=oT();if(!t)throw vg();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=Cg("d",r.d);Cg("x",r.x);let s=eT.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+n.byteLength);return i.set(s),i.set(n,s.byteLength),i}catch(r){throw vg(r)}}o(sT,"decodeGeneratedKeyMaterial");function iT(e){let t=Rg.get(e);return t||(t=sT(e),Rg.set(e,t)),t}o(iT,"getMasterKeyMaterial");async function Ge(e){let t=bg.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(iT(e.keyMaterialPurpose));return bg.set(e.purpose,r),r}o(Ge,"readCachedDerivedKey");var aT="SHA-256",cT=32,dT="zuplo-mcp-gateway:",uT=new TextEncoder,Ig=new WeakMap;async function dt(e,t){let r=Ig.get(e);r||(r=new Map,Ig.set(e,r));let n=r.get(t);if(n)return n;let s=await lT(e,t);return r.set(t,s),s}o(dt,"deriveGatewaySigningKey");async function lT(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=uT.encode(`${dT}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:aT,salt:new Uint8Array,info:ye(s)},n,cT*8);return new Uint8Array(i)}o(lT,"hkdfExpand");var Ag=900,pT=900,mT=vm.extend({id:Gm,browserBinding:No.optional()}),hT=mT.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),Pg=ca.extend({id:Vm,purpose:p.literal("browser_connect")}),fT=ca.extend({purpose:p.literal("browser_connect")}),gT=Pg.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),_i=Ag*1e3;async function xg(){return Ge({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"oauth-state"),"derive")})}o(xg,"getOAuthStateKey");async function Og(){return Ge({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"browser-connect"),"derive")})}o(Og,"getBrowserConnectKey");async function Mg(e){let t=Math.floor(Date.now()/1e3)+Ag;return new kg(e).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await xg())}o(Mg,"signOAuthState");async function wi(e){try{let{payload:t}=await Eg(e,await xg(),{algorithms:[Re],issuer:he,audience:we});return hT.parse(t)}catch(t){throw t instanceof Tg.JWTExpired?new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}},{cause:t}):new k({message:"OAuth state could not be verified",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:t})}}o(wi,"verifyOAuthState");async function Ug(e){let t=Math.floor(Date.now()/1e3)+pT,r=fT.parse(e),n=Pg.parse({...r,id:Ym()});return new kg(n).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await Og())}o(Ug,"signBrowserConnectTicket");async function qg(e){try{let{payload:t}=await Eg(e,await Og(),{algorithms:[Re],issuer:he,audience:we});return gT.parse(t)}catch(t){throw t instanceof Tg.JWTExpired?new k({message:"Browser connect ticket has expired",extensionMembers:{[M]:"oauth_state_expired"}},{cause:t}):new k({message:"Browser connect ticket could not be verified",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:t})}}o(qg,"verifyBrowserConnectTicket");async function zg(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new k({message:"Browser connect ticket has already been used",extensionMembers:{[M]:"oauth_state_reused"}})}o(zg,"consumeBrowserConnectTicket");function yT(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(yT,"buildConnectRequiredMessage");async function ST(e){let t=ie(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Ug({..._o(e),purpose:"browser_connect"})),r.toString()}o(ST,"buildGatewayBrowserTicketUrl");function _T(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(_T,"buildGatewayConnectPath");async function Oc(e){return ST({...e,path:_T(e.upstreamServerId),redirect:!0})}o(Oc,"buildGatewayConnectUrl");async function Ri(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Oc(t),message:yT(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ri,"buildRedirectConnectRequiredResponse");function Ng(e){return jg({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(Ng,"buildAdminConnectRequiredResponse");function jg(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(jg,"buildAdminSetupRequiredResponse");function Dg(e){return Ce().byOperationId.get(e)?.downstreamOAuth!==void 0}o(Dg,"routeSupportsBrowserConnect");function $g(e){return jg({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o($g,"buildBrowserConnectUnavailableResponse");var Lg=12;async function Hg(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}o(Hg,"sha256Hex");async function pr(e){if(e)return(await Hg(e)).slice(0,Lg)}o(pr,"fingerprintSecret");async function Xr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Hg(t)).slice(0,Lg)}o(Xr,"fingerprintConnectionIdentity");var wT=6e4;function Qr(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,n)=>t.scopes[n]!==r)}o(Qr,"credentialGenerationChanged");function Pe(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+wT)return"near_expiry"}return"usable"}o(Pe,"describeAccessTokenState");var Bg=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function RT(e,t){return e&&e.length>0?e.join(t):void 0}o(RT,"joinOAuthScopes");function bT(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Bg)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o(bT,"sanitizeAuthorizationServerMetadata");function Fg(e){let t=bT(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(Fg,"sanitizeOAuthDiscoveryState");function Jg(e){let t=new URL(e);for(let r of Bg){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(Jg,"dedupeSingletonAuthorizationRequestParams");function bi(e){let t=new URL(e);return je(t)&&pm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(bi,"normalizeLoopbackOAuthRedirectUri");function Gg(e){return RT(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(Gg,"readProtectedResourceMetadataScope");function vT(e){return`Zuplo MCP Gateway - ${e}`}o(vT,"buildGatewayOAuthClientName");function CT(e,t){return e&&e.length>0?e.join(t):void 0}o(CT,"joinOAuthScopeList");function IT(e){if(e.clientRegistration.mode!=="auto")return CT(e.scopes,e.scopeDelimiter)}o(IT,"readPublicClientMetadataScope");function Mc(e){return new URL(ge().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}o(Mc,"buildOAuthClientMetadataDocumentUrl");function Uc(e){let t=zt(e.upstreamServerId);return{client_name:vT(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}o(Uc,"buildGatewayOAuthClientMetadata");function Vg(e,t,r){let n=Zr(t,r),s=IT(n);return{client_id:Mc({origin:e,upstreamServerId:t}),...Uc({origin:e,upstreamServerId:t,redirectUri:bi(new URL(n.redirectPath,e)).toString(),scope:s})}}o(Vg,"buildOAuthClientMetadataDocument");import{base64url as jt}from"jose";var TT="SHA-256",en="AES-GCM",ET=12,zc="zuplo-secret",Nc=1,Kg="generated:auth_private_key:token-encryption",kT=p.object({version:p.literal(Nc),keyId:p.literal(Kg),algorithm:p.literal(en),iv:p.string().min(1),ciphertext:p.string().min(1)}).strict();async function qc(){return Ge({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(TT,ye(e));return crypto.subtle.importKey("raw",t,{name:en},!1,["encrypt","decrypt"])},"derive")})}o(qc,"getEncryptionKey");function Wg(e){return ye(new TextEncoder().encode(`${zc}:v${e.version}:${e.keyId}`))}o(Wg,"getAssociatedData");function AT(e){return`${zc}:v${e.version}:${jt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(AT,"encodeEnvelope");function PT(e){let t=`${zc}:v${Nc}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(jt.decode(r));return kT.parse(JSON.parse(n))}o(PT,"decodeEnvelope");async function Rt(e){let t=await qc(),r=crypto.getRandomValues(new Uint8Array(ET)),n={version:Nc,keyId:Kg},s=await crypto.subtle.encrypt({name:en,iv:r,additionalData:Wg(n)},t,new TextEncoder().encode(e));return AT({...n,algorithm:en,iv:jt.encode(r),ciphertext:jt.encode(new Uint8Array(s))})}o(Rt,"encryptSecret");async function bt(e){let t=PT(e);if(t){let a=await qc(),c=await crypto.subtle.decrypt({name:en,iv:ye(jt.decode(t.iv)),additionalData:Wg(t)},a,ye(jt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new Te("Encrypted payload is malformed");let s=await qc(),i=await crypto.subtle.decrypt({name:en,iv:ye(jt.decode(r))},s,ye(jt.decode(n)));return new TextDecoder().decode(i)}o(bt,"decryptSecret");var Zg={issuer:p.string().min(1).optional()},xT=p.union([sr.extend(Zg),ho.extend(Zg)]),Yg=p.object({authorizationServerUrl:p.url(),resourceMetadataUrl:p.url().optional(),resourceMetadata:Ur.optional(),authorizationServerMetadata:p.union([qr,zr]).optional()}).passthrough(),OT="Bearer",MT="__zuplo_refresh_only_upstream_access_token__";function jc(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(jc,"splitScopes");function Dc(e,t){let r=new Set(e);return t.every(n=>r.has(n))}o(Dc,"scopesCover");function UT(e){return $r.parse(e)}o(UT,"parsePkceCodeVerifier");function qT(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}o(qT,"readTokenExpiry");async function $c(e){if(e!==void 0)return Rt(JSON.stringify(e))}o($c,"encryptJson");async function Xg(e,t){if(!e)return;let r=await bt(e);try{return t.parse(JSON.parse(r))}catch(n){throw new k({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:n})}}o(Xg,"decryptJson");function zT(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(zT,"clientInformationAllowsRedirectUri");function NT(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(NT,"clientInformationMatchesCurrentClientMetadataUrl");function jT(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(jT,"isUrlBasedClientInformation");function DT(e,t){return t===void 0?e:{...e,scope:t}}o(DT,"applyOAuthClientMetadataScope");function $T(e,t){return Gg({state:e,delimiter:t})}o($T,"readResourceMetadataScope");function LT(e,t){return e&&e.length>0?e.join(t):void 0}o(LT,"joinOAuthScopeList");function HT(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new Q(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return sr.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(HT,"buildManualOAuthClientInformation");function BT(e,t){let r=Mc({origin:new URL(t).origin,upstreamServerId:e});return Ga(r)?r:void 0}o(BT,"buildClientMetadataUrl");function FT(e){for(let t of e)if(t!==void 0)return t}o(FT,"firstDefined");function JT(e){let t=Zr(e.target.upstreamServerId,e.target.authProfileId),r=LT(t.scopes,t.scopeDelimiter),n=Uc({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:HT({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=BT(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}o(JT,"buildInitialOAuthClientSetup");function GT(e,t){if(t===void 0)return FT([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(GT,"readEncryptedClientInformation");function VT(e){return e.pendingState?.encryptedDiscoveryState}o(VT,"readEncryptedDiscoveryState");function vi(e,t){return t===void 0?e:{...e,issuer:t}}o(vi,"applyIssuerStamp");var Dt=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;skipIssuerMetadataValidationValue;skipResourceIndicatorValidationValue;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=JT({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.browserBinding=t.browserBinding,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.skipIssuerMetadataValidationValue=r.skipIssuerMetadataValidation,this.skipResourceIndicatorValidationValue=r.skipResourceIndicatorValidation,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=GT(t,this.configuredClientInformation),this.encryptedDiscoveryState=VT(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get skipIssuerMetadataValidation(){return this.skipIssuerMetadataValidationValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let n=jc(this.configuredScope??r??this.readEffectiveScope());return Dc(t.scopes,n)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Pe(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let n=oe();n&&n.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Xr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await pr(await bt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(n){let s=oe();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:n}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});s.error(i,"Upstream OAuth conditional storage write failed")}throw n}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return DT(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Mg({id:t.id,..._o({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId}),...this.browserBinding===void 0?{}:{browserBinding:this.browserBinding}})}async clientInformation(t){return this.configuredClientInformation?vi(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,oe()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!jT({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await $c(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!Ws({requestedResource:t,configuredResource:r}))throw new Error(`Protected resource ${r} does not match expected ${t} (or origin)`);return new URL(r)}}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Fg(Yg.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await $c(r),await this.syncPendingState(!1),oe()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ae(r.authorizationServerUrl),resourceMetadataHost:ae(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=$T(r,this.scopeDelimiter);let n=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&n!==void 0){let s=jc(this.configuredScope).filter(i=>!n.includes(i));s.length>0&&oe()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:n},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return vi(r,t?.issuer)}async saveTokens(t){let r=Pt.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,a=r.refresh_token?await Rt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:Pt.parse({...r,refresh_token:await bt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Hs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Rt(r.access_token),encryptedRefreshToken:a,scopes:jc(r.scope??this.readEffectiveScope()),expiresAt:qT(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),m=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Pe(u.connection)!=="usable"||!Dc(u.connection.scopes,c.scopes)||!Qr(s,u.connection))){m=!0;let f=u.connection,S={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};oe()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,Qr(s,u.connection)&&Pe(u.connection)==="usable"&&Dc(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),m){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";oe()?.info({event:`upstream_oauth_bounded_rebase_${f}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${f}`)}let h=u.kind==="persisted"?u.connection:void 0;oe()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await pr(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:m,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Jg(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:UT(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new k({message:"OAuth code verifier is missing",extensionMembers:{[M]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),s&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Zm(),..._o({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:J(new Date(Date.now()+_i)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await Xg(this.encryptedClientInformation,xT)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!zT(r,this.redirectUriValue)||!NT({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r!==void 0&&r.issuer===void 0&&t?.issuer!==void 0&&(r=vi(r,t.issuer),this.encryptedClientInformation=await $c(r)),r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=vi(ho.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await Xg(this.encryptedDiscoveryState,Yg)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){oe()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await bt(t.encryptedAccessToken):void 0,n=t.encryptedRefreshToken?await bt(t.encryptedRefreshToken):void 0;if(!r&&!n)return;let s=oe();this.usedRefreshTokenFingerprintValue=s?await pr(n):void 0,s?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!n,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Pt.parse({access_token:r??MT,token_type:OT,refresh_token:n,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=i,i}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let n=r.status,s=r.updatedAt,i={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let a=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,Qr(r,a.connection)&&Pe(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=oe();if(c){let d=a.kind==="missing"?void 0:a.connection,u={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:n,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...u,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(u,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(u,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var KT=3e4,WT=256*1024,ZT=2,YT="does not support dynamic client registration",XT=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],QT=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],eE=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],tE="Protected resource ",rE=" does not match expected ",nE=["HTTP 403 Forbidden","Access Denied","permission to access"],oE=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function sE(e){return e instanceof Error&&e.message.includes(YT)}o(sE,"isDynamicClientRegistrationUnsupported");function iE(e){return e instanceof Error&&XT.some(t=>e.message.includes(t))}o(iE,"isProtectedResourceMetadataUnavailable");function aE(e){return e instanceof Error&&QT.some(t=>e.message.includes(t))}o(aE,"isAuthorizationServerMetadataUnavailable");function cE(e){return e instanceof Error&&eE.some(t=>e.message.includes(t))}o(cE,"isAuthorizationServerIncompatible");function dE(e){return e instanceof Error&&e.message.includes(tE)&&e.message.includes(rE)}o(dE,"isProtectedResourceMismatch");function uE(e){return e instanceof Error&&nE.some(t=>e.message.includes(t))}o(uE,"isUpstreamProviderAccessDenied");function lE(e){return e instanceof Ut&&oE.has(e.code)}o(lE,"isStoredConnectionReconsentError");function vt(e){let t=e.diagnostics??{};return new k({message:e.message,extensionMembers:{[M]:e.code,[Ps]:e.upstreamServerId,[Br]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[lt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[ut]:t.httpStatus},...t.providerError===void 0?{}:{[Fr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Jr]:t.providerErrorDescription}}},{cause:e.cause})}o(vt,"buildUpstreamSetupProblem");function pE(e,t){return`The authorization server for ${e} failed RFC 8414 \xA73.3 issuer validation: the gateway discovered it at "${t.expected}", but its metadata document declares issuer "${t.received}". Providers that publish a path-scoped authorization server whose metadata reports the root origin hit this; if that is the case here, set skipIssuerMetadataValidation on this upstream's OAuth config to accept it \u2014 that weakens the authorization-server mix-up defense, so scope it to this upstream. Otherwise correct the authorization server URL this upstream points at, or ask the provider to fix the published issuer.`}o(pE,"describeIssuerMetadataMismatch");var mE=128,Ci=256;function Ho(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}o(Ho,"truncateProviderDetail");function hE(e){let{error:t,errorDescription:r}=Hc(e.body),n=Ho(t,mE),s=Ho(r,Ci);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(hE,"readRegistrationRejectionDiagnostics");function fE(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}o(fE,"describeRegistrationRejection");function gE(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(gE,"readDiscoveryEndpointUrl");function yE(e){if(e.error instanceof k&&e.error.extensionMembers?.[M]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(sE(e.error))return vt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`});if(e.error instanceof Fa){let r=hE(e.error);return vt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${fE(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof Ao&&e.error.kind==="metadata")return vt({...t,code:"upstream_oauth_issuer_mismatch",message:pE(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ti)return vt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} publishes the non-HTTPS token endpoint "${e.error.tokenEndpoint}". The gateway will not send credentials to it. Ask the provider to serve the token endpoint over TLS before retrying.`,diagnostics:{upstreamUrl:e.error.tokenEndpoint}});if(cE(e.error))return vt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} cannot run the OAuth flow the gateway requires: ${e.error.message}. Ask the provider to support the authorization code flow with PKCE (S256), or configure this upstream to use an authorization server that does.`});if(aE(e.error)){let r=gE(e.error.message);return vt({...t,code:"upstream_oauth_discovery_unavailable",message:`The gateway could not load OAuth authorization server metadata for the upstream MCP server "${e.upstreamServerId}": ${e.error.message}. Confirm the authorization server advertised by "${e.resourceMetadataUrl}" publishes RFC 8414 or OpenID Connect discovery metadata and is reachable from the gateway, then retry.`,diagnostics:r===void 0?{}:{upstreamUrl:r}})}if(dE(e.error))return vt({...t,code:"upstream_oauth_discovery_unavailable",message:`The protected resource metadata at "${e.resourceMetadataUrl}" names a resource that does not match the configured MCP URL for ${e.upstreamServerId}: ${e.error.message}. Point this upstream's MCP URL at the resource the provider publishes, or ask the provider to correct the advertised resource.`});if(iE(e.error))return vt({...t,code:"upstream_oauth_discovery_unavailable",message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`});if(uE(e.error))return vt({...t,code:"upstream_provider_access_denied",message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`})}o(yE,"mapUpstreamOAuthSetupError");function SE(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(SE,"readOAuthFetchRequest");function _E(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(_E,"readOAuthFetchMethod");function wE(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(wE,"responseLooksJson");function RE(e,t){let r=e.headers.get("content-type")??"",n=t.trimStart().toLowerCase();return r.includes("html")||n.startsWith("<!doctype html")||n.startsWith("<html")}o(RE,"responseLooksHtml");var bE=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function vE(e){return bE.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o(vE,"isMetadataDiscoveryRequest");function CE(e,t,r){return e!=="GET"||!vE(t)?!1:r>=400&&r<500||r===502}o(CE,"sdkRetriesDiscoveryCandidate");function IE(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new k({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[M]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ut]:e.response.status,[Lr]:r,[lt]:e.request.url.toString(),[Hr]:e.body}})}o(IE,"throwUpstreamHtmlError");var TE=["message","error_message","detail","title"];function Qg(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}o(Qg,"readStringField");function EE(e){for(let r of TE){let n=Qg(e,r);if(n!==void 0)return n}let t=e.error;if(typeof t=="object"&&t!==null)return Qg(t,"message")}o(EE,"readProviderMessage");function Hc(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t,n=typeof r.error=="string"?r.error:void 0,s=typeof r.error_description=="string"?r.error_description:void 0;return{error:n,errorDescription:s,providerMessage:s===void 0?EE(r):void 0}}catch{return{}}}o(Hc,"readUpstreamOAuthErrorBody");function kE(e){let{error:t,errorDescription:r,providerMessage:n}=Hc(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ae(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:Ho(r,Ci),providerMessage:Ho(n,Ci)},"Upstream OAuth HTTP request returned an error response")}o(kE,"logUpstreamOAuthHttpError");var AE=[/\b(?:unknown|unrecognized|unrecognised)\s+client(?:[\s_-]?id)?(?=\s*(?:$|[.,:;!?'"`(]))/i,/\bclient(?:[\s_-]?id)?\s+(?:not\s+found|is\s+unknown|does\s+not\s+exist)\b/i];function PE(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}o(PE,"isTokenEndpointRequest");function xE(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:n}=Hc(t);if(!(r!==void 0||n===void 0))return AE.some(s=>s.test(n))?n:void 0}o(xE,"readUnknownClientRejection");function OE(e,t){let r=new Headers(e.headers);return r.set("content-type","application/json"),r.delete("content-length"),r.delete("content-encoding"),new Response(JSON.stringify({error:"invalid_client",error_description:t}),{status:e.status,statusText:e.statusText,headers:r})}o(OE,"rewriteUnknownClientRejection");function ty(e){return async(t,r)=>{let n=SE(t),s=_E(t,r),i=oe(),a=Date.now(),c=await yg(t,r,{maxRedirects:ZT,maxResponseBytes:WT,problemCode:"upstream_token_exchange_failed",timeoutMs:KT}),d=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:ae(n.url),path:n.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:d.length},"Upstream OAuth HTTP request completed"),c.ok||kE({log:i,upstreamServerId:e,method:s,request:n,response:c,body:d}),CE(s,n.url,c.status))return c;if(PE(s,r)){let u=xE(c.status,d);if(u!==void 0)return i?.info({event:"upstream_oauth_unknown_client_rejected",upstreamServerId:e,host:ae(n.url),path:n.url.pathname,status:c.status,providerMessage:Ho(u,Ci)},"Upstream OAuth provider no longer recognizes the gateway's client; treating it as invalid_client"),OE(c,u)}if(!c.ok&&RE(c,d)&&IE({upstreamServerId:e,request:n,response:c,body:d}),!wE(c,d))return c;try{JSON.parse(d)}catch(u){throw new k({message:`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[M]:"upstream_token_exchange_failed"}},{cause:u})}return c}}o(ty,"createUpstreamOAuthFetch");function ry(e){oe()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ae(e.serverUrl),resourceMetadataHost:ae(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}o(ry,"logUpstreamOAuthFlowStarted");function ny(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ae(e.serverUrl);r!==void 0&&(t.serverHost=r);let n=e.error instanceof k?e.error.extensionMembers?.[M]:void 0;typeof n=="string"&&(t.code=n),ke(t,"error",e.error),oe()?.warn(t,"Upstream OAuth flow failed before a connection was established")}o(ny,"logUpstreamOAuthFlowFailed");function oy(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(oy,"readAuthorizationRequestScope");async function sy(e,t){e.applyChallengeScope(t.requestedScope),ry({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:ty(t.upstreamServerId)},n=oy(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await Ja(e,r)}catch(r){ny({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=yE({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(sy,"runUpstreamOAuth");async function ME(e,t){e.applyChallengeScope(t.requestedScope),ry({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:ty(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=oy(e,t);n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await Ja(e,r)}catch(s){throw ny({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(ME,"exchangeUpstreamAuthorizationCode");async function ey(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await H().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Pe(r)!=="usable"||!Qr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}o(ey,"adoptPeerCredentialAtResolutionBoundary");async function iy(e,t){let r=await sy(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new k({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}}):new k({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}})}o(iy,"requireUpstreamAuthorizationRedirect");async function ay(e){let t=Pe(e.connection),r=!!e.forceRefresh,n=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=oe(),i=s?await Xr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(s?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:i,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!n,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},n?"Reusing stored upstream access token":"Refreshing upstream credential"),n)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a;try{a=await sy(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!lE(c))throw c;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await ey({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Lc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Lc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new k({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new k({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});return await ey({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Lc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(ay,"authorizeUpstreamOAuthSession");async function UE(e){let t=await wi(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),n=qE(r);return zE({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),NE(n),n}o(UE,"consumeStoredCallbackState");function qE(e){switch(e.kind){case"consumed":throw new k({message:"OAuth state has already been used",extensionMembers:{[M]:"oauth_state_reused"}});case"missing":throw new k({message:"OAuth state is missing or expired",extensionMembers:{[M]:"oauth_state_expired"}});case"available":return e.record}}o(qE,"readConsumedCallbackState");function zE(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new k({message:"OAuth callback did not match the initiating request",extensionMembers:{[M]:"oauth_callback_mismatch"}})}o(zE,"assertStoredCallbackStateMatches");function NE(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}})}o(NE,"assertStoredCallbackStateFresh");async function Lc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Ng(r)}if(Nt()&&!Dg(e.operationId))return oe()?.warn({event:"upstream_connect_link_unavailable",upstreamServerId:e.upstreamServerId,operationId:e.operationId},"User-owned upstream needs a connection, but this MCP route has no gateway MCP OAuth sign-in to bind a connect link to; returning an administrator answer instead of a link"),$g({upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,...e.connection===void 0?{}:{connectionId:e.connection.id},requiresReconsent:!!e.connection});let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Ri(t)}o(Lc,"buildOAuthConnectRequiredResponse");async function cy(e){let t=await UE({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Us(t),[n]=await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(s.connection=n);let i=new Dt(s),a=await ME(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(a==="AUTHORIZED"){let c=i.readUsablePeerAdoption();if(c!==void 0&&await i.adoptConnectionForDirectResolution(c,"cas_loss"),!i.tokenWriteWasPersisted&&c===void 0)throw new k({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new k({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}}):new k({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}})}o(cy,"finishUpstreamOAuthCallback");import{importPKCS8 as jE,SignJWT as DE}from"jose";var uy=1e4,ly=64*1024,py=2,$E=300,tt=p.string().min(1),LE=p.object({access_token:tt,issued_token_type:p.literal(ua),token_type:p.string().optional(),expires_in:p.number().int().positive().optional(),scope:tt.optional()}).passthrough(),HE=p.object({id_token:tt,token_type:tt.optional(),expires_in:p.number().int().positive().optional(),refresh_token:tt.optional(),scope:tt.optional()}).passthrough(),BE=p.object({access_token:tt,token_type:tt,expires_in:p.number().int().positive().optional(),scope:tt.optional(),resource:tt.optional(),refresh_token:tt.optional()}).passthrough();function dy(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(dy,"formEncodeClientCredential");function FE(e){return e.replaceAll("\\n",`
41
+ `)}o(FE,"normalizePem");async function JE(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??$E,n=await jE(FE(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new DE({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(n)}o(JE,"createPrivateKeyJwtClientAssertion");async function GE(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=dy(e.clientAuth.clientId),r=dy(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Ns),e.form.set("client_assertion",await JE({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(GE,"appendClientAuthentication");async function Bc(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await GE({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(Bc,"buildFormRequest");function my(e){return(t,r)=>Si(t,r,{context:e,maxRedirects:py,maxResponseBytes:ly,problemCode:"upstream_token_exchange_failed",timeoutMs:uy})}o(my,"defaultIdpFetchJson");function VE(e){return(t,r)=>Sg(t,r,{context:e,maxRedirects:py,maxResponseBytes:ly,problemCode:"upstream_token_exchange_failed",timeoutMs:uy})}o(VE,"defaultResourceAsFetchJson");function Ii(e){let t={[M]:e.code,[lt]:e.tokenUrl};return e.response!==void 0&&(t[ut]=e.response.status),new k({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}o(Ii,"runtimeError");function Fc(e){if(!e.response.ok)throw Ii({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}o(Fc,"assertTokenEndpointSucceeded");function KE(e){let t=HE.safeParse(e.json);if(!t.success)throw Ii({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(KE,"parseIdpRefreshTokenResponse");function WE(e){let t=LE.safeParse(e.json);if(!t.success)throw Ii({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(WE,"parseIdJagTokenExchangeResponse");function ZE(e){let t=BE.safeParse(e.json);if(!t.success)throw Ii({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}o(ZE,"parseAccessTokenResponse");async function hy(e){let t=new URLSearchParams({grant_type:zs,requested_token_type:ua,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??my(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Bc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Fc({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),WE({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(hy,"requestIdJag");async function fy(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??my(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Bc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Fc({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),KE({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(fy,"refreshIdpSubjectToken");async function gy(e){let t=new URLSearchParams({grant_type:Mt,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??VE(e.context),{response:n,json:s}=await r(e.resourceAs.tokenUrl,await Bc({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Fc({response:n,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),ZE({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(gy,"exchangeIdJagForAccessToken");function YE(e){return Pe(e)==="usable"}o(YE,"hasUsableAccessToken");function XE(e){if(e.tokenType.toLowerCase()!=="bearer")throw new k({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[M]:"upstream_token_response_invalid"}})}o(XE,"assertBearerToken");function yy(e,t){if(t===Vr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(yy,"hasExpiredSubjectToken");async function QE(e){let t=await bt(e.encryptedSubjectToken);if(e.subjectTokenType!==Vr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await fy({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:wo};let n=await H().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await Rt(r.refreshToken),idpSubjectTokenType:Vr,idpSubjectTokenExpiresAt:void 0}});return oe()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:n.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await pr(t),newSubjectRefreshTokenFingerprint:await pr(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:n,subjectToken:r.idToken,subjectTokenType:wo}}o(QE,"resolveIdJagSubjectToken");async function Sy(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Pe(t),n=!!e.forceRefresh,s=!n&&r==="usable",i=oe(),a=i?await Xr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(i?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:a,connectionId:t?.id,accessTokenState:r,forceRefresh:n,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&YE(t))return{kind:"authorized",credential:{type:"bearer_token",token:await bt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||yy(t,d))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:d,subjectTokenExpired:d!==void 0&&yy(t,d)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let u=zt(e.upstreamServerId),m=ug(e.upstreamServerId,e.authProfileId),h=m.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),S=await QE({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),R=await hy({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:m.resourceAs.audience,resource:h,scope:f,clientAuth:m.idp.clientAuth,context:e.context}),_=R.scope??f,y=await gy({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:R.assertion,resource:h,scope:_,clientAuth:m.resourceAs.clientAuth,context:e.context});if(XE(y),t!==void 0){let I=(y.scope??_)?.split(/[,\s]+/).filter(Boolean)??[],A=y.expiresIn===void 0?void 0:J(new Date(Date.now()+y.expiresIn*1e3)),v=await H().upsertUpstreamConnection({id:S.connection.id,ownerMode:S.connection.ownerMode,subjectId:S.connection.subjectId,upstreamServerId:S.connection.upstreamServerId,authProfileId:S.connection.authProfileId,status:"active",encryptedAccessToken:await Rt(y.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:I,expiresAt:A,metadata:S.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:v.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:I.length,expiresAt:A},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}o(Sy,"authorizeUpstreamIdJagRequest");var Ti=new Map;function ek(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(ek,"normalizeRefreshFlightScope");function tk(e){return bi(new URL(e.callbackPath,ie(e.requestUrl,e.requestHeaders))).toString()}o(tk,"buildGatewayOAuthRedirectUri");async function Jc(e){let t=zt(e.upstreamServerId),r=Zr(e.upstreamServerId,e.authProfileId),n=tk({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:n,returnOrigin:ie(e.request.url,e.request.headers)}}}o(Jc,"prepareUpstreamOAuthRequest");async function _y(e){let t=await Jc(e),r=new Dt({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return iy(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(_y,"startUpstreamConnect");async function wy(e){let t=await Jc(e),r=new Dt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>ay({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n();let s=Km({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,ek(r.configuredAuthorizationScope??e.requestedScope)]),a=Ti.get(i);if(a!==void 0){oe()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let u=await a;if(u.kind==="usable"&&r.connectionSatisfiesRequestedScope(u.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(u.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:m,...h}=e;if(t=await Jc(h),r=new Dt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n()}let c=n(),d;return d=c.then(()=>{let u=r.currentConnection;return u!==void 0&&Pe(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{Ti.get(i)===d&&Ti.delete(i)}),Ti.set(i,d),c}o(wy,"authorizeUpstreamRequest");async function tn(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return wy({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Sy({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Te(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(tn,"resolveUpstreamCredentialForRoute");async function Ry(e){if(e.connectRequest.authMode==="id-jag")throw new Te(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await _y({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding}});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}o(Ry,"startUpstreamConnectForRequest");async function rk(e,t){if(t===void 0)throw new k({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[M]:"oauth_callback_mismatch"}});let r=await gi({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new k({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[M]:"oauth_callback_mismatch"}})}o(rk,"requireCallbackBrowser");async function by(e){let t=await wi(e.callbackRequest.state);Nt()&&await rk(e,t.browserBinding);let r=t.authProfileId;if(mi({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Te(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return cy({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:zt(e.callbackRequest.upstreamServerId)})}o(by,"finishUpstreamCallbackForRequest");function nk(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(nk,"buildRouteAuthBaseFromConnection");function vy(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Cm(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(vy,"buildRouteAuthBaseFromPolicyOptions");function Ei(e,t){let n=Ce().byOperationId.get(t);if(!n)throw new Q(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(n.connection===void 0)throw new Q(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(n.connection.upstreamServerId!==e)throw new Q(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return nk({connection:n.connection,operationId:t})}o(Ei,"resolveRouteAuthBase");function Gc(e,t){switch(e){case"user":return Gr(t);case"shared":return bm()}}o(Gc,"buildOwnerForSubject");function rn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:Gc("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:Gc("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:Gc("user",t),initiatedBySubjectId:t}}}o(rn,"resolveRouteAuthForSubject");import{base64url as ok,errors as sk,jwtVerify as ik,SignJWT as ak}from"jose";var Vc="zuplo-connect.",ck=600,Cy="mcp_connect_request_state",dk=p.object({purpose:p.literal(Cy),binding:p.string().min(1),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),uk=new TextEncoder;async function Iy(){return Ge({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"connect-request-state"),"derive")})}o(Iy,"getConnectRequestStateKey");async function Ty(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",uk.encode(t));return ok.encode(new Uint8Array(r))}o(Ty,"digestBinding");function Kc(e){return typeof e=="string"&&e.startsWith(Vc)}o(Kc,"isConnectRequestState");async function Ey(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new ak({purpose:Cy,binding:await Ty(e)}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt(r).setExpirationTime(r+ck).sign(await Iy());return`${Vc}${n}`}o(Ey,"signConnectRequestState");async function ky(e,t,r=new Date){if(!Kc(e))return"invalid";let n;try{let{payload:s}=await ik(e.slice(Vc.length),await Iy(),{algorithms:[Re],issuer:he,audience:we,currentDate:r,clockTolerance:0});n=dk.parse(s)}catch(s){return s instanceof sk.JWTExpired?"expired":"invalid"}return n.binding===await Ty(t)?void 0:"mismatch"}o(ky,"verifyConnectRequestState");var lk=new Set(["tools/call","prompts/get","resources/read"]);var pk=-32021,mk="Invalid or expired requestState";function nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(nn,"isRecord");function Ay(e,t){if(!(!fe()||!nn(t)||typeof t.method!="string"||!Nr(e,t)))return{message:t,method:t.method}}o(Ay,"readModernMcpRequest");function Wc(e){return!Object.hasOwn(e.message,"id")}o(Wc,"isModernNotification");function Zc(){return new Response(null,{status:202})}o(Zc,"acceptedNotificationResponse");function Yc(e){let t=e.message.params;return nn(t)?t:void 0}o(Yc,"readParams");function Py(e){if(!lk.has(e.method))return;let t=Yc(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}o(Py,"readInputRequiredTarget");function xy(e,t,r){return{...e,method:t.method,target:r}}o(xy,"buildBinding");function hk(e){let t=Me(e.message);return Response.json(yt({...t===void 0?{}:{id:t},error:{code:P.InvalidParams,message:mk,data:{reason:"invalid_request_state"}}}))}o(hk,"invalidRequestStateResponse");function fk(e){if(!nn(e))return;let t=e[jr],r=nn(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}o(fk,"readElicitationAction");function gk(e){let t={...Yc(e)};if(delete t.requestState,nn(t.inputResponses)){let r={...t.inputResponses};delete r[jr],Object.keys(r).length===0?delete t.inputResponses:t.inputResponses=r}return{...e.message,params:t}}o(gk,"stripConnectState");async function Oy(e){let t=Yc(e.request),r=t?.requestState;if(!Kc(r))return{kind:"none"};let n=Py(e.request),s=n===void 0?"mismatch":await ky(r,xy(e.binding,e.request,n),e.now);if(s!==void 0)return{kind:"rejected",reason:s,response:hk(e.request)};let i=gk(e.request),a=new TextEncoder().encode(JSON.stringify(i));return{kind:"accepted",body:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),request:{message:i,method:e.request.method},action:fk(t?.inputResponses)}}o(Oy,"readModernConnectRetry");function yk(e){let t=om(e.message)?.elicitation;return nn(t)&&t.url!==void 0}o(yk,"declaresUrlElicitation");function Sk(e,t){return Response.json(yt({...e===void 0?{}:{id:e},error:{code:P.InvalidRequest,message:t.message,data:{connectRequired:t}}}))}o(Sk,"connectRequiredErrorResponse");async function My(e){if(Wc(e.request))return Zc();let t=Me(e.request.message),r=Py(e.request),n=e.payload.authUrl;if(r===void 0||n===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return Sk(t,e.payload);if(!yk(e.request))return Response.json(yt({...t===void 0?{}:{id:t},error:{code:pk,message:`${e.payload.message} The client must declare URL elicitation (clientCapabilities.elicitation.url) to be sent the connect link.`,data:{requiredCapabilities:{elicitation:{url:{}}},connectRequired:e.payload}}}),{status:400});let s=await Ey(xy(e.binding,e.request,r),e.now);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"input_required",inputRequests:{[jr]:{method:"elicitation/create",params:{mode:"url",message:e.payload.message,url:n}}},requestState:s,_meta:{[ar]:e.serverInfo}}})}o(My,"modernConnectRequiredResponse");var Xc=[go],_k=0,wk="private",Rk="0.0.0";function bk(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(bk,"buildGatewayDiscoverCapabilities");function Qc(e){let{connection:t}=e,r=t.serverInfo,n=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...n===void 0?{}:{title:n},version:r?.version??Rk,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}o(Qc,"buildGatewayDiscoverServerInfo");function Uy(e){let t=Me(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...Xc],capabilities:bk(e.capabilityFilter),_meta:{[ar]:Qc({connection:e.connection,icons:e.icons})},ttlMs:_k,cacheScope:wk}})}o(Uy,"gatewayDiscoverResponse");var ed=new WeakMap;function qy(e,t){ed.set(e,t)}o(qy,"setUpstreamAuthRetry");function zy(e){let t=ed.get(e);return ed.delete(e),t}o(zy,"takeUpstreamAuthRetry");var vk=P.InvalidRequest,Ck="The upstream connection returned no OAuth tokens.";function Ny(e){let t=Ka(e);return Response.json(yt({id:t,error:{code:P.InternalError,message:Ck}}),{status:t===void 0?500:200})}o(Ny,"noUpstreamTokensJsonRpcResponse");function Ik(e,t){return{credentialType:e.type,forceRefresh:t}}o(Ik,"buildCredentialResolvedAttributes");function Tk(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(Tk,"connectRequiredReasonCode");function jy(e){ee(e.context,{eventType:G.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:Ik(e.credential,e.forceRefresh===!0)})}o(jy,"emitCredentialResolvedAnalyticsEvent");function Dy(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(ee(e.context,{eventType:G.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){ee(e.context,{eventType:G.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}ee(e.context,{eventType:G.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:Tk(e.payload.state),reasonClass:"auth",attributes:t})}o(Dy,"emitCredentialMissingAnalyticsEvents");function Ek(e){let t=e.route.raw();return Ms.parse(t?.operationId)}o(Ek,"readOperationId");async function kk(e,t,r,n,s){let i=await tn({request:e,context:n,routeAuth:t});if(i.kind==="connect_required")return Dy({context:n,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),n.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(jy({context:n,credential:a,routeBinding:t,mcpProtocolVersion:s}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(n.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}o(kk,"buildCredentialHeaders");var Ak=new Set(["authorization","cookie","cookie2"]);function Pk(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(Pk,"parseJsonRequestBody");function xk(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(xk,"readJsonRequestMethod");function Ok(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Ok,"isJsonResponse");function $t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o($t,"isRecord");function $y(e){return Array.isArray(e)&&e.length>0}o($y,"hasIconList");function Ly(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=ui(wm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(Ly,"readFallbackServerIcons");function Mk(e){if(!$t(e.body))return e.body;let t=e.body.result;if(!$t(t))return e.body;let r=t.serverInfo;return!$t(r)||$y(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(Mk,"addMissingServerIcons");function Uk(e){if(!$t(e.body))return e.body;let t=e.body.result;if(!$t(t))return e.body;let r=t._meta;if(!$t(r))return e.body;let n=r[ar];return!$t(n)||$y(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[ar]:{...n,icons:e.icons}}}}}o(Uk,"addMissingDiscoverServerIcons");function qk(e,t){let r=Hy(e.headers);for(let n of Ak)r.delete(n);for(let[n,s]of t)r.set(n,s);return new At(e,{headers:r})}o(qk,"applyUpstreamHeaders");function Hy(e){let t=new Headers(e);return nu(t),t}o(Hy,"buildProxyHeaders");async function zk(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(zk,"readRetryBody");function Nk(e,t){let r=t.authUrl===void 0?void 0:df({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(yt({id:Ka(e),error:{code:r?.code??vk,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}o(Nk,"connectRequiredJsonRpcResponse");function jk(e){let t=e.modern;if(t===void 0)return{respond:o(async s=>Nk(e.requestBody,s),"respond")};let r=o(()=>Ly({connection:e.connection,context:e.context}),"readIcons"),n=t.request.method==="server/discover"?async()=>Uy({request:t.request,connection:e.connection,capabilityFilter:Dk(e.context),icons:r()}):s=>My({request:t.request,payload:s,binding:t.binding,previousAction:t.previousAction,serverInfo:Qc({connection:e.connection,icons:r()})});return{respond:o(async s=>{let i=eg({headers:e.headers,message:t.request.message,supportedVersions:Xc});return i!==void 0?i:Wc(t.request)?Zc():n(s)},"respond")}}o(jk,"createConnectRequiredResponder");function Dk(e){return qs()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(Dk,"readRouteCapabilityFilter");async function $k(e){let{scope:t}=nf(e.upstreamResponse),r=await tn({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return Dy({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let n=new Headers(e.headers),s=r.credential;if(jy({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return n.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:n};let i=await s.provider.tokens();return i?(n.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:n}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"no_tokens"})}o($k,"applyRefreshedCredentialHeaders");function Lk(e){qy(e.context,{refresh:o(async(t,r)=>{let n=await $k({request:e.request,context:e.context,headers:Hy(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return n.kind==="connect_required"?{kind:"response",response:await e.connectRequired.respond(n.payload)}:n.kind==="no_tokens"?{kind:"response",response:Ny(e.requestBody)}:n},"refresh")})}o(Lk,"registerUpstreamAuthRetry");function Hk(e){return e.body!==null&&e.status>=200&&e.status<=299&&it(e.headers.get("content-type"))==="text/event-stream"&&!at(e.headers)}o(Hk,"isRewritableEventStream");function Bk(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(Bk,"answersRequestId");function Fk(e,t){if(e.data===void 0||e.data===""||e.event!==void 0&&e.event!=="message")return;let r;try{r=JSON.parse(e.data)}catch{return}if(!(!$t(r)||"method"in r||!("result"in r||"error"in r)||!Bk(r.id,t)))return r}o(Fk,"readResponseInEvent");function Jk(e){let t=!1;return ni(e.response,r=>{if(t)return;let n=Fk(r,e.requestId);if(n===void 0)return;t=!0;let s=e.addMissingIcons({body:n,icons:e.icons});return s===n?void 0:Mo(r,JSON.stringify(s))},{failureMode:"open"})}o(Jk,"addMissingIconsToEventStream");function Gk(e){let t=xk(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?Mk:Uk,n=Ly({connection:e.connection,context:e.context});if(n===void 0||n.length===0)return;let s=fe()?Me(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!Ok(i))return s!==void 0&&Hk(i)?Jk({response:i,requestId:s,addMissingIcons:r,icons:n}):i;let a;try{a=await i.clone().json()}catch{return i}let c=r({body:a,icons:n});if(c===a)return i;let d=lf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(Gk,"installInitializeIconHook");function Vk(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new At(e,{headers:r,body:t})}o(Vk,"withRequestBody");async function td(e,t,r){let n=Date.now(),s=Ek(t),i=e,a=await zk(i),c=Pk(a),d=o(async(A,v)=>(await dg({request:i,context:t,requestJson:c,requestBody:a,response:A,startTime:n,...v===void 0?{}:{outcome:v}}),A),"answer"),u=ir(i.headers,c),m=vy({connection:r,operationId:s}),h=cr(i.user,i.url,i.headers);t.log.setLogProperties?.({requestId:t.requestId}),Am(t,h);let f=rn(m,h.subjectId),S=Ay(i.headers,c),R={subjectId:h.subjectId,operationId:s,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId},_;if(S!==void 0){let A=await Oy({request:S,binding:R});if(A.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:A.reason,upstreamServerId:f.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),d(A.response);A.kind==="accepted"&&(i=Vk(i,A.body),a=A.body,c=A.request.message,S=A.request,_=A.action)}let y=jk({requestBody:a,headers:i.headers,modern:S===void 0?void 0:{request:S,binding:R,previousAction:_},context:t,connection:r}),b=await kk(i,f,r,t,u);if(b.kind==="connect_required")return d(await y.respond(b.payload));if(b.kind==="no_tokens")return d(Ny(a),"no_upstream_tokens");let I=qk(i,b.headers);return Lk({request:I,context:t,requestBody:a,connectRequired:y,routeAuth:f,mcpProtocolVersion:u}),Gk({context:t,requestJson:c,connection:r,modern:S!==void 0}),I}o(td,"mcpTokenExchangePolicy");var rd=class extends ws{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=Im(t,r);super(n,r),this.#e=n}async handler(t,r){return td(t,r,this.#e)}};var By=Symbol("Html");function Kk(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(Kk,"escapeHtml");function Wk(e){return e===null||typeof e!="object"?!1:e[By]===!0}o(Wk,"isHtml");function ki(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ki).join(""):Wk(e)?e.value:Kk(String(e))}o(ki,"renderValue");function Ve(e){return{[By]:!0,value:e}}o(Ve,"trustedHtml");var Ke=Ve("");function W(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=ki(t[n]),r+=e[n+1]??"";return Ve(r)}o(W,"html");function on(e,t=Ke){let r=ki(t),n="",s=!0;for(let i of e)s||(n+=r),n+=ki(i),s=!1;return Ve(n)}o(on,"joinHtml");function sn(e){return e.value}o(sn,"renderHtml");function Fy(e){return W`<section class="page-section" aria-labelledby="error-next-steps"><h2 class="section-label" id="error-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol>${e.action}</section><section class="page-section" aria-labelledby="error-reference"><h2 class="section-label" id="error-reference">Reference</h2><dl class="kv kv--boxed">${e.reference}</dl></section><section class="page-section tech" aria-labelledby="error-technical"><h2 class="section-label" id="error-technical">Technical details <span class="section-label__count">for administrators</span></h2><dl class="kv">${e.diagnostics}</dl>${e.upstreamResponse}</section>`}o(Fy,"renderBrowserErrorPage");var Jy=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><path d="m8.25 12.25 2.5 2.5 5-5.25"/></svg>'),Gy=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><line x1="12" y1="7.5" x2="12" y2="12.75"/><circle cx="12" cy="16.25" r=".9" fill="currentColor" stroke="none"/></svg>'),an=Ve('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}.card__status{border:1px solid;border-radius:50%;justify-content:center;align-items:center;width:48px;height:48px;margin:0 auto 16px;display:flex}.card__status svg{width:24px;height:24px}.card__status--error{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger)}.card__status--success{background:var(--success-bg);border-color:var(--success-border);color:var(--success)}.card__status--neutral{background:var(--surface-2);border-color:var(--border);color:var(--text-3)}.page-section{flex-direction:column;gap:10px;display:flex}.steps{counter-reset:step;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.steps li{counter-increment:step;color:var(--text-2);align-items:flex-start;gap:10px;font-size:13.5px;line-height:1.5;display:flex}.steps li:before{content:counter(step);border:1px solid var(--border-strong);background:var(--surface);width:20px;height:20px;color:var(--text-2);border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;margin-top:1px;font-size:11.5px;font-weight:600;line-height:1;display:inline-flex}.kv{flex-direction:column;margin:0;display:flex}.kv__row{border-top:1px solid var(--border);grid-template-columns:124px minmax(0,1fr);gap:2px 12px;padding:7px 0;display:grid}.kv__row:first-child{border-top:0;padding-top:0}.kv__row:last-child{padding-bottom:0}.kv__row--block{grid-template-columns:minmax(0,1fr)}.kv__label{color:var(--text-3);margin:0;padding-top:1px;font-size:12px;font-weight:500}.kv__value{min-width:0;color:var(--text);overflow-wrap:anywhere;margin:0;font-size:13px;line-height:1.5}.kv__value code{font-family:var(--font-mono);color:var(--text);font-size:12px}.kv__row--fix .kv__value{color:var(--text);font-weight:500}.kv--boxed{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px}.kv--boxed .kv__row{grid-template-columns:92px minmax(0,1fr);padding:6px 0}.kv--boxed .kv__row:first-child{padding-top:0}.kv--boxed .kv__row:last-child{padding-bottom:0}.tech{border-top:1px solid var(--border);padding-top:18px}.provider-response{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2)}.provider-response__summary{cursor:pointer;user-select:none;color:var(--text-2);align-items:center;gap:8px;padding:9px 12px;font-size:12.5px;font-weight:500;list-style:none;display:flex}.provider-response__summary::-webkit-details-marker{display:none}.provider-response__summary:before{content:"";border-bottom:1.5px solid;border-right:1.5px solid;flex-shrink:0;width:6px;height:6px;margin-left:2px;transition:transform .15s;transform:rotate(-45deg)}.provider-response[open]>.provider-response__summary:before{transform:rotate(45deg)}.provider-response__summary:hover{color:var(--text)}.provider-response__summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--radius)}.provider-response__frame{border:0;border-top:1px solid var(--border);border-radius:0 0 var(--radius)var(--radius);background:#fff;width:100%;min-height:240px;display:block}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.kv__row{grid-template-columns:minmax(0,1fr)}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function cn(e){return W`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
42
42
  ${e.styles}
43
- </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(an,"renderShell");function xi(e){return W`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?Dy:Ly}</div>`}o(xi,"renderStatusIcon");var Bk="text/html; charset=utf-8";function Lt(e){try{return new URL(e).host}catch{return""}}o(Lt,"safeHostFromUrl");function We(e){let t=e.kind??"authorization_failed",r=Jk(t),n=Fk(e),s=e.title??r.title;return new Response(on(an({title:s,iconHref:"",styles:sn,headerIcon:xi(t==="access_denied"?"neutral":"error"),heading:s,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:jy({steps:nn(r.steps.map(i=>W`<li>${i}</li>`)),action:Kk(e.action),reference:Wk(n),diagnostics:Zk({diagnostic:n,detail:e.detail}),upstreamResponse:Yk(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":Bk,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(We,"browserErrorPageResponse");function Fk(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Vk(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??Gk(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(Fk,"buildBrowserErrorDiagnostic");function Jk(e){switch(e){case"session_expired":return{title:"Authorization expired",steps:["Return to your MCP client and reconnect.","Expired authorization requests cannot be resumed, so start a new connection instead of reloading this page."]};case"access_denied":return{title:"Authorization canceled",steps:["Return to your MCP client.","If you want to grant access, start the connection again and approve the request."]};case"configuration_error":return{title:"Configuration needs attention",steps:["Contact your workspace admin and share the reference below.","The gateway or upstream configuration must be fixed before retrying."]};case"connection_failed":return{title:"Connection failed",steps:["Return to your MCP client and reconnect this upstream.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"invalid_request":return{title:"Authorization request invalid",steps:["Return to your MCP client and try connecting again.","If this keeps happening, the client request may need to be fixed."]};case"admin_required":return{title:"Admin setup required",steps:["Contact your workspace admin and share the reference below.","This connection cannot be completed until setup is finished."]};case"internal_error":return{title:"Gateway error",steps:["Try again later from your MCP client.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"authorization_failed":return{title:"Authorization failed",steps:["Return to your MCP client and start authorization again.","If this keeps happening, contact your gateway administrator and share the reference below."]}}}o(Jk,"readBrowserErrorPagePresentation");function Vk(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}o(Vk,"readBrowserErrorStage");function Gk(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}o(Gk,"readBrowserErrorSuggestedFix");function Kk(e){return e===void 0?Ke:W`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(Kk,"renderAction");function Oi(e){if(e.value===void 0||e.value==="")return Ke;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return W`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}o(Oi,"renderRow");function Le(e){return Oi({label:e.label,value:e.value===void 0?void 0:W`<code>${e.value}</code>`})}o(Le,"renderCodeRow");function Wk(e){return nn([Oi({label:"Error code",value:W`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Le({label:"Request ID",value:e.requestId}),Le({label:"Time",value:e.timestamp})])}o(Wk,"renderReference");function Zk(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return nn([Oi({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Oi({label:"Reason",value:r,block:!0}),Le({label:"Stage",value:t.stage}),Le({label:"Gateway route",value:t.routePath}),Le({label:"Operation ID",value:t.operationId}),Le({label:"Upstream",value:t.upstreamServerId}),Le({label:"Auth profile",value:t.authProfileId}),Le({label:"Upstream URL",value:t.upstreamUrl}),Le({label:"Metadata URL",value:t.metadataUrl}),Le({label:"HTTP status",value:t.httpStatus}),Le({label:"Content type",value:t.contentType}),Le({label:"Provider error",value:t.providerError}),Le({label:"Provider error description",value:t.providerErrorDescription})])}o(Zk,"renderDiagnostics");function Yk(e){return e===void 0?Ke:W`<details class="provider-response"><summary class="provider-response__summary">Show the provider's response</summary><iframe title="Upstream HTML error response" sandbox class="provider-response__frame" srcdoc="${e}"></iframe></details>`}o(Yk,"renderUpstreamHtml");var $y="application/json",Xk="application/x-www-form-urlencoded";function Mi(e,t){return new k({message:e,extensionMembers:{[O]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Mi,"invalidRequestError");function Qk(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(Qk,"normalizeContentType");function eA(e,t){return e===t?!0:t===$y&&e.endsWith("+json")}o(eA,"contentTypeMatches");function tA(e,t){if(!t||t.length===0)return;let r=Qk(e.headers.get("content-type"));if(!t.some(n=>eA(r,n)))throw Mi(`Request body must be ${t.join(" or ")}.`)}o(tA,"assertExpectedContentType");function rA(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw Mi(`${r} exceeded the maximum allowed size.`)}o(rA,"assertContentLengthWithinLimit");async function Hy(e,t){let r=t.label??"Request body";tA(e,t.expectedContentTypes),rA(e,t.maxBytes,r);let n=await Ri(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Mi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(Hy,"readBoundedTextBody");async function By(e,t){let r=await Hy(e,{...t,expectedContentTypes:[$y]});try{return JSON.parse(r)}catch(n){throw Mi("Request body must be valid JSON.",n)}}o(By,"readBoundedJsonBody");async function Fy(e,t){let r=await Hy(e,{...t,expectedContentTypes:[Xk]});return new URLSearchParams(r)}o(Fy,"readBoundedFormUrlEncodedBody");import{errors as Vy,jwtVerify as Gy,SignJWT as td}from"jose";import{base64url as nA}from"jose";var oA="mcp-browser-login-pkce:",sA=new TextEncoder;async function iA(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(iA,"importHmacKey");async function ed(e){let t=await iA(e.signingKey),r=sA.encode(`${oA}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return Dr.parse(nA.encode(new Uint8Array(n)))}o(ed,"deriveBrowserLoginPkceVerifier");async function Jy(e){let t=await ed(e),r=await Ks(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:jr}}o(Jy,"deriveBrowserLoginPkceParams");var aA={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},T=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=aA[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var cA=300,Ky=p.string().min(1).optional(),dA=p.object({purpose:p.literal("gateway_browser_login"),transactionId:ma,stateId:Bs,binding:Do,authorizationServerIssuer:Ky,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),uA=p.object({purpose:p.literal("gateway_browser_login_return"),stateId:Bs,binding:Do,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),lA=p.discriminatedUnion("purpose",[dA,uA]),pA=p.object({purpose:p.literal("gateway_authorization_setup"),transactionId:ma,stateId:Bs,authorizationServerIssuer:Ky,exp:p.number().int().positive(),iat:p.number().int().positive().optional()});async function cn(){return Ve({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-login"),"derive")})}o(cn,"getBrowserLoginKey");async function Wy(){return Ve({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"authorization-csrf"),"derive")})}o(Wy,"getCsrfKey");function Zy(e){return{now:e.now??new Date,ttlSeconds:rd()}}o(Zy,"readPendingTransactionDependencies");function rd(){return Ee().browserLogin.stateTtlSeconds}o(rd,"readBrowserLoginStateTtlSeconds");function mA(e){let t=ge();return je(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o(mA,"isLoopbackDevLoginUrl");async function Yy(e){let t=Ee().browserLogin,r=ge(),n=new URL(Pt("url")),s=new URL(r.actionPath("/oauth/callback"),xt(e.requestUrl,e.requestHeaders));if(mA(n))return n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("state",e.state),n;if(n.searchParams.set("response_type","code"),n.searchParams.set("client_id",Pt("clientId")),n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("scope",t.scope),n.searchParams.set("state",e.state),n.searchParams.set("nonce",e.nonce),t.audience&&n.searchParams.set("audience",t.audience),t.pkce===jr){let i=await Jy({stateId:e.stateId,signingKey:await cn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(Yy,"buildBrowserLoginUrl");function hA(e,t){return e.subjectId===t.subjectId}o(hA,"principalsMatch");function Xy(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(Xy,"toPendingPrincipal");function Qy(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:J(e.now),expiresAt:J(pt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw z("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:Xy(e.principal)}}o(Qy,"createTransactionRecord");async function eS(e){let{id:t,...r}=e.record,n=await H().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw z("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new T("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new T("invalid_request","redirect_uri is not registered for the client.")}}o(eS,"startPendingTransaction");async function fA(e){return new td({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await cn())}o(fA,"signBrowserLoginState");async function tS(e){return new td({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Js(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Wy())}o(tS,"signCsrfToken");async function nd(e){try{let{payload:t}=await Gy(e,await cn(),{algorithms:[Re],issuer:he,audience:we}),r=lA.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding,authorizationServerIssuer:r.authorizationServerIssuer}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof Vy.JWTExpired?z("oauth_state_expired","Browser login state has expired.",t):z("oauth_state_invalid","Browser login state could not be verified.",t)}}o(nd,"verifyAnyBrowserLoginStateToken");async function gA(e){let t=await nd(e);if(t.kind!=="authorization")throw z("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding,authorizationServerIssuer:t.authorizationServerIssuer}}o(gA,"verifyBrowserLoginStateToken");async function Ui(e){try{let{payload:t}=await Gy(e,await Wy(),{algorithms:[Re],issuer:he,audience:we}),r=pA.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof Vy.JWTExpired?z("oauth_state_expired","Authorization setup state has expired.",t):z("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Ui,"verifyCsrfToken");function od(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(od,"pendingStateErrorCode");function yA(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(yA,"toPendingAuthorizationGetResult");function SA(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(SA,"toPendingAuthorizationAdvanceResult");function sd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":od(e==="consumed_already"?"consumed_already":e)}o(sd,"setupDecisionErrorCode");async function rS(e){let t=e.now??new Date,r=await Ui(e.csrfToken),n=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(n.kind!=="marked")throw z(sd(n.kind),"Authorization setup state is invalid, expired, or already used.");return nS({kind:"available",record:n.transaction})}o(rS,"markSetupApproved");function nS(e){if(e.kind!=="available")throw z(od(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(nS,"requireAwaitingSetup");function _A(e){if(!hA(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(_A,"requireCurrentPrincipalMatches");async function oS(e){let t=e.now??new Date,r=rd(),n=ha(),s=Js(),i=await $o({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await fA({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=Qy({id:n,transaction:e.transaction,currentStateHash:await ae(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await eS({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await Yy({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:u,browserBindingCookie:i.setCookie}}o(oS,"startAwaitingLogin");async function sS(e){let t=rd(),r=Js(),n=await $o({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new td({purpose:"gateway_browser_login_return",stateId:r,binding:n.claim}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await cn());return{browserLoginUrl:await Yy({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(sS,"startReturnToBrowserLogin");async function iS(e){let{now:t,ttlSeconds:r}=Zy(e),n=ha(),s=await tS({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=Qy({id:n,transaction:e.transaction,currentStateHash:await ae(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await eS({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}o(iS,"startAwaitingSetup");async function aS(e){let{now:t,ttlSeconds:r}=Zy(e),n=await gA(e.browserLoginStateToken),s=await tS({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=SA(await H().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await ae(e.browserLoginStateToken),nextStateHash:await ae(s),nextPhase:"awaiting_setup",principal:Xy(e.principal),now:J(t)}));if(i.kind!=="advanced")throw z(od(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}o(aS,"completeLogin");async function cS(e){let t=await id(e);return _A({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(cS,"getSetup");async function id(e){let t=e.now??new Date,r=await Ui(e.csrfToken);return nS(yA(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await ae(e.csrfToken),now:J(t)})))}o(id,"getSetupTransaction");async function wA(e){let t=await Ui(e.csrfToken),r=ht(),n=J(pt(e.now,cA)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await ae(r),authorizationCodeExpiresAt:n,grantId:Nm(),now:J(e.now)});if(s.kind!=="approved")throw z(s.kind==="cancelled"?"oauth_state_invalid":sd(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),qi(i,t.authorizationServerIssuer),i}o(wA,"createAuthorizationCodeRedirectWithDecision");async function RA(e){let t=await Ui(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw z(r.kind==="approved"?"oauth_state_invalid":sd(r.kind),"Authorization setup state is invalid, expired, or already used.");return bA({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(RA,"createCancelRedirectWithDecision");function qi(e,t){t!==void 0&&fe()&&e.searchParams.set("iss",t)}o(qi,"setAuthorizationResponseIssuer");function bA(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),qi(t,e.authorizationServerIssuer),t}o(bA,"buildClientCancelRedirect");async function dS(e){let t=e.now??new Date;return wA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(dS,"approve");async function uS(e){let t=e.now??new Date;return RA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(uS,"cancel");import{createRemoteJWKSet as vA,errors as dn,jwtVerify as lS,SignJWT as CA}from"jose";var IA="zuplo_mcp_session",TA=p.object({purpose:p.literal("gateway_browser_session"),sub:_o,browserLoginOrigin:p.string().min(1),roles:p.array(p.string().min(1)).optional(),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),EA=p.object({id_token:p.string().min(1),token_type:p.string().min(1).optional(),expires_in:p.number().optional(),access_token:p.string().min(1).optional(),refresh_token:p.string().min(1).optional(),scope:p.string().min(1).optional()}),kA=p.object({error:p.string().min(1).optional(),error_description:p.string().min(1).optional(),error_uri:p.string().min(1).optional()}),AA=p.object({sub:_o,nonce:p.string().min(1)}).catchall(p.unknown()),ad;async function pS(){return Ve({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-session"),"derive")})}o(pS,"getBrowserSessionKey");function dd(e,t){let r=_i(e,t);return{name:Tc(IA,r),secure:r}}o(dd,"browserSessionCookieName");function cd(e,t){let{name:r,secure:n}=dd(e,t);return Lo({name:r,value:"",maxAgeSeconds:0,secure:n})}o(cd,"buildBrowserSessionEvictionCookie");function PA(e){let{name:t,secure:r}=dd(e.requestUrl,e.requestHeaders);return Lo({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}o(PA,"serializeSessionCookie");function mS(){return new URL(Pt("url")).origin}o(mS,"readBrowserLoginOrigin");function xA(e){let t=kA.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(xA,"readIdpErrorFields");function OA(e){return e instanceof dn.JWTExpired?"expired":e instanceof dn.JWTClaimValidationFailed?"claim":e instanceof dn.JWSSignatureVerificationFailed?"signature":e instanceof dn.JWKSNoMatchingKey?"jwks_no_match":e instanceof dn.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(OA,"readJwtFailureKind");function MA(e){return e instanceof Error&&"cause"in e?e.cause:e}o(MA,"readErrorCause");function UA(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(UA,"readRuntimeGatewayCode");function qA(){if(!ad){let e=Ee();ad=vA(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return ad}o(qA,"readFederatedJwks");function hS(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ar(e.user,e.url)}o(hS,"resolveCurrentRequestPrincipal");async function un(e,t={}){let r=Ec(e.headers.get("cookie")).get(dd(e.url,e.headers).name);if(!r)return{};try{let{payload:n}=await lS(r,await pS(),{algorithms:[Re],issuer:he,audience:we}),s=TA.parse(n);if(s.browserLoginOrigin!==mS())return{evictCookie:cd(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(n){return n instanceof dn.JWTExpired?{evictCookie:cd(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:cd(e.url,e.headers)})}}o(un,"readBrowserSession");async function Fo(e){let t=Ee().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:mS()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new CA(r).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await pS());return PA({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(Fo,"createBrowserSessionCookie");async function zA(e){let t=Ee(),r=Pt("tokenUrl"),n=Pt("clientId"),s=Pt("clientSecret"),i=new URL(ge().actionPath("/oauth/callback"),xt(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:s});if(t.browserLogin.pkce===jr){let c=await ed({stateId:e.stateId,signingKey:await cn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await bi(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let S=xA(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ue(r),idpStatus:c.status,...S},"Federated browser login token exchange returned non-2xx from the identity provider"),z({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${S.idpError?` idp_error=${S.idpError}`:""}${S.idpErrorDescription?` idp_error_description=${S.idpErrorDescription}`:""})`)})}let u=EA.parse(d),m;try{({payload:m}=await lS(u.id_token,qA(),{issuer:t.oidc.issuer,audience:n}))}catch(S){let R={};throw ke(R,"error",S),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:OA(S),idpHost:ue(r),expectedIssuer:t.oidc.issuer,...R},"Federated id_token failed jose verification"),S}if(m.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ue(r),nonceMissingFromIdToken:m.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),z("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=AA.parse(m);return{principal:ar({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:bo,expiresAt:typeof m.exp=="number"?J(new Date(m.exp*1e3)):void 0}}}catch(c){let d=lt(c)??UA(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",MA(c))}}o(zA,"exchangeFederatedAuthorizationCode");async function ud(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return zA({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await un(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw z("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}o(ud,"resolveBrowserLoginCallbackIdentity");var NA=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function jA(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(jA,"readScheme");function DA(e){return e.protocol==="https:"}o(DA,"isSpecCompliantRedirectUri");function LA(e){let t=jA(e);return t.length>0&&t!=="http"&&t!=="https"&&!NA.has(t)}o(LA,"isNativeAppCustomSchemeRedirectUri");var gS=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>DA(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>je(e),"accepts"),matches:o((e,t)=>je(e)&&je(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>LA(e),"accepts")}];function yS(e){let t=gS.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(yS,"evaluateBuiltInRedirectUriCompatibility");function fS(e){try{return new URL(e)}catch{return}}o(fS,"parseUrl");function SS(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=fS(e.registeredRedirectUri),r=fS(e.requestedRedirectUri);return t===void 0||r===void 0?!1:gS.some(n=>n.matches?.(t,r))}o(SS,"redirectUriMatchesBuiltInCompatibility");var $A=1e4,HA=5*1024,BA=0,FA=2160*60*60,_S=["authorization_code","refresh_token",$s,Ot],JA=["authorization_code","refresh_token"],wS=[Um],VA=["code"],GA=p.object({client_name:p.string().min(1).optional(),redirect_uris:p.array(p.string().min(1)).min(1),grant_types:p.array(p.enum(_S)).min(1).max(_S.length).optional(),authorization_grant_profiles_supported:p.array(p.enum(wS)).min(1).max(wS.length).optional(),response_types:p.array(p.enum(VA)).min(1).max(1).optional(),scope:p.literal(pe).optional(),token_endpoint_auth_method:zm.optional(),jwks_uri:p.string().min(1).optional()});function KA(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&je(t))&&t.pathname!=="/"}catch{return!1}}o(KA,"isCimdClientIdCandidate");function RS(e,t){throw new T("invalid_client",Vm({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(RS,"invalidCimdClientError");function ln(e,t="invalid_request"){if(WA(e))throw new T(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new T(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new T(t,"redirect_uris must not include credentials or fragments.");if(yS({url:r}).kind==="rejected")throw new T(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(ln,"assertValidRedirectUri");function WA(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(WA,"hasForbiddenRawRedirectUriCharacter");async function ZA(e){let{response:t,json:r}=await lg(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:BA,maxResponseBytes:HA,timeoutMs:$A});if(!t.ok)throw z("invalid_request","CIMD metadata could not be fetched.");let n=Fs(r);for(let s of n.redirect_uris)ln(s,"invalid_request");if(n.jwks_uri!==void 0&&Co(n.jwks_uri),n.client_id!==e.clientId)throw z("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(ZA,"fetchCimdMetadata");async function YA(e){let t=Vs(e),r=await ZA({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(YA,"resolveCimdClient");async function zi(e,t){let r=mt.parse(e);if(KA(r)){Ee().gateway.downstreamCimdEnabled||RS(r);try{return await YA(r)}catch(s){RS(r,s)}}let n=await H().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=Km(s.clientId),a=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",c=s.jwksUri??i;if(a==="private_key_jwt"&&c===void 0)throw new T("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=Fs({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),u={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(u.hashedClientSecret=s.hashedClientSecret),u}throw new T("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(zi,"resolveClient");function bS(e,t){if(!e.metadata.redirect_uris.some(r=>SS({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(bS,"assertRedirectRegistered");function XA(e){return e===void 0?[...JA]:Array.from(new Set(e))}o(XA,"normalizeGrantTypes");function QA(e){try{Co(e)}catch(t){throw new T("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}o(QA,"assertValidDcrJwksUri");function eP(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?mt.parse(Gm({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):mt.parse(`dcr:${crypto.randomUUID()}`)}o(eP,"createDcrClientId");function pn(e){if(e===void 0||e===pe)return pe;throw new T("invalid_request",`Only the ${pe} scope is supported.`)}o(pn,"assertSupportedOAuthScope");function lr(e,t,r){let n;try{n=new URL(t)}catch{throw new T("invalid_target","resource must be an absolute URI.")}if(n.hash)throw new T("invalid_target","resource must not include a fragment.");if(n.protocol!=="https:"&&!je(n))throw new T("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ie(e,r),i=Ls(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new T("invalid_target","resource must match a published MCP route.");return a}o(lr,"resolveResource");async function vS(e){let t;try{t=GA.parse(e)}catch(S){if(S instanceof p.ZodError){let R=S.issues.some(_=>_.path[0]==="redirect_uris");throw new T(R?"invalid_redirect_uri":"invalid_client_metadata",S.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:S})}throw S}for(let S of t.redirect_uris)ln(S,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new T("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&QA(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=eP({tokenEndpointAuthMethod:n,jwksUri:t.jwks_uri}),a=Fs({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:n,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=pt(r,FA),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),m={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:XA(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:pe,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:J(r),clientExpiresAt:J(c)};if(n==="client_secret_basic"||n==="client_secret_post"){let S=ht();h.hashedClientSecret=await ae(S),h.clientSecretExpiresAt=J(c),m.client_secret=S,m.client_secret_expires_at=u,m.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw z("invalid_request","OAuth client is already registered.");return m}o(vS,"registerDownstreamClient");function tP(e){return e?.metadata?.idpSubjectTokenType!==Vr&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}o(tP,"hasStoredIdJagSubjectTokenBinding");async function CS(e){let t=Jr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(CS,"readIdJagSubjectConnection");async function ld(e){let t=Ce().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await CS({connection:t.connection,principal:e.principal});return!tP(r)}o(ld,"requiresIdJagSubjectTokenBinding");async function IS(e){if(e.subjectToken===void 0)return;let t=Ce().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await CS({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??Gs(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await wt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}o(IS,"bindIdJagSubjectTokenForAuthorizationTransaction");function TS(e){return W`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(TS,"renderShellIcon");function ES(e){return W`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(ES,"renderActions");var kS=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function AS(e){return W`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(AS,"renderBannerWarning");var UL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),qL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var zL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var rP="data:,",PS=W`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,xS=W`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function nP(e,t,r){if(e)try{let n=new URL(t).origin,s=new URL(e,n);return s.origin!==n||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}o(nP,"safeGatewayConnectHref");function oP(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(oP,"deriveMode");function sP(e){return ES({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:PS,authorizeAttrs:Ke})}o(sP,"renderActions");function pd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=nP(s.connectUrl,t,n);if(i)return i}}o(pd,"firstUserConnectHref");function iP(e){let t=e.connectHref===void 0?Ke:W`<a class="button button--primary" href="${e.connectHref}" ${xS}>Connect</a>`;return W`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${PS}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}o(iP,"renderSetupActions");function aP(e){return e?W`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${xS}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Ke}o(aP,"renderReconnectAction");function cP(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}o(cP,"isRenderableIconHref");function OS(e){return e?.find(t=>cP(t.src))?.src}o(OS,"readIconHref");function dP(e){return OS(e.serverIcons)??(e.transportHost===void 0?void 0:vc(e.transportHost).src)}o(dP,"readUpstreamIconHref");function uP(e){let t=OS(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=dP(r);if(n!==void 0)return n}}o(uP,"readHeaderIconHref");function lP(e){let t=e.setupMessage===void 0?Ke:AS({icon:kS,message:e.setupMessage});return W`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}o(lP,"renderBody");function md(e){let t=oP(e.upstreams),r=pd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),n=pd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=pd(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??n:void 0,a=t==="setup"?e.upstreams.find(u=>u.ownerMode==="user"&&u.status!=="active"&&u.connectUrl===void 0&&u.setupMessage!==void 0)?.setupMessage:void 0,c=uP({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?W`<footer class="card__footer">${iP({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:W`<footer class="card__footer">${aP(s)}${sP({state:e.state,gateway:e.gateway})}</footer>`;return on(an({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??rP,styles:sn,headerIcon:c===void 0?Ke:TS({iconHref:c,fallbackIconHref:Wf}),heading:"Authorize access",subhead:Ke,body:lP({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(md,"renderConsentPage");var pP=1e4,mP=2e3,hP=64*1024,NS={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},MS="mcp-session-id",fP;function jS(){return{tools:[],prompts:[],resources:[]}}o(jS,"emptyCapabilities");function US(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":fa})}o(US,"buildReadinessHeaders");async function qS(e){if(e.type==="bearer_token"){let n=US();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=US();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(qS,"buildAsyncCredentialHeaders");function gP(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(nr.parse({jsonrpc:rr,id:1,method:"initialize",params:{protocolVersion:fa,capabilities:{},clientInfo:NS}}))})}o(gP,"buildInitializePreflight");function yP(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",So),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:rr,id:1,method:"server/discover",params:{_meta:{[Ms]:So,[om]:{},[sm]:NS}}})})}o(yP,"buildDiscoverPreflight");async function SP(e){if(e.status!==400&&e.status!==404)return!1;let t=await _P(e);if(t===void 0)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&"error"in r&&typeof r.error=="object"&&r.error!==null&&"code"in r.error&&typeof r.error.code=="number"}catch{return!1}}o(SP,"isModernRejectionOfInitialize");async function _P(e){let t=e.body?.getReader();if(t===void 0)return;let r,n=new Promise(i=>{r=setTimeout(()=>i("timeout"),mP)}),s=(async()=>{let i=new TextDecoder,a="",c=0;for(;;){let{done:d,value:u}=await t.read();if(d)return a+i.decode();if(c+=u.byteLength,c>hP)return;a+=i.decode(u,{stream:!0})}})();try{let i=await Promise.race([s,n]);return i==="timeout"?void 0:i}catch{return}finally{clearTimeout(r),t.cancel().catch(()=>{})}}o(_P,"readBoundedBody");async function hd(e){vo(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),pP);try{let n=new Request(e,{redirect:"manual",signal:t.signal});return await Qd.fetch(n)}finally{clearTimeout(r)}}o(hd,"runPreflight");function Jo(e){e.body?.cancel().catch(()=>{})}o(Jo,"releasePreflightBody");async function wP(e){let t=e.response.headers.get(MS);if(!t)return;let r=new Headers(e.headers);r.set(MS,t),r.delete("content-type");try{let n=await hd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Jo(n)}catch{}}o(wP,"terminatePreflightSession");async function DS(e){let{response:t}=e;return Jo(t),t.status>=200&&t.status<300?(await wP(e),{kind:"ready",upstreamStatus:t.status,capabilities:jS()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}o(DS,"classifyResponse");function zS(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}o(zS,"connectRequiredResult");async function LS(e){let t=await hd(gP(e));if(!fe()||!await SP(t))return t;try{let r=await hd(yP(e));if(r.status>=200&&r.status<300)return Jo(t),r;Jo(r)}catch{}return t}o(LS,"probeUpstream");async function RP(e){try{return DS({response:await LS(e),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}o(RP,"classifyPreflight");async function bP(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:jS()};let r=Ai(t.upstreamServerId,e.route.operationId),n=tn(r,e.subjectId),s=e.returnTo===void 0?n:{...n,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await en({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return zS(a.payload);let c=await qS(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d;try{d=await LS({upstreamUrl:t.mcpUrl,headers:c})}catch(h){return{kind:"upstream_unavailable",message:h instanceof Error?h.message:"Upstream MCP server readiness preflight failed."}}if(d.status!==401)return DS({response:d,upstreamUrl:t.mcpUrl,headers:c});Jo(d);let u=await en({request:i,routeAuth:s,forceRefresh:!0});if(u.kind==="connect_required")return zS(u.payload);let m=await qS(u.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:RP({upstreamUrl:t.mcpUrl,headers:m})}o(bP,"checkUpstreamRouteReadinessImpl");function $S(e){return(fP??bP)(e)}o($S,"checkUpstreamRouteReadiness");function vP(e){try{return new URL(e).host}catch{return}}o(vP,"safeUrlHost");function HS(e){return e!==void 0&&e.length>0}o(HS,"hasItems");function CP(e){let t=e.serverInfo?.icons;if(HS(t))return t;let r=fi(e.mcpUrl);return r===void 0?void 0:[r]}o(CP,"readServerIcons");async function IP(e){let{authConfig:t,authMode:r,description:n,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",m=u&&r!=="id-jag",h=e.readiness??(u?Qm(e.connection):{connected:!0,status:"active"}),f=m?e.readiness?.connectUrl??(e.returnTo!==void 0?await Pc({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,S=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:n,transportHost:vP(i),scopesRequested:HS(S)?S:void 0,serverIcons:CP(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:f,setupMessage:e.setupMessage,updatedAt:u&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}o(IP,"buildSetupRequirement");function BS(e){let t=Ce().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(BS,"requireRoute");async function fd(e){let t=BS(e.transaction.operationId),r=Jr(e.transaction.principal.subjectId),n=t.connection;if(n===void 0)return[];let i=n.ownerMode==="user"?(await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId}]))[0]:void 0,a=await $S({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),c="connectionStatus"in a?a.connectionStatus:void 0,d=(a.kind==="connect_required"||a.kind==="admin_setup_required")&&a.payload.authUrl!==void 0?a.payload.authUrl:void 0,u=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await IP({connection:i,registeredConnection:n,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:u,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}o(fd,"requirementsForSetup");async function gd(e){let t=BS(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),n=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ie(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:n?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}o(gd,"consentContext");function yd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(yd,"hasUnresolvedUserUpstream");var TP=["mcp_user"],EP="dev-browser-user",kP=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),AP=p.object({response_type:p.literal("code"),client_id:p.string().min(1),redirect_uri:p.string().min(1),resource:p.url(),code_challenge:p.string().min(43),code_challenge_method:Rm,state:p.string().min(1).optional(),scope:p.literal(pe).default(pe)}),PP=p.enum(["continue","approve","cancel"]).default("continue"),xP=p.object({state:p.string().min(1),decision:PP}),$t=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;authorizationServerIssuer;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription,this.authorizationServerIssuer=t.authorizationServerIssuer}};function FS(e){return typeof e=="string"&&e.length>0?e:void 0}o(FS,"readQueryString");function OP(e,t){let r=FS(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new T("invalid_target",kP)}let n=Hm(t,e.url,e.headers);if(r===void 0||r===n)return n;throw new T("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(OP,"requireAuthorizeResource");async function MP(e,t){let r={};t!==void 0&&(r.context=t);let n=await un(e,r);if(n.principal)return{principal:n.principal};if(!e.user)return n.evictCookie===void 0?{}:{setCookie:n.evictCookie};let s=hS(e);return{principal:s,setCookie:await Fo({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o(MP,"resolveBrowserPrincipal");async function UP(e,t){let r={};t!==void 0&&(r.context=t);let n=await un(e,r);if(!n.principal)throw z("authentication_required","Authorization setup requires a current browser session.");return n.principal}o(UP,"requireSetupPrincipal");function JS(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(JS,"buildSetupReturnTo");async function VS(e){let t=await fd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:JS(e.csrfToken)}),r=await gd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),n={kind:"setup_page",html:md({state:e.csrfToken,operationId:e.transaction.operationId,gateway:ge(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(n.setCookies=e.setCookies),n}o(VS,"renderSetup");function qP(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(qP,"toAuthorizationTransactionClient");async function Sd(e,t={}){let r=AP.parse({...e.query,resource:OP(e,t.operationId),state:FS(e.query.state)}),n=pn(r.scope);ln(r.redirect_uri,"invalid_request");let s=fe()?t.operationId===void 0?xt(e.url,e.headers):jm({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=mt.parse(r.client_id),c=await zi(r.client_id,i);bS(c,r.redirect_uri);try{let d=lr(e.url,r.resource,e.headers),u=qP(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:d.operationId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&te(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type}});let m={clientId:c?.clientId??a,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state},authorizationServerIssuer:s},{principal:h,setCookie:f}=await MP(e,t.context),S=h===void 0?!1:await ld({operationId:d.operationId,principal:h});if(!h||S){let _=await oS({transaction:m,requestUrl:e.url,requestHeaders:e.headers,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:d.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:_.browserLoginUrl,setCookies:[...f===void 0?[]:[f],_.browserBindingCookie]}}let R=await iS({transaction:m,principal:h,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:d.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&te(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type,subjectId:h.subjectId}}),VS({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw zP({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Sd,"authorizeDownstreamClient");function zP(e){if(e.cause instanceof $t)return e.cause;let t=NP(e.cause);return t?new $t({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(zP,"toDownstreamAuthorizeRedirectError");function NP(e){if(e instanceof T)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof p.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(NP,"mapToOAuthRedirectError");async function GS(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let u=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...u===void 0?{}:{idpErrorDescription:u},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),z("provider_access_denied",u??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),z("oauth_state_invalid","Browser login callback is missing state.");let s=await nd(n),i=await wi({purpose:"login",claim:s.binding,request:e});if(!i.matched&&zt())throw t.context?.log.warn({event:"browser_login_callback_binding_mismatch",code:"oauth_callback_mismatch",stateKind:s.kind},"Browser login callback arrived in a browser that did not start the login"),z("oauth_callback_mismatch","Browser login was not started in this browser.");let a={request:e,stateId:s.stateId};if(t.context!==void 0&&(a.context=t.context),s.kind==="return_to"){let u=jP(i.payload),m=await ud(a);return{kind:"redirect",location:new URL(u,ie(e.url,e.headers)),setCookies:[await Fo({principal:m.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await ud(a),d=await aS({browserLoginStateToken:n,principal:c.principal});if(await IS({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await ld({operationId:d.transaction.operationId,principal:c.principal}))throw z("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return VS({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await Fo({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}o(GS,"completeBrowserLoginCallback");function jP(e){let t=wo(e),r=ge().actionPath("/auth/connections/"),n=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||n===void 0||!n.startsWith(r)||!/^[^/]+\/connect$/u.test(n.slice(r.length)))throw z("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}o(jP,"readConnectReturnTo");async function KS(e){let t=await sS(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(KS,"startConnectBrowserLogin");async function WS(e){let t=Ee(),r=new URL(e.url);if(!je(r))throw z("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw z("oauth_state_invalid","Local browser login is missing state.");let s=ge().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ie(e.url)),a=new URL(ie(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw z("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",n);let c={subjectId:_o.parse(EP),roles:TP};return{kind:"redirect",location:i,setCookies:[await Fo({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(WS,"completeLocalDevBrowserLogin");function DP(e){let t=e.method==="POST"?e.body:e.query;return xP.parse(t)}o(DP,"readSetupContinueRequest");async function ZS(e){let{state:t,decision:r}=DP({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await id({csrfToken:t,now:n}),i=await UP(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await uS({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await cS({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await fd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:JS(t)});if(r==="approve"&&yd(c)&&await rS({csrfToken:t,currentBrowserPrincipal:i,now:n}),yd(c)){let d=await gd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:md({state:t,operationId:a.operationId,gateway:ge(),upstreams:c,...d})}}return{kind:"redirect",location:await dS({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(ZS,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as XP,decodeJwt as QP,errors as Go,jwtVerify as ex}from"jose";import{createRemoteJWKSet as LP,decodeJwt as $P,decodeProtectedHeader as HP,errors as Vo,jwtVerify as BP}from"jose";var t_=30,ce=p.string().min(1),FP=p.union([ce,p.array(ce).min(1)]),JP=p.union([ce,p.array(ce).min(1)]),VP=p.object({type:ce,locations:p.array(ce).optional(),actions:p.array(ce).optional(),datatypes:p.array(ce).optional(),identifier:ce.optional(),privileges:p.array(ce).optional()}).passthrough(),GP=p.object({iss:p.url(),sub:ce,aud:FP,client_id:ce,resource:JP.optional(),scope:ce.optional(),authorization_details:p.array(VP).optional(),jti:ce,iat:p.number().int(),nbf:p.number().int().optional(),exp:p.number().int(),tenant:ce.optional(),aud_tenant:ce.optional(),aud_sub:ce.optional(),sub_id:ce.optional(),act:p.unknown().optional(),email:ce.optional(),auth_time:p.number().int().optional(),acr:ce.optional(),amr:p.array(ce).optional(),cnf:p.unknown().optional()}).passthrough();function $e(e){throw new T("invalid_grant",e)}o($e,"throwInvalidGrant");function KP(e){return e instanceof Vo.JWTExpired?"expired":e instanceof Vo.JWTClaimValidationFailed?"claim":e instanceof Vo.JWSSignatureVerificationFailed?"signature":e instanceof Vo.JWKSNoMatchingKey?"jwks_no_match":e instanceof Vo.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(KP,"readJwtFailureKind");function WP(e){return Array.isArray(e.aud)?(e.aud.length!==1&&$e("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}o(WP,"readSingleAudience");function YS(e){try{let t=GP.parse(e);return WP(t),t}catch(t){if(t instanceof T)throw t;$e("ID-JAG claims are invalid.")}}o(YS,"parseIdJagClaims");function ZP(e,t){e.idJag.enabled||$e("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(n=>n.issuer===t);return r===void 0&&$e("ID-JAG issuer is not trusted."),r}o(ZP,"readTrustedIssuer");function YP(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(n=>r.has(n.type))}o(YP,"readGrantedAuthorizationDetails");function XS(e){if(e.clientAuth.method==="none")throw new T("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&$e("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&$e("ID-JAG client_id is not allowed for this issuer.")}o(XS,"assertClientBinding");function QS(e){e.cnf!==void 0&&$e("ID-JAG cnf-bound assertions require DPoP support.")}o(QS,"assertProofOfPossessionNotDeferred");function e_(e){let t=Math.floor(e.now.getTime()/1e3)+t_;e.claims.iat>t&&$e("ID-JAG iat must not be in the future.")}o(e_,"assertIssuedAtNotInFuture");async function r_(e){let t;try{t=HP(e.assertion)}catch{$e("ID-JAG assertion is malformed.")}t.typ!==la&&$e('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=YS($P(e.assertion))}catch(c){if(c instanceof T)throw c;$e("ID-JAG assertion is malformed.")}let n=xt(e.requestUrl,e.requestHeaders),s=[n];e.requestedResource!==void 0&&e.requestedResource!==n&&s.push(e.requestedResource);let i=ZP(e.config,r.iss);s.includes(r.iss)&&$e("ID-JAG issuer must be different from the gateway."),XS({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),QS(r),e_({claims:r,now:e.now});let a;try{let c=LP(new URL(i.jwksUrl)),{payload:d}=await BP(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:t_,typ:la});a=YS(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:KP(c)},"OAuth ID-JAG assertion verification failed"),$e("ID-JAG assertion verification failed.")}return XS({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),QS(a),e_({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:Bm({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:YP({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(r_,"verifyIdJagAssertion");var tx=new Set(["authorization_code","refresh_token",Ot]),rx=1e4,nx=32*1024,ox=2,sx=3600,_d=p.object({client_id:p.string().min(1).optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),ix=p.discriminatedUnion("grant_type",[_d.extend({grant_type:p.literal("authorization_code"),code:p.string().min(1),redirect_uri:p.string().min(1),code_verifier:Dr,resource:p.url().optional(),scope:p.literal(pe).optional()}),_d.extend({grant_type:p.literal("refresh_token"),refresh_token:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional()}),_d.extend({grant_type:p.literal(Ot),assertion:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional(),authorization_details:p.string().min(1).optional()})]);function ax(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!tx.has(t)))throw new T("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(ax,"assertSupportedGrantType");var cx=p.object({token:p.string().min(1),client_id:p.string().min(1).optional(),token_type_hint:p.string().optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),dx=p.object({keys:p.array(p.record(p.string(),p.unknown())).min(1)}).passthrough();function o_(){return Ee().gateway.accessTokenTtlSeconds}o(o_,"readAccessTokenTtlSeconds");function ux(){return Ee().gateway.refreshTokenTtlSeconds}o(ux,"readRefreshTokenTtlSeconds");function n_(e,t){let r=o_(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,n);return{expiresAt:J(pt(e,s)),expiresIn:s}}o(n_,"calculateAccessTokenExpiresAt");function lx(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new T("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new T("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}o(lx,"readIdJagResource");function px(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new T("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}o(px,"readIdJagGrantedAuthorizationDetails");function mx(e){if(e.claimScope?.split(/\s+/).includes(pe)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return pe;if(e.claimScope===void 0)throw new T("invalid_grant",`ID-JAG must include ${pe} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(pe))throw new T("invalid_grant",`ID-JAG scope must include ${pe}.`);return pe}o(mx,"readIdJagGrantedScope");function hx(e){if(e!==void 0&&e.get("dpop")!==null)throw new T("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}o(hx,"assertNoDpopProofForIdJag");function s_(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new T("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}}o(s_,"readBasicClientSecret");function i_(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new T("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=QP(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new T("invalid_client","Malformed private_key_jwt client assertion.")}throw new T("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new T("invalid_client","Client authentication or client_id is required.")}o(i_,"resolveAuthenticatedClientId");function fx(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(fx,"resolveClientSecretInput");function gx(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(gx,"hasClientAssertion");function yx(e){if(e.requestUrl===void 0)throw new T("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(ge().actionPath(e.pathname),ie(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}o(yx,"buildEndpointAudience");function Sx(e){return e instanceof Go.JWTExpired?"expired":e instanceof Go.JWTClaimValidationFailed?"claim":e instanceof Go.JWSSignatureVerificationFailed?"signature":e instanceof Go.JWKSNoMatchingKey?"jwks_no_match":e instanceof Go.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(Sx,"readJwtFailureKind");async function _x(e){let{response:t,json:r}=await pg(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:ox,maxResponseBytes:nx,timeoutMs:rx});if(!t.ok)throw new T("invalid_client","Client JWKS could not be fetched.");return dx.parse(r)}o(_x,"fetchClientJwks");async function wx(e){if(e.clientAssertionType!==Hs||e.clientAssertion===void 0)throw new T("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=mt.parse(e.clientId),r=await zi(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new T("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new T("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=yx({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await _x({jwksUri:n,context:e.context}),{payload:a}=await ex(e.clientAssertion,XP(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+sx;if(typeof a.exp!="number"||a.exp>c)throw new T("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Sx(i)},"OAuth private_key_jwt client authentication failed"),new T("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(wx,"verifyPrivateKeyJwtClientAssertion");async function Rx(e){let t=mt.parse(e.clientId);if(Wm(t))throw new T("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await ae(e.clientSecret)}}o(Rx,"buildRuntimeHttpClientAuth");async function a_(e){if(gx({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return wx(e)}let t=fx({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Rx({clientId:e.clientId,...t})}o(a_,"resolveRuntimeHttpClientAuth");async function c_(e){ax(e.body);let t=ix.parse(e.body),r=s_(e.authorizationHeader),n=i_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await a_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:s,context:e.context});return bx({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(c_,"exchangeDownstreamToken");async function bx(e){if(e.parsed.grant_type==="authorization_code"){ln(e.parsed.redirect_uri,"invalid_request"),pn(e.parsed.scope),e.parsed.resource!==void 0&&lr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=ht(),d=ht(),u=J(pt(e.now,ux())),m=n_(e.now,u),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await ae(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Ks(e.parsed.code_verifier),currentRefreshTokenHash:await ae(c),accessTokenHash:await ae(d),grantExpiresAt:u,accessTokenExpiresAt:m.expiresAt,now:J(e.now)});if(h.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new T("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:m.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===Ot){pn(e.parsed.scope),hx(e.requestHeaders);let c=await r_({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:Ee()}),d=lx({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=lr(e.requestUrl??d,d,e.requestHeaders),m=px({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=mx({claimScope:c.claims.scope,grantedAuthorizationDetails:m}),f=ht(),S=J(new Date(c.claims.exp*1e3)),R=n_(e.now,S),_=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await ae(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:m,accessTokenExpiresAt:R.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:S}});if(_.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(_.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:f,token_type:"Bearer",expires_in:R.expiresIn,scope:_.grant.scope,resource:_.grant.resource,...m===void 0?{}:{authorization_details:m}}}pn(e.parsed.scope),e.parsed.resource!==void 0&&lr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await ae(e.parsed.refresh_token),r=e.parsed.refresh_token,n=ht(),s=J(pt(e.now,o_())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await ae(n),resource:e.parsed.resource,accessTokenExpiresAt:s,now:J(e.now)});if(i.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new T("invalid_grant","Refresh token is invalid, expired, or revoked.");lr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(bx,"exchangeDownstreamTokenWithRuntimeHttp");async function d_(e){let t=cx.parse(e.body),r=s_(e.authorizationHeader),n=i_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await a_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:s,context:e.context}),tokenHash:await ae(t.token),now:J(s)})).kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(d_,"revokeDownstreamToken");var vx=64*1024,Cx=16*1024,Ix="text/html; charset=utf-8";function Tx(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(Tx,"formDataToObject");async function Ex(e){return By(e,{maxBytes:vx,label:"Request body"})}o(Ex,"readJsonBody");async function Rd(e){return Tx(await Fy(e,{maxBytes:Cx,label:"Request body"}))}o(Rd,"readFormBody");async function u_(e,t,r){let n=lt(r),s=r instanceof p.ZodError?Ht(r):void 0,i={code:n??(r instanceof p.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),Ns(e,t,i)}o(u_,"handleProblem");function l_(e){return e?.requestId}o(l_,"readBrowserRequestId");function p_(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[$r];return typeof t=="string"?t:void 0}o(p_,"readUpstreamHtmlError");function mn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(mn,"readRuntimeErrorExtensionString");function kx(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(kx,"readRuntimeErrorExtensionNumber");function Ax(e){try{return new URL(e.url).pathname}catch{return}}o(Ax,"readBrowserRequestPath");function pr(e){let t={code:e.code,requestId:e.requestId,routePath:Ax(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=kx(e.error,dt),t.contentType=mn(e.error,Lr),t.upstreamUrl=mn(e.error,ut),t.upstreamServerId=mn(e.error,qs),t.metadataUrl=mn(e.error,Hr),t.providerError=mn(e.error,Br),t.providerErrorDescription=mn(e.error,Fr)),t}o(pr,"buildBrowserErrorDiagnostic");function Ko(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Ko,"oauthErrorResponse");function Px(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(Px,"readOAuthProtocolHeaders");function xx(e,t){let r=et("internal_server_error");return Ko({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Px(e,t)})}o(xx,"oauthProtocolErrorResponse");function wd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(wd,"readZodOAuthErrorCode");function Ox(e){let t={error:wd(e)},r=Ht(e);return r!==void 0&&(t.errorDescription=r),Ko(t)}o(Ox,"oauthZodErrorResponse");function Mx(e){let t=lt(e);if(t===void 0)return;let r=et(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:qx(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ko(n)}o(Mx,"oauthGatewayProblemResponse");function Ux(){let t={error:"server_error",status:500,errorDescription:et("internal_server_error").publicDetail};return Ko(t)}o(Ux,"oauthFallbackErrorResponse");function qx(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(qx,"readOAuthStatus");function bd(e,t={}){return e instanceof $t?f_(e):e instanceof T?xx(e,t):e instanceof p.ZodError?Ox(e):Mx(e)??Ux()}o(bd,"oauthProblemResponse");function vd(e,t,r){let n=Lt(e.url),s=l_(t);if(r instanceof $t)return f_(r);if(r instanceof T){let c=et("internal_server_error");return We({host:n,kind:zx(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?c.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?c.publicDetail:r.message,code:r.errorCode,diagnostic:pr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Ht(r)??"The authorization request was invalid.",developerDetail:Ht(r)??"The authorization request was invalid.",code:wd(r),diagnostic:pr({request:e,requestId:s,code:wd(r),underlyingError:Ht(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=lt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:h_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:pr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:p_(r),status:c.status})}let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:pr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(vd,"browserOAuthProblemResponse");function m_(e,t,r){let n=Lt(e.url),s=l_(t),i=lt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:h_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:pr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:p_(r),status:c.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Ht(r)??"The authorization request was invalid.",developerDetail:Ht(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:pr({request:e,requestId:s,code:"invalid_request",underlyingError:Ht(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:pr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(m_,"browserGatewayProblemResponse");function zx(e){return e==="server_error"?"internal_error":"invalid_request"}o(zx,"readOAuthBrowserErrorKind");function h_(e){if(et(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(h_,"readGatewayBrowserErrorKind");function vt(e,t,r){let n={event:t},s=!1;if(r instanceof T)n.oauthError=r.errorCode,n.status=r.status,ke(n,"error",r);else if(r instanceof $t)n.oauthError=r.errorCode,ke(n,"error",r);else if(r instanceof p.ZodError){n.code="invalid_request",ke(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=lt(r);if(i!==void 0){let a=et(i);n.code=i,n.status=a.status,a.oauthError!==void 0&&(n.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",ke(n,"error",r)}else s=!0,ke(n,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(vt,"logUnexpectedOAuthHandlerError");function f_(e){let t;try{t=new URL(e.redirectUri)}catch{return Ko({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),qi(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(f_,"downstreamAuthorizeRedirectErrorResponse");function Ht(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Ht,"formatZodErrorDetail");function Nx(e,t){let r={event:"browser_login_callback_failed",code:lt(t)??"invalid_request"};ke(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(Nx,"logBrowserLoginCallbackFailure");function g_(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(null,{status:302,headers:t})}o(g_,"redirectResultResponse");function Ni(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Ix,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(e.html,{status:200,headers:t})}return g_(e)}o(Ni,"authorizeResultResponse");async function y_(e,t){try{return Response.json(Dm(e.url,e.headers))}catch(r){return vt(t,"oauth_authorization_server_metadata_failed",r),u_(e,t,r)}}o(y_,"authorizationServerMetadataHandler");async function S_(e,t){try{let r=ga(e.params.routePath);return Response.json(Lm({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return vt(t,"oauth_authorization_server_metadata_failed",r),u_(e,t,r)}}o(S_,"scopedAuthorizationServerMetadataHandler");async function __(e,t){try{let r=await vS(await Ex(e)),n=r.client_id,s=r.client_name,i=r.redirect_uris.length,a=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:n,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),te(t,{eventType:V.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:n,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return vt(t,"oauth_register_failed",r),bd(r)}}o(__,"registerHandler");async function w_(e,t){try{return Ni(await Sd(e,{context:t}))}catch(r){return vt(t,"oauth_authorize_failed",r),vd(e,t,r)}}o(w_,"authorizeHandler");async function R_(e,t){try{let r=ga(e.params.routePath);return Ni(await Sd(e,{operationId:r.operationId,context:t}))}catch(r){return vt(t,"oauth_authorize_scoped_failed",r),vd(e,t,r)}}o(R_,"scopedAuthorizeHandler");async function b_(e,t){try{let r=await GS(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ni(r)}catch(r){return Nx(t,r),m_(e,t,r)}}o(b_,"callbackHandler");async function v_(e,t){try{return g_(await WS(e))}catch(r){return vt(t,"oauth_dev_login_failed",r),vd(e,t,r)}}o(v_,"devLoginHandler");async function C_(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await ZS({request:e,body:e.method==="POST"?await Rd(e):void 0,context:t});return Ni(r)}catch(r){return vt(t,"oauth_setup_failed",r),m_(e,t,r)}}o(C_,"setupHandler");async function I_(e,t){try{return Response.json(await c_({body:await Rd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return vt(t,"oauth_token_failed",r),bd(r)}}o(I_,"tokenHandler");async function T_(e,t){try{return await d_({body:await Rd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return vt(t,"oauth_revoke_failed",r),bd(r)}}o(T_,"revokeHandler");var E_="0.0.0",jx=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function Wo(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}o(Wo,"firstNonBlank");function Zo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}o(Zo,"clampToCodePoints");function Dx(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}o(Dx,"shortHash");function k_(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${Dx(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(k_,"clampNameSegment");function Lx(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(Lx,"sanitizeRegistryNameSegment");var $x=/^\d{1,3}(\.\d{1,3}){3}$/u;function Hx(e){let t=new URL(e).hostname.toLowerCase();if($x.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(n=>n.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(n=>n.length>0);return r.length>0?r.join("."):"local"}o(Hx,"buildRegistryNamespaceFromOrigin");function Bx(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}o(Bx,"sanitizeWebsiteUrl");function Fx(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let n;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;n=i.toString()}catch{continue}if(n.length>255||r.mimeType!==void 0&&!jx.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:n,...r.mimeType===void 0?{}:{mimeType:r.mimeType},...s===void 0||s.length===0?{}:{sizes:s},...r.theme===void 0?{}:{theme:r.theme}})}return t.length>0?t:void 0}o(Fx,"sanitizeIcons");function Jx(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(Jx,"localNameFromRoutePath");function A_(e){return e.includes("{")||e.includes(":")}o(A_,"isParameterizedRoutePath");var Vx=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function P_(e){let t=Wo(e)??E_;return Vx.test(t)?E_:Zo(t,255)}o(P_,"sanitizeRegistryVersion");function x_(e){let t=k_(Hx(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=k_(Lx(c),r),u=d;for(let m=2;n.has(u);m++){let h=`-${m}`;u=`${[...d].slice(0,r-h.length).join("")}${h}`}return n.add(u),u}o(i,"claimLocalName");function a(c,d){let u=`${t}/${i(c)}`;s.push({name:u,response:{server:{...d,name:u},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}o(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(A_(c.routePath))continue;let d=c.connection,u=d?.serverInfo,m=Zo(Wo(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=Wo(u?.title,d?.displayName),f=Bx(u?.websiteUrl),S=Fx(u?.icons);a(c.operationId,{description:m,...h===void 0?{}:{title:Zo(h,100)},version:P_(u?.version),...f===void 0?{}:{websiteUrl:f},...S===void 0?{}:{icons:S},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(A_(c.routePath))continue;let d=c.operationId??Jx(c.routePath),u=Zo(Wo(c.summary,c.description,c.serverName,c.operationId,d)??d,100),m=Wo(c.serverName);a(d,{description:u,...m===void 0?{}:{title:Zo(m,100)},version:P_(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o(x_,"buildMcpRegistryDirectory");var Gx=30,O_=100;function rt(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(rt,"registryErrorResponse");function Id(e){return x_({registry:Ce(),origin:ie(e.url,e.headers)})}o(Id,"readEntries");function Cd(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}o(Cd,"decodePathParam");function M_(e,t){return e.find(r=>r.name===t)}o(M_,"findEntryByName");function Kx(e){let t=e.get("limit");return t===null?{ok:!0,value:Gx}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),O_)}}o(Kx,"parseLimit");function Wx(e){let t=e.get("cursor");return t===null?{ok:!0,value:0}:/^\d+$/u.test(t)?{ok:!0,value:Number.parseInt(t,10)}:{ok:!1}}o(Wx,"parseCursor");var Zx=/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(\.\d+)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;function Yx(e){let t=Zx.exec(e);if(!t)return!1;let[,r,n,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(n)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(n)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}o(Yx,"isValidRfc3339Timestamp");async function U_(e,t){let r=new URL(e.url).searchParams,n=Kx(r);if(!n.ok)return rt(400,`Invalid 'limit' parameter: expected a positive integer (max ${O_}).`);let s=Wx(r);if(!s.ok)return rt(400,"Invalid 'cursor' parameter: pass the exact 'metadata.nextCursor' value returned by a previous list response.");let i=r.get("updated_since");if(i!==null&&!Yx(i))return rt(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let a=r.get("search")?.toLowerCase(),c=r.get("version"),d=Id(e).sort((h,f)=>h.name<f.name?-1:h.name>f.name?1:0);a!==void 0&&a!==""&&(d=d.filter(h=>h.name.toLowerCase().includes(a))),c!==null&&c!=="latest"&&(d=d.filter(h=>h.response.server.version===c));let u=d.slice(s.value,s.value+n.value),m=s.value+n.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...m<d.length?{nextCursor:String(m)}:{}}})}o(U_,"listMcpRegistryServersHandler");async function q_(e,t){let r=Cd(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=M_(Id(e),r.value);return n===void 0?rt(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(q_,"listMcpRegistryServerVersionsHandler");async function z_(e,t){let r=Cd(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Cd(e.params.version);if(!n.ok)return rt(400,"Invalid version: malformed encoding.");let s=M_(Id(e),r.value);return s===void 0?rt(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?rt(404,"Server or version not found"):Response.json(s.response)}o(z_,"getMcpRegistryServerVersionHandler");function ji(e,t){return(r,n)=>rt(e,t)}o(ji,"createWriteNotSupportedHandler");async function N_(e,t){return rt(404,"Not found")}o(N_,"mcpRegistryNotFoundHandler");var j_=ji(501,"Publishing is not supported by this registry"),D_=ji(501,"Updates are not supported by this registry"),L_=ji(501,"Deletion is not supported by this registry"),Td=ji(403,"You do not have publish or edit permissions for this server");function $_(e){return W`<section class="page-section" aria-labelledby="result-next-steps"><h2 class="section-label" id="result-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol></section>`}o($_,"renderBrowserResult");var Xx="text/html; charset=utf-8";function Qx(e){return an({title:e.title,iconHref:bc(e.host),styles:sn,headerIcon:xi("success"),heading:e.title,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:$_({steps:nn(e.steps.map(t=>W`<li>${t}</li>`))}),footer:""})}o(Qx,"browserResultHtml");function eO(e,t=200){return new Response(on(e),{status:t,headers:{"content-type":Xx,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(eO,"browserResultResponse");function H_(e){return eO(Qx(e))}o(H_,"browserConnectionSuccessResponse");function Di(e,t,r={}){let n=vm(t);return We({host:e,kind:tO(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(Di,"browserConnectionFailureResponse");function tO(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}o(tO,"readCallbackFailureBrowserErrorKind");var rO={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},B_=Symbol("upstream-request");function Yo(e,t){Object.defineProperty(e,B_,{configurable:!0,value:t})}o(Yo,"setUpstreamRequestContext");function nO(e){let t=e[B_];if(!t)throw new Te("Upstream request context has not been set");return t}o(nO,"readUpstreamRequestContext");function oO(e,t){return t.some(r=>r===e)}o(oO,"requestContextMatchesKind");function sO(e){return typeof e=="string"?[e]:e}o(sO,"toExpectedKinds");function Xo(e,t){let r=nO(e),n=sO(t);if(!oO(r.kind,n)){let s=rO[n[0]];throw new Te(`${s} request context has not been set`)}return r}o(Xo,"requireUpstreamRequestContext");function Bt(e){if(typeof e=="string"&&e.length!==0)return e}o(Bt,"readOptionalQueryString");function iO(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Te(`Validated path parameter ${t} is missing`);return aO(r,t)}o(iO,"requirePathString");function aO(e,t){try{return decodeURIComponent(e)}catch(r){throw new k({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[O]:"invalid_request"}},{cause:r})}}o(aO,"decodePathString");function cO(e){let t=Bt(e);return t?js.parse(t):void 0}o(cO,"readOptionalOperationId");function dO(e){let t=Ce().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new k({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[O]:"unknown_upstream_server"}})}o(dO,"readRegisteredAuthProfileId");function uO(e){let t=cO(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[O]:"invalid_request"}});return t}o(uO,"readRequiredOperationId");async function Ed(e){return e.redirect?We({host:Lt(e.request.url),kind:"authorization_failed",title:e.title,detail:e.detail,code:e.status===401?"authentication_required":"forbidden",requestId:e.context.requestId,status:e.status}):e.status===401?Ne.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):Ne.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}o(Ed,"browserConnectRefusal");function lO(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let n of t)r.append("set-cookie",n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(lO,"withSetCookies");async function pO(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(_m(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await Ed({request:t,context:r,redirect:s,status:403,title:"Ask an administrator",detail:"This gateway cannot confirm who opened this link, so it cannot connect an account from it. Ask an administrator to connect this service."});let i=await un(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return lO(await Ed({request:t,context:r,redirect:s,status:401,title:"Sign in required",detail:"Open this connect link in a browser. The gateway asks you to sign in before it connects an account."}),a);let d=new URL(t.url),u=wo(`${d.pathname}${d.search}`);if(u===void 0)throw new Te("Connect request path is empty");let m=await KS({returnTo:u,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:m.location.toString(),"cache-control":"no-store"});for(let f of[...a,m.setCookie])h.append("set-cookie",f);return new Response(null,{status:302,headers:h})}let c=n.ownerMode==="user"?n.ownerSubjectId:n.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await Ed({request:t,context:r,redirect:s,status:403,title:"This link is for another account",detail:"This connect link was created for a different gateway user, so it cannot connect an account in this browser. Ask your MCP client for its own connect link, or sign in to the gateway as the user who received this one."})}o(pO,"requireTicketOwnerBrowser");async function mO(e,t,r){let n=Ai(r,uO(e.query.operationId));if(n.authMode==="id-jag")throw new k({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[O]:"invalid_request"}});let s=e.query.redirect==="true",i=Bt(e.query.browserTicket);if(e.user){if(i)throw new k({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[O]:"invalid_request"}});let d=ar(e.user,e.url),u={kind:"connect",...tn(n,d.subjectId),redirect:s},m=wo(Bt(e.query.returnTo));return m!==void 0&&(u.returnTo=m),u}if(!i)throw new k({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[O]:"authentication_required"}});let a=await Eg(i);if(a.ownerMode!==n.ownerMode||a.upstreamServerId!==n.upstreamServerId||a.authProfileId!==n.authProfileId||a.operationId!==n.operationId)throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});if(zt()){let d=await pO({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await kg(a);let c=Ds(a);switch(n.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}case"user-oauth":{if(c.mode!=="user")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}o(mO,"resolveConnectContext");async function hO(e,t,r){let n=Im.parse(iO(e,"connection"));switch(r){case"connect":{let s=await mO(e,t,n);if(s instanceof Response)return s;Yo(e,s);return}case"callback":{let s=Bt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Bt(e.query.error_description);d!==void 0&&(c.errorDescription=d),Yo(e,c);return}let i=Bt(e.query.code),a=Bt(e.query.state);if(i&&a){let c=Bt(e.query.iss);Yo(e,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:a,...c===void 0?{}:{iss:c}});return}Yo(e,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":Yo(e,{kind:"client_metadata",upstreamServerId:n,authProfileId:dO(n)});return}}o(hO,"resolveUpstreamRequestInbound");async function fO(e,t,r){try{return await hO(e,t,r)}catch(n){let s=n instanceof k?n.extensionMembers?.[O]:void 0,i=n instanceof Error?n.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return Ne.badRequest(e,t,{code:s,detail:i});case"authentication_required":return Ne.unauthorized(e,t,{code:s,detail:i});default:throw n}}}o(fO,"applyUpstreamRequestContext");function Li(e,t){return o(async(n,s)=>{let i=await fO(n,s,e);return i||t(n,s)},"wrapped")}o(Li,"withUpstreamRequestContext");var gO=["callback_authorization_code","callback_provider_error","callback_invalid"];function kd(e){try{return new URL(e.url).pathname}catch{return}}o(kd,"readBrowserRequestPath");function yO(e){return"cause"in e?e.cause:void 0}o(yO,"readErrorCause");function SO(e){return e.stack?.split(`
44
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(SO,"readFirstStackFrame");function F_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=SO(r))}o(F_,"addErrorAttributes");function Ad(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[O];return zs(t)?t:void 0}o(Ad,"readRuntimeGatewayCode");function Qo(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(Qo,"readRuntimeErrorExtensionString");function _O(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(_O,"readRuntimeErrorExtensionNumber");function wO(e,t,r,n){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),te(t,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),Di(n,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:kd(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Di(n,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:kd(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}o(wO,"requireAuthorizationCallbackRequest");function RO(e,t){te(e,{eventType:V.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(RO,"emitCallbackReceivedAnalyticsEvent");function bO(e,t){te(e,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(bO,"emitTokenExchangeSucceededAnalyticsEvent");function vO(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return H_({host:Lt(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}o(vO,"buildSuccessfulCallbackResponse");function CO(e){let t={detail:e instanceof Error?e.message:void 0};return F_(t,"error",e),e instanceof Error&&F_(t,"cause",yO(e)),t}o(CO,"buildTokenExchangeFailureAttributes");function IO(e){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Ad(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:CO(e.error)})}o(IO,"emitTokenExchangeFailedAnalyticsEvent");function TO(e){let t=e.error,r=Ad(t),n=bm(r)?r:"upstream_token_exchange_failed",s={code:n,requestId:e.context.requestId,routePath:kd(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof k?{httpStatus:_O(t,dt),contentType:Qo(t,Lr),upstreamUrl:Qo(t,ut),metadataUrl:Qo(t,Hr),providerError:Qo(t,Br),providerErrorDescription:Qo(t,Fr)}:{}};return Di(e.host,n,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:EO(t)})}o(TO,"tokenExchangeFailureResponse");function J_(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(J_,"withSetCookie");function EO(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[$r];return typeof t=="string"?t:void 0}o(EO,"readUpstreamHtmlError");async function Pd(e,t){let r=Xo(e,gO),n=Lt(e.url),s=wO(e,t,r,n);if(s instanceof Response)return s;RO(t,s);let i;try{let a=await gy({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return bO(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),J_(vO(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:Ad(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return ke(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),IO({context:t,callbackRequest:s,error:a}),J_(TO({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(Pd,"callbackHandler");function kO(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(kO,"clientMetadataProblemDetail");async function V_(e,t){let r=Xo(e,"connect"),n=r.redirect?await $o({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:vi/1e3}):void 0,s=await fy({request:e,connectRequest:r,...n===void 0?{}:{browserBinding:n.claim}});if(te(t,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),n!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":n.setCookie,"cache-control":"no-store"}});let i=await Ii({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}o(V_,"connectHandler");async function G_(e,t){let r=Xo(e,"client_metadata");try{let n=ie(e.url,e.headers),s=Dg(n,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(n){if(!(n instanceof ee))throw n;let s=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),Ne.notFound(e,t,{code:"not_found",detail:kO(n)})}}o(G_,"oauthClientMetadataHandler");function AO(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(AO,"resolveInternalRoutePath");var PO={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function xO(){return new Response(null,{status:204,headers:PO})}o(xO,"buildWellKnownPreflightResponse");function OO(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(OO,"withWellKnownCorsHeaders");function mr(e){return async(t,r)=>t.method==="OPTIONS"?xO():OO(await e(t,r))}o(mr,"wrapWellKnownHandler");var K_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:mr(y_),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:mr(S_),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:mr($m),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:__},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:w_},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:R_},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:b_},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:v_},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:C_},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:I_},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:T_},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Li("client_metadata",G_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Li("connect",V_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Li("callback",Pd)}],MO=K_.filter(e=>!e.routeName.startsWith("upstream_")),UO=K_.filter(e=>e.routeName.startsWith("upstream_"));function qO(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:mr(U_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:mr(q_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:mr(z_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:j_},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:D_},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:L_},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Td},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Td},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:mr(N_),corsPolicy:"anything-goes"}]}o(qO,"buildMcpRegistryInternalRoutes");function zO(e){let t=Pm({routes:e.routes,policies:e.policies,gateway:e.gateway});return xm(t),t}o(zO,"initializeMcpGatewayConnectionRegistry");function NO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(NO,"hasDownstreamOAuthRoutes");function jO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(jO,"hasIdJagDownstreamOAuth");function DO(e){let t=new Map;for(let n of e.byOperationId.values())n.downstreamOAuth&&t.set(n.downstreamOAuth.policyName,n.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new Te("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(n=>`"${n}"`).join(", ");throw new ee(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}o(DO,"readSingletonDownstreamOAuthConfig");function LO(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(qm(n));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?Ns(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}o(LO,"readScopedDownstreamOAuthConfig");function $O(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o($O,"routeUsesScopedOAuthConfig");function xd(e,t,r){return async(n,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let d=await r(n,s);if(d instanceof Response)return d;d&&Sm(s,d)}let i=n.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:n.method},`MCP gateway: ${e} received`);let c=await t(n,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}o(xd,"wrapInternalHandler");function Od(e,t,r,n){e.addPluginRoute({path:AO(t,r),methods:t.methods,handler:n,processors:[ou],corsPolicy:t.corsPolicy??"none"})}o(Od,"addInternalRoute");function W_(e,t){let r=zO(t);if(r.gateway.registry.enabled){ot("plugin.mcp-gateway.registry");for(let c of qO(r.gateway.registry))Od(e,c,r.gateway,xd(c.routeName,c.handler))}let n=NO(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=DO(r)),i),"readSingletonOAuthConfig");if(n){ot("plugin.mcp-gateway.downstream-oauth"),jO(r)&&ot("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of MO){let d=$O(c)?(u,m)=>LO(r,u,m):a;Od(e,c,r.gateway,xd(c.routeName,c.handler,d))}}if(s){ot("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())ot(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of UO)Od(e,c,r.gateway,xd(c.routeName,c.handler,n?a:void 0))}}o(W_,"registerMcpGatewayInternalRoutes");var Md=class extends nu{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),ot("plugin.mcp-gateway"),this.#e=wm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&W_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as Dw}from"@opentelemetry/api";var zd=256*1024,es=34,HO=92,hn=123,fn=125,$i=91,ts=93,rs=44,Ud=58,Q_=new Set(["jsonrpc","method","id"]),ew=new Set(["name","uri"]),tw=new Set([Ms]),rw="_meta",nw=[...Q_,...ew,...tw,"params",rw],ow=Math.max(...nw.map(e=>e.length)),BO=ow+2,FO=ow*6+2,JO=1024,VO=1e3,Z_=new TextDecoder("utf-8",{fatal:!0}),qd=class{constructor(t,r){this.bytes=t;this.readMetaProtocolVersion=r}bytes;readMetaProtocolVersion;static{o(this,"EnvelopeScanner")}pos=0;scan(){let t=this.bytes;t[0]===239&&t[1]===187&&t[2]===191&&(this.pos=3),this.skipWhitespace();let r;return t[this.pos]===hn?r=this.readObject():t[this.pos]===$i?r=this.readBatch():this.fail(),this.skipWhitespace(),this.expect(this.pos===t.length),r}readBatch(){let t=[];if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===ts)return this.pos++,t;for(;;){if(this.skipWhitespace(),this.bytes[this.pos]===hn){let n=this.readObject();(n.id!==void 0||n.method!==void 0)&&(this.expect(t.length<VO),t.push(n))}else this.skipValue();this.skipWhitespace();let r=this.bytes[this.pos++];if(r===ts)return t;this.expect(r===rs)}}fail(){throw new SyntaxError("Unscannable request body")}expect(t){t||this.fail()}skipWhitespace(){for(;;){let t=this.bytes[this.pos];if(t!==32&&t!==10&&t!==13&&t!==9)return;this.pos++}}skipString(){this.expect(this.bytes[this.pos]===es),this.pos++;let t=!1;for(;;){let r=this.bytes[this.pos++];if(r===es)return t;r===HO?(t=!0,this.pos++):this.expect(r!==void 0)}}skipValue(){this.skipWhitespace();let t=this.bytes[this.pos];if(t===es){this.skipString();return}if(t!==void 0&&t!==hn&&t!==$i&&t!==fn&&t!==ts&&t!==rs&&t!==Ud){for(;!Y_(this.bytes[this.pos]);)this.pos++;return}let r=[];for(;;){this.skipWhitespace();let n=this.bytes[this.pos];if(this.expect(n!==void 0),n===es)this.skipString();else if(n===hn||n===$i){r.push(n),this.pos++;continue}else if(n===fn||n===ts)this.expect(r.pop()===(n===fn?hn:$i)),this.pos++;else if(n===rs||n===Ud){this.expect(r.length>0),this.pos++;continue}else for(;!Y_(this.bytes[this.pos]);)this.pos++;if(r.length===0)return}}readKey(){let t=this.pos,r=this.skipString(),n=this.pos-t;if(r)return n>FO?void 0:JSON.parse(Z_.decode(this.bytes.subarray(t,this.pos)));if(n>BO)return;let s=n-2;for(let i of nw){if(i.length!==s)continue;let a=0;for(;a<s&&this.bytes[t+1+a]===i.charCodeAt(a);)a++;if(a===s)return i}}readObject(t="message"){let r=t==="message"?Q_:t==="params"?ew:tw,n=t==="message"?"params":t==="params"&&this.readMetaProtocolVersion?rw:void 0,s={};if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===fn)return this.pos++,s;for(;;){this.skipWhitespace();let i=this.readKey();this.skipWhitespace(),this.expect(this.bytes[this.pos++]===Ud),this.skipWhitespace();let a=this.pos;if(n!==void 0&&i===n)if(delete s[n],this.bytes[a]===hn){let d=this.readObject(t==="message"?"params":"meta");Object.keys(d).length>0&&(s[n]=d)}else this.skipValue();else if(this.skipValue(),i!==void 0&&r.has(i)){delete s[i];let d=this.readPrimitive(a);(t==="meta"?Us(d):typeof d=="string"||typeof d=="number"&&i==="id")&&(s[i]=d)}this.skipWhitespace();let c=this.bytes[this.pos++];if(c===fn)return s;this.expect(c===rs)}}readPrimitive(t){let r=this.bytes[t];if(!(r===es||r===45||r>=48&&r<=57)||this.pos-t>JO)return;let s=Z_.decode(this.bytes.subarray(t,this.pos)),i=JSON.parse(s);return typeof i=="number"&&!sw(s,i)?void 0:i}};function Y_(e){return e===void 0||e===rs||e===fn||e===ts||e===32||e===10||e===13||e===9}o(Y_,"isDelimiter");function GO(e,t){try{return new qd(new Uint8Array(e),t).scan()}catch{return{}}}o(GO,"sniffEnvelope");var KO=/^(-)?(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function X_(e){let t=KO.exec(e);if(!t)return;let[,r,n,s="",i]=t,a=`${n}${s}`.replace(/^0+/,""),c=Number(i??0)-s.length;if(a==="")return"0";let d=/0*$/.exec(a)?.[0].length??0;return a=a.slice(0,a.length-d),c+=d,`${r??""}${a}e${c}`}o(X_,"canonicalDecimal");function sw(e,t){if(!Number.isFinite(t)||Object.is(t,-0))return!1;let r=X_(e),n=X_(JSON.stringify(t));return r!==void 0&&r===n}o(sw,"isLosslessNumberLiteral");function iw(e){let t=!0,r=o((n,s,i)=>(typeof s=="number"&&t&&(t=typeof i?.source=="string"&&sw(i.source,s)),s),"reviver");try{JSON.parse(new TextDecoder().decode(e),r)}catch{return!1}return t}o(iw,"jsonRoundTrips");function aw(e,t={}){if(!(e===void 0||e.byteLength===0)){if(e.byteLength>zd)return{value:GO(e,t.readMetaProtocolVersion===!0)};try{return{value:JSON.parse(new TextDecoder().decode(e))}}catch{return}}}o(aw,"parseRequestJson");var WO="zuplo_mcp_",ZO=["__host-","__secure-"];function YO(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of ZO)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(WO)}o(YO,"setsGatewayCookie");function cw(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!YO(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let n=new Headers(e.headers);n.delete("clear-site-data"),n.delete("set-cookie");for(let s of r)n.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}o(cw,"stripUpstreamOriginStateHeaders");function Ze(e){return e&&typeof e=="object"?e:void 0}o(Ze,"readRecord");function ns(e,t){let r=Ze(e)?.[t];return typeof r=="string"?r:void 0}o(ns,"readStringProperty");function uw(e,t){let r=Ze(e)?.[t];return typeof r=="number"?r:void 0}o(uw,"readNumberProperty");function dw(e,t){return uw(e,"code")??(t>=400?t:void 0)}o(dw,"readErrorCode");function lw(e){return Array.isArray(e)?e.map(lw).find(t=>t?.method):Ze(e)}o(lw,"readJsonRpcMessage");function Nd(e){let t=lw(e),r=typeof t?.method=="string"?t.method:"",n=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:ns(n,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:ns(n,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=ns(n,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}o(Nd,"buildBaseCapabilityInput");function Hi(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}o(Hi,"isCapabilityListMethod");function XO(e,t,r){let i=Ze(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}o(XO,"readItemCount");function pw(e){let t=Nd(e);return!t||Hi(t.mcpMethod)?null:{eventType:V.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(pw,"buildCapabilityInvokedAnalyticsInput");function QO(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}o(QO,"readMissingResponseFailure");function mw(e,t,r={}){let n=Nd(e);if(!n)return null;let s=Ze(t.message),i=Ze(s?.error),a=Ze(i?.data),c=s?.result,d=n.mcpMethod==="tools/call"&&Ze(c)?.isError===!0,u=Ze(c),m=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&Ze(Ze(u.inputRequests)?.[Nr])!==void 0;if(Ze(a?.connectRequired)||m)return{eventType:V.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...n,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:uw(i,"code"),mcpErrorType:ns(i,"message")};let h=t.status<400?QO(t):void 0;if(h&&!i)return{eventType:Hi(n.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,...h};if(Hi(n.mcpMethod)){let f=t.status>=400?void 0:XO(n.mcpMethod,n.capabilityType,c),S=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:V.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...n,httpStatusCode:t.status,...S?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:dw(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:V.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:dw(i,t.status),mcpErrorType:ns(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:"success",...n,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...n,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}o(mw,"buildCapabilityFinalAnalyticsInput");function hw(e,t){let r=Nd(e);return r?{eventType:Hi(r.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}o(hw,"buildCapabilityThrownAnalyticsInput");var jd={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},fw={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},gw={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};import{context as eM,TraceFlags as tM,trace as rM}from"@opentelemetry/api";var yw="mcp-session-id",nM=256*1024;function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(gn,"isPlainObject");function oM(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(oM,"isJsonContentType");function Sw(e,t,r){if(t===void 0||r===void 0||r.byteLength>zd||!oM(e))return;let n=t.value;if(!gn(n)||typeof n.method!="string"||n.params!==void 0&&!gn(n.params))return;let s=n.id;return{message:n,method:n.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...n.params===void 0?{}:{params:n.params},...typeof n.jsonrpc=="string"?{jsonrpc:n.jsonrpc}:{}}}o(Sw,"parseMcpRequestMessage");function Dd(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}o(Dd,"readStringParam");function sM(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Dd(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Dd(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Dd(e.params,"uri")};default:return{}}}o(sM,"readCapability");function _w(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(_w,"readHeader");function iM(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let n=new URL(r.__rewriteFunction(e,su(t))),s=n.port!==""?Number(n.port):n.protocol==="https:"?443:n.protocol==="http:"?80:void 0;return{serverAddress:n.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}o(iM,"readUpstreamServer");function ww(e){let{request:t,context:r,parsed:n}=e,s=sr(t.headers,n.message),i=_w(t.headers,yw),a={methodName:n.method,...sM(n),...n.id===void 0?{}:{jsonRpcRequestId:n.id},...n.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:n.jsonrpc},...i===void 0?{}:{mcpSessionId:i}},c=mm({...a,mcpProtocolVersion:s??um,params:n.params}),d;try{Ki(c.span);let u=c.span.isRecording()||pm()?iM(t,r):{};return d=eM.with(c.ctx,()=>hm({...a,...s===void 0?{}:{mcpProtocolVersion:s},...u})),Ki(d.span),nm(r,c.span.spanContext()),{server:c,client:d}}catch(u){throw Ld(d===void 0?[c]:[d,c]),u}}o(ww,"startMcpProxySpans");var aM=["content-digest","repr-digest","digest","content-md5"];function cM(e){return aM.some(t=>e.has(t))}o(cM,"hasBodyIntegrityHeader");function Rw(e,t,r,n){let s=rM.getSpanContext(t.client.ctx);if(r.byteLength>nM||n!==void 0&&cM(n)||s===void 0||(s.traceFlags&tM.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!gn(i))return r;try{let a=da(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!iw(r))return r;let c=da(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}o(Rw,"injectTraceContextIntoBody");function dM(e,t){if(e){if(gn(e.error)){let r=e.error.code,n=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof n=="string"?{message:xs(n,lm)}:{},httpStatusCode:t}}if(gn(e.result)&&e.result.isError===!0)return{isError:!0}}}o(dM,"readSpanResponse");function uM(e,t,r){let n=_w(t.headers,yw),s=r?.result,i=rm(gn(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);hr(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(uM,"recordInitializeResult");function bw(e){let{spans:t}=e,r=[t.client,t.server];try{lM(r,e)}catch{}finally{Ld(r)}}o(bw,"finishMcpProxySpans");function lM(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&uM(e,n,s.message);let i=dM(s.message,n.status);i?hr(e,a=>a.setResponse(i)):s.ended==="errored"?hr(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?hr(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?hr(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?hr(e,a=>a.setErrorType("response_replaced","A different response was sent before the JSON-RPC response arrived.")):t.expectsResponse&&s.ended==="complete"&&!s.message&&!s.truncated&&!s.uninspected&&hr(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(lM,"recordOutcome");function hr(e,t){for(let r of e)try{t(r)}catch{}}o(hr,"forEachHandle");function Ld(e){for(let t of e)try{t.end()}catch{}}o(Ld,"endEach");function $d(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}o($d,"failMcpProxySpans");function Hd(e){for(let t of[e.client,e.server])try{t.setErrorType("cancelled","The client cancelled the request before the upstream sent response headers.")}catch{}finally{Ld([t])}}o(Hd,"cancelMcpProxySpans");var Vd=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),Bd=64*1024,Gd=1024*1024,pM=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function vw(e,t={}){return e===void 0?Bd:pM.has(e)||t.modern===!0&&e==="server/discover"?Gd:Bd}o(vw,"tapMaxBytesForMethod");function mM(e){let t=it(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(mM,"readTapMode");function hM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(hM,"isPlainObject");function fM(e){return hM(e)&&!("method"in e)&&("result"in e||"error"in e)}o(fM,"isResponseShaped");function gM(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(gM,"isSameJsonRpcIdValue");function Cw(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(fM);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>gM(a.id,t));if(i||r)return i}return s[0]}o(Cw,"selectResponse");function Iw(e){try{return JSON.parse(e)}catch{return}}o(Iw,"tryParseJson");var Fd=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{o(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let n of this.#e)t.set(n,r),r+=n.byteLength;this.#e=[],this.#n=Cw(Iw(new TextDecoder().decode(t)),this.requestId,!1)}},Jd=class{constructor(t,r){this.requestId=t;this.#e=new Mo({maxEventChars:r,onOversize:"discard"})}requestId;static{o(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let n=t(r);this.#r||=r.discardedEvents>0;for(let s of n){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=Cw(Iw(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},yM={push(){},end(){},message:void 0,truncated:!1};function SM(e,t,r){switch(e){case"json":return new Fd(t,r);case"sse":return new Jd(t,r);case"passthrough":return yM}}o(SM,"createObserver");function Tw(e,t={}){let r=e.body;if(r===null){let I=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:I,outcome:I}}let n=at(e.headers)?"passthrough":mM(e),s=SM(n,t.requestId,t.maxBytes??Bd),i,a=new Promise(I=>{i=I}),c,d=new Promise(I=>{c=I}),u=!1,m=o(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,S=o((I,U)=>{if(f)return;if(f=!0,I==="complete")try{s.end()}catch{}let v={ended:I,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...n==="passthrough"&&h>0?{uninspected:!0}:{},...U===void 0?{}:{error:U}};i(v),u||(u=!0,c(v))},"settle"),R=r.getReader(),_=new ReadableStream({async pull(I){let U;try{U=await R.read()}catch(v){S("errored",v),I.error(v);return}if(U.done){S("complete"),I.close();return}if(h+=U.value.byteLength,!f)try{s.push(U.value)}catch{}I.enqueue(U.value),m()},async cancel(I){S(I===Vd?"released":"cancelled"),await R.cancel(I)}},{highWaterMark:0}),y=mf(new Headers(e.headers)),b;try{b=new Response(_,{status:e.status,statusText:e.statusText,headers:y})}catch(I){throw R.cancel(I).catch(()=>{}),I}return{response:b,done:a,outcome:d}}o(Tw,"tapJsonRpcResponse");var _M=-32603,wM="The upstream MCP server ended the response stream without a response to this request.",RM="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function Ew(e){return`${typeof e}:${String(e)}`}o(Ew,"idKey");function bM(e,t){if(e.delete(Ew(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(bM,"clearAnsweredRequest");function kw(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!Aw(n)||typeof n.method!="string"||typeof n.id!="string"&&typeof n.id!="number")continue;let s=Me(n);s!==void 0&&r.push(s)}return r}o(kw,"readJsonRpcRequestIds");function Aw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Aw,"isRecord");function vM(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)Aw(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&n.push(s.id);return n}o(vM,"readResponseIds");function CM(e){let t=e.getReader();return new ReadableStream({async pull(r){let n;try{n=await t.read()}catch{r.close();return}if(n.done){r.close();return}r.enqueue(n.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}o(CM,"endOnError");function Pw(e,t,r=Gd,n){let s=new Map;for(let a of t)s.set(Ew(a),a);let i=!1;return tc(CM(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of vM(a.data))bM(s,c)},{failureMode:"open",maxEventChars:r,onFailure:o((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:o(()=>{if(s.size===0||i)return[];let a=n?.aborted?RM:wM;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:_M,message:a}})}))},"end")})}o(Pw,"answerUnansweredRequests");var IM={Allow:"POST"},xw="mcp-session-id";async function TM(e){try{return await e.clone().arrayBuffer()}catch{return}}o(TM,"readRequestBody");function Wd(e){try{let t=Om(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}o(Wd,"readRouteAnalyticsFields");function Zd(e){return Fm(e.user,e.url,e.headers)?.subjectId}o(Zd,"readRequestSubjectId");function Ow(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}o(Ow,"readRequestMethod");function Mw(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Mw,"readHeader");function Yd(e){let t=Mw(e.request.headers,xw)??(e.response?Mw(e.response.headers,xw):void 0),r=e.tapResult?.message?.result,n=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=sr(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Yd,"readMcpProtocolFields");function EM(e){let t=pw(e.requestJson?.value);t&&te(e.context,{...t,...Wd(e.context),...Yd({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http"})}o(EM,"emitCapabilityInvokedAnalytics");function kM(e){let t=mw(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended},{modern:e.modern,gatewayAnswered:e.gatewayAnswered});t&&ya(e.context,{...t,...Wd(e.context),...Yd(e),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(kM,"emitCapabilityFinalAnalytics");function Bi(e){let t=hw(e.requestJson?.value,e.details);t&&(e.late?ya:te)(e.context,{...t,...Wd(e.context),...Yd({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(Bi,"emitCapabilityThrownAnalytics");async function Uw(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let n=new kt(e.request,{headers:t,...r===void 0?{}:{body:r}}),s=o(i=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=i)},"onTimeoutSignal");return fm(n,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}o(Uw,"callUpstream");function AM(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(AM,"readClientSignal");function qw(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(qw,"throwIfClientCancelled");function PM(e){let{clientSignal:t,context:r,onCancel:n}=e,s=!1,i=o(()=>(t.removeEventListener("abort",a),s?!1:(s=!0,!0)),"claim"),a=o(()=>{i()&&r.waitUntil(Promise.resolve().then(n).catch(c=>{try{vs.getLogger(r).error(c,"Error recording an MCP request whose client cancelled before headers")}catch{}}))},"onAbort");return t.addEventListener("abort",a,{once:!0}),{claim:i}}o(PM,"watchClientCancelBeforeHeaders");async function Kd(e){try{await e.body?.cancel()}catch{}}o(Kd,"discardBody");function xM(e,t){return e===t.reason?!0:e instanceof Error||e instanceof DOMException?e.name==="AbortError"||e instanceof Error&&e.cause===t.reason:!1}o(xM,"isClientAbortError");function OM(e,t){try{vs.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(OM,"logErrorAfterClientLeft");async function zw(e){qw(e.clientSignal);let t=await Uw(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=Py(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await Kd(t);let n=o(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await Dw.with(e.refreshContext,n):await n();return qw(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await Uw({...e,headers:s.headers}),gatewayAnswered:!1}}o(zw,"forwardToUpstream");function MM(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?zw({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):Dw.with(i.client.ctx,()=>zw({request:t,context:r,bodyBytes:n===void 0?void 0:Rw(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(MM,"callUpstreamOperation");function UM(e,t,r){if(e.body===null||e.status<200||e.status>299||it(e.headers.get("content-type"))!=="text/event-stream"||at(e.headers))return e;let n=kw(t?.value);if(n.length===0)return e;let s=yt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(Pw(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(UM,"withUnansweredRequestErrors");function qM(e,t){if(e.body===null||!t.rewritten&&!t.clientSignal)return e;let r=new Headers(e.headers);return t.rewritten&&r.set("x-accel-buffering","no"),new Response(zM(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(qM,"finishModernResponse");function zM(e,t){if(!t)return e;let r=e.getReader(),n=!1,s=o(()=>{},"onAbort"),i=o(()=>{n=!0,t.removeEventListener("abort",s)},"finish");return new ReadableStream({start(a){s=o(()=>{if(!n){i(),r.cancel(t.reason).catch(()=>{});try{a.close()}catch{}}},"onAbort"),t.aborted?s():t.addEventListener("abort",s,{once:!0})},async pull(a){let c;try{c=await r.read()}catch(d){n||(i(),a.error(d));return}if(!n){if(c.done){i(),a.close();return}a.enqueue(c.value)}},async cancel(a){i(),await r.cancel(a)}},{highWaterMark:0})}o(zM,"cancelOnClientAbort");function NM(e,t){iu.findContextExtensions(e)?.addPipelineExitHook(r=>{let n=t.body;r===t||n===null||r?.body===n||n.locked||n.cancel(Vd).catch(()=>{})})}o(NM,"releaseBodyIfNotSent");function Nw(e,t){return Ne.format({type:"https://httpproblems.com/http-status/499",title:"Client Closed Request",status:499,detail:"The client cancelled the request before the upstream MCP server responded."},e,t)}o(Nw,"clientClosedResponse");function jw(e){return e instanceof ee?gw:fw}o(jw,"thrownDetails");async function jM(e,t){if(ot("handler.mcp-gateway-proxy"),e.method==="GET")return Ne.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},IM);let r=Date.now(),n=await TM(e),s=aw(n,{readMetaProtocolVersion:fe()});rh(t,sr(e.headers,s?.value));let i=Sw(e,s,n),a;if(i!==void 0)try{a=ww({request:e,context:t,parsed:i})}catch{a=void 0}EM({context:t,request:e,requestJson:s});let c=fe()&&zr(e.headers,s?.value),d=c&&Ow(s)==="subscriptions/listen",u=c?AM(e):void 0,m=u?PM({clientSignal:u,context:t,onCancel:o(()=>{a&&Hd(a),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c,late:!0})},"onCancel")}):void 0,h={},f,S;try{let y=await MM({request:e,context:t,requestBody:n,parsed:i,spans:a,modern:c,listen:d,clientSignal:u,upstreamTimeout:h});S=y.gatewayAnswered,f=cw(y.response)}catch(y){let b=m?.claim()??!0;if(u?.aborted)return xM(y,u)||OM(t,y),b&&(a&&Hd(a),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c})),Nw(e,t);throw a&&$d(a,y),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jw(y),modern:c}),y}if(m&&!m.claim())return await Kd(f),Nw(e,t);let R,_;try{R=Tw(f,{requestId:Me(s?.value),maxBytes:vw(Ow(s),{modern:c})});let y=UM(R.response,s,h.signal);_=c?qM(y,{rewritten:y!==R.response,clientSignal:u}):y,NM(t,_)}catch(y){throw await Kd(R?.response??f),a&&$d(a,y),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jw(y),modern:c}),y}return t.waitUntil(R.outcome.then(y=>{try{kM({context:t,request:e,requestJson:s,response:f,tapResult:y,startedAt:r,modern:c,gatewayAnswered:S})}finally{a&&i&&bw({spans:a,method:i.method,response:f,tapResult:y,expectsResponse:i.id!==void 0})}}).catch(y=>{try{vs.getLogger(t).error(y,"Error emitting MCP gateway capability analytics")}catch{}})),_}o(jM,"McpProxyHandler");export{Yw as McpAuth0OAuthInboundPolicy,hc as McpCapabilityFilterInboundPolicy,$w as McpClerkOAuthInboundPolicy,Hw as McpCognitoOAuthInboundPolicy,Bw as McpEntraOAuthInboundPolicy,Md as McpGatewayPlugin,Fw as McpGoogleOAuthInboundPolicy,Jw as McpKeycloakOAuthInboundPolicy,Vw as McpLogtoOAuthInboundPolicy,Xw as McpOAuthInboundPolicy,Gw as McpOktaOAuthInboundPolicy,Kw as McpOneLoginOAuthInboundPolicy,Ww as McpPingOAuthInboundPolicy,jM as McpProxyHandler,Qc as McpTokenExchangeInboundPolicy,Zw as McpWorkosOAuthInboundPolicy,zf as claimsCapabilityResolver};
43
+ </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(cn,"renderShell");function Ai(e){return W`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?Jy:Gy}</div>`}o(Ai,"renderStatusIcon");var Zk="text/html; charset=utf-8";function Lt(e){try{return new URL(e).host}catch{return""}}o(Lt,"safeHostFromUrl");function We(e){let t=e.kind??"authorization_failed",r=Xk(t),n=Yk(e),s=e.title??r.title;return new Response(sn(cn({title:s,iconHref:"",styles:an,headerIcon:Ai(t==="access_denied"?"neutral":"error"),heading:s,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:Fy({steps:on(r.steps.map(i=>W`<li>${i}</li>`)),action:tA(e.action),reference:rA(n),diagnostics:nA({diagnostic:n,detail:e.detail}),upstreamResponse:oA(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":Zk,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(We,"browserErrorPageResponse");function Yk(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Qk(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??eA(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(Yk,"buildBrowserErrorDiagnostic");function Xk(e){switch(e){case"session_expired":return{title:"Authorization expired",steps:["Return to your MCP client and reconnect.","Expired authorization requests cannot be resumed, so start a new connection instead of reloading this page."]};case"access_denied":return{title:"Authorization canceled",steps:["Return to your MCP client.","If you want to grant access, start the connection again and approve the request."]};case"configuration_error":return{title:"Configuration needs attention",steps:["Contact your workspace admin and share the reference below.","The gateway or upstream configuration must be fixed before retrying."]};case"connection_failed":return{title:"Connection failed",steps:["Return to your MCP client and reconnect this upstream.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"invalid_request":return{title:"Authorization request invalid",steps:["Return to your MCP client and try connecting again.","If this keeps happening, the client request may need to be fixed."]};case"admin_required":return{title:"Admin setup required",steps:["Contact your workspace admin and share the reference below.","This connection cannot be completed until setup is finished."]};case"internal_error":return{title:"Gateway error",steps:["Try again later from your MCP client.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"authorization_failed":return{title:"Authorization failed",steps:["Return to your MCP client and start authorization again.","If this keeps happening, contact your gateway administrator and share the reference below."]}}}o(Xk,"readBrowserErrorPagePresentation");function Qk(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}o(Qk,"readBrowserErrorStage");function eA(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}o(eA,"readBrowserErrorSuggestedFix");function tA(e){return e===void 0?Ke:W`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(tA,"renderAction");function Pi(e){if(e.value===void 0||e.value==="")return Ke;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return W`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}o(Pi,"renderRow");function $e(e){return Pi({label:e.label,value:e.value===void 0?void 0:W`<code>${e.value}</code>`})}o($e,"renderCodeRow");function rA(e){return on([Pi({label:"Error code",value:W`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),$e({label:"Request ID",value:e.requestId}),$e({label:"Time",value:e.timestamp})])}o(rA,"renderReference");function nA(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return on([Pi({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Pi({label:"Reason",value:r,block:!0}),$e({label:"Stage",value:t.stage}),$e({label:"Gateway route",value:t.routePath}),$e({label:"Operation ID",value:t.operationId}),$e({label:"Upstream",value:t.upstreamServerId}),$e({label:"Auth profile",value:t.authProfileId}),$e({label:"Upstream URL",value:t.upstreamUrl}),$e({label:"Metadata URL",value:t.metadataUrl}),$e({label:"HTTP status",value:t.httpStatus}),$e({label:"Content type",value:t.contentType}),$e({label:"Provider error",value:t.providerError}),$e({label:"Provider error description",value:t.providerErrorDescription})])}o(nA,"renderDiagnostics");function oA(e){return e===void 0?Ke:W`<details class="provider-response"><summary class="provider-response__summary">Show the provider's response</summary><iframe title="Upstream HTML error response" sandbox class="provider-response__frame" srcdoc="${e}"></iframe></details>`}o(oA,"renderUpstreamHtml");var Vy="application/json",sA="application/x-www-form-urlencoded";function xi(e,t){return new k({message:e,extensionMembers:{[M]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(xi,"invalidRequestError");function iA(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(iA,"normalizeContentType");function aA(e,t){return e===t?!0:t===Vy&&e.endsWith("+json")}o(aA,"contentTypeMatches");function cA(e,t){if(!t||t.length===0)return;let r=iA(e.headers.get("content-type"));if(!t.some(n=>aA(r,n)))throw xi(`Request body must be ${t.join(" or ")}.`)}o(cA,"assertExpectedContentType");function dA(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw xi(`${r} exceeded the maximum allowed size.`)}o(dA,"assertContentLengthWithinLimit");async function Ky(e,t){let r=t.label??"Request body";cA(e,t.expectedContentTypes),dA(e,t.maxBytes,r);let n=await yi(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>xi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(Ky,"readBoundedTextBody");async function Wy(e,t){let r=await Ky(e,{...t,expectedContentTypes:[Vy]});try{return JSON.parse(r)}catch(n){throw xi("Request body must be valid JSON.",n)}}o(Wy,"readBoundedJsonBody");async function Zy(e,t){let r=await Ky(e,{...t,expectedContentTypes:[sA]});return new URLSearchParams(r)}o(Zy,"readBoundedFormUrlEncodedBody");import{errors as Xy,jwtVerify as Qy,SignJWT as od}from"jose";import{base64url as uA}from"jose";var lA="mcp-browser-login-pkce:",pA=new TextEncoder;async function mA(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(mA,"importHmacKey");async function nd(e){let t=await mA(e.signingKey),r=pA.encode(`${lA}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return $r.parse(uA.encode(new Uint8Array(n)))}o(nd,"deriveBrowserLoginPkceVerifier");async function Yy(e){let t=await nd(e),r=await Bs(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Dr}}o(Yy,"deriveBrowserLoginPkceParams");var hA={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},T=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=hA[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var fA=300,eS=p.string().min(1).optional(),gA=p.object({purpose:p.literal("gateway_browser_login"),transactionId:la,stateId:js,binding:No,authorizationServerIssuer:eS,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),yA=p.object({purpose:p.literal("gateway_browser_login_return"),stateId:js,binding:No,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),SA=p.discriminatedUnion("purpose",[gA,yA]),_A=p.object({purpose:p.literal("gateway_authorization_setup"),transactionId:la,stateId:js,authorizationServerIssuer:eS,exp:p.number().int().positive(),iat:p.number().int().positive().optional()});async function dn(){return Ge({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"browser-login"),"derive")})}o(dn,"getBrowserLoginKey");async function tS(){return Ge({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"authorization-csrf"),"derive")})}o(tS,"getCsrfKey");function rS(e){return{now:e.now??new Date,ttlSeconds:sd()}}o(rS,"readPendingTransactionDependencies");function sd(){return Ee().browserLogin.stateTtlSeconds}o(sd,"readBrowserLoginStateTtlSeconds");function wA(e){let t=ge();return je(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o(wA,"isLoopbackDevLoginUrl");async function nS(e){let t=Ee().browserLogin,r=ge(),n=new URL(xt("url")),s=new URL(r.actionPath("/oauth/callback"),Ot(e.requestUrl,e.requestHeaders));if(wA(n))return n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("state",e.state),n;if(n.searchParams.set("response_type","code"),n.searchParams.set("client_id",xt("clientId")),n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("scope",t.scope),n.searchParams.set("state",e.state),n.searchParams.set("nonce",e.nonce),t.audience&&n.searchParams.set("audience",t.audience),t.pkce===Dr){let i=await Yy({stateId:e.stateId,signingKey:await dn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(nS,"buildBrowserLoginUrl");function RA(e,t){return e.subjectId===t.subjectId}o(RA,"principalsMatch");function oS(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(oS,"toPendingPrincipal");function sS(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:J(e.now),expiresAt:J(mt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw z("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:oS(e.principal)}}o(sS,"createTransactionRecord");async function iS(e){let{id:t,...r}=e.record,n=await H().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw z("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new T("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new T("invalid_request","redirect_uri is not registered for the client.")}}o(iS,"startPendingTransaction");async function bA(e){return new od({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await dn())}o(bA,"signBrowserLoginState");async function aS(e){return new od({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:$s(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await tS())}o(aS,"signCsrfToken");async function id(e){try{let{payload:t}=await Qy(e,await dn(),{algorithms:[Re],issuer:he,audience:we}),r=SA.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding,authorizationServerIssuer:r.authorizationServerIssuer}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof Xy.JWTExpired?z("oauth_state_expired","Browser login state has expired.",t):z("oauth_state_invalid","Browser login state could not be verified.",t)}}o(id,"verifyAnyBrowserLoginStateToken");async function vA(e){let t=await id(e);if(t.kind!=="authorization")throw z("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding,authorizationServerIssuer:t.authorizationServerIssuer}}o(vA,"verifyBrowserLoginStateToken");async function Oi(e){try{let{payload:t}=await Qy(e,await tS(),{algorithms:[Re],issuer:he,audience:we}),r=_A.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof Xy.JWTExpired?z("oauth_state_expired","Authorization setup state has expired.",t):z("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Oi,"verifyCsrfToken");function ad(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(ad,"pendingStateErrorCode");function CA(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(CA,"toPendingAuthorizationGetResult");function IA(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(IA,"toPendingAuthorizationAdvanceResult");function cd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":ad(e==="consumed_already"?"consumed_already":e)}o(cd,"setupDecisionErrorCode");async function cS(e){let t=e.now??new Date,r=await Oi(e.csrfToken),n=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await ce(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(n.kind!=="marked")throw z(cd(n.kind),"Authorization setup state is invalid, expired, or already used.");return dS({kind:"available",record:n.transaction})}o(cS,"markSetupApproved");function dS(e){if(e.kind!=="available")throw z(ad(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(dS,"requireAwaitingSetup");function TA(e){if(!RA(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(TA,"requireCurrentPrincipalMatches");async function uS(e){let t=e.now??new Date,r=sd(),n=pa(),s=$s(),i=await Do({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await bA({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=sS({id:n,transaction:e.transaction,currentStateHash:await ce(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await iS({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await nS({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:u,browserBindingCookie:i.setCookie}}o(uS,"startAwaitingLogin");async function lS(e){let t=sd(),r=$s(),n=await Do({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new od({purpose:"gateway_browser_login_return",stateId:r,binding:n.claim}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await dn());return{browserLoginUrl:await nS({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(lS,"startReturnToBrowserLogin");async function pS(e){let{now:t,ttlSeconds:r}=rS(e),n=pa(),s=await aS({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=sS({id:n,transaction:e.transaction,currentStateHash:await ce(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await iS({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}o(pS,"startAwaitingSetup");async function mS(e){let{now:t,ttlSeconds:r}=rS(e),n=await vA(e.browserLoginStateToken),s=await aS({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=IA(await H().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await ce(e.browserLoginStateToken),nextStateHash:await ce(s),nextPhase:"awaiting_setup",principal:oS(e.principal),now:J(t)}));if(i.kind!=="advanced")throw z(ad(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}o(mS,"completeLogin");async function hS(e){let t=await dd(e);return TA({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(hS,"getSetup");async function dd(e){let t=e.now??new Date,r=await Oi(e.csrfToken);return dS(CA(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await ce(e.csrfToken),now:J(t)})))}o(dd,"getSetupTransaction");async function EA(e){let t=await Oi(e.csrfToken),r=ft(),n=J(mt(e.now,fA)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await ce(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await ce(r),authorizationCodeExpiresAt:n,grantId:Mm(),now:J(e.now)});if(s.kind!=="approved")throw z(s.kind==="cancelled"?"oauth_state_invalid":cd(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),Mi(i,t.authorizationServerIssuer),i}o(EA,"createAuthorizationCodeRedirectWithDecision");async function kA(e){let t=await Oi(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await ce(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw z(r.kind==="approved"?"oauth_state_invalid":cd(r.kind),"Authorization setup state is invalid, expired, or already used.");return AA({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(kA,"createCancelRedirectWithDecision");function Mi(e,t){t!==void 0&&fe()&&e.searchParams.set("iss",t)}o(Mi,"setAuthorizationResponseIssuer");function AA(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),Mi(t,e.authorizationServerIssuer),t}o(AA,"buildClientCancelRedirect");async function fS(e){let t=e.now??new Date;return EA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(fS,"approve");async function gS(e){let t=e.now??new Date;return kA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(gS,"cancel");import{createRemoteJWKSet as PA,errors as un,jwtVerify as yS,SignJWT as xA}from"jose";var OA="zuplo_mcp_session",MA=p.object({purpose:p.literal("gateway_browser_session"),sub:yo,browserLoginOrigin:p.string().min(1),roles:p.array(p.string().min(1)).optional(),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),UA=p.object({id_token:p.string().min(1),token_type:p.string().min(1).optional(),expires_in:p.number().optional(),access_token:p.string().min(1).optional(),refresh_token:p.string().min(1).optional(),scope:p.string().min(1).optional()}),qA=p.object({error:p.string().min(1).optional(),error_description:p.string().min(1).optional(),error_uri:p.string().min(1).optional()}),zA=p.object({sub:yo,nonce:p.string().min(1)}).catchall(p.unknown()),ud;async function SS(){return Ge({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>dt(e,"browser-session"),"derive")})}o(SS,"getBrowserSessionKey");function pd(e,t){let r=fi(e,t);return{name:kc(OA,r),secure:r}}o(pd,"browserSessionCookieName");function ld(e,t){let{name:r,secure:n}=pd(e,t);return jo({name:r,value:"",maxAgeSeconds:0,secure:n})}o(ld,"buildBrowserSessionEvictionCookie");function NA(e){let{name:t,secure:r}=pd(e.requestUrl,e.requestHeaders);return jo({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}o(NA,"serializeSessionCookie");function _S(){return new URL(xt("url")).origin}o(_S,"readBrowserLoginOrigin");function jA(e){let t=qA.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(jA,"readIdpErrorFields");function DA(e){return e instanceof un.JWTExpired?"expired":e instanceof un.JWTClaimValidationFailed?"claim":e instanceof un.JWSSignatureVerificationFailed?"signature":e instanceof un.JWKSNoMatchingKey?"jwks_no_match":e instanceof un.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(DA,"readJwtFailureKind");function $A(e){return e instanceof Error&&"cause"in e?e.cause:e}o($A,"readErrorCause");function LA(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(LA,"readRuntimeGatewayCode");function HA(){if(!ud){let e=Ee();ud=PA(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return ud}o(HA,"readFederatedJwks");function wS(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return cr(e.user,e.url)}o(wS,"resolveCurrentRequestPrincipal");async function ln(e,t={}){let r=Ac(e.headers.get("cookie")).get(pd(e.url,e.headers).name);if(!r)return{};try{let{payload:n}=await yS(r,await SS(),{algorithms:[Re],issuer:he,audience:we}),s=MA.parse(n);if(s.browserLoginOrigin!==_S())return{evictCookie:ld(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(n){return n instanceof un.JWTExpired?{evictCookie:ld(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:ld(e.url,e.headers)})}}o(ln,"readBrowserSession");async function Bo(e){let t=Ee().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:_S()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new xA(r).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await SS());return NA({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(Bo,"createBrowserSessionCookie");async function BA(e){let t=Ee(),r=xt("tokenUrl"),n=xt("clientId"),s=xt("clientSecret"),i=new URL(ge().actionPath("/oauth/callback"),Ot(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:s});if(t.browserLogin.pkce===Dr){let c=await nd({stateId:e.stateId,signingKey:await dn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await Si(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let S=jA(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ae(r),idpStatus:c.status,...S},"Federated browser login token exchange returned non-2xx from the identity provider"),z({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${S.idpError?` idp_error=${S.idpError}`:""}${S.idpErrorDescription?` idp_error_description=${S.idpErrorDescription}`:""})`)})}let u=UA.parse(d),m;try{({payload:m}=await yS(u.id_token,HA(),{issuer:t.oidc.issuer,audience:n}))}catch(S){let R={};throw ke(R,"error",S),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:DA(S),idpHost:ae(r),expectedIssuer:t.oidc.issuer,...R},"Federated id_token failed jose verification"),S}if(m.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ae(r),nonceMissingFromIdToken:m.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),z("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=zA.parse(m);return{principal:cr({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:wo,expiresAt:typeof m.exp=="number"?J(new Date(m.exp*1e3)):void 0}}}catch(c){let d=pt(c)??LA(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",$A(c))}}o(BA,"exchangeFederatedAuthorizationCode");async function md(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return BA({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await ln(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw z("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}o(md,"resolveBrowserLoginCallbackIdentity");var FA=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function JA(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(JA,"readScheme");function GA(e){return e.protocol==="https:"}o(GA,"isSpecCompliantRedirectUri");function VA(e){let t=JA(e);return t.length>0&&t!=="http"&&t!=="https"&&!FA.has(t)}o(VA,"isNativeAppCustomSchemeRedirectUri");var bS=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>GA(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>je(e),"accepts"),matches:o((e,t)=>je(e)&&je(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>VA(e),"accepts")}];function vS(e){let t=bS.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(vS,"evaluateBuiltInRedirectUriCompatibility");function RS(e){try{return new URL(e)}catch{return}}o(RS,"parseUrl");function CS(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=RS(e.registeredRedirectUri),r=RS(e.requestedRedirectUri);return t===void 0||r===void 0?!1:bS.some(n=>n.matches?.(t,r))}o(CS,"redirectUriMatchesBuiltInCompatibility");var KA=1e4,WA=5*1024,ZA=0,YA=2160*60*60,IS=["authorization_code","refresh_token",zs,Mt],XA=["authorization_code","refresh_token"],TS=[Pm],QA=["code"],eP=p.object({client_name:p.string().min(1).optional(),redirect_uris:p.array(p.string().min(1)).min(1),grant_types:p.array(p.enum(IS)).min(1).max(IS.length).optional(),authorization_grant_profiles_supported:p.array(p.enum(TS)).min(1).max(TS.length).optional(),response_types:p.array(p.enum(QA)).min(1).max(1).optional(),scope:p.literal(pe).optional(),token_endpoint_auth_method:Om.optional(),jwks_uri:p.string().min(1).optional()});function tP(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&je(t))&&t.pathname!=="/"}catch{return!1}}o(tP,"isCimdClientIdCandidate");function ES(e,t){throw new T("invalid_client",Hm({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(ES,"invalidCimdClientError");function pn(e,t="invalid_request"){if(rP(e))throw new T(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new T(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new T(t,"redirect_uris must not include credentials or fragments.");if(vS({url:r}).kind==="rejected")throw new T(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(pn,"assertValidRedirectUri");function rP(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(rP,"hasForbiddenRawRedirectUriCharacter");async function nP(e){let{response:t,json:r}=await _g(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:ZA,maxResponseBytes:WA,timeoutMs:KA});if(!t.ok)throw z("invalid_request","CIMD metadata could not be fetched.");let n=Ds(r);for(let s of n.redirect_uris)pn(s,"invalid_request");if(n.jwks_uri!==void 0&&bo(n.jwks_uri),n.client_id!==e.clientId)throw z("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(nP,"fetchCimdMetadata");async function oP(e){let t=Ls(e),r=await nP({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(oP,"resolveCimdClient");async function Ui(e,t){let r=ht.parse(e);if(tP(r)){Ee().gateway.downstreamCimdEnabled||ES(r);try{return await oP(r)}catch(s){ES(r,s)}}let n=await H().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=Fm(s.clientId),a=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",c=s.jwksUri??i;if(a==="private_key_jwt"&&c===void 0)throw new T("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=Ds({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),u={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(u.hashedClientSecret=s.hashedClientSecret),u}throw new T("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(Ui,"resolveClient");function kS(e,t){if(!e.metadata.redirect_uris.some(r=>CS({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(kS,"assertRedirectRegistered");function sP(e){return e===void 0?[...XA]:Array.from(new Set(e))}o(sP,"normalizeGrantTypes");function iP(e){try{bo(e)}catch(t){throw new T("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}o(iP,"assertValidDcrJwksUri");function aP(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?ht.parse(Bm({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):ht.parse(`dcr:${crypto.randomUUID()}`)}o(aP,"createDcrClientId");function mn(e){if(e===void 0||e===pe)return pe;throw new T("invalid_request",`Only the ${pe} scope is supported.`)}o(mn,"assertSupportedOAuthScope");function mr(e,t,r){let n;try{n=new URL(t)}catch{throw new T("invalid_target","resource must be an absolute URI.")}if(n.hash)throw new T("invalid_target","resource must not include a fragment.");if(n.protocol!=="https:"&&!je(n))throw new T("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ie(e,r),i=qs(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new T("invalid_target","resource must match a published MCP route.");return a}o(mr,"resolveResource");async function AS(e){let t;try{t=eP.parse(e)}catch(S){if(S instanceof p.ZodError){let R=S.issues.some(_=>_.path[0]==="redirect_uris");throw new T(R?"invalid_redirect_uri":"invalid_client_metadata",S.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:S})}throw S}for(let S of t.redirect_uris)pn(S,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new T("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&iP(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=aP({tokenEndpointAuthMethod:n,jwksUri:t.jwks_uri}),a=Ds({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:n,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=mt(r,YA),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),m={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:sP(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:pe,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:J(r),clientExpiresAt:J(c)};if(n==="client_secret_basic"||n==="client_secret_post"){let S=ft();h.hashedClientSecret=await ce(S),h.clientSecretExpiresAt=J(c),m.client_secret=S,m.client_secret_expires_at=u,m.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw z("invalid_request","OAuth client is already registered.");return m}o(AS,"registerDownstreamClient");function cP(e){return e?.metadata?.idpSubjectTokenType!==Vr&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}o(cP,"hasStoredIdJagSubjectTokenBinding");async function PS(e){let t=Gr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(PS,"readIdJagSubjectConnection");async function hd(e){let t=Ce().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await PS({connection:t.connection,principal:e.principal});return!cP(r)}o(hd,"requiresIdJagSubjectTokenBinding");async function xS(e){if(e.subjectToken===void 0)return;let t=Ce().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await PS({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??Hs(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await Rt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}o(xS,"bindIdJagSubjectTokenForAuthorizationTransaction");function OS(e){return W`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(OS,"renderShellIcon");function MS(e){return W`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(MS,"renderActions");var US=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function qS(e){return W`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(qS,"renderBannerWarning");var M$=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),U$=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var q$=Ve('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var dP="data:,",zS=W`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,NS=W`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function uP(e,t,r){if(e)try{let n=new URL(t).origin,s=new URL(e,n);return s.origin!==n||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}o(uP,"safeGatewayConnectHref");function lP(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(lP,"deriveMode");function pP(e){return MS({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:zS,authorizeAttrs:Ke})}o(pP,"renderActions");function fd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=uP(s.connectUrl,t,n);if(i)return i}}o(fd,"firstUserConnectHref");function mP(e){let t=e.connectHref===void 0?Ke:W`<a class="button button--primary" href="${e.connectHref}" ${NS}>Connect</a>`;return W`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${zS}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}o(mP,"renderSetupActions");function hP(e){return e?W`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${NS}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Ke}o(hP,"renderReconnectAction");function fP(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}o(fP,"isRenderableIconHref");function jS(e){return e?.find(t=>fP(t.src))?.src}o(jS,"readIconHref");function gP(e){return jS(e.serverIcons)??(e.transportHost===void 0?void 0:Rc(e.transportHost).src)}o(gP,"readUpstreamIconHref");function yP(e){let t=jS(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=gP(r);if(n!==void 0)return n}}o(yP,"readHeaderIconHref");function SP(e){let t=e.setupMessage===void 0?Ke:qS({icon:US,message:e.setupMessage});return W`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}o(SP,"renderBody");function gd(e){let t=lP(e.upstreams),r=fd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),n=fd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=fd(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??n:void 0,a=t==="setup"?e.upstreams.find(u=>u.ownerMode==="user"&&u.status!=="active"&&u.connectUrl===void 0&&u.setupMessage!==void 0)?.setupMessage:void 0,c=yP({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?W`<footer class="card__footer">${mP({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:W`<footer class="card__footer">${hP(s)}${pP({state:e.state,gateway:e.gateway})}</footer>`;return sn(cn({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??dP,styles:an,headerIcon:c===void 0?Ke:OS({iconHref:c,fallbackIconHref:Kf}),heading:"Authorize access",subhead:Ke,body:SP({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(gd,"renderConsentPage");var _P=1e4,wP=2e3,RP=64*1024,BS={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},DS="mcp-session-id",bP;function FS(){return{tools:[],prompts:[],resources:[]}}o(FS,"emptyCapabilities");function $S(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":ma})}o($S,"buildReadinessHeaders");async function LS(e){if(e.type==="bearer_token"){let n=$S();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=$S();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(LS,"buildAsyncCredentialHeaders");function vP(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(or.parse({jsonrpc:nr,id:1,method:"initialize",params:{protocolVersion:ma,capabilities:{},clientInfo:BS}}))})}o(vP,"buildInitializePreflight");function CP(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",go),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:nr,id:1,method:"server/discover",params:{_meta:{[Qp]:go,[em]:{},[tm]:BS}}})})}o(CP,"buildDiscoverPreflight");async function IP(e){if(e.status!==400&&e.status!==404)return!1;let t=await TP(e);if(t===void 0)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&"error"in r&&typeof r.error=="object"&&r.error!==null&&"code"in r.error&&typeof r.error.code=="number"}catch{return!1}}o(IP,"isModernRejectionOfInitialize");async function TP(e){let t=e.body?.getReader();if(t===void 0)return;let r,n=new Promise(i=>{r=setTimeout(()=>i("timeout"),wP)}),s=(async()=>{let i=new TextDecoder,a="",c=0;for(;;){let{done:d,value:u}=await t.read();if(d)return a+i.decode();if(c+=u.byteLength,c>RP)return;a+=i.decode(u,{stream:!0})}})();try{let i=await Promise.race([s,n]);return i==="timeout"?void 0:i}catch{return}finally{clearTimeout(r),t.cancel().catch(()=>{})}}o(TP,"readBoundedBody");async function yd(e){Ro(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),_P);try{let n=new Request(e,{redirect:"manual",signal:t.signal});return await Wd.fetch(n)}finally{clearTimeout(r)}}o(yd,"runPreflight");function Fo(e){e.body?.cancel().catch(()=>{})}o(Fo,"releasePreflightBody");async function EP(e){let t=e.response.headers.get(DS);if(!t)return;let r=new Headers(e.headers);r.set(DS,t),r.delete("content-type");try{let n=await yd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Fo(n)}catch{}}o(EP,"terminatePreflightSession");async function JS(e){let{response:t}=e;return Fo(t),t.status>=200&&t.status<300?(await EP(e),{kind:"ready",upstreamStatus:t.status,capabilities:FS()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}o(JS,"classifyResponse");function HS(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}o(HS,"connectRequiredResult");async function GS(e){let t=await yd(vP(e));if(!fe()||!await IP(t))return t;try{let r=await yd(CP(e));if(r.status>=200&&r.status<300)return Fo(t),r;Fo(r)}catch{}return t}o(GS,"probeUpstream");async function kP(e){try{return JS({response:await GS(e),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}o(kP,"classifyPreflight");async function AP(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:FS()};let r=Ei(t.upstreamServerId,e.route.operationId),n=rn(r,e.subjectId),s=e.returnTo===void 0?n:{...n,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await tn({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return HS(a.payload);let c=await LS(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d;try{d=await GS({upstreamUrl:t.mcpUrl,headers:c})}catch(h){return{kind:"upstream_unavailable",message:h instanceof Error?h.message:"Upstream MCP server readiness preflight failed."}}if(d.status!==401)return JS({response:d,upstreamUrl:t.mcpUrl,headers:c});Fo(d);let u=await tn({request:i,routeAuth:s,forceRefresh:!0});if(u.kind==="connect_required")return HS(u.payload);let m=await LS(u.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:kP({upstreamUrl:t.mcpUrl,headers:m})}o(AP,"checkUpstreamRouteReadinessImpl");function VS(e){return(bP??AP)(e)}o(VS,"checkUpstreamRouteReadiness");function PP(e){try{return new URL(e).host}catch{return}}o(PP,"safeUrlHost");function KS(e){return e!==void 0&&e.length>0}o(KS,"hasItems");function xP(e){let t=e.serverInfo?.icons;if(KS(t))return t;let r=ui(e.mcpUrl);return r===void 0?void 0:[r]}o(xP,"readServerIcons");async function OP(e){let{authConfig:t,authMode:r,description:n,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",m=u&&r!=="id-jag",h=e.readiness??(u?Wm(e.connection):{connected:!0,status:"active"}),f=m?e.readiness?.connectUrl??(e.returnTo!==void 0?await Oc({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,S=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:n,transportHost:PP(i),scopesRequested:KS(S)?S:void 0,serverIcons:xP(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:f,setupMessage:e.setupMessage,updatedAt:u&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}o(OP,"buildSetupRequirement");function WS(e){let t=Ce().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(WS,"requireRoute");async function Sd(e){let t=WS(e.transaction.operationId),r=Gr(e.transaction.principal.subjectId),n=t.connection;if(n===void 0)return[];let i=n.ownerMode==="user"?(await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId}]))[0]:void 0,a=await VS({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),c="connectionStatus"in a?a.connectionStatus:void 0,d=(a.kind==="connect_required"||a.kind==="admin_setup_required")&&a.payload.authUrl!==void 0?a.payload.authUrl:void 0,u=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await OP({connection:i,registeredConnection:n,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:u,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}o(Sd,"requirementsForSetup");async function _d(e){let t=WS(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),n=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ie(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:n?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}o(_d,"consentContext");function wd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(wd,"hasUnresolvedUserUpstream");var MP=["mcp_user"],UP="dev-browser-user",qP=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),zP=p.object({response_type:p.literal("code"),client_id:p.string().min(1),redirect_uri:p.string().min(1),resource:p.url(),code_challenge:p.string().min(43),code_challenge_method:ym,state:p.string().min(1).optional(),scope:p.literal(pe).default(pe)}),NP=p.enum(["continue","approve","cancel"]).default("continue"),jP=p.object({state:p.string().min(1),decision:NP}),Ht=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;authorizationServerIssuer;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription,this.authorizationServerIssuer=t.authorizationServerIssuer}};function ZS(e){return typeof e=="string"&&e.length>0?e:void 0}o(ZS,"readQueryString");function DP(e,t){let r=ZS(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new T("invalid_target",qP)}let n=jm(t,e.url,e.headers);if(r===void 0||r===n)return n;throw new T("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(DP,"requireAuthorizeResource");async function $P(e,t){let r={};t!==void 0&&(r.context=t);let n=await ln(e,r);if(n.principal)return{principal:n.principal};if(!e.user)return n.evictCookie===void 0?{}:{setCookie:n.evictCookie};let s=wS(e);return{principal:s,setCookie:await Bo({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o($P,"resolveBrowserPrincipal");async function LP(e,t){let r={};t!==void 0&&(r.context=t);let n=await ln(e,r);if(!n.principal)throw z("authentication_required","Authorization setup requires a current browser session.");return n.principal}o(LP,"requireSetupPrincipal");function YS(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(YS,"buildSetupReturnTo");async function XS(e){let t=await Sd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:YS(e.csrfToken)}),r=await _d({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),n={kind:"setup_page",html:gd({state:e.csrfToken,operationId:e.transaction.operationId,gateway:ge(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(n.setCookies=e.setCookies),n}o(XS,"renderSetup");function HP(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(HP,"toAuthorizationTransactionClient");async function Rd(e,t={}){let r=zP.parse({...e.query,resource:DP(e,t.operationId),state:ZS(e.query.state)}),n=mn(r.scope);pn(r.redirect_uri,"invalid_request");let s=fe()?t.operationId===void 0?Ot(e.url,e.headers):Um({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=ht.parse(r.client_id),c=await Ui(r.client_id,i);kS(c,r.redirect_uri);try{let d=mr(e.url,r.resource,e.headers),u=HP(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:d.operationId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&ee(t.context,{eventType:G.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type}});let m={clientId:c?.clientId??a,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state},authorizationServerIssuer:s},{principal:h,setCookie:f}=await $P(e,t.context),S=h===void 0?!1:await hd({operationId:d.operationId,principal:h});if(!h||S){let _=await uS({transaction:m,requestUrl:e.url,requestHeaders:e.headers,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:d.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:_.browserLoginUrl,setCookies:[...f===void 0?[]:[f],_.browserBindingCookie]}}let R=await pS({transaction:m,principal:h,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:d.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&ee(t.context,{eventType:G.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type,subjectId:h.subjectId}}),XS({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw BP({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Rd,"authorizeDownstreamClient");function BP(e){if(e.cause instanceof Ht)return e.cause;let t=FP(e.cause);return t?new Ht({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(BP,"toDownstreamAuthorizeRedirectError");function FP(e){if(e instanceof T)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof p.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(FP,"mapToOAuthRedirectError");async function QS(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let u=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...u===void 0?{}:{idpErrorDescription:u},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),z("provider_access_denied",u??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),z("oauth_state_invalid","Browser login callback is missing state.");let s=await id(n),i=await gi({purpose:"login",claim:s.binding,request:e});if(!i.matched&&Nt())throw t.context?.log.warn({event:"browser_login_callback_binding_mismatch",code:"oauth_callback_mismatch",stateKind:s.kind},"Browser login callback arrived in a browser that did not start the login"),z("oauth_callback_mismatch","Browser login was not started in this browser.");let a={request:e,stateId:s.stateId};if(t.context!==void 0&&(a.context=t.context),s.kind==="return_to"){let u=JP(i.payload),m=await md(a);return{kind:"redirect",location:new URL(u,ie(e.url,e.headers)),setCookies:[await Bo({principal:m.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await md(a),d=await mS({browserLoginStateToken:n,principal:c.principal});if(await xS({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await hd({operationId:d.transaction.operationId,principal:c.principal}))throw z("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return XS({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await Bo({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}o(QS,"completeBrowserLoginCallback");function JP(e){let t=So(e),r=ge().actionPath("/auth/connections/"),n=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||n===void 0||!n.startsWith(r)||!/^[^/]+\/connect$/u.test(n.slice(r.length)))throw z("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}o(JP,"readConnectReturnTo");async function e_(e){let t=await lS(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(e_,"startConnectBrowserLogin");async function t_(e){let t=Ee(),r=new URL(e.url);if(!je(r))throw z("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw z("oauth_state_invalid","Local browser login is missing state.");let s=ge().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ie(e.url)),a=new URL(ie(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw z("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",n);let c={subjectId:yo.parse(UP),roles:MP};return{kind:"redirect",location:i,setCookies:[await Bo({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(t_,"completeLocalDevBrowserLogin");function GP(e){let t=e.method==="POST"?e.body:e.query;return jP.parse(t)}o(GP,"readSetupContinueRequest");async function r_(e){let{state:t,decision:r}=GP({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await dd({csrfToken:t,now:n}),i=await LP(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await gS({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await hS({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Sd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:YS(t)});if(r==="approve"&&wd(c)&&await cS({csrfToken:t,currentBrowserPrincipal:i,now:n}),wd(c)){let d=await _d({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:gd({state:t,operationId:a.operationId,gateway:ge(),upstreams:c,...d})}}return{kind:"redirect",location:await fS({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(r_,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as sx,decodeJwt as ix,errors as Go,jwtVerify as ax}from"jose";import{createRemoteJWKSet as VP,decodeJwt as KP,decodeProtectedHeader as WP,errors as Jo,jwtVerify as ZP}from"jose";var a_=30,de=p.string().min(1),YP=p.union([de,p.array(de).min(1)]),XP=p.union([de,p.array(de).min(1)]),QP=p.object({type:de,locations:p.array(de).optional(),actions:p.array(de).optional(),datatypes:p.array(de).optional(),identifier:de.optional(),privileges:p.array(de).optional()}).passthrough(),ex=p.object({iss:p.url(),sub:de,aud:YP,client_id:de,resource:XP.optional(),scope:de.optional(),authorization_details:p.array(QP).optional(),jti:de,iat:p.number().int(),nbf:p.number().int().optional(),exp:p.number().int(),tenant:de.optional(),aud_tenant:de.optional(),aud_sub:de.optional(),sub_id:de.optional(),act:p.unknown().optional(),email:de.optional(),auth_time:p.number().int().optional(),acr:de.optional(),amr:p.array(de).optional(),cnf:p.unknown().optional()}).passthrough();function Le(e){throw new T("invalid_grant",e)}o(Le,"throwInvalidGrant");function tx(e){return e instanceof Jo.JWTExpired?"expired":e instanceof Jo.JWTClaimValidationFailed?"claim":e instanceof Jo.JWSSignatureVerificationFailed?"signature":e instanceof Jo.JWKSNoMatchingKey?"jwks_no_match":e instanceof Jo.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(tx,"readJwtFailureKind");function rx(e){return Array.isArray(e.aud)?(e.aud.length!==1&&Le("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}o(rx,"readSingleAudience");function n_(e){try{let t=ex.parse(e);return rx(t),t}catch(t){if(t instanceof T)throw t;Le("ID-JAG claims are invalid.")}}o(n_,"parseIdJagClaims");function nx(e,t){e.idJag.enabled||Le("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(n=>n.issuer===t);return r===void 0&&Le("ID-JAG issuer is not trusted."),r}o(nx,"readTrustedIssuer");function ox(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(n=>r.has(n.type))}o(ox,"readGrantedAuthorizationDetails");function o_(e){if(e.clientAuth.method==="none")throw new T("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&Le("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&Le("ID-JAG client_id is not allowed for this issuer.")}o(o_,"assertClientBinding");function s_(e){e.cnf!==void 0&&Le("ID-JAG cnf-bound assertions require DPoP support.")}o(s_,"assertProofOfPossessionNotDeferred");function i_(e){let t=Math.floor(e.now.getTime()/1e3)+a_;e.claims.iat>t&&Le("ID-JAG iat must not be in the future.")}o(i_,"assertIssuedAtNotInFuture");async function c_(e){let t;try{t=WP(e.assertion)}catch{Le("ID-JAG assertion is malformed.")}t.typ!==da&&Le('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=n_(KP(e.assertion))}catch(c){if(c instanceof T)throw c;Le("ID-JAG assertion is malformed.")}let n=Ot(e.requestUrl,e.requestHeaders),s=[n];e.requestedResource!==void 0&&e.requestedResource!==n&&s.push(e.requestedResource);let i=nx(e.config,r.iss);s.includes(r.iss)&&Le("ID-JAG issuer must be different from the gateway."),o_({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),s_(r),i_({claims:r,now:e.now});let a;try{let c=VP(new URL(i.jwksUrl)),{payload:d}=await ZP(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:a_,typ:da});a=n_(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:tx(c)},"OAuth ID-JAG assertion verification failed"),Le("ID-JAG assertion verification failed.")}return o_({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),s_(a),i_({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:Dm({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:ox({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(c_,"verifyIdJagAssertion");var cx=new Set(["authorization_code","refresh_token",Mt]),dx=1e4,ux=32*1024,lx=2,px=3600,bd=p.object({client_id:p.string().min(1).optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),mx=p.discriminatedUnion("grant_type",[bd.extend({grant_type:p.literal("authorization_code"),code:p.string().min(1),redirect_uri:p.string().min(1),code_verifier:$r,resource:p.url().optional(),scope:p.literal(pe).optional()}),bd.extend({grant_type:p.literal("refresh_token"),refresh_token:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional()}),bd.extend({grant_type:p.literal(Mt),assertion:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional(),authorization_details:p.string().min(1).optional()})]);function hx(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!cx.has(t)))throw new T("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(hx,"assertSupportedGrantType");var fx=p.object({token:p.string().min(1),client_id:p.string().min(1).optional(),token_type_hint:p.string().optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),gx=p.object({keys:p.array(p.record(p.string(),p.unknown())).min(1)}).passthrough();function u_(){return Ee().gateway.accessTokenTtlSeconds}o(u_,"readAccessTokenTtlSeconds");function yx(){return Ee().gateway.refreshTokenTtlSeconds}o(yx,"readRefreshTokenTtlSeconds");function d_(e,t){let r=u_(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,n);return{expiresAt:J(mt(e,s)),expiresIn:s}}o(d_,"calculateAccessTokenExpiresAt");function Sx(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new T("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new T("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}o(Sx,"readIdJagResource");function _x(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new T("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}o(_x,"readIdJagGrantedAuthorizationDetails");function wx(e){if(e.claimScope?.split(/\s+/).includes(pe)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return pe;if(e.claimScope===void 0)throw new T("invalid_grant",`ID-JAG must include ${pe} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(pe))throw new T("invalid_grant",`ID-JAG scope must include ${pe}.`);return pe}o(wx,"readIdJagGrantedScope");function Rx(e){if(e!==void 0&&e.get("dpop")!==null)throw new T("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}o(Rx,"assertNoDpopProofForIdJag");function l_(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new T("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}}o(l_,"readBasicClientSecret");function p_(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new T("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=ix(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new T("invalid_client","Malformed private_key_jwt client assertion.")}throw new T("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new T("invalid_client","Client authentication or client_id is required.")}o(p_,"resolveAuthenticatedClientId");function bx(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(bx,"resolveClientSecretInput");function vx(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(vx,"hasClientAssertion");function Cx(e){if(e.requestUrl===void 0)throw new T("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(ge().actionPath(e.pathname),ie(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}o(Cx,"buildEndpointAudience");function Ix(e){return e instanceof Go.JWTExpired?"expired":e instanceof Go.JWTClaimValidationFailed?"claim":e instanceof Go.JWSSignatureVerificationFailed?"signature":e instanceof Go.JWKSNoMatchingKey?"jwks_no_match":e instanceof Go.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(Ix,"readJwtFailureKind");async function Tx(e){let{response:t,json:r}=await wg(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:lx,maxResponseBytes:ux,timeoutMs:dx});if(!t.ok)throw new T("invalid_client","Client JWKS could not be fetched.");return gx.parse(r)}o(Tx,"fetchClientJwks");async function Ex(e){if(e.clientAssertionType!==Ns||e.clientAssertion===void 0)throw new T("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=ht.parse(e.clientId),r=await Ui(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new T("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new T("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=Cx({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await Tx({jwksUri:n,context:e.context}),{payload:a}=await ax(e.clientAssertion,sx(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+px;if(typeof a.exp!="number"||a.exp>c)throw new T("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Ix(i)},"OAuth private_key_jwt client authentication failed"),new T("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(Ex,"verifyPrivateKeyJwtClientAssertion");async function kx(e){let t=ht.parse(e.clientId);if(Jm(t))throw new T("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await ce(e.clientSecret)}}o(kx,"buildRuntimeHttpClientAuth");async function m_(e){if(vx({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return Ex(e)}let t=bx({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return kx({clientId:e.clientId,...t})}o(m_,"resolveRuntimeHttpClientAuth");async function h_(e){hx(e.body);let t=mx.parse(e.body),r=l_(e.authorizationHeader),n=p_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await m_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:s,context:e.context});return Ax({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(h_,"exchangeDownstreamToken");async function Ax(e){if(e.parsed.grant_type==="authorization_code"){pn(e.parsed.redirect_uri,"invalid_request"),mn(e.parsed.scope),e.parsed.resource!==void 0&&mr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=ft(),d=ft(),u=J(mt(e.now,yx())),m=d_(e.now,u),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await ce(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Bs(e.parsed.code_verifier),currentRefreshTokenHash:await ce(c),accessTokenHash:await ce(d),grantExpiresAt:u,accessTokenExpiresAt:m.expiresAt,now:J(e.now)});if(h.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new T("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&ee(e.context,{eventType:G.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:m.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===Mt){mn(e.parsed.scope),Rx(e.requestHeaders);let c=await c_({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:Ee()}),d=Sx({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=mr(e.requestUrl??d,d,e.requestHeaders),m=_x({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=wx({claimScope:c.claims.scope,grantedAuthorizationDetails:m}),f=ft(),S=J(new Date(c.claims.exp*1e3)),R=d_(e.now,S),_=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await ce(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:m,accessTokenExpiresAt:R.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:S}});if(_.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(_.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&ee(e.context,{eventType:G.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:f,token_type:"Bearer",expires_in:R.expiresIn,scope:_.grant.scope,resource:_.grant.resource,...m===void 0?{}:{authorization_details:m}}}mn(e.parsed.scope),e.parsed.resource!==void 0&&mr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await ce(e.parsed.refresh_token),r=e.parsed.refresh_token,n=ft(),s=J(mt(e.now,u_())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await ce(n),resource:e.parsed.resource,accessTokenExpiresAt:s,now:J(e.now)});if(i.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new T("invalid_grant","Refresh token is invalid, expired, or revoked.");mr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&ee(e.context,{eventType:G.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(Ax,"exchangeDownstreamTokenWithRuntimeHttp");async function f_(e){let t=fx.parse(e.body),r=l_(e.authorizationHeader),n=p_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await m_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:s,context:e.context}),tokenHash:await ce(t.token),now:J(s)})).kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&ee(e.context,{eventType:G.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(f_,"revokeDownstreamToken");var Px=64*1024,xx=16*1024,Ox="text/html; charset=utf-8";function Mx(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(Mx,"formDataToObject");async function Ux(e){return Wy(e,{maxBytes:Px,label:"Request body"})}o(Ux,"readJsonBody");async function Cd(e){return Mx(await Zy(e,{maxBytes:xx,label:"Request body"}))}o(Cd,"readFormBody");async function g_(e,t,r){let n=pt(r),s=r instanceof p.ZodError?Bt(r):void 0,i={code:n??(r instanceof p.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),Os(e,t,i)}o(g_,"handleProblem");function y_(e){return e?.requestId}o(y_,"readBrowserRequestId");function S_(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Hr];return typeof t=="string"?t:void 0}o(S_,"readUpstreamHtmlError");function hn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(hn,"readRuntimeErrorExtensionString");function qx(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(qx,"readRuntimeErrorExtensionNumber");function zx(e){try{return new URL(e.url).pathname}catch{return}}o(zx,"readBrowserRequestPath");function hr(e){let t={code:e.code,requestId:e.requestId,routePath:zx(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=qx(e.error,ut),t.contentType=hn(e.error,Lr),t.upstreamUrl=hn(e.error,lt),t.upstreamServerId=hn(e.error,Ps),t.metadataUrl=hn(e.error,Br),t.providerError=hn(e.error,Fr),t.providerErrorDescription=hn(e.error,Jr)),t}o(hr,"buildBrowserErrorDiagnostic");function Vo(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Vo,"oauthErrorResponse");function Nx(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(Nx,"readOAuthProtocolHeaders");function jx(e,t){let r=et("internal_server_error");return Vo({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Nx(e,t)})}o(jx,"oauthProtocolErrorResponse");function vd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(vd,"readZodOAuthErrorCode");function Dx(e){let t={error:vd(e)},r=Bt(e);return r!==void 0&&(t.errorDescription=r),Vo(t)}o(Dx,"oauthZodErrorResponse");function $x(e){let t=pt(e);if(t===void 0)return;let r=et(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:Hx(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Vo(n)}o($x,"oauthGatewayProblemResponse");function Lx(){let t={error:"server_error",status:500,errorDescription:et("internal_server_error").publicDetail};return Vo(t)}o(Lx,"oauthFallbackErrorResponse");function Hx(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(Hx,"readOAuthStatus");function Id(e,t={}){return e instanceof Ht?R_(e):e instanceof T?jx(e,t):e instanceof p.ZodError?Dx(e):$x(e)??Lx()}o(Id,"oauthProblemResponse");function Td(e,t,r){let n=Lt(e.url),s=y_(t);if(r instanceof Ht)return R_(r);if(r instanceof T){let c=et("internal_server_error");return We({host:n,kind:Bx(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?c.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?c.publicDetail:r.message,code:r.errorCode,diagnostic:hr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Bt(r)??"The authorization request was invalid.",developerDetail:Bt(r)??"The authorization request was invalid.",code:vd(r),diagnostic:hr({request:e,requestId:s,code:vd(r),underlyingError:Bt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=pt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:w_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:hr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:S_(r),status:c.status})}let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:hr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(Td,"browserOAuthProblemResponse");function __(e,t,r){let n=Lt(e.url),s=y_(t),i=pt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:w_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:hr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:S_(r),status:c.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Bt(r)??"The authorization request was invalid.",developerDetail:Bt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:hr({request:e,requestId:s,code:"invalid_request",underlyingError:Bt(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:hr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(__,"browserGatewayProblemResponse");function Bx(e){return e==="server_error"?"internal_error":"invalid_request"}o(Bx,"readOAuthBrowserErrorKind");function w_(e){if(et(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(w_,"readGatewayBrowserErrorKind");function Ct(e,t,r){let n={event:t},s=!1;if(r instanceof T)n.oauthError=r.errorCode,n.status=r.status,ke(n,"error",r);else if(r instanceof Ht)n.oauthError=r.errorCode,ke(n,"error",r);else if(r instanceof p.ZodError){n.code="invalid_request",ke(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=pt(r);if(i!==void 0){let a=et(i);n.code=i,n.status=a.status,a.oauthError!==void 0&&(n.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",ke(n,"error",r)}else s=!0,ke(n,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Ct,"logUnexpectedOAuthHandlerError");function R_(e){let t;try{t=new URL(e.redirectUri)}catch{return Vo({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),Mi(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(R_,"downstreamAuthorizeRedirectErrorResponse");function Bt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Bt,"formatZodErrorDetail");function Fx(e,t){let r={event:"browser_login_callback_failed",code:pt(t)??"invalid_request"};ke(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(Fx,"logBrowserLoginCallbackFailure");function b_(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(null,{status:302,headers:t})}o(b_,"redirectResultResponse");function qi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Ox,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(e.html,{status:200,headers:t})}return b_(e)}o(qi,"authorizeResultResponse");async function v_(e,t){try{return Response.json(qm(e.url,e.headers))}catch(r){return Ct(t,"oauth_authorization_server_metadata_failed",r),g_(e,t,r)}}o(v_,"authorizationServerMetadataHandler");async function C_(e,t){try{let r=ha(e.params.routePath);return Response.json(zm({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return Ct(t,"oauth_authorization_server_metadata_failed",r),g_(e,t,r)}}o(C_,"scopedAuthorizationServerMetadataHandler");async function I_(e,t){try{let r=await AS(await Ux(e)),n=r.client_id,s=r.client_name,i=r.redirect_uris.length,a=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:n,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),ee(t,{eventType:G.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:n,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Ct(t,"oauth_register_failed",r),Id(r)}}o(I_,"registerHandler");async function T_(e,t){try{return qi(await Rd(e,{context:t}))}catch(r){return Ct(t,"oauth_authorize_failed",r),Td(e,t,r)}}o(T_,"authorizeHandler");async function E_(e,t){try{let r=ha(e.params.routePath);return qi(await Rd(e,{operationId:r.operationId,context:t}))}catch(r){return Ct(t,"oauth_authorize_scoped_failed",r),Td(e,t,r)}}o(E_,"scopedAuthorizeHandler");async function k_(e,t){try{let r=await QS(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),qi(r)}catch(r){return Fx(t,r),__(e,t,r)}}o(k_,"callbackHandler");async function A_(e,t){try{return b_(await t_(e))}catch(r){return Ct(t,"oauth_dev_login_failed",r),Td(e,t,r)}}o(A_,"devLoginHandler");async function P_(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await r_({request:e,body:e.method==="POST"?await Cd(e):void 0,context:t});return qi(r)}catch(r){return Ct(t,"oauth_setup_failed",r),__(e,t,r)}}o(P_,"setupHandler");async function x_(e,t){try{return Response.json(await h_({body:await Cd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Ct(t,"oauth_token_failed",r),Id(r)}}o(x_,"tokenHandler");async function O_(e,t){try{return await f_({body:await Cd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Ct(t,"oauth_revoke_failed",r),Id(r)}}o(O_,"revokeHandler");var M_="0.0.0",Jx=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function Ko(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}o(Ko,"firstNonBlank");function Wo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}o(Wo,"clampToCodePoints");function Gx(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}o(Gx,"shortHash");function U_(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${Gx(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(U_,"clampNameSegment");function Vx(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(Vx,"sanitizeRegistryNameSegment");var Kx=/^\d{1,3}(\.\d{1,3}){3}$/u;function Wx(e){let t=new URL(e).hostname.toLowerCase();if(Kx.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(n=>n.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(n=>n.length>0);return r.length>0?r.join("."):"local"}o(Wx,"buildRegistryNamespaceFromOrigin");function Zx(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}o(Zx,"sanitizeWebsiteUrl");function Yx(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let n;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;n=i.toString()}catch{continue}if(n.length>255||r.mimeType!==void 0&&!Jx.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:n,...r.mimeType===void 0?{}:{mimeType:r.mimeType},...s===void 0||s.length===0?{}:{sizes:s},...r.theme===void 0?{}:{theme:r.theme}})}return t.length>0?t:void 0}o(Yx,"sanitizeIcons");function Xx(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(Xx,"localNameFromRoutePath");function q_(e){return e.includes("{")||e.includes(":")}o(q_,"isParameterizedRoutePath");var Qx=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function z_(e){let t=Ko(e)??M_;return Qx.test(t)?M_:Wo(t,255)}o(z_,"sanitizeRegistryVersion");function N_(e){let t=U_(Wx(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=U_(Vx(c),r),u=d;for(let m=2;n.has(u);m++){let h=`-${m}`;u=`${[...d].slice(0,r-h.length).join("")}${h}`}return n.add(u),u}o(i,"claimLocalName");function a(c,d){let u=`${t}/${i(c)}`;s.push({name:u,response:{server:{...d,name:u},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}o(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(q_(c.routePath))continue;let d=c.connection,u=d?.serverInfo,m=Wo(Ko(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=Ko(u?.title,d?.displayName),f=Zx(u?.websiteUrl),S=Yx(u?.icons);a(c.operationId,{description:m,...h===void 0?{}:{title:Wo(h,100)},version:z_(u?.version),...f===void 0?{}:{websiteUrl:f},...S===void 0?{}:{icons:S},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(q_(c.routePath))continue;let d=c.operationId??Xx(c.routePath),u=Wo(Ko(c.summary,c.description,c.serverName,c.operationId,d)??d,100),m=Ko(c.serverName);a(d,{description:u,...m===void 0?{}:{title:Wo(m,100)},version:z_(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o(N_,"buildMcpRegistryDirectory");var eO=30,j_=100;function rt(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(rt,"registryErrorResponse");function kd(e){return N_({registry:Ce(),origin:ie(e.url,e.headers)})}o(kd,"readEntries");function Ed(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}o(Ed,"decodePathParam");function D_(e,t){return e.find(r=>r.name===t)}o(D_,"findEntryByName");function tO(e){let t=e.get("limit");return t===null?{ok:!0,value:eO}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),j_)}}o(tO,"parseLimit");function rO(e){let t=e.get("cursor");return t===null?{ok:!0,value:0}:/^\d+$/u.test(t)?{ok:!0,value:Number.parseInt(t,10)}:{ok:!1}}o(rO,"parseCursor");var nO=/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(\.\d+)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;function oO(e){let t=nO.exec(e);if(!t)return!1;let[,r,n,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(n)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(n)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}o(oO,"isValidRfc3339Timestamp");async function $_(e,t){let r=new URL(e.url).searchParams,n=tO(r);if(!n.ok)return rt(400,`Invalid 'limit' parameter: expected a positive integer (max ${j_}).`);let s=rO(r);if(!s.ok)return rt(400,"Invalid 'cursor' parameter: pass the exact 'metadata.nextCursor' value returned by a previous list response.");let i=r.get("updated_since");if(i!==null&&!oO(i))return rt(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let a=r.get("search")?.toLowerCase(),c=r.get("version"),d=kd(e).sort((h,f)=>h.name<f.name?-1:h.name>f.name?1:0);a!==void 0&&a!==""&&(d=d.filter(h=>h.name.toLowerCase().includes(a))),c!==null&&c!=="latest"&&(d=d.filter(h=>h.response.server.version===c));let u=d.slice(s.value,s.value+n.value),m=s.value+n.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...m<d.length?{nextCursor:String(m)}:{}}})}o($_,"listMcpRegistryServersHandler");async function L_(e,t){let r=Ed(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=D_(kd(e),r.value);return n===void 0?rt(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(L_,"listMcpRegistryServerVersionsHandler");async function H_(e,t){let r=Ed(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Ed(e.params.version);if(!n.ok)return rt(400,"Invalid version: malformed encoding.");let s=D_(kd(e),r.value);return s===void 0?rt(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?rt(404,"Server or version not found"):Response.json(s.response)}o(H_,"getMcpRegistryServerVersionHandler");function zi(e,t){return(r,n)=>rt(e,t)}o(zi,"createWriteNotSupportedHandler");async function B_(e,t){return rt(404,"Not found")}o(B_,"mcpRegistryNotFoundHandler");var F_=zi(501,"Publishing is not supported by this registry"),J_=zi(501,"Updates are not supported by this registry"),G_=zi(501,"Deletion is not supported by this registry"),Ad=zi(403,"You do not have publish or edit permissions for this server");function V_(e){return W`<section class="page-section" aria-labelledby="result-next-steps"><h2 class="section-label" id="result-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol></section>`}o(V_,"renderBrowserResult");var sO="text/html; charset=utf-8";function iO(e){return cn({title:e.title,iconHref:wc(e.host),styles:an,headerIcon:Ai("success"),heading:e.title,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:V_({steps:on(e.steps.map(t=>W`<li>${t}</li>`))}),footer:""})}o(iO,"browserResultHtml");function aO(e,t=200){return new Response(sn(e),{status:t,headers:{"content-type":sO,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(aO,"browserResultResponse");function K_(e){return aO(iO(e))}o(K_,"browserConnectionSuccessResponse");function Ni(e,t,r={}){let n=_m(t);return We({host:e,kind:cO(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(Ni,"browserConnectionFailureResponse");function cO(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}o(cO,"readCallbackFailureBrowserErrorKind");var dO={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},W_=Symbol("upstream-request");function Zo(e,t){Object.defineProperty(e,W_,{configurable:!0,value:t})}o(Zo,"setUpstreamRequestContext");function uO(e){let t=e[W_];if(!t)throw new Te("Upstream request context has not been set");return t}o(uO,"readUpstreamRequestContext");function lO(e,t){return t.some(r=>r===e)}o(lO,"requestContextMatchesKind");function pO(e){return typeof e=="string"?[e]:e}o(pO,"toExpectedKinds");function Yo(e,t){let r=uO(e),n=pO(t);if(!lO(r.kind,n)){let s=dO[n[0]];throw new Te(`${s} request context has not been set`)}return r}o(Yo,"requireUpstreamRequestContext");function Ft(e){if(typeof e=="string"&&e.length!==0)return e}o(Ft,"readOptionalQueryString");function mO(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Te(`Validated path parameter ${t} is missing`);return hO(r,t)}o(mO,"requirePathString");function hO(e,t){try{return decodeURIComponent(e)}catch(r){throw new k({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[M]:"invalid_request"}},{cause:r})}}o(hO,"decodePathString");function fO(e){let t=Ft(e);return t?Ms.parse(t):void 0}o(fO,"readOptionalOperationId");function gO(e){let t=Ce().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new k({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[M]:"unknown_upstream_server"}})}o(gO,"readRegisteredAuthProfileId");function yO(e){let t=fO(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[M]:"invalid_request"}});return t}o(yO,"readRequiredOperationId");async function Pd(e){return e.redirect?We({host:Lt(e.request.url),kind:"authorization_failed",title:e.title,detail:e.detail,code:e.status===401?"authentication_required":"forbidden",requestId:e.context.requestId,status:e.status}):e.status===401?Ne.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):Ne.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}o(Pd,"browserConnectRefusal");function SO(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let n of t)r.append("set-cookie",n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(SO,"withSetCookies");async function _O(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(fm(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await Pd({request:t,context:r,redirect:s,status:403,title:"Ask an administrator",detail:"This gateway cannot confirm who opened this link, so it cannot connect an account from it. Ask an administrator to connect this service."});let i=await ln(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return SO(await Pd({request:t,context:r,redirect:s,status:401,title:"Sign in required",detail:"Open this connect link in a browser. The gateway asks you to sign in before it connects an account."}),a);let d=new URL(t.url),u=So(`${d.pathname}${d.search}`);if(u===void 0)throw new Te("Connect request path is empty");let m=await e_({returnTo:u,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:m.location.toString(),"cache-control":"no-store"});for(let f of[...a,m.setCookie])h.append("set-cookie",f);return new Response(null,{status:302,headers:h})}let c=n.ownerMode==="user"?n.ownerSubjectId:n.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await Pd({request:t,context:r,redirect:s,status:403,title:"This link is for another account",detail:"This connect link was created for a different gateway user, so it cannot connect an account in this browser. Ask your MCP client for its own connect link, or sign in to the gateway as the user who received this one."})}o(_O,"requireTicketOwnerBrowser");async function wO(e,t,r){let n=Ei(r,yO(e.query.operationId));if(n.authMode==="id-jag")throw new k({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[M]:"invalid_request"}});let s=e.query.redirect==="true",i=Ft(e.query.browserTicket);if(e.user){if(i)throw new k({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[M]:"invalid_request"}});let d=cr(e.user,e.url),u={kind:"connect",...rn(n,d.subjectId),redirect:s},m=So(Ft(e.query.returnTo));return m!==void 0&&(u.returnTo=m),u}if(!i)throw new k({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[M]:"authentication_required"}});let a=await qg(i);if(a.ownerMode!==n.ownerMode||a.upstreamServerId!==n.upstreamServerId||a.authProfileId!==n.authProfileId||a.operationId!==n.operationId)throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});if(Nt()){let d=await _O({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await zg(a);let c=Us(a);switch(n.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}case"user-oauth":{if(c.mode!=="user")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}o(wO,"resolveConnectContext");async function RO(e,t,r){let n=Rm.parse(mO(e,"connection"));switch(r){case"connect":{let s=await wO(e,t,n);if(s instanceof Response)return s;Zo(e,s);return}case"callback":{let s=Ft(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Ft(e.query.error_description);d!==void 0&&(c.errorDescription=d),Zo(e,c);return}let i=Ft(e.query.code),a=Ft(e.query.state);if(i&&a){let c=Ft(e.query.iss);Zo(e,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:a,...c===void 0?{}:{iss:c}});return}Zo(e,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":Zo(e,{kind:"client_metadata",upstreamServerId:n,authProfileId:gO(n)});return}}o(RO,"resolveUpstreamRequestInbound");async function bO(e,t,r){try{return await RO(e,t,r)}catch(n){let s=n instanceof k?n.extensionMembers?.[M]:void 0,i=n instanceof Error?n.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return Ne.badRequest(e,t,{code:s,detail:i});case"authentication_required":return Ne.unauthorized(e,t,{code:s,detail:i});default:throw n}}}o(bO,"applyUpstreamRequestContext");function ji(e,t){return o(async(n,s)=>{let i=await bO(n,s,e);return i||t(n,s)},"wrapped")}o(ji,"withUpstreamRequestContext");var vO=["callback_authorization_code","callback_provider_error","callback_invalid"];function xd(e){try{return new URL(e.url).pathname}catch{return}}o(xd,"readBrowserRequestPath");function CO(e){return"cause"in e?e.cause:void 0}o(CO,"readErrorCause");function IO(e){return e.stack?.split(`
44
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(IO,"readFirstStackFrame");function Z_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=IO(r))}o(Z_,"addErrorAttributes");function Od(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[M];return xs(t)?t:void 0}o(Od,"readRuntimeGatewayCode");function Xo(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(Xo,"readRuntimeErrorExtensionString");function TO(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(TO,"readRuntimeErrorExtensionNumber");function EO(e,t,r,n){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),ee(t,{eventType:G.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),Ni(n,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:xd(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Ni(n,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:xd(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}o(EO,"requireAuthorizationCallbackRequest");function kO(e,t){ee(e,{eventType:G.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(kO,"emitCallbackReceivedAnalyticsEvent");function AO(e,t){ee(e,{eventType:G.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(AO,"emitTokenExchangeSucceededAnalyticsEvent");function PO(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return K_({host:Lt(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}o(PO,"buildSuccessfulCallbackResponse");function xO(e){let t={detail:e instanceof Error?e.message:void 0};return Z_(t,"error",e),e instanceof Error&&Z_(t,"cause",CO(e)),t}o(xO,"buildTokenExchangeFailureAttributes");function OO(e){ee(e.context,{eventType:G.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Od(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:xO(e.error)})}o(OO,"emitTokenExchangeFailedAnalyticsEvent");function MO(e){let t=e.error,r=Od(t),n=Sm(r)?r:"upstream_token_exchange_failed",s={code:n,requestId:e.context.requestId,routePath:xd(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof k?{httpStatus:TO(t,ut),contentType:Xo(t,Lr),upstreamUrl:Xo(t,lt),metadataUrl:Xo(t,Br),providerError:Xo(t,Fr),providerErrorDescription:Xo(t,Jr)}:{}};return Ni(e.host,n,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:UO(t)})}o(MO,"tokenExchangeFailureResponse");function Y_(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(Y_,"withSetCookie");function UO(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Hr];return typeof t=="string"?t:void 0}o(UO,"readUpstreamHtmlError");async function Md(e,t){let r=Yo(e,vO),n=Lt(e.url),s=EO(e,t,r,n);if(s instanceof Response)return s;kO(t,s);let i;try{let a=await by({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return AO(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),Y_(PO(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:Od(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return ke(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),OO({context:t,callbackRequest:s,error:a}),Y_(MO({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(Md,"callbackHandler");function qO(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(qO,"clientMetadataProblemDetail");async function X_(e,t){let r=Yo(e,"connect"),n=r.redirect?await Do({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:_i/1e3}):void 0,s=await Ry({request:e,connectRequest:r,...n===void 0?{}:{browserBinding:n.claim}});if(ee(t,{eventType:G.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),n!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":n.setCookie,"cache-control":"no-store"}});let i=await Ri({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}o(X_,"connectHandler");async function Q_(e,t){let r=Yo(e,"client_metadata");try{let n=ie(e.url,e.headers),s=Vg(n,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(n){if(!(n instanceof Q))throw n;let s=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),Ne.notFound(e,t,{code:"not_found",detail:qO(n)})}}o(Q_,"oauthClientMetadataHandler");function zO(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(zO,"resolveInternalRoutePath");var NO={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function jO(){return new Response(null,{status:204,headers:NO})}o(jO,"buildWellKnownPreflightResponse");function DO(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(DO,"withWellKnownCorsHeaders");function fr(e){return async(t,r)=>t.method==="OPTIONS"?jO():DO(await e(t,r))}o(fr,"wrapWellKnownHandler");var ew=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:fr(v_),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:fr(C_),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:fr(Nm),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:I_},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:T_},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:E_},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:k_},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:A_},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:P_},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:x_},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:O_},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ji("client_metadata",Q_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ji("connect",X_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ji("callback",Md)}],$O=ew.filter(e=>!e.routeName.startsWith("upstream_")),LO=ew.filter(e=>e.routeName.startsWith("upstream_"));function HO(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:fr($_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:fr(L_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:fr(H_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:F_},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:J_},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:G_},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Ad},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Ad},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:fr(B_),corsPolicy:"anything-goes"}]}o(HO,"buildMcpRegistryInternalRoutes");function BO(e){let t=Tm({routes:e.routes,policies:e.policies,gateway:e.gateway});return Em(t),t}o(BO,"initializeMcpGatewayConnectionRegistry");function FO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(FO,"hasDownstreamOAuthRoutes");function JO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(JO,"hasIdJagDownstreamOAuth");function GO(e){let t=new Map;for(let n of e.byOperationId.values())n.downstreamOAuth&&t.set(n.downstreamOAuth.policyName,n.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new Te("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(n=>`"${n}"`).join(", ");throw new Q(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}o(GO,"readSingletonDownstreamOAuthConfig");function VO(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(xm(n));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?Os(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}o(VO,"readScopedDownstreamOAuthConfig");function KO(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o(KO,"routeUsesScopedOAuthConfig");function Ud(e,t,r){return async(n,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let d=await r(n,s);if(d instanceof Response)return d;d&&hm(s,d)}let i=n.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:n.method},`MCP gateway: ${e} received`);let c=await t(n,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}o(Ud,"wrapInternalHandler");function qd(e,t,r,n){e.addPluginRoute({path:zO(t,r),methods:t.methods,handler:n,processors:[eu],corsPolicy:t.corsPolicy??"none"})}o(qd,"addInternalRoute");function tw(e,t){let r=BO(t);if(r.gateway.registry.enabled){ot("plugin.mcp-gateway.registry");for(let c of HO(r.gateway.registry))qd(e,c,r.gateway,Ud(c.routeName,c.handler))}let n=FO(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=GO(r)),i),"readSingletonOAuthConfig");if(n){ot("plugin.mcp-gateway.downstream-oauth"),JO(r)&&ot("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of $O){let d=KO(c)?(u,m)=>VO(r,u,m):a;qd(e,c,r.gateway,Ud(c.routeName,c.handler,d))}}if(s){ot("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())ot(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of LO)qd(e,c,r.gateway,Ud(c.routeName,c.handler,n?a:void 0))}}o(tw,"registerMcpGatewayInternalRoutes");var zd=class extends Qd{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),ot("plugin.mcp-gateway"),this.#e=gm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&tw(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as Ew}from"@opentelemetry/api";var WO="zuplo_mcp_",ZO=["__host-","__secure-"];function YO(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of ZO)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(WO)}o(YO,"setsGatewayCookie");function rw(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!YO(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let n=new Headers(e.headers);n.delete("clear-site-data"),n.delete("set-cookie");for(let s of r)n.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}o(rw,"stripUpstreamOriginStateHeaders");function Ze(e){return e&&typeof e=="object"?e:void 0}o(Ze,"readRecord");function Qo(e,t){let r=Ze(e)?.[t];return typeof r=="string"?r:void 0}o(Qo,"readStringProperty");function ow(e,t){let r=Ze(e)?.[t];return typeof r=="number"?r:void 0}o(ow,"readNumberProperty");function nw(e,t){return ow(e,"code")??(t>=400?t:void 0)}o(nw,"readErrorCode");function sw(e){return Array.isArray(e)?e.map(sw).find(t=>t?.method):Ze(e)}o(sw,"readJsonRpcMessage");function Nd(e){let t=sw(e),r=typeof t?.method=="string"?t.method:"",n=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:Qo(n,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:Qo(n,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=Qo(n,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}o(Nd,"buildBaseCapabilityInput");function Di(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}o(Di,"isCapabilityListMethod");function XO(e,t,r){let i=Ze(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}o(XO,"readItemCount");function iw(e){let t=Nd(e);return!t||Di(t.mcpMethod)?null:{eventType:G.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(iw,"buildCapabilityInvokedAnalyticsInput");function QO(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}o(QO,"readMissingResponseFailure");function aw(e,t,r={}){let n=Nd(e);if(!n)return null;let s=Ze(t.message),i=Ze(s?.error),a=Ze(i?.data),c=s?.result,d=n.mcpMethod==="tools/call"&&Ze(c)?.isError===!0,u=Ze(c),m=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&Ze(Ze(u.inputRequests)?.[jr])!==void 0;if(Ze(a?.connectRequired)||m)return{eventType:G.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...n,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:ow(i,"code"),mcpErrorType:Qo(i,"message")};let h=t.status<400?QO(t):void 0;if(h&&!i)return{eventType:Di(n.mcpMethod)?G.MCP_CAPABILITY_LISTED:G.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,...h};if(Di(n.mcpMethod)){let f=t.status>=400?void 0:XO(n.mcpMethod,n.capabilityType,c),S=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:G.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...n,httpStatusCode:t.status,...S?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:nw(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:G.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:nw(i,t.status),mcpErrorType:Qo(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:G.MCP_CAPABILITY_COMPLETED,outcome:"success",...n,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:G.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...n,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}o(aw,"buildCapabilityFinalAnalyticsInput");function cw(e,t){let r=Nd(e);return r?{eventType:Di(r.mcpMethod)?G.MCP_CAPABILITY_LISTED:G.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}o(cw,"buildCapabilityThrownAnalyticsInput");var jd={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},dw={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},uw={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var Hd=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),Dd=64*1024,Bd=1024*1024,eM=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function lw(e,t={}){return e===void 0?Dd:eM.has(e)||t.modern===!0&&e==="server/discover"?Bd:Dd}o(lw,"tapMaxBytesForMethod");function tM(e){let t=it(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(tM,"readTapMode");function rM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(rM,"isPlainObject");function nM(e){return rM(e)&&!("method"in e)&&("result"in e||"error"in e)}o(nM,"isResponseShaped");function oM(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(oM,"isSameJsonRpcIdValue");function pw(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(nM);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>oM(a.id,t));if(i||r)return i}return s[0]}o(pw,"selectResponse");function mw(e){try{return JSON.parse(e)}catch{return}}o(mw,"tryParseJson");var $d=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{o(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let n of this.#e)t.set(n,r),r+=n.byteLength;this.#e=[],this.#n=pw(mw(new TextDecoder().decode(t)),this.requestId,!1)}},Ld=class{constructor(t,r){this.requestId=t;this.#e=new xo({maxEventChars:r,onOversize:"discard"})}requestId;static{o(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let n=t(r);this.#r||=r.discardedEvents>0;for(let s of n){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=pw(mw(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},sM={push(){},end(){},message:void 0,truncated:!1};function iM(e,t,r){switch(e){case"json":return new $d(t,r);case"sse":return new Ld(t,r);case"passthrough":return sM}}o(iM,"createObserver");function hw(e,t={}){let r=e.body;if(r===null){let I=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:I,outcome:I}}let n=at(e.headers)?"passthrough":tM(e),s=iM(n,t.requestId,t.maxBytes??Dd),i,a=new Promise(I=>{i=I}),c,d=new Promise(I=>{c=I}),u=!1,m=o(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,S=o((I,A)=>{if(f)return;if(f=!0,I==="complete")try{s.end()}catch{}let v={ended:I,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...n==="passthrough"&&h>0?{uninspected:!0}:{},...A===void 0?{}:{error:A}};i(v),u||(u=!0,c(v))},"settle"),R=r.getReader(),_=new ReadableStream({async pull(I){let A;try{A=await R.read()}catch(v){S("errored",v),I.error(v);return}if(A.done){S("complete"),I.close();return}if(h+=A.value.byteLength,!f)try{s.push(A.value)}catch{}I.enqueue(A.value),m()},async cancel(I){S(I===Hd?"released":"cancelled"),await R.cancel(I)}},{highWaterMark:0}),y=pf(new Headers(e.headers)),b;try{b=new Response(_,{status:e.status,statusText:e.statusText,headers:y})}catch(I){throw R.cancel(I).catch(()=>{}),I}return{response:b,done:a,outcome:d}}o(hw,"tapJsonRpcResponse");var aM=-32603,cM="The upstream MCP server ended the response stream without a response to this request.",dM="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function fw(e){return`${typeof e}:${String(e)}`}o(fw,"idKey");function uM(e,t){if(e.delete(fw(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(uM,"clearAnsweredRequest");function gw(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!yw(n)||typeof n.method!="string"||typeof n.id!="string"&&typeof n.id!="number")continue;let s=Me(n);s!==void 0&&r.push(s)}return r}o(gw,"readJsonRpcRequestIds");function yw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yw,"isRecord");function lM(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)yw(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&n.push(s.id);return n}o(lM,"readResponseIds");function pM(e){let t=e.getReader();return new ReadableStream({async pull(r){let n;try{n=await t.read()}catch{r.close();return}if(n.done){r.close();return}r.enqueue(n.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}o(pM,"endOnError");function Sw(e,t,r=Bd,n){let s=new Map;for(let a of t)s.set(fw(a),a);let i=!1;return Qa(pM(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of lM(a.data))uM(s,c)},{failureMode:"open",maxEventChars:r,onFailure:o((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:o(()=>{if(s.size===0||i)return[];let a=n?.aborted?dM:cM;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:aM,message:a}})}))},"end")})}o(Sw,"answerUnansweredRequests");var mM={Allow:"POST"},_w="mcp-session-id";async function hM(e){try{return await e.clone().arrayBuffer()}catch{return}}o(hM,"readRequestBody");function Jd(e){try{let t=km(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}o(Jd,"readRouteAnalyticsFields");function Gd(e){return $m(e.user,e.url,e.headers)?.subjectId}o(Gd,"readRequestSubjectId");function ww(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}o(ww,"readRequestMethod");function Rw(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Rw,"readHeader");function Vd(e){let t=Rw(e.request.headers,_w)??(e.response?Rw(e.response.headers,_w):void 0),r=e.tapResult?.message?.result,n=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=ir(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Vd,"readMcpProtocolFields");function fM(e){let t=iw(e.requestJson?.value);t&&ee(e.context,{...t,...Jd(e.context),...Vd({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:Gd(e.request),transport:"http"})}o(fM,"emitCapabilityInvokedAnalytics");function gM(e){let t=aw(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended},{modern:e.modern,gatewayAnswered:e.gatewayAnswered});t&&fa(e.context,{...t,...Jd(e.context),...Vd(e),httpMethod:e.request.method,subjectId:Gd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(gM,"emitCapabilityFinalAnalytics");function $i(e){let t=cw(e.requestJson?.value,e.details);t&&(e.late?fa:ee)(e.context,{...t,...Jd(e.context),...Vd({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:Gd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o($i,"emitCapabilityThrownAnalytics");async function bw(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let n=new At(e.request,{headers:t,...r===void 0?{}:{body:r}}),s=o(i=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=i)},"onTimeoutSignal");return lm(n,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}o(bw,"callUpstream");function yM(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(yM,"readClientSignal");function vw(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(vw,"throwIfClientCancelled");function SM(e){let{clientSignal:t,context:r,onCancel:n}=e,s=!1,i=o(()=>(t.removeEventListener("abort",a),s?!1:(s=!0,!0)),"claim"),a=o(()=>{i()&&r.waitUntil(Promise.resolve().then(n).catch(c=>{try{_s.getLogger(r).error(c,"Error recording an MCP request whose client cancelled before headers")}catch{}}))},"onAbort");return t.addEventListener("abort",a,{once:!0}),{claim:i}}o(SM,"watchClientCancelBeforeHeaders");async function Fd(e){try{await e.body?.cancel()}catch{}}o(Fd,"discardBody");function _M(e,t){return e===t.reason?!0:e instanceof Error||e instanceof DOMException?e.name==="AbortError"||e instanceof Error&&e.cause===t.reason:!1}o(_M,"isClientAbortError");function wM(e,t){try{_s.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(wM,"logErrorAfterClientLeft");async function Cw(e){vw(e.clientSignal);let t=await bw(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=zy(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await Fd(t);let n=o(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await Ew.with(e.refreshContext,n):await n();return vw(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await bw({...e,headers:s.headers}),gatewayAnswered:!1}}o(Cw,"forwardToUpstream");function RM(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?Cw({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):Ew.with(i.client.ctx,()=>Cw({request:t,context:r,bodyBytes:n===void 0?void 0:ig(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(RM,"callUpstreamOperation");function bM(e,t,r){if(e.body===null||e.status<200||e.status>299||it(e.headers.get("content-type"))!=="text/event-stream"||at(e.headers))return e;let n=gw(t?.value);if(n.length===0)return e;let s=St(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(Sw(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(bM,"withUnansweredRequestErrors");function vM(e,t){if(e.body===null||!t.rewritten&&!t.clientSignal)return e;let r=new Headers(e.headers);return t.rewritten&&r.set("x-accel-buffering","no"),new Response(CM(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(vM,"finishModernResponse");function CM(e,t){if(!t)return e;let r=e.getReader(),n=!1,s=o(()=>{},"onAbort"),i=o(()=>{n=!0,t.removeEventListener("abort",s)},"finish");return new ReadableStream({start(a){s=o(()=>{if(!n){i(),r.cancel(t.reason).catch(()=>{});try{a.close()}catch{}}},"onAbort"),t.aborted?s():t.addEventListener("abort",s,{once:!0})},async pull(a){let c;try{c=await r.read()}catch(d){n||(i(),a.error(d));return}if(!n){if(c.done){i(),a.close();return}a.enqueue(c.value)}},async cancel(a){i(),await r.cancel(a)}},{highWaterMark:0})}o(CM,"cancelOnClientAbort");function IM(e,t){ru.findContextExtensions(e)?.addPipelineExitHook(r=>{let n=t.body;r===t||n===null||r?.body===n||n.locked||n.cancel(Hd).catch(()=>{})})}o(IM,"releaseBodyIfNotSent");function Iw(e,t){return Ne.format({type:"https://httpproblems.com/http-status/499",title:"Client Closed Request",status:499,detail:"The client cancelled the request before the upstream MCP server responded."},e,t)}o(Iw,"clientClosedResponse");function Tw(e){return e instanceof Q?uw:dw}o(Tw,"thrownDetails");async function TM(e,t){if(ot("handler.mcp-gateway-proxy"),e.method==="GET")return Ne.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},mM);let r=Date.now(),n=await hM(e),s=eh(n,{readMetaProtocolVersion:fe()});th(t,ir(e.headers,s?.value));let i=Ic(e,s,n),a;if(i!==void 0)try{a=sg({request:e,context:t,parsed:i})}catch{a=void 0}fM({context:t,request:e,requestJson:s});let c=fe()&&Nr(e.headers,s?.value),d=c&&ww(s)==="subscriptions/listen",u=c?yM(e):void 0,m=u?SM({clientSignal:u,context:t,onCancel:o(()=>{a&&Ec(a),$i({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c,late:!0})},"onCancel")}):void 0,h={},f,S;try{let y=await RM({request:e,context:t,requestBody:n,parsed:i,spans:a,modern:c,listen:d,clientSignal:u,upstreamTimeout:h});S=y.gatewayAnswered,f=rw(y.response)}catch(y){let b=m?.claim()??!0;if(u?.aborted)return _M(y,u)||wM(t,y),b&&(a&&Ec(a),$i({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c})),Iw(e,t);throw a&&Tc(a,y),$i({context:t,request:e,requestJson:s,startedAt:r,details:Tw(y),modern:c}),y}if(m&&!m.claim())return await Fd(f),Iw(e,t);let R,_;try{R=hw(f,{requestId:Me(s?.value),maxBytes:lw(ww(s),{modern:c})});let y=bM(R.response,s,h.signal);_=c?vM(y,{rewritten:y!==R.response,clientSignal:u}):y,IM(t,_)}catch(y){throw await Fd(R?.response??f),a&&Tc(a,y),$i({context:t,request:e,requestJson:s,startedAt:r,details:Tw(y),modern:c}),y}return t.waitUntil(R.outcome.then(y=>{try{gM({context:t,request:e,requestJson:s,response:f,tapResult:y,startedAt:r,modern:c,gatewayAnswered:S})}finally{a&&i&&cg({spans:a,method:i.method,response:f,tapResult:y,expectsResponse:i.id!==void 0})}}).catch(y=>{try{_s.getLogger(t).error(y,"Error emitting MCP gateway capability analytics")}catch{}})),_}o(TM,"McpProxyHandler");export{Dw as McpAuth0OAuthInboundPolicy,pc as McpCapabilityFilterInboundPolicy,Aw as McpClerkOAuthInboundPolicy,Pw as McpCognitoOAuthInboundPolicy,xw as McpEntraOAuthInboundPolicy,zd as McpGatewayPlugin,Ow as McpGoogleOAuthInboundPolicy,Mw as McpKeycloakOAuthInboundPolicy,Uw as McpLogtoOAuthInboundPolicy,$w as McpOAuthInboundPolicy,qw as McpOktaOAuthInboundPolicy,zw as McpOneLoginOAuthInboundPolicy,Nw as McpPingOAuthInboundPolicy,TM as McpProxyHandler,rd as McpTokenExchangeInboundPolicy,jw as McpWorkosOAuthInboundPolicy,qf as claimsCapabilityResolver};
45
45
  /*! For license information please see index.js.LEGAL.txt */
46
46
  //# sourceMappingURL=index.js.map