@zuplo/runtime 7.14.5 → 7.14.8

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 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}
25
+ import{$ as Nr,$a as gl,$b as fa,$c as om,$f as Xm,$g as lh,Aa as ma,Ab as Bl,Ac as Up,Ad as vm,Ag as nh,Ah as G,Ba as Ju,Bb as Fl,Bc as ba,Bd as Am,Bg as oh,Bh as ne,C as Iu,Ca as Vu,Cb as Jl,Cc as Ns,Cd as Io,Cg as sh,Ch as qa,Da as Gu,Db as Vl,Dc as js,Dd as Pm,Dg as ih,Dh as ye,E as Os,Ea as Ku,Eb as Gl,Ec as qp,Ed as Ls,Eg as Ie,Eh as St,Fa as Wu,Fb as Kl,Fc as zp,Fd as $s,Ff as Jm,Fg as ge,Fh as de,Ga as Zu,Gb as Wl,Gc as Np,Gd as lr,Gf as He,Gg as ah,Gh as ei,H as Ms,Ha as Yu,Hb as Zl,Hc as jp,Hd as xm,Hf as Vm,Hg as rn,Hh as Ae,Ia as Xu,Ib as Yl,Ic as Dp,Id as Ca,If as Gm,Ig as W,Ih as ie,Ja as Qu,Jb as Xl,Jc as Lp,Jd as Vr,Jf as Km,Jg as gt,Jh as Ph,Ka as el,Kb as Ql,Kc as $p,Kd as Hs,Kf as ce,Kg as qt,Kh as se,La as tl,Lb as ep,Lc as Hp,Ld as Om,Lf as Wm,Lg as ch,Lh as xh,Ma as rl,Mb as tp,Mc as Bp,Md as Mm,Mf as Gr,Mg as zt,Mh as Oh,N as Tu,Na as nl,Nb as rp,Nc as Fp,Nd as Um,Nf as Zm,Ng as Aa,Nh as Mh,Oa as ol,Ob as np,Oc as Jp,Od as Bs,Of as Kr,Og as Gs,Oh as Uh,Pa as sl,Pb as op,Pc as Vp,Pd as Nm,Pf as M,Pg as Pa,Ph as V_,Q as Eu,Qa as il,Qb as sp,Qc as Gp,Qd as jm,Qf as Wr,Qg as Ks,Qh as G_,Ra as al,Rb as ip,Rc as Kp,Rd as Ia,Rf as Zr,Rg as Po,Sa as ha,Sb as ap,Sc as Wp,Sd as Dm,Sf as lt,Sg as nn,T as ku,Ta as cl,Tb as cp,Tc as Zp,Td as Lm,Tf as pt,Tg as dh,Ua as dl,Ub as dp,Uc as Yp,Ud as $m,Uf as To,Ug as yt,Va as ul,Vb as up,Vc as Xp,Vd as Ta,Vf as Yr,Vg as xa,Wa as ll,Wb as lp,Wc as Qp,Wd as Hm,Wf as Xr,Wg as Ws,Xa as pl,Xb as pp,Xc as em,Xd as Ea,Xf as Qr,Xg as uh,Ya as ml,Yb as mp,Yc as tm,Yd as Bm,Yf as Fs,Yg as Zs,Za as hl,Zb as hp,Zc as rm,Zf as Ym,Zg as Oa,_ as Us,_a as fl,_b as fp,_c as nm,_f as ot,_g as Ys,aa as jr,ab as yl,ac as gp,ad as sm,ag as Be,ah as he,b as xs,ba as wo,bb as Sl,bc as yp,bd as im,bg as z,bh as ph,ca as Dr,cb as Rl,cc as Sp,cd as am,cg as en,ch as mh,da as Lr,db as wl,dc as Rp,dd as cm,de as Fm,dg as ke,dh as hh,ea as _o,eb as _l,ec as wp,ed as dm,eg as Ut,eh as Ma,fa as ar,fb as bl,fc as _p,fd as um,fg as z_,fh,ga as Au,gb as vl,gc as bp,gd as lm,gg as N_,gh,ha as Pu,hb as Cl,hc as vp,hd as pm,hg as j_,hh as Ua,ia as xu,ib as Il,ic as Cp,id as mm,ig as D_,ih as yh,ja as Ou,jb as Tl,jc as Ip,jd as hm,jg as L_,jh as pr,ka as Mu,kb as El,kc as Tp,kd as $r,kg as $_,kh as Sh,la as Uu,lb as kl,lc as Ep,ld as Hr,lg as H_,lh as xo,ma as qu,mb as Al,mc as kp,md as fm,mg as B_,mh as Rh,n as ut,na as zu,nb as Pl,nc as Ap,nd as Br,ng as F_,nh as Xs,oa as Nu,ob as xl,oc as Pp,od as Ot,og as J_,oh as Oo,pa as ju,pb as Ol,pc as xp,pd as va,pg as Qm,ph as wh,qa as Du,qb as Ml,qc as ga,qd as Ds,qg as eh,qh as _h,ra as Lu,rb as Ul,rc as qs,rd as gm,rg as Js,rh as bh,sa as $u,sb as ql,sc as zs,sd as vo,sg as Eo,sh as vh,ta as Hu,tb as zl,tc as ya,td as dr,tg as ko,th as Ch,u as Ne,ua as Bu,ub as Nl,uc as Sa,ud as ym,ug as tn,uh as Ih,v as Cu,va as Fu,vb as jl,vc as Ra,vd as Sm,vg as th,vh as Th,wa as cr,wb as Dl,wc as Op,wd as Rm,wg as ka,wh as Eh,x as Z,xa as la,xb as Ll,xc as wa,xd as wm,xg as rh,xh as Qs,ya as pa,yb as $l,yc as _a,yd as _m,yg as Ao,yh as kh,za as bo,zb as Hl,zc as Mp,zd as bm,zg as Vs,zh as Ah}from"../chunk-DB6LKZ36.js";import"../chunk-VP5Q3DEN.js";import"../chunk-SNTU476S.js";import{a as xt,b as te,c as ur,d as Cm,e as Im,f as Tm,g as Mt,i as Co,j as Em,k as km,l as Fr,m as Jr,t as qm,u as zm}from"../chunk-PY52EHDX.js";import"../chunk-A3QGJZO7.js";import{A as m,b as ca,c as _u,d as l,e as bu,f as vu,g as A,h as D,i as As,k as F,l as C,m as g,n as V,o as q,p as da,q as So,r as U,s as K,t as _,u as J,v as ua,w as Ps,y as Ro}from"../chunk-6R2COTV6.js";import"../chunk-UKQQD2JN.js";import{$ as zr,a as Ee,aa as wu,c as k,d as re}from"../chunk-2HVCLUM4.js";import{a as o}from"../chunk-TYV53J3B.js";var K_=Object.create,ti=Object.defineProperty,W_=Object.getOwnPropertyDescriptor,Z_=Object.getOwnPropertyNames,Y_=Object.getPrototypeOf,X_=Object.prototype.hasOwnProperty,qh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),zh=o((e,t)=>{let r={};for(var n in e)ti(r,n,{get:e[n],enumerable:!0});return t&&ti(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Q_=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=Z_(t),i=0,a=s.length,c;i<a;i++)c=s[i],!X_.call(e,c)&&c!==r&&ti(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=W_(t,c))||n.enumerable});return e},"__copyProps"),Nh=o((e,t,r)=>(r=e!=null?K_(Y_(e)):{},Q_(t||!e||!e.__esModule?ti(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var eb=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function jh(e){return typeof e=="string"&&eb.has(e.replace(/#$/,""))}o(jh,"declares2019Dialect");var $a=Symbol.for("mcp.sdk.errorBrands");function mr(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,$a,{value:r,enumerable:!1,configurable:!0})}o(mr,"stampErrorBrands");function Fe(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,$a)){let r=t[$a];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}o(Fe,"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})({}),Nt=class Wh extends Error{static{o(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Fe(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 Fe(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",mr(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 Wh(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})({}),pe=class extends Error{static{o(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Fe(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 Fe(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",mr(this,new.target)}},pb=class extends pe{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 Zh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Zh,"resourceUrlFromServerUrl");function Ga(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}o(Ga,"withoutIssuer");function ii({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(ii,"checkResourceAllowed");var mb="2026-07-28";function Yh(e){return e>=mb}o(Yh,"isModernProtocolVersion");function Xh(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(Xh,"appendTextFallbackForNonObject");var Qh=["task","inputRequests","requestState"];function hb(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Qh.some(t=>t in e)?e:{...e,content:[]}}o(hb,"normalizeContentlessToolResult");function fb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),A().int()]),n=l(),s=g({ttl:A().optional()}),i=g({taskId:l()}),a=V({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()}),p=g({_meta:a.optional()}),h=g({method:l(),params:p.loose().optional()}),f=V({_meta:a.optional()}),y=q([l(),A().int()]),b=f.strict(),w=p.extend({requestId:y.optional(),reason:l().optional()}),S=h.extend({method:_("notifications/cancelled"),params:w}),R=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:K(["light","dark"]).optional()}),v=g({icons:C(R).optional()}),x=g({name:l(),title:l().optional()}),N=x.extend({...x.shape,...v.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),T=So(g({applyDefaults:D().optional()}),t),O=Ps(Ce=>Ce&&typeof Ce=="object"&&!Array.isArray(Ce)&&Object.keys(Ce).length===0?{form:{}}:Ce,So(g({form:T.optional(),url:t.optional()}),t.optional())),L=V({list:t.optional(),cancel:t.optional(),requests:V({sampling:V({createMessage:t.optional()}).optional(),elicitation:V({create:t.optional()}).optional()}).optional()}),Q=V({list:t.optional(),cancel:t.optional(),requests:V({tools:V({call:t.optional()}).optional()}).optional()}),P=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:O.optional(),roots:g({listChanged:D().optional()}).optional(),tasks:L.optional(),extensions:U(l(),t).optional()}),$=c.extend({protocolVersion:l(),capabilities:P,clientInfo:N}),j=u.extend({method:_("initialize"),params:$}),B=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:D().optional()}).optional(),resources:g({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:g({listChanged:D().optional()}).optional(),tasks:Q.optional(),extensions:U(l(),t).optional()}),ee=f.extend({protocolVersion:l(),capabilities:B,serverInfo:N,instructions:l().optional()}),Ue=h.extend({method:_("notifications/initialized"),params:p.optional()}),De=u.extend({method:_("ping"),params:c.optional()}),Ge=g({progress:A(),total:J(A()),message:J(l())}),Y=g({...p.shape,...Ge.shape,progressToken:r}),le=h.extend({method:_("notifications/progress"),params:Y}),qe=c.extend({cursor:n.optional()}),oe=u.extend({params:qe.optional()}),tt=f.extend({nextCursor:n.optional()}),_r=g({uri:l(),mimeType:J(l()),_meta:U(l(),F()).optional()}),br=_r.extend({text:l()}),Wt=l().refine(Ce=>{try{return atob(Ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),vr=_r.extend({blob:Wt}),dt=K(["user","assistant"]),rt=g({audience:C(dt).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),Zt=g({...x.shape,...v.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:rt.optional(),_meta:J(V({}))}),Cn=g({...x.shape,...v.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:rt.optional(),_meta:J(V({}))}),In=oe.extend({method:_("resources/list")}),Tn=tt.extend({resources:C(Zt)}),Et=oe.extend({method:_("resources/templates/list")}),Cr=tt.extend({resourceTemplates:C(Cn)}),Yt=c.extend({uri:l()}),En=Yt,kn=u.extend({method:_("resources/read"),params:En}),An=f.extend({contents:C(q([br,vr]))}),Pn=h.extend({method:_("notifications/resources/list_changed"),params:p.optional()}),xn=Yt,On=u.extend({method:_("resources/subscribe"),params:xn}),Mn=Yt,Un=u.extend({method:_("resources/unsubscribe"),params:Mn}),qn=p.extend({uri:l()}),zn=h.extend({method:_("notifications/resources/updated"),params:qn}),Nn=g({name:l(),description:J(l()),required:J(D())}),jn=g({...x.shape,...v.shape,description:J(l()),arguments:J(C(Nn)),_meta:J(V({}))}),Dn=oe.extend({method:_("prompts/list")}),Ln=tt.extend({prompts:C(jn)}),$n=c.extend({name:l(),arguments:U(l(),l()).optional()}),Hn=u.extend({method:_("prompts/get"),params:$n}),Xt=g({type:_("text"),text:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Qt=g({type:_("image"),data:Wt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),er=g({type:_("audio"),data:Wt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Bn=g({type:_("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),kt=g({type:_("resource"),resource:q([br,vr]),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Fn=Zt.extend({type:_("resource_link")}),Ke=q([Xt,Qt,er,Fn,kt]),Ir=g({role:dt,content:Ke}),Tr=f.extend({description:l().optional(),messages:C(Ir)}),tr=h.extend({method:_("notifications/prompts/list_changed"),params:p.optional()}),Jn=g({title:l().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Er=g({taskSupport:K(["required","optional","forbidden"]).optional()}),rr=g({...x.shape,...v.shape,description:l().optional(),inputSchema:g({type:_("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(F()),outputSchema:g({type:_("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(F()).optional(),annotations:Jn.optional(),execution:Er.optional(),_meta:U(l(),F()).optional()}),kr=oe.extend({method:_("tools/list")}),Ar=tt.extend({tools:C(rr)}),Pr=f.extend({content:C(Ke),structuredContent:U(l(),F()).optional(),isError:D().optional()}),ve=d.extend({name:l(),arguments:U(l(),F()).optional()}),Vn=u.extend({method:_("tools/call"),params:ve}),ms=h.extend({method:_("notifications/tools/list_changed"),params:p.optional()}),xr=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Gn=c.extend({level:xr}),Kn=u.extend({method:_("logging/setLevel"),params:Gn}),Wn=p.extend({level:xr,logger:l().optional(),data:F()}),Zn=h.extend({method:_("notifications/message"),params:Wn}),Yn=g({name:l().optional()}),Xn=g({hints:C(Yn).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Qn=g({mode:K(["auto","required","none"]).optional()}),hs=g({type:_("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Ke),structuredContent:g({}).loose().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),eo=da("type",[Xt,Qt,er]),At=da("type",[Xt,Qt,er,Bn,hs]),to=g({role:dt,content:q([At,C(At)]),_meta:U(l(),F()).optional()}),ro=d.extend({messages:C(to),modelPreferences:Xn.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(rr).optional(),toolChoice:Qn.optional()}),no=u.extend({method:_("sampling/createMessage"),params:ro}),oo=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens"]).or(l())),role:dt,content:eo}),so=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:dt,content:q([At,C(At)])}),io=g({type:_("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),ao=g({type:_("string"),title:l().optional(),description:l().optional(),minLength:A().optional(),maxLength:A().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),co=g({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),uo=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),lo=g({type:_("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),po=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),mo=q([uo,lo]),nr=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:_("string"),enum:C(l())}),default:C(l()).optional()}),or=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),fs=q([nr,or]),gs=q([po,mo,fs]),Le=q([gs,io,ao,co]),$e=d.extend({mode:_("form").optional(),message:l(),requestedSchema:g({type:_("object"),properties:U(l(),Le),required:C(l()).optional()}).catchall(F())}),ho=d.extend({mode:_("url"),message:l(),elicitationId:l(),url:l().url()}),nt=q([$e,ho]),ys=u.extend({method:_("elicitation/create"),params:nt}),Ss=p.extend({elicitationId:l()}),Rs=h.extend({method:_("notifications/elicitation/complete"),params:Ss}),ws=f.extend({action:K(["accept","decline","cancel"]),content:Ps(Ce=>Ce===null?void 0:Ce,U(l(),q([l(),A(),D(),C(l())])).optional())}),_s=g({type:_("ref/resource"),uri:l()}),bs=g({type:_("ref/prompt"),name:l()}),vs=c.extend({ref:q([bs,_s]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()}),fo=u.extend({method:_("completion/complete"),params:vs}),Cs=f.extend({completion:V({values:C(l()).max(100),total:J(A().int()),hasMore:J(D())})}),Is=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),F()).optional()}),Or=u.extend({method:_("roots/list"),params:c.optional()}),go=f.extend({roots:C(Is)}),Ts=h.extend({method:_("notifications/roots/list_changed"),params:p.optional()}),Es=V({ttl:A().optional(),pollInterval:A().optional()}),yo=K(["working","input_required","completed","failed","cancelled"]),Pt=g({taskId:l(),status:yo,ttl:q([A(),As()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:J(A()),statusMessage:J(l())}),ze=f.extend({task:Pt}),ks=p.merge(Pt),sr=h.extend({method:_("notifications/tasks/status"),params:ks}),Mr=u.extend({method:_("tasks/get"),params:c.extend({taskId:l()})}),Ur=f.merge(Pt),qr=u.extend({method:_("tasks/result"),params:c.extend({taskId:l()})}),aa=f.loose(),Te=oe.extend({method:_("tasks/list")}),ae=tt.extend({tasks:C(Pt)}),ir=u.extend({method:_("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:p,NotificationSchema:h,ResultSchema:f,RequestIdSchema:y,EmptyResultSchema:b,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:S,IconSchema:R,IconsSchema:v,BaseMetadataSchema:x,ImplementationSchema:N,ClientTasksCapabilitySchema:L,ServerTasksCapabilitySchema:Q,ClientCapabilitiesSchema:P,InitializeRequestParamsSchema:$,InitializeRequestSchema:j,ServerCapabilitiesSchema:B,InitializeResultSchema:ee,InitializedNotificationSchema:Ue,PingRequestSchema:De,ProgressSchema:Ge,ProgressNotificationParamsSchema:Y,ProgressNotificationSchema:le,PaginatedRequestParamsSchema:qe,PaginatedRequestSchema:oe,PaginatedResultSchema:tt,ResourceContentsSchema:_r,TextResourceContentsSchema:br,BlobResourceContentsSchema:vr,RoleSchema:dt,AnnotationsSchema:rt,ResourceSchema:Zt,ResourceTemplateSchema:Cn,ListResourcesRequestSchema:In,ListResourcesResultSchema:Tn,ListResourceTemplatesRequestSchema:Et,ListResourceTemplatesResultSchema:Cr,ResourceRequestParamsSchema:Yt,ReadResourceRequestParamsSchema:En,ReadResourceRequestSchema:kn,ReadResourceResultSchema:An,ResourceListChangedNotificationSchema:Pn,SubscribeRequestParamsSchema:xn,SubscribeRequestSchema:On,UnsubscribeRequestParamsSchema:Mn,UnsubscribeRequestSchema:Un,ResourceUpdatedNotificationParamsSchema:qn,ResourceUpdatedNotificationSchema:zn,PromptArgumentSchema:Nn,PromptSchema:jn,ListPromptsRequestSchema:Dn,ListPromptsResultSchema:Ln,GetPromptRequestParamsSchema:$n,GetPromptRequestSchema:Hn,TextContentSchema:Xt,ImageContentSchema:Qt,AudioContentSchema:er,ToolUseContentSchema:Bn,EmbeddedResourceSchema:kt,ResourceLinkSchema:Fn,ContentBlockSchema:Ke,PromptMessageSchema:Ir,GetPromptResultSchema:Tr,PromptListChangedNotificationSchema:tr,ToolAnnotationsSchema:Jn,ToolExecutionSchema:Er,ToolSchema:rr,ListToolsRequestSchema:kr,ListToolsResultSchema:Ar,CallToolResultSchema:Pr,CallToolRequestParamsSchema:ve,CallToolRequestSchema:Vn,ToolListChangedNotificationSchema:ms,LoggingLevelSchema:xr,SetLevelRequestParamsSchema:Gn,SetLevelRequestSchema:Kn,LoggingMessageNotificationParamsSchema:Wn,LoggingMessageNotificationSchema:Zn,ModelHintSchema:Yn,ModelPreferencesSchema:Xn,ToolChoiceSchema:Qn,ToolResultContentSchema:hs,SamplingContentSchema:eo,SamplingMessageContentBlockSchema:At,SamplingMessageSchema:to,CreateMessageRequestParamsSchema:ro,CreateMessageRequestSchema:no,CreateMessageResultSchema:oo,CreateMessageResultWithToolsSchema:so,BooleanSchemaSchema:io,StringSchemaSchema:ao,NumberSchemaSchema:co,UntitledSingleSelectEnumSchemaSchema:uo,TitledSingleSelectEnumSchemaSchema:lo,LegacyTitledEnumSchemaSchema:po,SingleSelectEnumSchemaSchema:mo,UntitledMultiSelectEnumSchemaSchema:nr,TitledMultiSelectEnumSchemaSchema:or,MultiSelectEnumSchemaSchema:fs,EnumSchemaSchema:gs,PrimitiveSchemaDefinitionSchema:Le,ElicitRequestFormParamsSchema:$e,ElicitRequestURLParamsSchema:ho,ElicitRequestParamsSchema:nt,ElicitRequestSchema:ys,ElicitationCompleteNotificationParamsSchema:Ss,ElicitationCompleteNotificationSchema:Rs,ElicitResultSchema:ws,ResourceTemplateReferenceSchema:_s,PromptReferenceSchema:bs,CompleteRequestParamsSchema:vs,CompleteRequestSchema:fo,CompleteResultSchema:Cs,RootSchema:Is,ListRootsRequestSchema:Or,ListRootsResultSchema:go,RootsListChangedNotificationSchema:Ts,TaskCreationParamsSchema:Es,TaskStatusSchema:yo,TaskSchema:Pt,CreateTaskResultSchema:ze,TaskStatusNotificationParamsSchema:ks,TaskStatusNotificationSchema:sr,GetTaskRequestSchema:Mr,GetTaskResultSchema:Ur,GetTaskPayloadRequestSchema:qr,GetTaskPayloadResultSchema:aa,ListTasksRequestSchema:Te,ListTasksResultSchema:ae,CancelTaskRequestSchema:ir,CancelTaskResultSchema:f.merge(Pt),ClientRequestSchema:q([De,j,fo,Kn,Hn,Dn,In,Et,kn,On,Un,Vn,kr,Mr,qr,Te,ir]),ClientNotificationSchema:q([S,le,Ue,Ts,sr]),ClientResultSchema:q([b,oo,so,ws,go,Ur,ae,ze]),ServerRequestSchema:q([De,no,ys,Or,Mr,qr,Te,ir]),ServerNotificationSchema:q([S,le,Zn,zn,Pn,ms,tr,sr,Rs]),ServerResultSchema:q([b,ee,Cs,Tr,Ln,Tn,Cr,An,Pr,Ar,Ur,ae,ze]),CallToolResultWireSchema:F().superRefine((Ce,q_)=>{if(!(typeof Ce!="object"||Ce===null||Array.isArray(Ce)||Ce.content!==void 0)){for(let Ru of Qh)if(Ru in Ce){q_.addIssue({code:"custom",message:`content is required when the body carries '${Ru}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(hb).pipe(Pr)}}o(fb,"build$1");var gb;function Ka(){return gb??=fb()}o(Ka,"buildSchemas2025");function ef(e){return e.type!=="object"}o(ef,"isNonObjectJsonSchemaRoot");var yb=new Set(["const","enum","default","examples"]),Sb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Dh(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(Dh,"establishesNewBase");function Rb(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Dh(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=jh(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&&Dh(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:yb.has(d)?a[d]=u:Sb.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(Rb,"wrapOutputSchemaForLegacy");var tf={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},rf={"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},wb={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},ri;function ai(){if(ri)return ri;let e=Ka();return ri={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}},ri}o(ai,"registryMaps");function _b(){ai()}o(_b,"warmRegistryMaps2025");function nf(e){return Object.prototype.hasOwnProperty.call(tf,e)}o(nf,"hasRequestMethod2025");function of(e){return Object.prototype.hasOwnProperty.call(rf,e)}o(of,"hasNotificationMethod2025");function bb(e){return Object.prototype.hasOwnProperty.call(wb,e)}o(bb,"hasResultMethod");function vb(e){return bb(e)?ai().resultSchemas[e]:void 0}o(vb,"getResultSchema");function Cb(e){return nf(e)?ai().requestSchemas[e]:void 0}o(Cb,"getRequestSchema");function Ib(e){return of(e)?ai().notificationSchemas[e]:void 0}o(Ib,"getNotificationSchema");var dU=Object.keys(tf),uU=Object.keys(rf);function Ha(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ha,"isPlainObject$5");function ni(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(ni,"triState$1");var Lh={ok:!1,reason:"not-in-era"};function $h(e){return Ha(e)&&Ha(e.outputSchema)&&ef(e.outputSchema)}o($h,"toolNeedsLegacyWrap");var Wa={era:"2025-11-25",hasRequestMethod:nf,hasNotificationMethod:of,validateRequest:o((e,t)=>ni(Cb(e),t),"validateRequest"),validateResult:o((e,t)=>ni(vb(e),t),"validateResult"),validateNotification:o((e,t)=>ni(Ib(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>Lh,"validateInputRequest"),validateInputResponse:o(()=>Lh,"validateInputResponse"),samplingResultVariant:o(((e,t)=>{let r=Ka();return ni(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:o(e=>{},"outboundEnvelope"),validateEnvelopeMeta:o(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Xh(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&ef(t);return!s&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ha(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=>$h(n))?t:{...t,tools:r.map(n=>$h(n)?{...n,outputSchema:Rb(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function Tb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),A().int()]),n=l(),s=q([l(),A().int()]),i=K(["user","assistant"]),a=K(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(ae=>{try{return atob(ae),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:A().optional()}),u=g({taskId:l()}),p=V({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:p.optional()}),f=h.extend({task:d.optional()}),y=g({_meta:p.optional()}),b=g({method:l(),params:y.loose().optional()}),w=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:K(["light","dark"]).optional()}),S=g({icons:C(w).optional()}),R=g({name:l(),title:l().optional()}),v=R.extend({...R.shape,...S.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),x=So(g({applyDefaults:D().optional()}),t),N=Ps(ae=>ae&&typeof ae=="object"&&!Array.isArray(ae)&&Object.keys(ae).length===0?{form:{}}:ae,So(g({form:x.optional(),url:t.optional()}),t.optional())),T=V({list:t.optional(),cancel:t.optional(),requests:V({sampling:V({createMessage:t.optional()}).optional(),elicitation:V({create:t.optional()}).optional()}).optional()}),O=V({list:t.optional(),cancel:t.optional(),requests:V({tools:V({call:t.optional()}).optional()}).optional()}),L=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:D().optional()}).optional(),tasks:T.optional(),extensions:U(l(),t).optional()}),Q=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:D().optional()}).optional(),resources:g({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:g({listChanged:D().optional()}).optional(),tasks:O.optional(),extensions:U(l(),t).optional()}),P=g({progress:A(),total:J(A()),message:J(l())}),$=g({...y.shape,...P.shape,progressToken:r}),j=b.extend({method:_("notifications/progress"),params:$}),B=y.extend({level:a,logger:l().optional(),data:F()}),ee=b.extend({method:_("notifications/message"),params:B}),Ue=g({uri:l(),mimeType:J(l()),_meta:U(l(),F()).optional()}),De=Ue.extend({text:l()}),Ge=Ue.extend({blob:c}),Y=g({audience:C(i).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),le=g({...R.shape,...S.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:Y.optional(),_meta:J(V({}))}),qe=g({...R.shape,...S.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:Y.optional(),_meta:J(V({}))}),oe=b.extend({method:_("notifications/resources/list_changed"),params:y.optional()}),tt=y.extend({uri:l()}),_r=b.extend({method:_("notifications/resources/updated"),params:tt}),br=g({name:l(),description:J(l()),required:J(D())}),Wt=g({...R.shape,...S.shape,description:J(l()),arguments:J(C(br)),_meta:J(V({}))}),vr=b.extend({method:_("notifications/prompts/list_changed"),params:y.optional()}),dt=g({type:_("text"),text:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),rt=g({type:_("image"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Zt=g({type:_("audio"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Cn=g({type:_("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),In=g({type:_("resource"),resource:q([De,Ge]),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Tn=le.extend({type:_("resource_link")}),Et=q([dt,rt,Zt,Tn,In]),Cr=g({role:i,content:Et}),Yt=g({title:l().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),En=b.extend({method:_("notifications/tools/list_changed"),params:y.optional()}),kn=g({name:l().optional()}),An=g({hints:C(kn).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Pn=g({mode:K(["auto","required","none"]).optional()}),xn=g({type:_("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),On=g({type:_("string"),title:l().optional(),description:l().optional(),minLength:A().optional(),maxLength:A().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),Mn=g({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),Un=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),qn=g({type:_("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),zn=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),Nn=q([Un,qn]),jn=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:_("string"),enum:C(l())}),default:C(l()).optional()}),Dn=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),Ln=q([jn,Dn]),$n=q([zn,Nn,Ln]),Hn=q([$n,xn,On,Mn]),Xt=f.extend({mode:_("form").optional(),message:l(),requestedSchema:g({type:_("object"),properties:U(l(),Hn),required:C(l()).optional()}).catchall(F())}),Qt=g({type:_("ref/resource"),uri:l()}),er=g({type:_("ref/prompt"),name:l()}),Bn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),F()).optional()}),kt=L.shape,Fn=g({experimental:kt.experimental,sampling:kt.sampling,elicitation:kt.elicitation,roots:kt.roots,extensions:kt.extensions}),Ke=Q.shape,Ir=g({experimental:Ke.experimental,logging:Ke.logging,completions:Ke.completions,prompts:Ke.prompts,resources:Ke.resources,tools:Ke.tools,extensions:Ke.extensions}),Tr=V({progressToken:r.optional(),[jr]:l(),[wo]:v.optional(),[Lr]:Fn,[_o]:a.optional()}),tr=g({...R.shape,...S.shape,description:l().optional(),inputSchema:V({$schema:l().optional(),type:_("object")}),outputSchema:V({$schema:l().optional()}).optional(),annotations:Yt.optional(),_meta:U(l(),F()).optional()}),Jn=g({type:_("tool_result"),toolUseId:l(),content:C(Et),structuredContent:F().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),Er=q([dt,rt,Zt,Cn,Jn]),rr=g({role:i,content:q([Er,C(Er)]),_meta:U(l(),F()).optional()}),kr=l(),Ar=V({[Dr]:v.optional().catch(void 0)}),Pr=Ar.optional();function ve(ae){return V({_meta:Pr,resultType:kr.default("complete"),...ae})}o(ve,"wireResult");let Vn=ve({}),ms=ve({nextCursor:n.optional()}),xr=ve({content:C(Et),structuredContent:F().optional(),isError:D().optional()}),Gn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:C(tr),nextCursor:n.optional()}),Kn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:C(Wt),nextCursor:n.optional()}),Wn=ve({description:l().optional(),messages:C(Cr)}),Zn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:C(le),nextCursor:n.optional()}),Yn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:C(qe),nextCursor:n.optional()}),Xn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:C(q([De,Ge]))}),Qn=ve({completion:g({values:C(l()).max(100),total:A().int().optional(),hasMore:D().optional()}).loose()}),hs=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"])}),eo=ve({ttlMs:A().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:Ir,instructions:l().optional()}),At=g({messages:C(rr),modelPreferences:An.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(tr).optional(),toolChoice:Pn.optional()}),to=g({method:_("sampling/createMessage"),params:At}),ro=g({method:_("roots/list"),params:g({_meta:U(l(),F()).optional()}).optional()}),no=g({...rr.shape,model:l(),stopReason:l().optional()}),oo=g({roots:C(Bn)}),so=g({action:K(["accept","decline","cancel"]),content:U(l(),q([l(),A(),D(),C(l())])).optional()}),io=g({mode:_("url"),message:l(),url:l().url()}),ao=q([Xt,io]),co=g({method:_("elicitation/create"),params:ao}),uo=q([to,ro,co]),lo=q([no,oo,so]),po=U(l(),uo),mo=U(l(),lo),nr=ve({inputRequests:po.optional(),requestState:l().optional()}),or={inputResponses:mo.optional(),requestState:l().optional()},fs=g({_meta:Tr,...or}),gs=V({progressToken:r.optional()});function Le(ae,ir){return g({method:_(ae),params:g({_meta:Tr,...ir})})}o(Le,"wireRequest");function $e(ae,ir){return g({method:_(ae),params:g({_meta:gs.optional(),...ir}).optional()})}o($e,"dispatchRequest");let ho={name:l(),arguments:U(l(),F()).optional(),...or},nt={cursor:n.optional()},ys=Le("tools/call",ho),Ss=Le("tools/list",nt),Rs=Le("prompts/list",nt),ws=Le("prompts/get",{name:l(),arguments:U(l(),l()).optional(),...or}),_s=Le("resources/list",nt),bs=Le("resources/templates/list",nt),vs=Le("resources/read",{uri:l(),...or}),fo={ref:q([er,Qt]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()},Cs=Le("completion/complete",fo),Is=Le("server/discover",{}),Or=g({toolsListChanged:D().optional(),promptsListChanged:D().optional(),resourcesListChanged:D().optional(),resourceSubscriptions:C(l()).optional()}),go={notifications:Or},Ts=Le("subscriptions/listen",go),Es=Ar.extend({"io.modelcontextprotocol/subscriptionId":s}),yo=V({_meta:Es,resultType:kr.default("complete")}),Pt={"tools/call":$e("tools/call",ho),"tools/list":$e("tools/list",nt),"prompts/get":$e("prompts/get",{name:l(),arguments:U(l(),l()).optional()}),"prompts/list":$e("prompts/list",nt),"resources/list":$e("resources/list",nt),"resources/templates/list":$e("resources/templates/list",nt),"resources/read":$e("resources/read",{uri:l()}),"completion/complete":$e("completion/complete",fo),"server/discover":$e("server/discover",{}),"subscriptions/listen":$e("subscriptions/listen",go)};function ze(ae){return V({_meta:Pr,...ae})}o(ze,"liftedResult");let ks={"tools/call":ze({content:C(Et),structuredContent:F().optional(),isError:D().optional()}),"tools/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:C(tr),nextCursor:n.optional()}),"prompts/get":ze({description:l().optional(),messages:C(Cr)}),"prompts/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:C(Wt),nextCursor:n.optional()}),"resources/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:C(le),nextCursor:n.optional()}),"resources/templates/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:C(qe),nextCursor:n.optional()}),"resources/read":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:C(q([De,Ge]))}),"completion/complete":ze({completion:g({values:C(l()).max(100),total:A().int().optional(),hasMore:D().optional()}).loose()}),"server/discover":ze({ttlMs:A().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:Ir,instructions:l().optional()}),"subscriptions/listen":ze({})},sr=V({"io.modelcontextprotocol/subscriptionId":s.optional()}),Mr=g({method:_("notifications/subscriptions/acknowledged"),params:g({_meta:sr.optional(),notifications:Or})}),Ur=g({_meta:sr.optional(),requestId:s,reason:l().optional()}),qr=g({method:_("notifications/cancelled"),params:Ur}),aa={"notifications/cancelled":qr,"notifications/progress":j,"notifications/message":ee,"notifications/resources/updated":_r,"notifications/resources/list_changed":oe,"notifications/tools/list_changed":En,"notifications/prompts/list_changed":vr,"notifications/subscriptions/acknowledged":Mr},Te=o(ae=>g({jsonrpc:_("2.0"),id:q([l(),A().int()]),result:ae}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:p,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:y,NotificationSchema:b,IconSchema:w,IconsSchema:S,BaseMetadataSchema:R,ImplementationSchema:v,ClientTasksCapabilitySchema:T,ServerTasksCapabilitySchema:O,ClientCapabilitiesSchema:L,ServerCapabilitiesSchema:Q,ProgressSchema:P,ProgressNotificationParamsSchema:$,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:B,LoggingMessageNotificationSchema:ee,ResourceContentsSchema:Ue,TextResourceContentsSchema:De,BlobResourceContentsSchema:Ge,AnnotationsSchema:Y,ResourceSchema:le,ResourceTemplateSchema:qe,ResourceListChangedNotificationSchema:oe,ResourceUpdatedNotificationParamsSchema:tt,ResourceUpdatedNotificationSchema:_r,PromptArgumentSchema:br,PromptSchema:Wt,PromptListChangedNotificationSchema:vr,TextContentSchema:dt,ImageContentSchema:rt,AudioContentSchema:Zt,ToolUseContentSchema:Cn,EmbeddedResourceSchema:In,ResourceLinkSchema:Tn,ContentBlockSchema:Et,PromptMessageSchema:Cr,ToolAnnotationsSchema:Yt,ToolListChangedNotificationSchema:En,ModelHintSchema:kn,ModelPreferencesSchema:An,ToolChoiceSchema:Pn,BooleanSchemaSchema:xn,StringSchemaSchema:On,NumberSchemaSchema:Mn,UntitledSingleSelectEnumSchemaSchema:Un,TitledSingleSelectEnumSchemaSchema:qn,LegacyTitledEnumSchemaSchema:zn,SingleSelectEnumSchemaSchema:Nn,UntitledMultiSelectEnumSchemaSchema:jn,TitledMultiSelectEnumSchemaSchema:Dn,MultiSelectEnumSchemaSchema:Ln,EnumSchemaSchema:$n,PrimitiveSchemaDefinitionSchema:Hn,ElicitRequestFormParamsSchema:Xt,ResourceTemplateReferenceSchema:Qt,PromptReferenceSchema:er,RootSchema:Bn,ClientCapabilities2026Schema:Fn,ServerCapabilities2026Schema:Ir,RequestMetaEnvelopeSchema:Tr,ToolSchema:tr,ToolResultContentSchema:Jn,SamplingMessageContentBlockSchema:Er,SamplingMessageSchema:rr,ResultTypeSchema:kr,ResultMetaSchema:Ar,ResultSchema:Vn,PaginatedResultSchema:ms,CallToolResultSchema:xr,ListToolsResultSchema:Gn,ListPromptsResultSchema:Kn,GetPromptResultSchema:Wn,ListResourcesResultSchema:Zn,ListResourceTemplatesResultSchema:Yn,ReadResourceResultSchema:Xn,CompleteResultSchema:Qn,CacheableResultSchema:hs,DiscoverResultSchema:eo,CreateMessageRequestParamsSchema:At,CreateMessageRequestSchema:to,ListRootsRequestSchema:ro,CreateMessageResultSchema:no,ListRootsResultSchema:oo,ElicitResultSchema:so,ElicitRequestURLParamsSchema:io,ElicitRequestParamsSchema:ao,ElicitRequestSchema:co,InputRequestSchema:uo,InputResponseSchema:lo,InputRequestsSchema:po,InputResponsesSchema:mo,InputRequiredResultSchema:nr,InputResponseRequestParamsSchema:fs,CallToolRequestSchema:ys,ListToolsRequestSchema:Ss,ListPromptsRequestSchema:Rs,GetPromptRequestSchema:ws,ListResourcesRequestSchema:_s,ListResourceTemplatesRequestSchema:bs,ReadResourceRequestSchema:vs,CompleteRequestSchema:Cs,DiscoverRequestSchema:Is,SubscriptionFilterSchema:Or,SubscriptionsListenRequestSchema:Ts,SubscriptionsListenResultMetaSchema:Es,SubscriptionsListenResultSchema:yo,dispatchRequestSchemas:Pt,dispatchResultSchemas:ks,NotificationMetaSchema:sr,SubscriptionsAcknowledgedNotificationSchema:Mr,CancelledNotificationParamsSchema:Ur,CancelledNotificationSchema:qr,notificationSchemas2026:aa,JSONRPCResultResponseSchema:Te(Vn),CallToolResultResponseSchema:Te(q([xr,nr])),ListToolsResultResponseSchema:Te(Gn),ListPromptsResultResponseSchema:Te(Kn),GetPromptResultResponseSchema:Te(q([Wn,nr])),ListResourcesResultResponseSchema:Te(Zn),ListResourceTemplatesResultResponseSchema:Te(Yn),ReadResourceResultResponseSchema:Te(q([Xn,nr])),CompleteResultResponseSchema:Te(Qn),DiscoverResultResponseSchema:Te(eo),SubscriptionsListenResultResponseSchema:Te(yo)}}o(Tb,"build");var Eb;function Rt(){return Eb??=Tb()}o(Rt,"buildSchemas2026");var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Ab(e){return kb.includes(e)}o(Ab,"isCacheableResultMethod");var Za=Symbol("modelcontextprotocol.resultCacheHintFallback");function Pb(e){return e[Za]}o(Pb,"cacheHintFallbackOf");function sf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(sf,"isValidCacheTtlMs");function af(e){return e==="public"||e==="private"}o(af,"isValidCacheScope");var I=(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})({}),Re=class cf extends Error{static{o(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Fe(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 Fe(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",mr(this,new.target)}static fromError(t,r,n){if(t===I.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ci(s.elicitations,r)}if(t===I.UnsupportedProtocolVersion&&n){let s=n;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new uf({supported:s.supported,requested:s.requested},r)}if(t===I.InvalidParams||t===I.ResourceNotFound){let s=n;if(typeof s?.uri=="string"&&(t===I.ResourceNotFound||Object.keys(s).length===1))return new df(s.uri,r)}if(t===I.MissingRequiredClientCapability&&n){let s=n;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new lf({requiredCapabilities:s.requiredCapabilities},r)}return new cf(t,r,n)}},df=class extends Re{static{o(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(I.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ci=class extends Re{static{o(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},uf=class extends Re{static{o(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(I.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},lf=class extends Re{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(I.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},xb=0,Ob="private",Mb=["tools/call","prompts/get","resources/read"];function Ub(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Mb.includes(e))return t;throw new Re(I.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}o(Ub,"stampResultType");function qb(e,t){let r=Pb(t);if(t.resultType!=="complete"||!Ab(e))return r===void 0?t:Lb(t);let n=t,s=sf(n.ttlMs)?n.ttlMs:jb(r),i=af(n.cacheScope)?n.cacheScope:Db(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Za],a}o(qb,"fillCacheFields");function zb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(zb,"isPlainObject$4");function Nb(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Dr]:t}}:!zb(r)||r[Dr]!==void 0?e:{...e,_meta:{...r,[Dr]:t}}}o(Nb,"stampServerInfoMeta");function jb(e){return e!==void 0&&sf(e.ttlMs)?e.ttlMs:xb}o(jb,"resolveTtlMs");function Db(e){return e!==void 0&&af(e.cacheScope)?e.cacheScope:Ob}o(Db,"resolveCacheScope");function Lb(e){let t={...e};return delete t[Za],t}o(Lb,"stripCacheHintFallback");var $b=["elicitation/create","sampling/createMessage","roots/list"],oi;function Ya(){if(oi)return oi;let e=Rt();return oi={request:{"elicitation/create":g({method:_("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:_("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:_("roots/list"),params:V({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},oi}o(Ya,"inputSchemaMaps");function Hb(){Ya()}o(Hb,"warmInputSchemaMaps2026");function pf(e){return $b.includes(e)}o(pf,"isInputRequestMethod2026");function za(e){return pf(e)?Ya().request[e]:void 0}o(za,"getInputRequestSchema2026");function Bb(e){return pf(e)?Ya().response[e]:void 0}o(Bb,"getInputResponseSchema2026");var Xa={"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},mf={"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 hf(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o(hf,"hasRequestMethod2026");function ff(e){return Object.prototype.hasOwnProperty.call(mf,e)}o(ff,"hasNotificationMethod2026");function Fb(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o(Fb,"hasResultMethod2026");function Jb(e){return hf(e)?Rt().dispatchRequestSchemas[e]:void 0}o(Jb,"getRequestSchema2026");function Vb(e){return Fb(e)?Rt().dispatchResultSchemas[e]:void 0}o(Vb,"getResultSchema2026");function Gb(e){return ff(e)?Rt().notificationSchemas2026[e]:void 0}o(Gb,"getNotificationSchema2026");var lU=Object.keys(Xa),pU=Object.keys(mf);function qo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(qo,"isPlainObject$3");function Mo(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(Mo,"triState");var Kb={ok:!1,reason:"not-in-era"},Wb=[jr,Lr];function Zb(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=>qo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!qo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(qo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}o(Zb,"enforceDeletedFields");var Qa={era:"2026-07-28",hasRequestMethod:hf,hasNotificationMethod:ff,hasInputRequestMethod:o(e=>za(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>Mo(Jb(e),t),"validateRequest"),validateResult:o((e,t)=>Mo(Vb(e),t),"validateResult"),validateNotification:o((e,t)=>Mo(Gb(e),t),"validateNotification"),validateInputRequest:o((e,t)=>Mo(za(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>Mo(Bb(e),t),"validateInputResponse"),samplingResultVariant:o(()=>Kb,"samplingResultVariant"),outboundEnvelope(e){return{[jr]:e.protocolVersion,[wo]:e.clientInfo,[Lr]:e.clientCapabilities,...e.logLevel!==void 0&&{[_o]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Wb)n in e||t.push({key:n,problem:"missing"});let r=Rt().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=>Xh(e),"projectCallToolResult"),inputRequestSchema:za,decodeResult(e,t){if(!qo(t))return{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new pe(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 pe(Se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=qo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:Rt().ResultMetaSchema.safeParse(t._meta),p=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new pe(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},...p!==void 0&&{_meta:p}}}if(r!=="complete")return{kind:"invalid",error:new pe(Se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=gf(),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 pe(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 Nb(qb(e,Ub(e,Zb(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=Rt().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("; ")}`}},si;function gf(){if(si)return si;let e=Rt();return si={"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},si}o(gf,"getWireResultSchemas");function Yb(){gf()}o(Yb,"warmWireResultSchemas2026");var ec="2026-07-28";function No(e){return e!==void 0&&Yh(e)?Qa:Wa}o(No,"codecForVersion");function Hh(e){return e.revision!==void 0?No(e.revision).era:e.era==="modern"?Qa.era:Wa.era}o(Hh,"classifiedWireEra");function Na(e){return yf.some(t=>t.hasRequestMethod(e))}o(Na,"isSpecRequestMethod");function ja(e){return yf.some(t=>t.hasNotificationMethod(e))}o(ja,"isSpecNotificationMethod");function Bh(e){return e==="tasks/get"||e==="tasks/cancel"}o(Bh,"isExtensionReusedRequestMethod");var yf=[Wa,Qa],Xb=zh({AnnotationsSchema:o(()=>Rl,"AnnotationsSchema"),AudioContentSchema:o(()=>Xl,"AudioContentSchema"),BaseMetadataSchema:o(()=>Yu,"BaseMetadataSchema"),BaseRequestParamsSchema:o(()=>Nu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:o(()=>yl,"BlobResourceContentsSchema"),BooleanSchemaSchema:o(()=>ga,"BooleanSchemaSchema"),CallToolRequestParamsSchema:o(()=>mp,"CallToolRequestParamsSchema"),CallToolRequestSchema:o(()=>hp,"CallToolRequestSchema"),CallToolResultSchema:o(()=>lp,"CallToolResultSchema"),CancelTaskRequestSchema:o(()=>am,"CancelTaskRequestSchema"),CancelTaskResultSchema:o(()=>cm,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:o(()=>Gu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:o(()=>Ku,"CancelledNotificationSchema"),ClientCapabilitiesSchema:o(()=>tl,"ClientCapabilitiesSchema"),ClientNotificationSchema:o(()=>um,"ClientNotificationSchema"),ClientRequestSchema:o(()=>dm,"ClientRequestSchema"),ClientResultSchema:o(()=>lm,"ClientResultSchema"),ClientTasksCapabilitySchema:o(()=>Qu,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:o(()=>pp,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:o(()=>Hp,"CompleteRequestParamsSchema"),CompleteRequestSchema:o(()=>Bp,"CompleteRequestSchema"),CompleteResultSchema:o(()=>Fp,"CompleteResultSchema"),ContentBlockSchema:o(()=>rp,"ContentBlockSchema"),CreateMessageRequestParamsSchema:o(()=>kp,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:o(()=>Ap,"CreateMessageRequestSchema"),CreateMessageResultSchema:o(()=>Pp,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:o(()=>xp,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:o(()=>Xp,"CreateTaskResultSchema"),CursorSchema:o(()=>Mu,"CursorSchema"),DiscoverRequestSchema:o(()=>al,"DiscoverRequestSchema"),DiscoverResultSchema:o(()=>ha,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:o(()=>Ns,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:o(()=>qp,"ElicitRequestParamsSchema"),ElicitRequestSchema:o(()=>zp,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:o(()=>js,"ElicitRequestURLParamsSchema"),ElicitResultSchema:o(()=>Dp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:o(()=>Np,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:o(()=>jp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:o(()=>ep,"EmbeddedResourceSchema"),EmptyResultSchema:o(()=>Vu,"EmptyResultSchema"),EnumSchemaSchema:o(()=>Up,"EnumSchemaSchema"),GetPromptRequestParamsSchema:o(()=>Kl,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:o(()=>Wl,"GetPromptRequestSchema"),GetPromptResultSchema:o(()=>op,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:o(()=>nm,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:o(()=>om,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:o(()=>tm,"GetTaskRequestSchema"),GetTaskResultSchema:o(()=>rm,"GetTaskResultSchema"),IconSchema:o(()=>Wu,"IconSchema"),IconsSchema:o(()=>Zu,"IconsSchema"),ImageContentSchema:o(()=>Yl,"ImageContentSchema"),ImplementationSchema:o(()=>Xu,"ImplementationSchema"),InitializeRequestParamsSchema:o(()=>rl,"InitializeRequestParamsSchema"),InitializeRequestSchema:o(()=>nl,"InitializeRequestSchema"),InitializeResultSchema:o(()=>sl,"InitializeResultSchema"),InitializedNotificationSchema:o(()=>il,"InitializedNotificationSchema"),JSONArraySchema:o(()=>xu,"JSONArraySchema"),JSONObjectSchema:o(()=>Pu,"JSONObjectSchema"),JSONRPCErrorResponseSchema:o(()=>bo,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:o(()=>ma,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:o(()=>la,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:o(()=>cr,"JSONRPCRequestSchema"),JSONRPCResponseSchema:o(()=>Ju,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:o(()=>pa,"JSONRPCResultResponseSchema"),JSONValueSchema:o(()=>Au,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:o(()=>Ra,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:o(()=>fa,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:o(()=>Vl,"ListPromptsRequestSchema"),ListPromptsResultSchema:o(()=>Gl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:o(()=>Cl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:o(()=>Il,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:o(()=>bl,"ListResourcesRequestSchema"),ListResourcesResultSchema:o(()=>vl,"ListResourcesResultSchema"),ListRootsRequestSchema:o(()=>Vp,"ListRootsRequestSchema"),ListRootsResultSchema:o(()=>Gp,"ListRootsResultSchema"),ListTasksRequestSchema:o(()=>sm,"ListTasksRequestSchema"),ListTasksResultSchema:o(()=>im,"ListTasksResultSchema"),ListToolsRequestSchema:o(()=>dp,"ListToolsRequestSchema"),ListToolsResultSchema:o(()=>up,"ListToolsResultSchema"),LoggingLevelSchema:o(()=>gp,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:o(()=>Rp,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:o(()=>wp,"LoggingMessageNotificationSchema"),ModelHintSchema:o(()=>_p,"ModelHintSchema"),ModelPreferencesSchema:o(()=>bp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:o(()=>Mp,"MultiSelectEnumSchemaSchema"),NotificationSchema:o(()=>$u,"NotificationSchema"),NotificationsParamsSchema:o(()=>Lu,"NotificationsParamsSchema"),NumberSchemaSchema:o(()=>zs,"NumberSchemaSchema"),PaginatedRequestParamsSchema:o(()=>pl,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:o(()=>ml,"PaginatedRequestSchema"),PaginatedResultSchema:o(()=>hl,"PaginatedResultSchema"),PingRequestSchema:o(()=>cl,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:o(()=>ba,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:o(()=>ul,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:o(()=>ll,"ProgressNotificationSchema"),ProgressSchema:o(()=>dl,"ProgressSchema"),ProgressTokenSchema:o(()=>Ou,"ProgressTokenSchema"),PromptArgumentSchema:o(()=>Fl,"PromptArgumentSchema"),PromptListChangedNotificationSchema:o(()=>sp,"PromptListChangedNotificationSchema"),PromptMessageSchema:o(()=>np,"PromptMessageSchema"),PromptReferenceSchema:o(()=>$p,"PromptReferenceSchema"),PromptSchema:o(()=>Jl,"PromptSchema"),ReadResourceRequestParamsSchema:o(()=>El,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:o(()=>kl,"ReadResourceRequestSchema"),ReadResourceResultSchema:o(()=>Al,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:o(()=>qu,"RelatedTaskMetadataSchema"),RequestIdSchema:o(()=>Fu,"RequestIdSchema"),RequestMetaSchema:o(()=>zu,"RequestMetaSchema"),RequestSchema:o(()=>Du,"RequestSchema"),ResourceContentsSchema:o(()=>fl,"ResourceContentsSchema"),ResourceLinkSchema:o(()=>tp,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:o(()=>Pl,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:o(()=>Tl,"ResourceRequestParamsSchema"),ResourceSchema:o(()=>wl,"ResourceSchema"),ResourceTemplateReferenceSchema:o(()=>Lp,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:o(()=>_l,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:o(()=>Hl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:o(()=>Bl,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:o(()=>Hu,"ResultMetaObjectSchema"),ResultSchema:o(()=>Bu,"ResultSchema"),RoleSchema:o(()=>Sl,"RoleSchema"),RootSchema:o(()=>Jp,"RootSchema"),RootsListChangedNotificationSchema:o(()=>Kp,"RootsListChangedNotificationSchema"),SamplingContentSchema:o(()=>Ip,"SamplingContentSchema"),SamplingMessageContentBlockSchema:o(()=>Tp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:o(()=>Ep,"SamplingMessageSchema"),ServerCapabilitiesSchema:o(()=>ol,"ServerCapabilitiesSchema"),ServerNotificationSchema:o(()=>mm,"ServerNotificationSchema"),ServerRequestSchema:o(()=>pm,"ServerRequestSchema"),ServerResultSchema:o(()=>hm,"ServerResultSchema"),ServerTasksCapabilitySchema:o(()=>el,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:o(()=>yp,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:o(()=>Sp,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:o(()=>Op,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:o(()=>qs,"StringSchemaSchema"),SubscribeRequestParamsSchema:o(()=>xl,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:o(()=>Ol,"SubscribeRequestSchema"),SubscriptionFilterSchema:o(()=>ql,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:o(()=>jl,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:o(()=>Dl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:o(()=>zl,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:o(()=>Nl,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:o(()=>Ll,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:o(()=>$l,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:o(()=>ju,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:o(()=>Wp,"TaskCreationParamsSchema"),TaskMetadataSchema:o(()=>Uu,"TaskMetadataSchema"),TaskSchema:o(()=>Yp,"TaskSchema"),TaskStatusNotificationParamsSchema:o(()=>Qp,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:o(()=>em,"TaskStatusNotificationSchema"),TaskStatusSchema:o(()=>Zp,"TaskStatusSchema"),TextContentSchema:o(()=>Zl,"TextContentSchema"),TextResourceContentsSchema:o(()=>gl,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:o(()=>_a,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:o(()=>Sa,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:o(()=>ip,"ToolAnnotationsSchema"),ToolChoiceSchema:o(()=>vp,"ToolChoiceSchema"),ToolExecutionSchema:o(()=>ap,"ToolExecutionSchema"),ToolListChangedNotificationSchema:o(()=>fp,"ToolListChangedNotificationSchema"),ToolResultContentSchema:o(()=>Cp,"ToolResultContentSchema"),ToolSchema:o(()=>cp,"ToolSchema"),ToolUseContentSchema:o(()=>Ql,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:o(()=>Ml,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:o(()=>Ul,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:o(()=>wa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:o(()=>ya,"UntitledSingleSelectEnumSchemaSchema")});var Sf=o(e=>cr.safeParse(e).success,"isJSONRPCRequest"),Rf=o(e=>la.safeParse(e).success,"isJSONRPCNotification"),Ba=o(e=>pa.safeParse(e).success,"isJSONRPCResultResponse"),wf=o(e=>bo.safeParse(e).success,"isJSONRPCErrorResponse");var zo=-32020,mU=[{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:[I.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:[zo,I.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:[I.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:[I.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:[I.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:[zo],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:[I.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:[zo],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."}],hU={[I.ParseError]:400,[I.InvalidRequest]:400,[I.MethodNotFound]:404,[I.UnsupportedProtocolVersion]:400,[I.MissingRequiredClientCapability]:400,[zo]:400};function tc(e,t){return _u(e,t)}o(tc,"parseSchema");function Uo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}o(Uo,"shapeKeys");function Fa(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(Fa,"isStandardSchema");var Fh=!1,Ja="draft-2020-12";function Qb(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Ja});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().");Fh||(Fh=!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=ca(e,{target:Ja,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:_f(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(Qb,"standardSchemaToJsonSchema");function _f(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"||_f(n)))}return!1}o(_f,"isProvablyObjectShapedRoot");function ev(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(ev,"formatIssue");async function Da(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>ev(n)).join(", ")}:{success:!0,data:r.value}}o(Da,"validateStandardSchema");function tv(e){let t=ca(e,{target:Ja,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(tv,"zodEmittedPattern");var rv=/\\\.\\d\{(\d+)\}/;function nv(e){let t=rv.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=>Ro.datetime({local:n,offset:s,precision:i}))))}o(nv,"datetimeReferenceSchemas");function ov(e,t){let r;switch(e){case"email":r=[bu()];break;case"uri":r=[vu()];break;case"date":r=[Ro.date()];break;case"date-time":r=nv(t);break}return new Set(r.map(n=>tv(n)).filter(n=>n!==void 0))}o(ov,"referencePatternsForFormat");function sv(e,t,r){return r!=="zod"?!0:ov(e,t).has(t)}o(sv,"isLibraryFormatPattern");function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(jo,"isJsonObject");function iv(e){try{return Qb(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new Re(I.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}o(iv,"convertStandardElicitationSchema");var av=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function rc(e){return av.has(e)||e.startsWith("x-")}o(rc,"isAnnotationOnlyJsonSchemaKeyword");var cv=new Set(["$schema",...Object.keys(Ns.shape.requestedSchema.shape)]),Jh={string:Uo([qs,ya,Sa,Ra]),number:Uo([zs]),integer:Uo([zs]),boolean:Uo([ga]),array:Uo([wa,_a])},dv=new Set(qs.shape.format.unwrap().options);function uv(e,t,r,n){if(!jo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Jh,e.type)?Jh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||rc(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?dv.has(e.format)?(typeof c!="string"||!sv(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(uv,"walkProperty");function lv(e,t){let r={},n=[];for(let[s,i]of Object.entries(e))s==="properties"&&jo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,uv(c,`properties.${a}`,t,n)])):cv.has(s)?r[s]=i:rc(s)||n.push(s);if(n.length>0)throw new Re(I.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}o(lv,"walkRequestedSchema");function pv(e,t){if(!jo(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!tc(ba,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}o(pv,"describeUnsupportedProperties");function Va(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,s)=>Va(n,t[s],`${r}[${s}]`)):!jo(e)||!jo(t)?[]:Object.entries(e).flatMap(([n,s])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Va(s,t[n],i):rc(n)?[]:[i]})}o(Va,"findDroppedConstraintPaths");function mv(e){if(!Fa(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=lv(iv(e.requestedSchema),t),n=tc(Ns.shape.requestedSchema,r);if(!n.success)throw new Re(I.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${pv(r,n.error.message)}`);let s=Va(r,n.data);if(s.length>0)throw new Re(I.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 Re(I.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}o(mv,"normalizeElicitInputParams");function hv(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(hv,"buildInputRequired");var fU=Object.assign(hv,{elicit(e){try{return{method:"elicitation/create",params:mv(e)}}catch(t){throw t instanceof Re?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 fv=["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"],gv={IdJagTokenExchangeResponseSchema:va,OAuthClientInformationFullSchema:dr,OAuthClientInformationSchema:vo,OAuthClientMetadataSchema:gm,OAuthClientRegistrationErrorSchema:ym,OAuthErrorResponseSchema:Ds,OAuthMetadataSchema:Hr,OAuthProtectedResourceMetadataSchema:$r,OAuthTokenRevocationRequestSchema:Sm,OAuthTokensSchema:Ot,OpenIdProviderDiscoveryMetadataSchema:Br,OpenIdProviderMetadataSchema:fm},bf={},vf={};function Cf(e,t){let r=e.slice(0,-6);bf[r]=t,vf[r]=n=>t.safeParse(n).success}o(Cf,"register");for(let e of fv)Cf(e,Xb[e]);for(let[e,t]of Object.entries(gv))Cf(e,t);var yv=Object.freeze(bf),Sv=Object.freeze(vf);function Rv(e){switch(e){case"initialize":case"notifications/initialized":return No(void 0);case"server/discover":return No(ec);default:return}}o(Rv,"bootstrapOutboundCodec");var If=6e4,wv=[jr,wo,Lr,_o],_v=["inputResponses","requestState"];function Vh(e,t){let r=e.params;if(!La(r))return{message:e,lifted:{}};let n=r._meta,s=La(n)?wv.filter(d=>d in n):[],i=t==="request"?_v.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&La(n)){let d={},u={...n};for(let p of s)d[p]=n[p],delete u[p];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(Vh,"liftWireOnlyMaterial");function Gh(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(Gh,"codecResultValidator");function Tf(e){return()=>e}o(Tf,"requestStateAccessor");var bv=Tf(void 0),vv,Cv=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{vv=o((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Nr,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 pe(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 pe(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),Ba(s)||wf(s)?this._onresponse(s):Sf(s)?this._onrequest(s,i):Rf(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 pe(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}=Vh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Hh(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(ja(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}=Vh(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((w,S,R)=>{let v={jsonrpc:"2.0",id:r.id,error:{code:w,message:S,...R!==void 0&&{data:R}}};i?.send(v).catch(x=>this._onerror(new Error(`Failed to send an error response: ${x}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=Hh(t.classification);if(w!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${s.era}`));let S=t.classification.revision??w;a(I.UnsupportedProtocolVersion,`Unsupported protocol version: ${S}`,{supported:this._supportedProtocolVersions,requested:S});return}}if(Na(r.method)&&!s.hasRequestMethod(r.method)&&!(Bh(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(I.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(I.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(n);if(d!==void 0){a(I.InvalidParams,d);return}let u=o((w,S)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...S,relatedRequestId:r.id}),"sendNotification"),p=o((w,S,R)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,S,{...R,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:Iv(n.inputResponses),y={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?bv:Tf(n.requestState),signal:h.signal,send:o(((w,S,R)=>{let v=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(v,w.method),Fa(S))return p(w,S,R);let x=Gh(v,w.method);if(x===void 0)throw new TypeError(`'${w.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(w,x,S)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(y,t);Promise.resolve().then(()=>c(r,b)).then(async w=>{if(h.signal.aborted)return;let S;try{S=s.encodeResult(r.method,w,this._outboundServerInfo())}catch(v){this._onerror(new Error(`Failed to encode result for ${r.method}: ${v}`)),a(I.InternalError,"Internal error");return}let R={result:S,jsonrpc:"2.0",id:r.id};await i?.send(R)},async w=>{if(h.signal.aborted)return;let S=Number.isSafeInteger(w.code)?w.code:I.InternalError,R={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(S),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await i?.send(R)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).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),Ba(e)?r(e):r(Re.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(Fa(t))return Bh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=Gh(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 No(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Rv(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Na(t)&&!e.hasRequestMethod(t))throw new pe(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,p;return new Promise((h,f)=>{let y=o(O=>{f(O)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(O){y(O);return}if(n?.signal?.aborted){let O=n.signal.reason;throw O instanceof pe?O:new pe(Se.RequestTimeout,String(O))}let b=e.era===ec&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;p=w;let S={...t,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),S.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let R=this._envelopeOutbound(S),v=!1,x=o(O=>{v||(this._progressHandlers.delete(w),b===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(L=>this._onerror(new Error(`Failed to send cancellation: ${L}`))):b.abort(),f(O instanceof pe?O:new pe(Se.RequestTimeout,String(O))))},"cancel");this._responseHandlers.set(w,O=>{if(n?.signal?.aborted)return;if(v=!0,O instanceof Error)return f(O);let L;try{L=e.decodeResult(t.method,O.result)}catch(P){return f(P instanceof Error?P:new Error(String(P)))}if(L.kind==="invalid")return f(L.error);if(L.kind==="input_required"){if(n?.allowInputRequired===!0)return h(Tv(L));let P={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:d,retry:o(($,j)=>this._requestWithSchemaViaCodec(e,$===void 0?{method:t.method}:{method:t.method,params:$},r,j),"retry")};return h(this._resolveNonCompleteResult(L,P))}let Q=L.result;Da(r,Q).then(P=>{P.success?h(P.data):f(new pe(Se.InvalidResult,`Invalid result for ${t.method}: ${P.error}`))},f)}),u=o(()=>x(n?.signal?.reason),"onAbort"),n?.signal?.addEventListener("abort",u,{once:!0});let N=n?.timeout??If,T=o(()=>x(new pe(Se.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(w,N,n?.maxTotalTimeout,T,n?.resetTimeoutOnProgress??!1),this._transport.send(R,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:b?.signal}).catch(O=>{this._progressHandlers.delete(w),f(O)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),p!==void 0&&(this._responseHandlers.delete(p),this._cleanupTimeout(p))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new pe(Se.NotConnected,"Not connected");if(ja(t.method)&&!e.hasNotificationMethod(t.method))throw new pe(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(!Na(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 Re(I.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 Da(t.params,{...s.params});if(!a.success)throw new Re(I.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(!ja(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 Re(I.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 Da(t.params,{...n.params});if(!s.success)throw new Re(I.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function La(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(La,"isPlainObject$1");function Kh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Kh,"isPlainObject");function Iv(e){let t={},r=[];if(!Kh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!Kh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(Iv,"partitionInputResponses");function Tv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(Tv,"manualInputRequiredValue");var Ev=qh((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(";"),p=u!==-1?d.slice(0,u).trim():d.trim();if(!n.test(p))throw new TypeError("invalid media type");var h=new a(p.toLowerCase());if(u!==-1){var f,y,b;for(t.lastIndex=u;y=t.exec(d);){if(y.index!==u)throw new TypeError("invalid parameter format");u+=y[0].length,f=y[1].toLowerCase(),b=y[2],b.charCodeAt(0)===34&&(b=b.slice(1,-1),b.indexOf("\\")!==-1&&(b=b.replace(r,"$1"))),h.parameters[f]=b}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")})),gU=Nh(Ev(),1);var kv=10*1024*1024;var Av=new Set([301,302,303,307,308]),Pv=5;function xv(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(xv,"isWithinOrigin");function Ov(e,t){let r=Av.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Ov,"redirectTarget");var Mv=new WeakSet;function di(e){return Mv.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=Ov(s,a);if(!c||i===Pv)return a;let d=new URL(s),u=n==="GET"||a.status===307||a.status===308,p=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!p||!xv(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(di,"fetchWithinOrigin");function nc(){Ka(),Rt(),_b(),Hb(),Yb()}o(nc,"preloadSchemas");var kU=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 Uv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,qv=[0,31,28,31,30,31,30,31,31,30,31,30,31],zv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Nv=/^(?=.{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,jv=/^(?:[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,Dv=/^(?:(?:[^\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,Lv=/^(?:(?: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,$v=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Hv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Bv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Fv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Jv=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"),Vv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Gv=/^((([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,Kv=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 mt(e){return e.test.bind(e)}o(mt,"bind");var AU={date:Ef,time:kf.bind(void 0,!1),"date-time":Yv,duration:Kv,uri:eC,"uri-reference":mt(jv),"uri-template":mt(Dv),url:mt(Lv),email:Jv,hostname:mt(Nv),ipv4:mt(Vv),ipv6:mt(Gv),regex:rC,uuid:mt($v),"json-pointer":mt(Hv),"json-pointer-uri-fragment":mt(Bv),"relative-json-pointer":mt(Fv)};function Wv(e){return e%4===0&&(e%100!==0||e%400===0)}o(Wv,"isLeapYear");function Ef(e){let t=e.match(Uv);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&Wv(r)?29:qv[n])}o(Ef,"date");function kf(e,t){let r=t.match(zv);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(kf,"time");var Zv=/t|\s/i;function Yv(e){let t=e.split(Zv);return t.length==2&&Ef(t[0])&&kf(!0,t[1])}o(Yv,"date_time");var Xv=/\/|:/,Qv=/^(?:[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 eC(e){return Xv.test(e)&&Qv.test(e)}o(eC,"uri");var tC=/[^\\]\\Z/;function rC(e){if(tC.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(rC,"regex");nc();var Af=!1;var oc;oc=globalThis.crypto;async function oC(e){return(await oc).getRandomValues(new Uint8Array(e))}o(oC,"getRandomValues");async function sC(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await oC(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(sC,"random");async function iC(e){return await sC(e)}o(iC,"generateVerifier");async function aC(e){let t=await(await oc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(aC,"generateChallenge");async function sc(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await iC(e),r=await aC(t);return{code_verifier:t,code_challenge:r}}o(sc,"pkceChallenge");var Lo=class extends Error{static{o(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Fe(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 Fe(this,e)}constructor(e){super(e),this.name=new.target.name,mr(this,new.target)}},Do=class extends Lo{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}},uc=class extends Lo{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}},pi=class extends Lo{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}},li=class extends Lo{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}},Sq=class extends Lo{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 dc(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}):Mf(e.issuer,t)?e:void 0}o(dc,"discardIfIssuerMismatch");function Mf(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(Mf,"issuersMatch");var Rq=class extends Error{static{o(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Fe(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 Fe(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",mr(this,new.target)}};function Uf(e){return e?.authorization_response_iss_parameter_supported===!0}o(Uf,"isIssParameterSupported");function qf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Do("authorization_response",t,void 0);return}if(e!==t)throw new Do("authorization_response",t,e)}}o(qf,"validateAuthorizationResponseIssuer");function cC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(cC,"isClientAuthMethod");var ic="code",ac="S256";function dC(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&cC(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(dC,"selectClientAuthMethod");function uC(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":lC(s,i,r);return;case"client_secret_post":pC(s,i,n);return;case"none":mC(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(uC,"applyClientAuthentication");function lC(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(lC,"applyBasicAuth");function pC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(pC,"applyPostAuth");function mC(e,t){t.set("client_id",e)}o(mC,"applyPublicAuth");function zf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(zf,"isLoopbackHost");function hC(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!zf(t.hostname))throw new pi(t.href);return t}o(hC,"assertSecureTokenEndpoint");function fC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||zf(r.hostname))return"native"}return"web"}o(fC,"deriveApplicationType");function gC(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??fC(t.redirect_uris)}}o(gC,"resolveClientMetadata");async function Pf(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Ds.parse(JSON.parse(r));return Nt.fromResponse(n)}catch(n){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Nt(me.ServerError,s)}}o(Pf,"parseErrorResponse");function xf(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(xf,"warnCredentialInvalidation");async function lc(e,t){try{return await cc(e,t)}catch(r){if(r instanceof Nt){if(r.code===me.InvalidClient||r.code===me.UnauthorizedClient)return xf(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await cc(e,t);if(r.code===me.InvalidGrant||r.code===me.InvalidDpopProof)return xf(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await cc(e,t)}throw r}}o(lc,"auth");function yC(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(yC,"determineScope");async function cc(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=gC(e),p=await e.discoveryState?.(),h,f,y,b,w=i;if(!w&&p?.resourceMetadataUrl&&(w=new URL(p.resourceMetadataUrl)),p?.authorizationServerUrl){if(f=p.authorizationServerUrl,h=p.resourceMetadata,y=p.authorizationServerMetadata??await Lf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await jf(t,{resourceMetadataUrl:w},a)}catch(B){if(B instanceof TypeError)throw B}(y!==p.authorizationServerMetadata||h!==p.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:w?.toString(),resourceMetadata:h,authorizationServerMetadata:y})}else{let B=await CC(t,{resourceMetadataUrl:w,fetchFn:a,skipIssuerMetadataValidation:c});f=B.authorizationServerUrl,y=B.authorizationServerMetadata,h=B.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:w?.toString(),resourceMetadata:h,authorizationServerMetadata:y}}let S=y?.issuer??String(f),R={issuer:S};if(await e.saveAuthorizationServerUrl?.(S),r!==void 0){let B=p?.authorizationServerMetadata?.issuer??p?.authorizationServerUrl;if(B===void 0){if(e.saveDiscoveryState!==void 0)throw new li("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",S);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(!Mf(B,S))throw new li(B,S)}b&&await e.saveDiscoveryState?.(b);let v=await SC(t,e,h),x=v&&h&&!e.validateResourceURL?h.resource:v;x&&await e.saveResourceUrl?.(mc(x));let N=yC({requestedScope:s,resourceMetadata:h,authServerMetadata:y,clientMetadata:e.clientMetadata}),T=await Promise.resolve(e.clientInformation(R)),O=dc(T,S,{canPersistStamp:e.saveClientInformation!==void 0});if(O===void 0&&T?.issuer&&e.saveClientInformation===void 0)throw new li(T.issuer,S);if(O&&O.issuer===void 0&&(O={...O,issuer:S},await e.saveClientInformation?.(O,R)),!O){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let B=y?.client_id_metadata_document_supported===!0,ee=e.clientMetadataUrl;if(ee&&!pc(ee))throw new Nt(me.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ee}`);if(B&&ee)O={client_id:ee,issuer:S},await e.saveClientInformation?.(O,R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");O={...await AC(f,{metadata:y,clientMetadata:u,scope:N,fetchFn:a}),issuer:S},await e.saveClientInformation(O,R)}}let L=!e.redirectUrl;if(r!==void 0||L){r!==void 0&&qf({iss:n,expectedIssuer:y?.issuer,issParameterSupported:Uf(y)});let B=await kC(e,f,{metadata:y,resource:x,authorizationCode:r,iss:n,scope:N,fetchFn:a});return await e.saveTokens({...B,issuer:S},R),"AUTHORIZED"}let Q=dc(await e.tokens(R),S);if(Q&&Q.issuer===void 0&&(Q={...Q,issuer:S},await e.saveTokens(Q,R)),Q?.refresh_token&&!d){let B;try{B=await EC(f,{metadata:y,clientInformation:O,refreshToken:Q.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(ee){if(ee instanceof pi||!(!(ee instanceof Nt)||ee.code===me.ServerError))throw ee}if(B)return await e.saveTokens({...B,issuer:S},R),"AUTHORIZED"}let P=e.state?await e.state():void 0,{authorizationUrl:$,codeVerifier:j}=await IC(f,{metadata:y,clientInformation:O,state:P,redirectUrl:e.redirectUrl,scope:N,resource:x});return await e.saveCodeVerifier(j),await e.redirectToAuthorization($),"REDIRECT"}o(cc,"authInternal");function pc(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(pc,"isHttpsUrl");async function SC(e,t,r){let n=Zh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ii({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(SC,"selectResourceURL");var RC=new Set(["bearer","dpop"]);function Nf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!RC.has(r.toLowerCase())||!n)return{};let s=ui(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=ui(e,"scope")||void 0,c=ui(e,"error")||void 0,d=ui(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}o(Nf,"extractWWWAuthenticateParams");function ui(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(ui,"extractFieldFromWwwAuth");async function jf(e,t,r=fetch){let n=await bC(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 $r.parse(await n.json())}o(jf,"discoverOAuthProtectedResourceMetadata");async function Df(e,t,r=fetch){let n=di(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Af)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(Df,"fetchWithCorsRetry");function wC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(wC,"buildWellKnownPath");async function Of(e,t,r=fetch){return await Df(e,{"MCP-Protocol-Version":t},r)}o(Of,"tryMetadataDiscovery");function _C(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(_C,"shouldAttemptFallback");async function bC(e,t,r,n){let s=new URL(e),i=n?.protocolVersion??Us,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let d=wC(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await Of(a,i,r);return!n?.metadataUrl&&_C(c,s.pathname)&&(c=await Of(new URL(`/.well-known/${t}`,s),i,r)),c}o(bC,"discoverMetadataWithFallback");function vC(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(vC,"buildDiscoveryUrls");async function Lf(e,{fetchFn:t=fetch,protocolVersion:r=Us,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=vC(e);for(let{url:a,type:c}of i){let d=await Df(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"?Hr.parse(await d.json()):Br.parse(await d.json());if(!n){let p=typeof e=="string"?e:e.href;if(!(u.issuer===p||p.endsWith("/")&&u.issuer===p.slice(0,-1)))throw new Do("metadata",p,u.issuer)}return u}}o(Lf,"discoverAuthorizationServerMetadata");async function CC(e,t){let r,n;try{r=await jf(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 Lf(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(CC,"discoverOAuthServerInfo");function mc(e){return typeof e=="string"?e:e.href}o(mc,"resourceIndicatorToString");async function IC(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(ic))throw new Error(`Incompatible auth server: does not support response type ${ic}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ac))throw new Error(`Incompatible auth server: does not support code challenge method ${ac}`)}else c=new URL("/authorize",e);let d=await sc(),u=d.code_verifier,p=d.code_challenge;return c.searchParams.set("response_type",ic),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",ac),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",mc(a)),{authorizationUrl:c,codeVerifier:u}}o(IC,"startAuthorization");function TC(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(TC,"prepareAuthorizationCodeRequest");async function $f(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=hC(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",mc(i)),!s&&n&&uC(dC(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let p=o(async()=>{let y=new Headers(u);return s&&await s(y,r,d,t),a&&y.set("DPoP",await a.buildProof({htm:"POST",htu:d})),di(c??fetch)(d,{method:"POST",headers:y,body:r})},"requestOnce"),h=await p();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===me.UseDpopNonce&&(a.observeNonce(h,d),h=await p()),a?.observeNonce(h,d),!h.ok)throw await Pf(h);let f=await h.json();try{return Ot.parse(Ga(f))}catch(y){throw typeof f=="object"&&f!==null&&"error"in f?await Pf(JSON.stringify(f)):y}}o($f,"executeTokenRequest");async function EC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await $f(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(EC,"refreshAuthorization");async function kC(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&qf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Uf(r)});let d=r?.issuer??String(t),u=o(async()=>{let y=await e.clientInformation({issuer:d}),b=dc(y,d,{canPersistStamp:!1});if(y&&b===void 0)throw new li(String(y.issuer),d);return b},"readClientInformation"),p=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=TC(s,await e.codeVerifier(),e.redirectUrl)}return p??=await u(),$f(t,{metadata:r,tokenRequestParams:f,clientInformation:p,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(kC,"fetchToken");async function AC(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 di(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new uc({status:c.status,body:await c.text(),submittedMetadata:a});return dr.parse(Ga(await c.json()))}o(AC,"registerClient");var wq=class extends Error{static{o(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Fe(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 Fe(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,mr(this,new.target)}};function we(e){let t=cr.safeParse(e);return t.success?t.data.id:void 0}o(we,"parseJsonRpcRequestId");function hc(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return we(t)}catch{return}}o(hc,"readJsonRpcRequestIdFromBody");function Pe(e){return bo.parse({jsonrpc:ar,...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(Pe,"jsonRpcErrorResponse");function Hf(e){return new ci([js.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o(Hf,"urlElicitationRequiredError");var fc=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],$o=[ur,...fc],PC=0,xC="private",OC="0.0.0";function MC(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(MC,"buildGatewayDiscoverCapabilities");function gc(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??OC,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}o(gc,"buildGatewayDiscoverServerInfo");function Bf(e){let t=we(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...e.supportedVersions??$o],capabilities:MC(e.capabilityFilter),_meta:{[Mt]:gc({connection:e.connection,icons:e.icons})},ttlMs:PC,cacheScope:xC}})}o(Bf,"gatewayDiscoverResponse");var UC=/^\d{4}-\d{2}-\d{2}$/;var hi="2026-07-28",Ho;function qC(){return Ho??=new Map,Ho}o(qC,"store");function mi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(mi,"isRecord");function Ff(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string"&&UC.test(r)))].slice(0,32);return t.length===0?void 0:t}o(Ff,"readVersionList");function fi(e,t){if(!mi(t))return;if(e==="server/discover"&&mi(t.result))return Ff(t.result.supportedVersions);let r=t.error;if(mi(r)&&r.code===-32022&&mi(r.data))return Ff(r.data.supported)}o(fi,"readUpstreamSupportedVersions");function gi(e,t,r={}){let n=qC(),s=n.get(e),i=t.some(d=>d<hi),a=r.modernOnly===!0||s?.modernOnly===!0&&!i,c=!i&&!a&&s?.complete===!0?s.versions.filter(d=>d<hi):[];if(n.delete(e),n.set(e,{versions:[...t,...c],complete:a||i||c.length>0,modernOnly:a}),n.size>512){let d=n.keys().next().value;d!==void 0&&n.delete(d)}}o(gi,"recordUpstreamSupportedVersions");function yi(e,t){let r=e===void 0?void 0:Ho?.get(e);if(r===void 0)return t;let n=t.filter(s=>r.versions.includes(s));return n.length===0?t:r.complete?n:t.filter(s=>s<hi||n.includes(s))}o(yi,"advertisedSupportedVersions");function Jf(e){let t=Ho?.get(e);t?.modernOnly===!0&&Ho?.set(e,{versions:t.versions,complete:t.versions.some(r=>r<hi),modernOnly:!1})}o(Jf,"recordUpstreamAcceptsInitialize");var zC=-32e3,NC="2025-11-25",jC=/^\d{4}-\d{2}-\d{2}$/,Sc=I.InternalError;function yc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yc,"isRecord");function DC(e,t){return typeof e=="string"&&jC.test(e)&&e>=t}o(DC,"isAtLeast");function LC(e){if(e.method!=="initialize")return!1;let t=yc(e.params)?e.params:void 0,n=(yc(t?.capabilities)?t.capabilities:void 0)?.elicitation,s=t?.protocolVersion;return DC(s,NC)&&!Co(s)&&yc(n)&&n.url!==void 0}o(LC,"acceptsUrlElicitation");function Rc(e){let{payload:t}=e,r=t.authUrl===void 0||!e.urlElicitation?void 0:Hf({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Pe({...e.id===void 0?{}:{id:e.id},error:{code:r?.code??e.fallbackCode,message:t.message,data:{...r?.data??{},connectRequired:t}}})}o(Rc,"legacyConnectRequiredError");function Vf(e,t){let r=Vr(e,t);if(r!==void 0)return{kind:"invalid",error:r};let n=e,s=we(e);return s===void 0?{kind:"accepted",response:typeof n.method!="string"}:{kind:"request",id:s,message:n}}o(Vf,"classifyMessage");function on(e,t){return Response.json(Pe({error:{code:e,message:t}}),{status:400})}o(on,"unidentifiedError");function Gf(){return new Response(null,{status:202})}o(Gf,"acceptedResponse");function $C(e,t){return te()?jm(e,t):void 0}o($C,"modernBatchVersion");function HC(e,t){let r=e.get("mcp-protocol-version"),n=$C(e,t)??(Hs(r)?r??void 0:void 0);return n===void 0?void 0:on(I.InvalidRequest,`Invalid Request: protocol version ${n} does not support JSON-RPC batches`)}o(HC,"batchRefusal");function Kf(e,t,r){let n=(Array.isArray(t)?t:[t]).filter(i=>Vr(i)===void 0);if(n.length===0)return;if(n.some(wm))return n.length>1?on(I.InvalidRequest,"Invalid Request: Only one initialization request is allowed"):void 0;let s=e.get("mcp-protocol-version");if(!(s===null||r.accepted(s)))return on(zC,`Bad Request: Unsupported protocol version: ${s} (supported versions: ${r.listed.join(", ")})`)}o(Kf,"transportVersionRefusal");function Wf(e,t){return Kf(e,t,{accepted:o(r=>Nr.includes(r),"accepted"),listed:Nr})}o(Wf,"handlerTransportVersionRefusal");function BC(e,t,r){let n=yi(r,te()?$o:fc);return Kf(e,t,{accepted:o(s=>n.includes(s)||te()&&s===ur,"accepted"),listed:n})}o(BC,"gatewayTransportVersionRefusal");function FC(e){return{jsonrpc:"2.0",id:e,result:{}}}o(FC,"pingResult");function Zf(e){if(e.parsed===void 0)return on(I.ParseError,"Parse error: Invalid JSON");let t=Array.isArray(e.parsed)?HC(e.headers,e.parsed):void 0;if(t!==void 0)return t;let r=BC(e.headers,e.parsed,e.payload.upstreamServerId);if(r!==void 0)return r;let n=o(i=>i.message.method==="ping"?FC(i.id):Rc({id:i.id,payload:e.payload,urlElicitation:LC(i.message),fallbackCode:Sc}),"answer");if(Array.isArray(e.parsed)){if(e.parsed.length===0)return on(I.InvalidRequest,"Invalid Request: empty batch");let i=e.parsed.map((c,d)=>Vf(c,d)),a=i.flatMap(c=>{switch(c.kind){case"request":return[n(c)];case"invalid":return[c.error];case"accepted":return[]}});return i.every(c=>c.kind==="invalid")?Response.json(a,{status:400}):a.length===0?Gf():Response.json(a)}let s=Vf(e.parsed);switch(s.kind){case"request":return Response.json(n(s));case"accepted":return s.response&&te()&&Co(e.headers.get("mcp-protocol-version"))?on(I.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):Gf();case"invalid":return Response.json(s.error,{status:400})}}o(Zf,"legacyConnectRequiredResponse");function xe(){return zr.instance.build.COMPATIBILITY_FLAGS.mcpGatewaySpecCompliance===!0}o(xe,"isMcpGatewaySpecComplianceEnabled");var JC={Allow:"POST"};function Si(e,t){return Ne.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},JC)}o(Si,"gatewayMethodNotAllowed");function We(e){return(e??"").split(";")[0].trim().toLowerCase()}o(We,"mediaTypeEssence");var VC=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function wt(e){for(let t of VC)e.delete(t);return e}o(wt,"deleteEncodedBodyHeaders");function Yf(){let e=zr.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(Yf,"currentRuntime");var GC=new Set(["gzip","x-gzip","deflate","br","zstd"]);function ht(e,t=Yf()){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=>GC.has(n.trim()))}}o(ht,"isBodyStillEncoded");function Xf(e){return ht(e)?e:wt(e)}o(Xf,"deleteEncodedBodyHeadersIfDecoded");function Qf(e,t=Yf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?ht(e,t):e.has("content-length"))?e:wt(e)}o(Qf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var tg=10*1024*1024,KC=1024,WC=32,ZC=64,hr=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")}},YC=10;function XC(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o(XC,"handleRejection");function rg(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(rg,"fieldName");var fr=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=[];#R;#w;#_;#b=[];constructor(t={}){let r=t.maxEventChars??tg;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)===YC&&(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>=ZC&&(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 hr(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>KC&&(this.#g+=Math.max(0,WC-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.#R=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#_=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.#R,id:this.#w,retry:this.#_,comments:this.#b,terminated:r}),this.#x()}#x(){this.#c=[],this.#g=0,this.#y=[],this.#R=void 0,this.#w=void 0,this.#_=void 0,this.#b=[]}};function wc(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}o(wc,"assertSingleLine");function _c(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??[])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}
29
+ `:r}let t="";for(let r of e.comments??[])wc("comment",r),t+=`:${r}
30
+ `;if(e.event!==void 0&&(wc("event",e.event),t+=`event: ${e.event}
31
+ `),e.id!==void 0){if(wc("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(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?`
35
+ `}o(_c,"serializeSseEvent");var QC=new Set(["data","event","id","retry"]);function ng(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!QC.has(rg(t)))}o(ng,"hasUnknownSseFields");function Fo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>rg(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
36
+ `)}}o(Fo,"replaceSseData");var og=Symbol("sse.terminate");function vc(...e){return{[og]:!0,events:e}}o(vc,"terminateSse");function eI(e){return typeof e=="object"&&e!==null&&og in e}o(eI,"isTerminate");var tI=64,eg=new Uint8Array(0),bc=class{static{o(this,"SseRawEventBytes")}#e=eg;#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>=tI&&this.#l())}take(){let t;return this.#r===0?t=sI(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=eg,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}},Bo=10,Ri=13,rI=[239,187,191];function nI(e){let t=[],r=0;for(let n=0;n<e.length;n++){let s=e[n];(s===Bo||s===Ri&&e[n+1]!==Bo)&&(t.push(e.subarray(r,n+1)),r=n+1)}return r<e.length&&t.push(e.subarray(r)),t}o(nI,"splitLines");function oI(e){let t=e[e.length-1];return t===Bo||t===Ri}o(oI,"endsLine");function Cc(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??tg,a=new fr(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}},p=e.getReader(),h=!1,f=!1,y=0,b=new bc,w=0,S=!1,R,v,x=o(P=>{h=!0,d.abort(P),p.cancel(P).catch(()=>{})},"stop"),N=o((P,$)=>{try{XC(r.onFailure?.(P,$),()=>{})}catch{}},"report"),T=o(P=>{N(P,{mode:n,kind:"oversize",...P.comment?{comment:!0}:{}})},"reportOversize"),O=o(P=>{if(!("lines"in P))return _c(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($=>$.charCodeAt(0)===58)?_c({...P,terminated:!1}):_c(P)},"write"),L=o((P,$)=>eI(P)?{text:P.events.map(O).join(""),terminate:!0}:P===void 0?{text:$===void 0?"":O($),terminate:!1}:P===null?{text:"",terminate:!1}:{text:(Array.isArray(P)?P:[P]).map(O).join(""),terminate:!1},"render"),Q=o(P=>{if(!s)try{return a.push(P).map(j=>({event:j}))}catch(j){throw j instanceof hr&&T(j),j}let $=[];for(let j of nI(P)){if(S&&(S=!1,j[0]===Bo)){a.push(j),y+=j.length,$.push({raw:j,atStart:!1});continue}let B=a.discardedEvents,ee=a.discardedComments,Ue=a.discarding;!Ue&&b.length===0&&(w=y),y+=j.length;for(let De of a.push(j))$.push({event:De});Ue?($.push({raw:j,atStart:!1}),S=!a.discarding&&j[j.length-1]===Ri):a.discardedEvents>B?(T(new hr(i,a.discardedComments>ee)),b.push(j),$.push({raw:b.take(),atStart:w===0}),S=!a.discarding&&j[j.length-1]===Ri):oI(j)&&a.idle?b.clear():b.push(j)}return $},"parse");return new ReadableStream({async pull(P){if(v!==void 0){P.error(v.error);return}try{for(;;){let $=await p.read();if(h)return;let j,B=!1,ee=!1;if($.done){j=[],ee=s&&a.discarding;let Y=a.discardedEvents,le=a.discardedComments,qe;try{qe=a.end()}catch(oe){throw oe instanceof hr&&T(oe),oe}for(let oe of qe)oe.terminated?j.push({event:oe}):B=!0;a.discardedEvents>Y&&b.length>0&&(T(new hr(i,a.discardedComments>le)),j.push({raw:b.take(),atStart:w===0}),ee=!0),b.clear(),B||=ee}else j=Q($.value);let Ue=!1,De=o(Y=>{Y.length>0&&(P.enqueue(Y),Ue=!0,f=!0)},"enqueue"),Ge=o(Y=>{Y!==""&&De(c.encode(Y))},"emit");for(let Y of j){if("raw"in Y){!f&&!Y.atStart&&rI.every((oe,tt)=>Y.raw[tt]===oe)&&Ge(`
37
+ `),De(Y.raw.slice()),R=Y.raw[Y.raw.length-1];continue}let{event:le}=Y,qe;try{let oe=await t(le,u);if(h)return;qe=L(oe,le)}catch(oe){if(h)return;if(N(oe,{mode:n,kind:"transform",event:le}),n==="closed")throw oe;qe={text:O(le),terminate:!1}}if(Ge(qe.text),qe.terminate){x("SSE stream terminated by its rewriter"),P.close();return}}if($.done){if(r.end!==void 0){let Y;try{let le=await r.end({...u,unterminated:B});if(h)return;Y=L(le,void 0)}catch(le){if(h)return;if(N(le,{mode:n,kind:"end"}),n==="closed")throw le;Y={text:"",terminate:!1}}if(ee&&Y.text!==""&&Ge(R===Bo?`
38
38
  `:`
39
39
 
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>
40
+ `),Ge(Y.text),Y.terminate){x("SSE stream terminated by its rewriter"),P.close();return}}h=!0,P.close();return}if(Ue)return}}catch($){h||(x($),(P.desiredSize??0)<0?v={error:$}:P.error($))}},cancel(P){if(!h)return h=!0,d.abort(P),p.cancel(P)}},{highWaterMark:0})}o(Cc,"rewriteSseStream");function sI(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(sI,"concatBytes");function wi(e,t,r){if(e.body===null)return e;let n=wt(new Headers(e.headers));return n.set("content-type","text/event-stream"),new Response(Cc(e.body,t,r),{status:e.status,statusText:e.statusText,headers:n})}o(wi,"rewriteSseResponse");var ag=new Set(["jsonrpc","method","id","params"]),Ec=new Set(["name","uri","ref"]),cg=new Set(["type","name","uri"]),iI="subscriptions/listen",kc="notifications",dg="resourceSubscriptions",aI=new Set([...Ec,_t(kc)]),cI=new Set([_t(dg)]),dI=/[^\u0000-\u007f]/,uI=34,lI=92,sg=123,pI=125,mI=91,hI=93,fI=58,Ic=44;function Jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Jo,"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 ig(e,t){let r=_t(t);return Object.keys(e).some(n=>n!==t&&_t(n)===r)}o(ig,"hasCaseVariantOf");function gI(e,t){let r=o(a=>{switch(a.role){case"member":return ag;case"params":return t.has(a.member)?aI:Ec;case"ref":return cg;case"notifications":return cI;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===kc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===uI){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let p=0;for(;e.charCodeAt(d-1-p)===lI;)p++;if(p%2===0)break}let u=s>0?void 0:n.at(-1);if(u?.isObject&&u.expectKey){let p=e.slice(a,d+1),h=p.includes("\\")?JSON.parse(p):p.slice(1,-1);if(dI.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===sg||c===mI){let d=c===sg,u=s>0?void 0:i(d);if(u===void 0)s++;else{let p=n.at(-1)?.member??0;n.push({role:u,isObject:d,seen:new Set,member:p,expectKey:d})}}else if(c===pI||c===hI)s>0?s--:n.pop();else if(s===0&&(c===fI||c===Ic)){let d=n.at(-1);d?.isObject?d.expectKey=c===Ic:d?.role==="batch"&&c===Ic&&d.member++}}return!1}o(gI,"hasUnsafeKeyInText");function ug(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(Jo(s)){if(Tc(s,ag)||e.checksListen===!0&&s.method===iI&&(t.add(r),Jo(s.params)&&(ig(s.params,kc)||Jo(s.params.notifications)&&ig(s.params.notifications,dg))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!Jo(s.params))&&(Tc(s.params,Ec)||Jo(s.params.ref)&&Tc(s.params.ref,cg)))return!0}}return gI(e.text,t)}o(ug,"hasAmbiguousIdentifyingKeys");var yI=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),SI=47,lg=44,RI=38,Ac=o(e=>e!==SI&&e!==lg,"VALUE"),wI=o(e=>!yI(e),"ANY"),_I=o(e=>e!==RI,"QUERY_VALUE"),bI=["+","#",".","/","?","&"],Pc=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(Ac),!t)return;let r=this.current,n=this.#e();this.edges[r].push({test:o(s=>s===lg,"test"),to:n}),this.edges[n].push({test:Ac,to:r})}};function pg(e){let t=new Pc,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=bI.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,p)=>{t.literal(`${p===0?a:"&"}${u}=`),t.plus(_I)});break;case"+":case"#":t.plus(wI);break;case".":t.literal("."),t.plus(Ac);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(pg,"compileUriTemplate");function mg(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 p of r[u])s[p.to]!==a&&p.test(c)&&(s[p.to]=a,d.push(p.to));if(d.length===0)return!1;i=d}return i.includes(n)}o(mg,"matchesUriTemplate");var Ii=m.record(m.string(),m.unknown()),vI=m.record(m.string(),m.unknown()),jt=m.array(m.string().min(1)).min(1).optional(),CI=m.object({name:m.string().min(1),description:m.string().min(1).optional(),annotations:vI.optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),II=m.object({name:m.string().min(1),description:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),TI=m.object({uri:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),EI=m.object({uriTemplate:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),kI=m.array(m.union([m.string(),CI])),AI=m.array(m.union([m.string(),II])),PI=m.array(m.union([m.string(),TI])),xI=m.array(m.union([m.string(),EI])),OI=m.object({module:m.unknown(),export:m.string().min(1)}).strict(),MI=m.object({mode:m.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:m.string().min(1).optional(),groupClaim:m.string().min(1).optional(),identifier:OI.optional()}).strict(),UI=m.object({tools:kI.optional(),prompts:AI.optional(),resources:PI.optional(),resourceTemplates:xI.optional(),accessControl:MI.optional()}).strict(),bt=[{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 qI(e,t){return Vm(UI,e,`MCP capability filter policy "${t}"`)}o(qI,"parseMcpCapabilityFilterOptions");function H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(H,"isRecord");function je(e){return typeof e.method=="string"?e.method:void 0}o(je,"messageMethod");function Go(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}o(Go,"correlationKey");function vg(e){let t=new Set,r=new Map;for(let n of e){let s=Go(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=Go(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(vg,"createReplyIdMatcher");function hg(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(hg,"asStringArray");function fg(e,t){if(!H(e))return[];let r=t in e?e[t]:t.split(".").reduce((n,s)=>H(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(fg,"readClaimValues");function jc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!H(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:hg(e.roles),groups:hg(e.groups),public:e.public===!0}}o(jc,"normalizeEntry");function zI(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(zI,"isCallerAllowed");function _i(e,t,r,n){if(e===void 0)return;let s=[];for(let i of e){let a=jc(i,t);a!==void 0&&zI(a,r,n)&&s.push(a.key)}return s}o(_i,"allowedKeys");var Cg=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(fg(e.user?.data,n)),a=new Set(fg(e.user?.data,s));return{tools:_i(r.tools,"name",i,a),prompts:_i(r.prompts,"name",i,a),resources:_i(r.resources,"uri",i,a),resourceTemplates:_i(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function NI(e,t){let r=[];for(let n of bt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=jc(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 re(`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(NI,"assertNoConflictingMarkup");function jI(e,t){let r=[];for(let n of bt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=jc(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 re(`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(jI,"assertNoMarkup");function DI(e,t){let r=e.identifier;if(r===void 0)throw new re(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new re(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new re(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let n=r.module[r.export];if(typeof n!="function")throw new re(`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(DI,"buildCustomResolver");function LI(e,t){let r=e.accessControl,n=r?.mode??"allPublic";if(n==="function"){if(r===void 0)throw new re(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return DI(r,t)}if(n==="rolesAndGroups")return NI(e,t),Cg;jI(e,t)}o(LI,"buildCapabilityResolver");function $I(e){let t={};for(let r of bt){let n=e[r.option];if(n===void 0)continue;let s=new Map;for(let i of n){let a=uT(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o($I,"buildProjectionMaps");function Ig(e){return e===void 0?void 0:bt.find(t=>t.listMethod===e)}o(Ig,"findListRule");function Dc(e){return e===void 0?void 0:bt.find(t=>t.directMethods.includes(e))}o(Dc,"findDirectRule");var Ti="completion/complete",Tg=["prompts","resources","resourceTemplates"];function Eg(e){return e===Ti||Dc(e)!==void 0}o(Eg,"isCapabilityMethod");var Ci="subscriptions/listen",HI=[...bt.flatMap(e=>[e.listMethod,...e.directMethods]),Ti,Ci];function BI(e){let t=_t(e.trim()),r=HI.find(n=>_t(n)===t);return r!==void 0&&r!==e?r:void 0}o(BI,"methodVariantOf");function gg(e,[t,r]){return{code:I.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(gg,"invalidParams");function Lc(e){return t=>({code:I.InvalidParams,message:`${e} "${$s(t)}" not found`})}o(Lc,"namedNotFound");function FI(e,t){return{code:Am(t),message:"Resource not found",data:{uri:Ls(e,Pm)}}}o(FI,"resourceNotFound");var JI={legacy:Lc("Tool"),modern:Io.tool},xc={legacy:Lc("Prompt"),modern:Io.prompt},VI={legacy:FI,modern:Io.resource},GI={legacy:Lc("Resource template"),modern:Io.resourceTemplate};function KI(e){let t=je(e);if(t===void 0||!Eg(t))return[];let r=H(e.raw)?e.raw.params:void 0,n=o((d,u)=>H(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=o(d=>H(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==Ti){let d=Dc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:n(r,"uri"),issue:s("params.uri"),notFound:VI}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?JI:xc}]}let i=H(r)?r.ref:void 0,a=H(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:n(i,"name"),issue:["params.ref.name","a string"],notFound:xc}];if(a==="ref/resource"){let d=n(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&WI(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:GI}]}let c=H(r)?H(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Tg,target:void 0,issue:c,notFound:xc}]}o(KI,"capabilityAccesses");function WI(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 ZI(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(WI,"hasTemplateExpression");function ZI(e){return e>32&&e<127?!1:YI.test(String.fromCharCode(e))}o(ZI,"isWhitespaceCode");var YI=/\s/;function XI(e){return e.type==="invalid"&&(!H(e.raw)||e.raw.jsonrpc!=="2.0")}o(XI,"isNonJsonRpcMember");function QI(e){return H(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(QI,"hasNonStringMethod");function kg(e){return e.type==="request"||e.type==="invalid"&&je(e)!==void 0}o(kg,"awaitsReply");function eT(e){return H(e.raw)&&H(e.raw.params)?e.raw.params:void 0}o(eT,"rawParams");function tT(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:te()&&Fr(e.headers,r.raw)}o(tT,"isModernRequest");var yg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Oc="=?base64?",Mc="?=",rT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function nT(e){if(!e.startsWith(Oc)||!e.endsWith(Mc)||e.length<Oc.length+Mc.length)return e;let t=e.slice(Oc.length,e.length-Mc.length);if(rT.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(nT,"decodeMcpHeaderValue");var oT=-32020;function sT(e,t){let r=je(t);if(r===void 0)return;let n=H(t.raw)?t.raw.id:void 0,s=Ko(n)?n:void 0,i=e.headers.get("mcp-protocol-version"),a=Em(t.raw);if(i!==null&&a!==void 0&&i!==a)return bi(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 bi(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(yg,r)?yg[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let p=nT(d);if(p===void 0)return bi(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=eT(t)?.[u];if(typeof h=="string"&&p!==h)return bi(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${p}"`)}o(sT,"headerMismatchResponse");function bi(e,t,r){return st(400,{code:oT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(bi,"mismatchResponse");var iT={code:I.MethodNotFound,message:"Method not found"},Sg={code:I.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},aT={code:I.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},cT="2025-06-18";function Ko(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(Ko,"isValidRequestId");function Ag(e){return H(e.raw)&&!Object.hasOwn(e.raw,"id")}o(Ag,"isSentAsNotification");function Vo(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}o(Vo,"jsonRpcError");function st(e,t,r){return Response.json(Vo(t,r),{status:e})}o(st,"jsonRpcErrorResponse");function vi(e){return st(400,{code:I.InvalidRequest,message:`Invalid Request: ${e}`})}o(vi,"invalidRequestResponse");function Uc(e,t,r=!1){if(Ag(e))return{status:400,body:Vo({code:I.InvalidRequest,message:`Invalid Request: a notification cannot use ${$s(je(e)??"this method")}; send it as a request with an id`})};let n=H(e.raw)?e.raw.id:void 0;return Ko(n)?{status:r&&t.code===I.MethodNotFound?404:200,body:Vo(t,n)}:{status:400,body:Vo({code:I.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}o(Uc,"refusalOf");var Rg=-32e3;function dT(e,t){let r=e.headers.get("accept");if(r===null||!/application\/json/i.test(r))return st(406,{code:Rg,message:"Not Acceptable: Client must accept both application/json and text/event-stream"});if(!bm(e.headers.get("content-type")??void 0))return st(415,{code:Rg,message:"Unsupported Media Type: Content-Type must be application/json"});if(!(t.shape==="batch"&&Hs(e.headers.get("mcp-protocol-version")))){if(t.shape==="single"){let n=Vr(t.messages[0]?.raw);if(n!==void 0)return Response.json(n,{status:400})}return Wf(e.headers,t.shape==="batch"?t.messages.map(n=>n.raw):t.messages[0]?.raw)}}o(dT,"legacyTransportRefusal");function wg(e,t,r=!1,n=!1){let[s]=[...t];if(e.shape!=="batch"){let{status:d,body:u}=Uc(s[0],s[1],r);return Response.json(u,{status:d})}let i=e.protocolVersion;if(i!==void 0&&i>=cT)return vi(`protocol version ${$s(i)} does not support JSON-RPC batches`);let a=0,c=e.messages.flatMap((d,u)=>{let p=n?Vr(d.raw,u):void 0;if(p!==void 0)return a+=1,[p];if(d.type==="result"||d.type==="error"||Ag(d))return[];let h=H(d.raw)?d.raw.id:void 0;return n&&!t.has(d)&&je(d)==="ping"&&Ko(h)?[{jsonrpc:"2.0",id:h,result:{}}]:[Uc(d,t.get(d)??aT).body]});if(c.length===0){let{status:d,body:u}=Uc(s[0],s[1]);return Response.json(u,{status:d})}return Response.json(c,{status:a===e.messages.length?400:200})}o(wg,"refusalResponse");function uT(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!H(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(uT,"buildProjection");function _g(e){let t=e.base[e.property],r=e.overlay[e.property];return H(r)?H(t)?{...t,...r}:r:t}o(_g,"mergeRecordProperty");function lT(e,t){let r={...e,...t.overlay},n=_g({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=_g({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(lT,"applyProjection");var Oe=Symbol("unreadable"),sn=Symbol("dropped");function pT(e,t,r,n,s){let i=e.result;if(!H(i))return Oe;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?Oe:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!H(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(n!==void 0&&!n.has(u))return[];let p=r.get(u);return p===void 0?[]:[lT(d,p)]})}}}o(pT,"filterAndProjectItems");var Pg="resources/read";function mT(e){let t=e.result;return!H(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}o(mT,"withPrivateReadScope");function xg(e,t){let r=Ig(je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(xg,"listTargetOf");function hT(e,t,r){return H(e)&&bt.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(hT,"carriesUnfilteredList");function fT(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(S=>xg(S,r),"listTarget"),d=t.messages.filter(kg),u=new Map;for(let S of d){let R=Go(S.id);R!==void 0&&!u.get(R)&&u.set(R,c(S))}let p=vg(d.map(S=>S.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&je(h)===Pg,y=o(S=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let R=p(S);return R===void 0?void 0:u.get(R)},"targetForReply"),b=o(S=>{if(!H(S))return Oe;if(!("result"in S))return"method"in S&&!("error"in S)?w(S):"error"in S||"method"in S?S:Oe;let R=y(S.id);return R===void 0||hT(S.result,R,r)?Oe:R===null?f?mT(S):S:pT(S,R.rule,R.projections,n?.[R.rule.option],s)},"filterMessage"),w=o(S=>{if(a===void 0)return S;if(S.method==="notifications/resources/updated"){let R=H(S.params)?S.params.uri:void 0;return typeof R=="string"&&!a(R)?sn:S}if(S.method==="notifications/subscriptions/acknowledged"){let R=Ug(S.params,a);return R===void 0?S:{...S,params:R}}return S},"filterServerMessage");return S=>{if(!Array.isArray(S))return b(S);if(t.shape!=="batch")return Oe;let R=S.map(b);if(R.includes(Oe))return Oe;let v=R.filter(x=>x!==sn);return v.length===R.length?R:v.length===0?sn:v}}o(fT,"createReplyFilter");function gT(e){return We(e.headers.get("content-type")).includes("json")}o(gT,"isJsonResponse");function yT(e){return We(e.headers.get("content-type"))==="text/event-stream"}o(yT,"isEventStreamResponse");var ST=10*1024*1024,RT=/^[\w.~:/+=-]{0,256}$/;function wT(e){if(ng(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"&&RT.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(wT,"inspectSseLines");var Og="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",_T="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function zc(e,t){let r=e.messages.filter(kg),n=new Map,s=new Set;for(let u of r){let p=u.id,h=Go(p);p==null||h===void 0||(n.set(h,p),xg(u,t)!==null&&s.add(h))}let i=vg(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:Go(a.id),d=new Set;return{keyOf(u){if(!(!H(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(p=>{let h=n.get(p);return h===void 0?[]:(n.delete(p),d.add(p),[{jsonrpc:"2.0",id:h,error:{code:I.InternalError,message:s.has(p)?Og:_T}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(zc,"createReplyTracker");function Mg(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)?Oe:t(i);c!==sn&&(c!==Oe?(n.push(c),r.answer(a)):r.isPending(a)?n.push(...r.fail([a])):s++)}return{replies:n,dropped:s}}o(Mg,"filterBatchMembers");function bT(e){let{response:t,envelope:r,projectionMaps:n,filterReply:s,warn:i}=e,a=zc(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"),p=o(()=>a.pendingKeys().length===0,"isDone");return wi(t,h=>{let f=wT(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 y;try{y=JSON.parse(f.data)}catch{return d("its data is not JSON")}let b=a.keyOf(y);if(b!==void 0&&a.hasFailed(b))return null;let w=s(y);if(w===sn)return null;if(w===Oe&&r.shape==="batch"&&Array.isArray(y)){let{replies:S,dropped:R}=Mg(y,s,a);if(R>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),S.length===0)return null;let v=Fo(f,JSON.stringify(S));return p()?vc(v):v}if(w===Oe){if(!a.isPending(b))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 S=u(a.fail([b]));return p()?vc(...S):S}for(let S of Array.isArray(w)?w:[w])a.answer(a.keyOf(S));return w===y?f:Fo(f,JSON.stringify(w))},{maxEventChars:ST,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(bT,"filterEventStream");function $c(e){return je(e)===Ci}o($c,"isListenRequest");function vT(e){return te()&&e.messages.some($c)}o(vT,"filtersListen");function Ug(e,t){if(!H(e)||!H(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(Ug,"narrowSubscriptionParams");function CT(e,t,r){let n=!1,s=t.messages.map(a=>{if(!$c(a)||!H(a.raw))return a.raw;let c=Ug(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 xt(e,{headers:i,body:JSON.stringify(t.shape==="batch"?s:s[0])})}o(CT,"narrowListenSubscriptions");var qc=Symbol("access unresolved"),bg=10*1024*1024,qg="the request body could not be read";async function IT(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(),p=d?i.decode():i.decode(u,{stream:!0});if(a+=p.length,c&&=!/\S/.test(p),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}o(IT,"scanBody");function Hc(e){return Array.isArray(e)?`batch member 0: ${Hc(e[0])}`:H(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}o(Hc,"invalidMessageReason");async function TT(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)>bg)return r();let s=We(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(()=>st(400,{code:I.ParseError,message:`Parse error: ${qg}`}),"unreadable"),c;try{c=await IT(e,bg,!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(p){return p instanceof SyntaxError?st(400,{code:I.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=H(d)?d.id:void 0;return st(400,{code:I.InvalidRequest,message:`Invalid Request: ${Hc(d)}`},Ko(u)?u:void 0)}o(TT,"refuseUninspectable");var Nc=class extends Os{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=qI(t,r);super(n,r),this.#r=r,this.#e=$I(n),this.#t=LI(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,pg(i)]))}async handler(t,r){let n=await zm(t);if(n===null)return await TT(t,r)??t;let s=tT(t,n);if(s){let T=n.messages[0],O=T===void 0?void 0:sT(t,T);if(O!==void 0)return O}let i=n.messages.findIndex(XI);if(i!==-1)return vi(`batch member ${i}: ${Hc(n.messages[i].raw)}`);let a=n.messages.findIndex(QI);if(a!==-1)return vi(n.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=qm(n);if(c===void 0)try{c=await t.clone().text()}catch{return st(400,{code:I.ParseError,message:`Parse error: ${qg}`})}if(ug({envelope:n,text:c,isCapabilityMethod:Eg,checksListen:this.#a()}))return vi("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 T of n.messages){let O=je(T),L=O===void 0?void 0:BI(O);L!==void 0&&this.#u(L)&&d.set(T,iT)}let u=vT(n),p=d.size===0&&this.#t!==void 0&&n.messages.some(T=>this.#i(T,u))?await this.#s(t,r):void 0,h=s&&Co(t.headers.get("mcp-protocol-version")),f=!s&&xe();if(d.size===0)for(let T of n.messages){let O=p===qc?this.#i(T,u)?Sg:void 0:this.#m(T,p,h,n.protocolVersion,f);O!==void 0&&d.set(T,O)}if(d.size>0){let T=n.messages[0],O=te()&&(n.shape==="batch"?Ia(t.headers,n.messages.map(B=>B.raw))!==void 0:T!==void 0&&Bs(t.headers,T.raw));if(O){let B=Om(t);if(B!==void 0)return B;if(n.shape==="batch"){let ee=Ia(t.headers,n.messages.map(Ue=>Ue.raw));if(ee!==void 0)return st(ee.status,ee.error)}}let L=H(T?.raw)?T.raw.id:void 0,Q=Ko(L)?L:void 0,P=O&&n.shape==="single"&&T!==void 0?Nm(t.headers,T.raw):void 0;if(P!==void 0)return st(P.status,P.error,Q);let $=O&&n.shape==="single"&&H(T?.raw)&&typeof T.raw.method=="string"?Um(T.raw,{modern:!0,protocolVersion:t.headers.get("mcp-protocol-version"),hasResource:o(()=>!0,"hasResource")}):void 0;return $!==void 0?st(200,$.error,Q):(!s&&!O&&xe()?dT(t,n):void 0)??wg(n,d,s,!s&&f)}if(p===qc)return wg(n,new Map(n.messages.map(T=>[T,Sg])),s);let y=u||s?this.#l(p):void 0,b=y===void 0?t:CT(t,n,y),w=s&&this.#t!==void 0,S=w&&this.#p();if(!this.#h(n,u,S))return b;let R=fT({envelope:n,projectionMaps:this.#e,allowedSets:p,privateScope:w,privateReadScope:S,isResourceVisible:y}),v=o(T=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${T}`),"warn"),x=o((T,O)=>{v(`did not forward an upstream reply (${T}); answered -32603`);let L=zc(n,this.#e),Q=L.fail(L.pendingKeys()),P=wt(new Headers(O.headers));return P.set("content-type","application/json"),Q.length===0?new Response(JSON.stringify(Vo({code:I.InternalError,message:Og})),{status:502,headers:P}):new Response(JSON.stringify(n.shape==="batch"?Q:Q[0]),{status:200,headers:P})},"unreadable");r.addResponseSendingHook(async T=>{let O=!T.ok;if(T.body!==null&&ht(T.headers))return O?T:x("its body is still content-encoded",T);if(yT(T))return bT({response:T,envelope:n,projectionMaps:this.#e,filterReply:R,warn:v});if(!gT(T))return T.ok&&T.status!==202&&T.status!==204&&T.body!==null?x("no or an unknown media type",T):T;let L;try{L=await T.clone().json()}catch{return O?T:x("its body is not JSON",T)}if(O&&!Array.isArray(L)&&!(H(L)&&"result"in L))return T;let Q=R(L);if(Q===Oe&&n.shape==="batch"&&Array.isArray(L)){let $=zc(n,this.#e),{replies:j,dropped:B}=Mg(L,R,$);B>0&&j.push(...$.fail($.pendingKeys())),j.length>0&&(v("did not forward a batch reply member it could not read; sent the rest"),Q=j)}if(Q===Oe||Q===sn)return x("the filter could not read the reply",T);if(Q===L)return T;let P=wt(new Headers(T.headers));return new Response(JSON.stringify(Q),{status:T.status,statusText:T.statusText,headers:P})});let N=new xt(b);return N.headers.set("accept-encoding","gzip, br"),N}#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,i=!1){let a=o(d=>this.#e[d]!==void 0,"isConfigured"),c=o((d,u)=>{let p=r?.[d];return this.#e[d]?.has(u)===!0&&(p===void 0||p.has(u))},"isAllowed");for(let d of KI(t)){if(!(d.refusedBy??d.options).some(a))continue;let{target:u}=d;if(u===void 0)return gg(je(t)??"",d.issue);if(!(d.resource?this.#d(u,c):d.options.filter(a).some(h=>c(h,u)))){let h=je(t),f=H(t.raw)?t.raw.params:void 0,y=i&&h!==void 0?Mm(h,H(f)?f:void 0):void 0;return y!==void 0&&h!==void 0?gg(h,y):n?d.notFound.modern(u):d.notFound.legacy(u,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||!mg(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===Ti?Tg.some(r):Dc(t)?.option==="resources"&&r("resourceTemplates")?!0:bt.some(n=>r(n.option)&&(n.listMethod===t||n.directMethods.includes(t)))}#i(t,r){let n=je(t);return r&&n===Ci&&this.#p()?!0:n!==void 0&&this.#o(n)}#a(){return te()&&this.#p()}#u(t){return t===Ci?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)===Pg)return!0;let i=Ig(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),qc}let i={};for(let a of bt){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 p of d)typeof p=="string"&&c.has(p)&&u.add(p);i[a.option]=u}return i}};var Bc="zuplo.com",ET=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),kT=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function zg(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(zg,"s2FaviconHref");function AT(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(AT,"strictFaviconHref");var Ng=zg(Bc);function Fc(e){let t=e.toLowerCase();return t===Bc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?zg(Bc):AT(e)}o(Fc,"resolveIconHref");function PT(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(PT,"hostnameFromHost");function xT(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(xT,"isLocalOrAddressHost");function OT(e){let t=PT(e).toLowerCase().replace(/\.$/,"");if(xT(t)||kT.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=ET.has(n)?3:2;return r.slice(-s).join(".")}o(OT,"inferFaviconDomain");function Jc(e){return{src:Fc(OT(e)),mimeType:"image/png",sizes:["128x128"]}}o(Jc,"resolveMcpFaviconIcon");function Ei(e){try{return Jc(new URL(e).host)}catch{return}}o(Ei,"resolveMcpFaviconIconFromUrl");var MT=-32020,Vc="(missing)",UT=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"]),jg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Dg="=?base64?",Lg="?=",qT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function zT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(zT,"isRecord");function $g(e){return e===" "||e===" "}o($g,"isHttpOws");function NT(e){let t=0,r=e.length;for(;t<r&&$g(e[t]);)t++;for(;r>t&&$g(e[r-1]);)r--;return e.slice(t,r)}o(NT,"stripHttpOws");function an(e,t){return e.get(t)??void 0}o(an,"readHeader");function jT(e){if(!e.startsWith(Dg)||!e.endsWith(Lg))return e;let t=e.slice(Dg.length,e.length-Lg.length);if(qT.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(jT,"decodeMcpHeaderValue");function Kc(e,t,r){let n=we(e);return Response.json(Pe({...n===void 0?{}:{id:n},error:r}),{status:t})}o(Kc,"errorResponse");function Wo(e,t,r){return Kc(e,400,{code:MT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(Wo,"headerMismatchResponse");function DT(e,t,r){let n=t.method;if(an(e,"mcp-protocol-version")===void 0)return Wo(t,Vc,`the body envelope names protocol version ${r} but the required MCP-Protocol-Version header is absent`);if(an(e,"mcp-method")===void 0)return Wo(t,Vc,`the body names method ${String(n)} but the required Mcp-Method header is absent`);if(typeof n!="string"||!Object.hasOwn(jg,n))return;let s=jg[n],i=zT(t.params)?t.params[s]:void 0,a=typeof i=="string"?i:void 0,c=an(e,"mcp-name");if(c===void 0)return a===void 0?void 0:Wo(t,Vc,`the body carries params.${s}="${a}" but the required Mcp-Name header is absent`);let d=NT(c),u=jT(d);if(u===void 0)return Wo(t,d,"the Mcp-Name header carries an invalid Base64 sentinel value");if(a!==void 0&&u!==a)return Wo(t,d,`the body carries params.${s}="${a}" but the Mcp-Name header names "${u}"`)}o(DT,"standardHeadersResponse");function Hg(e){let{headers:t,message:r}=e,n=_m({httpMethod:"POST",...Gc("protocolVersionHeader",an(t,"mcp-protocol-version")),...Gc("mcpMethodHeader",an(t,"mcp-method")),...Gc("mcpNameHeader",an(t,"mcp-name")),body:r});if(n.kind==="reject")return UT.has(n.cell)||n.cell==="initialize-with-modern-header"&&xe()?Kc(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 Rm({supported:[...e.supportedVersions],requested:s??"unknown"});return Kc(r,400,{code:i.code,message:i.message,data:i.data})}return n.messageKind==="request"?DT(t,r,s):void 0}o(Hg,"validateModernGatewayRequest");function Gc(e,t){return t===void 0?{}:{[e]:t}}o(Gc,"optionalHeader");import{context as LT,TraceFlags as $T,trace as HT}from"@opentelemetry/api";var Bg="mcp-session-id",BT=256*1024;function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(it,"isPlainObject");function Fg(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Fg,"isJsonContentType");function Zc(e,t,r){if(t===void 0||r===void 0||r.byteLength>xh||!Fg(e))return;let n=t.value;if(!it(n)||typeof n.method!="string"||n.params!==void 0&&!it(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(Zc,"parseMcpRequestMessage");function Wc(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}o(Wc,"readStringParam");function FT(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Wc(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Wc(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Wc(e.params,"uri")};default:return{}}}o(FT,"readCapability");function Jg(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Jg,"readHeader");function JT(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(JT,"readUpstreamServer");function Vg(e,t,r){let n=lr(e.headers,r.message),s=Jg(e.headers,Bg),i={methodName:r.method,...FT(r),...r.id===void 0?{}:{jsonRpcRequestId:r.id},...r.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:r.jsonrpc},...s===void 0?{}:{mcpSessionId:s}};return{common:i,server:{...i,mcpProtocolVersion:n??Dm,clientAddress:t.incomingRequestProperties?.ip,params:r.params},requestedProtocolVersion:n}}o(Vg,"readServerSpanInput");function Gg(e){let{request:t,context:r,parsed:n}=e,{common:s,server:i,requestedProtocolVersion:a}=Vg(t,r,n),c=Ta(i),d;try{Ms(c.span);let u=c.span.isRecording()||$m()?JT(t,r):{};d=LT.with(c.ctx,()=>Hm({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Ms(d.span);let p={server:c,client:d,captureToolCallContent:e.captureToolCallContent===!0};return VT(p,n),Ca(r,c.span.spanContext()),p}catch(u){throw ki(d===void 0?[c]:[d,c]),u}}o(Gg,"startMcpProxySpans");function Kg(e,t,r){try{let n=e.filter(i=>i.span.isRecording());if(n.length===0)return;let s=Bm(r);if(s===void 0)return;Dt(n,i=>i.span.setAttribute(t,s))}catch{}}o(Kg,"setContentAttribute");function VT(e,t){e.captureToolCallContent!==!0||t.method!=="tools/call"||Kg([e.client,e.server],"gen_ai.tool.call.arguments",t.params?.arguments??{})}o(VT,"recordToolCallArguments");function GT(e,t){if(t.spans.captureToolCallContent!==!0||t.method!=="tools/call"||t.gatewayAnswered===!0)return;let r=t.tapResult.message?.result;!it(r)||r.isError===!0||Kg(e,"gen_ai.tool.call.result",r)}o(GT,"recordToolCallResult");var KT=["content-digest","repr-digest","digest","content-md5"];function WT(e){return KT.some(t=>e.has(t))}o(WT,"hasBodyIntegrityHeader");function Wg(e,t,r,n){let s=HT.getSpanContext(t.client.ctx);if(r.byteLength>BT||n!==void 0&&WT(n)||s===void 0||(s.traceFlags&$T.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!it(i))return r;try{let a=Ea(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!Oh(r))return r;let c=Ea(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}o(Wg,"injectTraceContextIntoBody");function Zg(e,t){if(e){if(it(e.error)){let r=e.error.code,n=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof n=="string"?{message:Ls(n,Lm)}:{},httpStatusCode:t}}if(it(e.result)&&e.result.isError===!0)return{isError:!0}}}o(Zg,"readSpanResponse");function ZT(e,t,r){let n=Jg(t.headers,Bg),s=r?.result,i=xm(it(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);Dt(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(ZT,"recordInitializeResult");function Yg(e){let{spans:t}=e,r=[t.client,t.server];try{YT(r,e)}catch{}finally{ki(r)}}o(Yg,"finishMcpProxySpans");function YT(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&ZT(e,n,s.message),GT(e,t);let i=Zg(s.message,n.status);i?Dt(e,a=>a.setResponse(i)):s.ended==="errored"?Dt(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?Dt(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?Dt(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?Dt(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&&Dt(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(YT,"recordOutcome");function Dt(e,t){for(let r of e)try{t(r)}catch{}}o(Dt,"forEachHandle");function ki(e){for(let t of e)try{t.end()}catch{}}o(ki,"endEach");function Yc(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}o(Yc,"failMcpProxySpans");function Xc(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{ki([t])}}o(Xc,"cancelMcpProxySpans");function XT(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.";case"upstream_token_refresh_unavailable":return"The upstream token endpoint could not refresh the connection; the request was not forwarded."}}o(XT,"gatewayAnswerMessage");var QT=64*1024;async function eE(e){if(e.body===null||!Fg(e))return;let t=await e.clone().text();if(t.length>QT)return;let r=JSON.parse(t);return it(r)?r:void 0}o(eE,"readGatewayAnswer");function tE(e){return it(e.error)?it(e.error.data)&&e.error.data.connectRequired!==void 0:it(e.result)&&e.result.resultType==="input_required"}o(tE,"isConnectRequiredAnswer");async function Xg(e){let t;try{let r=Zc(e.request,e.requestJson===void 0?void 0:{value:e.requestJson},e.requestBody);if(r===void 0)return;let{server:n}=Vg(e.request,e.context,r);t=Ta({...n,startTime:e.startTime}),Ms(t.span),Ca(e.context,t.span.spanContext());let s;try{s=await eE(e.response)}catch{}let i=Zg(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&&tE(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,XT(a))}catch{}finally{t&&ki([t])}}o(Xg,"recordGatewayAnsweredMcpSpan");function Lt(e){let t=Ie().connectionsById.get(e);if(!t)throw new re(`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(Lt,"getUpstreamServerConfig");function Ai(e){let t=Ie().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new re(`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(Ai,"getUpstreamAuthConfig");function cn(e,t){let r=Ai({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new re(`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(cn,"requireUpstreamOAuthConfig");function Qg(e,t){let r=Ai({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new re(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}o(Qg,"requireUpstreamIdJagConfig");import{base64url as Pi}from"jose";var rE="__Host-",nE=16,oE=32,ty=".",sE=!1;function $t(){return sE}o($t,"isBrowserBindingEnforced");var Zo=m.object({id:m.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:m.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function xi(e,t){return new URL(ce(e,t)).protocol==="https:"}o(xi,"isSecureGatewayOrigin");function Qc(e,t){return t?`${rE}${e}`:e}o(Qc,"gatewayCookieName");function Yo(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}o(Yo,"serializeGatewayCookie");function ed(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(ed,"parseCookieHeader");function ey(e){return Pi.encode(crypto.getRandomValues(new Uint8Array(e)))}o(ey,"randomBase64url");async function ry(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Pi.encode(new Uint8Array(t))}o(ry,"hashNonce");function iE(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(iE,"constantTimeEqual");function ny(e,t,r){return Qc(`zuplo_mcp_${e}_${t}`,r)}o(ny,"bindingCookieName");async function Xo(e){let t=ey(nE),r=ey(oE),n=xi(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${ty}${Pi.encode(e.payload)}`;return{claim:{id:t,hash:await ry(r)},setCookie:Yo({name:ny(e.purpose,t,n),value:s,maxAgeSeconds:e.ttlSeconds,secure:n})}}o(Xo,"startBrowserBinding");async function Oi(e){let t=xi(e.request.url,e.request.headers),r=ny(e.purpose,e.claim.id,t),n=Yo({name:r,value:"",maxAgeSeconds:0,secure:t}),s=ed(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:n};let i=s.indexOf(ty),a=i<0?s:s.slice(0,i);if(!iE(await ry(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(Pi.decode(s.slice(i+1))),clearCookie:n}}catch{return{matched:!1,clearCookie:n}}}o(Oi,"verifyBrowserBinding");function oy(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(oy,"mergeAbortSignals");async function aE(e){try{await e.cancel()}catch{}}o(aE,"cancelReader");async function Mi(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 aE(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(Mi,"readBoundedByteStream");var cE=2,dE=1024*1024,uE=1e4,lE=new Set([301,302,303,307,308]),pE=["authorization","proxy-authorization","cookie","cookie2"];function td(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(td,"readRequestUrl");function dn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(dn,"readRequestMethod");function mE(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(mE,"assertContentLengthWithinLimit");async function hE(e,t,r){return mE(e,t,r),Mi(e.body,{maxBytes:t,createLimitError:o(()=>new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[M]:r}}),"createLimitError")})}o(hE,"readBoundedResponseBody");function fE(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(fE,"responseFromBufferedBody");function gE(e,t){if(!lE.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(gE,"resolveRedirectUrl");function sy(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(sy,"validateOutboundUrl");var iy=new WeakSet;function ay(e){return e instanceof k&&iy.has(e)}o(ay,"isOutboundTransportFailure");function cy(e,t){if(e instanceof k&&Fs(e.extensionMembers?.[M]))throw e;let r=new k({message:"Outbound fetch failed.",extensionMembers:{[M]:t}},{cause:e});throw iy.add(r),r}o(cy,"normalizeFetchError");function Qo(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&&Ae(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Qo,"logOutboundFailure");async function yE(e,t,r,n,s,i,a){let c=dn(r,n);try{return await t(r,n)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Qo(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ie(i),error:d,extra:{abortReason:a()}}),cy(d,s)}}o(yE,"fetchWithNormalizedError");function SE(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(SE,"assertRedirectAllowed");function RE(e,t){let r=new Headers(e);for(let n of pE)r.delete(n);for(let n of t)r.delete(n);return r}o(RE,"stripCrossOriginHeaders");function wE(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=RE(e.headers,s)),i}o(wE,"buildRedirectInit");function _E(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(_E,"buildInitialRequestInit");function bE(e){let t=dn(e.currentInput,e.currentInit);SE({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=sy(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:wE(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(bE,"followRedirect");async function rd(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??cE,i=r.maxResponseBytes??dE,a=r.timeoutMs??uE,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,p=new AbortController,h=oy(p,t.signal),f=!1,y=setTimeout(()=>{f=!0,p.abort()},a),b=e,w=_E(e,t,p.signal),S;try{S=sy(td(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(v){throw Qo(u,{event:"outbound_url_blocked",problemCode:n,method:dn(e,t),host:ie(td(e)),error:v}),clearTimeout(y),h?.(),v}let R=0;try{for(;;){let v=await yE(u,c,b,w,n,S,()=>f?`timeout_after_${a}ms`:void 0),x=gE(v,S);if(x!==void 0)try{let N=bE({currentInput:b,currentInit:w,currentUrl:S,redirectUrl:x,redirects:R,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});b=N.currentInput,w=N.currentInit,S=N.currentUrl,R=N.redirects;continue}catch(N){throw Qo(u,{event:"outbound_redirect_blocked",problemCode:n,method:dn(b,w),host:ie(S),error:N,extra:{redirects:R,maxRedirects:s,redirectTargetHost:ie(x)}}),N}try{return fE(v,await hE(v,i,n))}catch(N){let T=N instanceof k;Qo(u,{event:T?"outbound_response_size_exceeded":"outbound_response_body_failed",problemCode:n,method:dn(b,w),host:ie(S),error:N,extra:{maxResponseBytes:i,status:v.status}}),cy(N,n)}}}finally{clearTimeout(y),h?.()}}o(rd,"runSafeOutboundExchange");async function es(e,t,r){let n=await rd(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(s){throw Qo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:dn(e,t),host:ie(td(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(es,"runSafeOutboundJsonExchange");function dy(e,t={},r={}){return rd(e,t,{...r,validateUrl:xo})}o(dy,"fetchConfiguredOutbound");function uy(e,t={},r={}){return es(e,t,{...r,validateUrl:xo})}o(uy,"fetchConfiguredOutboundJson");function Ui(e,t={},r={}){return es(e,t,{...r,validateUrl:Rh})}o(Ui,"fetchIdentityProviderJson");function ly(e,t={},r={}){return es(e,t,{...r,validateUrl:Xs})}o(ly,"fetchCimdClientMetadataJson");function py(e,t={},r={}){return es(e,t,{...r,validateUrl:Oo})}o(py,"fetchCimdClientJwksJson");import{errors as Sy,jwtVerify as Ry,SignJWT as wy}from"jose";var fe="zuplo-mcp-gateway",_e=fe,be="HS256";import{base64url as vE}from"jose";var CE=new TextEncoder,IE="MCP gateway could not initialize secure key material.",TE=32,my=new Map,hy=new Map,EE;function kE(){return EE??zr.instance.authPrivateKey}o(kE,"readAuthPrivateKey");function fy(e){return new Ee(IE,e===void 0?void 0:{cause:e})}o(fy,"createGeneratedKeyMaterialError");function gy(e,t){let r=vE.decode(t);if(r.byteLength!==TE)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(gy,"decodeJwkKeyField");function AE(e){let t=kE();if(!t)throw fy();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=gy("d",r.d);gy("x",r.x);let s=CE.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 fy(r)}}o(AE,"decodeGeneratedKeyMaterial");function PE(e){let t=my.get(e);return t||(t=AE(e),my.set(e,t)),t}o(PE,"getMasterKeyMaterial");async function Ze(e){let t=hy.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(PE(e.keyMaterialPurpose));return hy.set(e.purpose,r),r}o(Ze,"readCachedDerivedKey");var xE="SHA-256",OE=32,ME="zuplo-mcp-gateway:",UE=new TextEncoder,yy=new WeakMap;async function ft(e,t){let r=yy.get(e);r||(r=new Map,yy.set(e,r));let n=r.get(t);if(n)return n;let s=await qE(e,t);return r.set(t,s),s}o(ft,"deriveGatewaySigningKey");async function qE(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=UE.encode(`${ME}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:xE,salt:new Uint8Array,info:ye(s)},n,OE*8);return new Uint8Array(i)}o(qE,"hkdfExpand");var _y=900,zE=900,NE=rh.extend({id:Ch,browserBinding:Zo.optional()}),jE=NE.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),by=ka.extend({id:Ih,purpose:m.literal("browser_connect")}),DE=ka.extend({purpose:m.literal("browser_connect")}),LE=by.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),qi=_y*1e3;async function vy(){return Ze({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"oauth-state"),"derive")})}o(vy,"getOAuthStateKey");async function Cy(){return Ze({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-connect"),"derive")})}o(Cy,"getBrowserConnectKey");async function Iy(e){let t=Math.floor(Date.now()/1e3)+_y;return new wy(e).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await vy())}o(Iy,"signOAuthState");async function zi(e){try{let{payload:t}=await Ry(e,await vy(),{algorithms:[be],issuer:fe,audience:_e});return jE.parse(t)}catch(t){throw t instanceof Sy.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(zi,"verifyOAuthState");async function Ty(e){let t=Math.floor(Date.now()/1e3)+zE,r=DE.parse(e),n=by.parse({...r,id:Ah()});return new wy(n).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await Cy())}o(Ty,"signBrowserConnectTicket");async function Ey(e){try{let{payload:t}=await Ry(e,await Cy(),{algorithms:[be],issuer:fe,audience:_e});return LE.parse(t)}catch(t){throw t instanceof Sy.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(Ey,"verifyBrowserConnectTicket");async function ky(e){if((await G().consumeBrowserConnectTicket({id:e.id,expiresAt:W(new Date(e.exp*1e3)),now:W(new Date)})).kind==="consumed")throw new k({message:"Browser connect ticket has already been used",extensionMembers:{[M]:"oauth_state_reused"}})}o(ky,"consumeBrowserConnectTicket");function $E(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($E,"buildConnectRequiredMessage");async function HE(e){let t=ce(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 Ty({...Ao(e),purpose:"browser_connect"})),r.toString()}o(HE,"buildGatewayBrowserTicketUrl");function BE(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(BE,"buildGatewayConnectPath");async function nd(e){return HE({...e,path:BE(e.upstreamServerId),redirect:!0})}o(nd,"buildGatewayConnectUrl");async function Ni(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 nd(t),message:$E(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ni,"buildRedirectConnectRequiredResponse");function Ay(e){return Py({...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(Ay,"buildAdminConnectRequiredResponse");function Py(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(Py,"buildAdminSetupRequiredResponse");function xy(e){return Ie().byOperationId.get(e)?.downstreamOAuth!==void 0}o(xy,"routeSupportsBrowserConnect");function Oy(e){return Py({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o(Oy,"buildBrowserConnectUnavailableResponse");var My=12;async function Uy(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(Uy,"sha256Hex");async function gr(e){if(e)return(await Uy(e)).slice(0,My)}o(gr,"fingerprintSecret");async function un(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Uy(t)).slice(0,My)}o(un,"fingerprintConnectionIdentity");var FE=6e4;function ln(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(ln,"credentialGenerationChanged");function Me(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()+FE)return"near_expiry"}return"usable"}o(Me,"describeAccessTokenState");var qy=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function JE(e,t){return e&&e.length>0?e.join(t):void 0}o(JE,"joinOAuthScopes");function VE(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of qy)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o(VE,"sanitizeAuthorizationServerMetadata");function zy(e){let t=VE(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(zy,"sanitizeOAuthDiscoveryState");function Ny(e){let t=new URL(e);for(let r of qy){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(Ny,"dedupeSingletonAuthorizationRequestParams");function ji(e){let t=new URL(e);return He(t)&&Jm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(ji,"normalizeLoopbackOAuthRedirectUri");function jy(e){return JE(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(jy,"readProtectedResourceMetadataScope");function GE(e){return`Zuplo MCP Gateway - ${e}`}o(GE,"buildGatewayOAuthClientName");function KE(e,t){return e&&e.length>0?e.join(t):void 0}o(KE,"joinOAuthScopeList");function WE(e){if(e.clientRegistration.mode!=="auto")return KE(e.scopes,e.scopeDelimiter)}o(WE,"readPublicClientMetadataScope");function od(e){return new URL(ge().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}o(od,"buildOAuthClientMetadataDocumentUrl");function sd(e){let t=Lt(e.upstreamServerId);return{client_name:GE(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(sd,"buildGatewayOAuthClientMetadata");function Dy(e,t,r){let n=cn(t,r),s=WE(n);return{client_id:od({origin:e,upstreamServerId:t}),...sd({origin:e,upstreamServerId:t,redirectUri:ji(new URL(n.redirectPath,e)).toString(),scope:s})}}o(Dy,"buildOAuthClientMetadataDocument");import{base64url as Ht}from"jose";var ZE="SHA-256",pn="AES-GCM",YE=12,ad="zuplo-secret",cd=1,Ly="generated:auth_private_key:token-encryption",XE=m.object({version:m.literal(cd),keyId:m.literal(Ly),algorithm:m.literal(pn),iv:m.string().min(1),ciphertext:m.string().min(1)}).strict();async function id(){return Ze({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(ZE,ye(e));return crypto.subtle.importKey("raw",t,{name:pn},!1,["encrypt","decrypt"])},"derive")})}o(id,"getEncryptionKey");function $y(e){return ye(new TextEncoder().encode(`${ad}:v${e.version}:${e.keyId}`))}o($y,"getAssociatedData");function QE(e){return`${ad}:v${e.version}:${Ht.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(QE,"encodeEnvelope");function ek(e){let t=`${ad}:v${cd}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Ht.decode(r));return XE.parse(JSON.parse(n))}o(ek,"decodeEnvelope");async function vt(e){let t=await id(),r=crypto.getRandomValues(new Uint8Array(YE)),n={version:cd,keyId:Ly},s=await crypto.subtle.encrypt({name:pn,iv:r,additionalData:$y(n)},t,new TextEncoder().encode(e));return QE({...n,algorithm:pn,iv:Ht.encode(r),ciphertext:Ht.encode(new Uint8Array(s))})}o(vt,"encryptSecret");async function Ct(e){let t=ek(e);if(t){let a=await id(),c=await crypto.subtle.decrypt({name:pn,iv:ye(Ht.decode(t.iv)),additionalData:$y(t)},a,ye(Ht.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new Ee("Encrypted payload is malformed");let s=await id(),i=await crypto.subtle.decrypt({name:pn,iv:ye(Ht.decode(r))},s,ye(Ht.decode(n)));return new TextDecoder().decode(i)}o(Ct,"decryptSecret");var Hy={issuer:m.string().min(1).optional()},tk=m.union([dr.extend(Hy),vo.extend(Hy)]),By=m.object({authorizationServerUrl:m.url(),resourceMetadataUrl:m.url().optional(),resourceMetadata:$r.optional(),authorizationServerMetadata:m.union([Hr,Br]).optional()}).passthrough(),rk="Bearer",nk="__zuplo_refresh_only_upstream_access_token__";function dd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(dd,"splitScopes");function ud(e,t){let r=new Set(e);return t.every(n=>r.has(n))}o(ud,"scopesCover");function ok(e){return Kr.parse(e)}o(ok,"parsePkceCodeVerifier");function sk(e){if(typeof e.expires_in=="number")return W(new Date(Date.now()+e.expires_in*1e3))}o(sk,"readTokenExpiry");async function ld(e){if(e!==void 0)return vt(JSON.stringify(e))}o(ld,"encryptJson");async function Fy(e,t){if(!e)return;let r=await Ct(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(Fy,"decryptJson");function ik(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(ik,"clientInformationAllowsRedirectUri");function ak(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(ak,"clientInformationMatchesCurrentClientMetadataUrl");function ck(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(ck,"isUrlBasedClientInformation");function dk(e,t){return t===void 0?e:{...e,scope:t}}o(dk,"applyOAuthClientMetadataScope");function uk(e,t){return jy({state:e,delimiter:t})}o(uk,"readResourceMetadataScope");function lk(e,t){return e&&e.length>0?e.join(t):void 0}o(lk,"joinOAuthScopeList");function pk(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new re(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return dr.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(pk,"buildManualOAuthClientInformation");function mk(e,t){let r=od({origin:new URL(t).origin,upstreamServerId:e});return pc(r)?r:void 0}o(mk,"buildClientMetadataUrl");function hk(e){for(let t of e)if(t!==void 0)return t}o(hk,"firstDefined");function fk(e){let t=cn(e.target.upstreamServerId,e.target.authProfileId),r=lk(t.scopes,t.scopeDelimiter),n=sd({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:pk({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=mk(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(fk,"buildInitialOAuthClientSetup");function gk(e,t){if(t===void 0)return hk([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(gk,"readEncryptedClientInformation");function yk(e){return e.pendingState?.encryptedDiscoveryState}o(yk,"readEncryptedDiscoveryState");function Di(e,t){return t===void 0?e:{...e,issuer:t}}o(Di,"applyIssuerStamp");var Bt=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=fk({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=gk(t,this.configuredClientInformation),this.encryptedDiscoveryState=yk(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=dd(this.configuredScope??r??this.readEffectiveScope());return ud(t.scopes,n)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Me(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=se();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 un({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await gr(await Ct(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await G().conditionalUpsertUpstreamConnection(t,r)}catch(n){let s=se();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 dk(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Iy({id:t.id,...Ao({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?Di(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,se()?.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"),!ck({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await ld(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ii({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=zy(By.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await ld(r),await this.syncPendingState(!1),se()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ie(r.authorizationServerUrl),resourceMetadataHost:ie(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=uk(r,this.scopeDelimiter);let n=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&n!==void 0){let s=dd(this.configuredScope).filter(i=>!n.includes(i));s.length>0&&se()?.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 Di(r,t?.issuer)}async saveTokens(t){let r=Ot.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 vt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:Ot.parse({...r,refresh_token:await Ct(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Qs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await vt(r.access_token),encryptedRefreshToken:a,scopes:dd(r.scope??this.readEffectiveScope()),expiresAt:sk(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),p=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Me(u.connection)!=="usable"||!ud(u.connection.scopes,c.scopes)||!ln(s,u.connection))){p=!0;let f=u.connection,y={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};se()?.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:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(y,{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,ln(s,u.connection)&&Me(u.connection)==="usable"&&ud(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),p){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";se()?.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;se()?.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 gr(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:p,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=Ny(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:ok(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:kh(),...Ao({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:W(new Date(Date.now()+qi)),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 G().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 Fy(this.encryptedClientInformation,tk)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!ik(r,this.redirectUriValue)||!ak({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=Di(r,t.issuer),this.encryptedClientInformation=await ld(r)),r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Di(vo.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 Fy(this.encryptedDiscoveryState,By)}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"){se()?.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 Ct(t.encryptedAccessToken):void 0,n=t.encryptedRefreshToken?await Ct(t.encryptedRefreshToken):void 0;if(!r&&!n)return;let s=se();this.usedRefreshTokenFingerprintValue=s?await gr(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=Ot.parse({access_token:r??nk,token_type:rk,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,ln(r,a.connection)&&Me(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=se();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 Sk=3e4,Rk=256*1024,wk=2,_k="does not support dynamic client registration",bk=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],vk=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],Ck=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],Ik="Protected resource ",Tk=" does not match expected ",Ek=["HTTP 403 Forbidden","Access Denied","permission to access"],kk=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function Ak(e){return e instanceof Error&&e.message.includes(_k)}o(Ak,"isDynamicClientRegistrationUnsupported");function Pk(e){return e instanceof Error&&bk.some(t=>e.message.includes(t))}o(Pk,"isProtectedResourceMetadataUnavailable");function xk(e){return e instanceof Error&&vk.some(t=>e.message.includes(t))}o(xk,"isAuthorizationServerMetadataUnavailable");function Ok(e){return e instanceof Error&&Ck.some(t=>e.message.includes(t))}o(Ok,"isAuthorizationServerIncompatible");function Mk(e){return e instanceof Error&&e.message.includes(Ik)&&e.message.includes(Tk)}o(Mk,"isProtectedResourceMismatch");function Uk(e){return e instanceof Error&&Ek.some(t=>e.message.includes(t))}o(Uk,"isUpstreamProviderAccessDenied");function Jy(e){return e instanceof Nt&&kk.has(e.code)}o(Jy,"isStoredConnectionReconsentError");function It(e){let t=e.diagnostics??{};return new k({message:e.message,extensionMembers:{[M]:e.code,[To]:e.upstreamServerId,[Yr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[pt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[lt]:t.httpStatus},...t.providerError===void 0?{}:{[Xr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Qr]:t.providerErrorDescription}}},{cause:e.cause})}o(It,"buildUpstreamSetupProblem");function qk(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(qk,"describeIssuerMetadataMismatch");var zk=128,Li=256;function ts(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}o(ts,"truncateProviderDetail");function Nk(e){let{error:t,errorDescription:r}=$i(e.body),n=ts(t,zk),s=ts(r,Li);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(Nk,"readRegistrationRejectionDiagnostics");function jk(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(jk,"describeRegistrationRejection");function Dk(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(Dk,"readDiscoveryEndpointUrl");function Lk(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(Ak(e.error))return It({...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 uc){let r=Nk(e.error);return It({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${jk(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 Do&&e.error.kind==="metadata")return It({...t,code:"upstream_oauth_issuer_mismatch",message:qk(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof pi)return It({...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(Ok(e.error))return It({...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(xk(e.error)){let r=Dk(e.error.message);return It({...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(Mk(e.error))return It({...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(Pk(e.error))return It({...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(Uk(e.error))return It({...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(Lk,"mapUpstreamOAuthSetupError");function $k(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o($k,"readOAuthFetchRequest");function Hk(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Hk,"readOAuthFetchMethod");function Bk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(Bk,"responseLooksJson");function Fk(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(Fk,"responseLooksHtml");var Jk=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function Vk(e){return Jk.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o(Vk,"isMetadataDiscoveryRequest");function Gk(e,t,r){return e!=="GET"||!Vk(t)?!1:r>=400&&r<500||r===502}o(Gk,"sdkRetriesDiscoveryCandidate");function Kk(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",[lt]:e.response.status,[Wr]:r,[pt]:e.request.url.toString(),[Zr]:e.body}})}o(Kk,"throwUpstreamHtmlError");var Wk=["message","error_message","detail","title"];function Vy(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}o(Vy,"readStringField");function Zk(e){for(let r of Wk){let n=Vy(e,r);if(n!==void 0)return n}let t=e.error;if(typeof t=="object"&&t!==null)return Vy(t,"message")}o(Zk,"readProviderMessage");function $i(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?Zk(r):void 0}}catch{return{}}}o($i,"readUpstreamOAuthErrorBody");function Yk(e){let{error:t,errorDescription:r,providerMessage:n}=$i(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ie(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:ts(r,Li),providerMessage:ts(n,Li)},"Upstream OAuth HTTP request returned an error response")}o(Yk,"logUpstreamOAuthHttpError");function Xk(e,t){if(e!=="POST")return!1;let r=t?.body;return r instanceof URLSearchParams?r.get("grant_type")==="refresh_token":typeof r=="string"?new URLSearchParams(r).get("grant_type")==="refresh_token":!1}o(Xk,"isRefreshTokenGrant");var Qk=new Set([void 0,me.ServerError,me.TemporarilyUnavailable]);function eA(e,t){return e.status<500&&e.status!==429?!1:Qk.has($i(t).error)}o(eA,"isTransientTokenEndpointResponse");var tA=[/\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 rA(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}o(rA,"isTokenEndpointRequest");function nA(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:n}=$i(t);if(!(r!==void 0||n===void 0))return tA.some(s=>s.test(n))?n:void 0}o(nA,"readUnknownClientRejection");function oA(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(oA,"rewriteUnknownClientRejection");function Gy(e,t){return async(r,n)=>{let s=$k(r),i=Hk(r,n),a=t!==void 0&&Xk(i,n),c=se(),d=Date.now(),u;try{u=await dy(r,n,{maxRedirects:wk,maxResponseBytes:Rk,problemCode:"upstream_token_exchange_failed",timeoutMs:Sk})}catch(h){throw a&&ay(h)&&(t.failure={url:s.url,cause:h}),h}let p=await u.clone().text();if(c?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,host:ie(s.url),path:s.url.pathname,status:u.status,durationMs:Date.now()-d,responseChars:p.length},"Upstream OAuth HTTP request completed"),u.ok||Yk({log:c,upstreamServerId:e,method:i,request:s,response:u,body:p}),a&&eA(u,p)&&(t.failure={url:s.url,status:u.status}),Gk(i,s.url,u.status))return u;if(rA(i,n)){let h=nA(u.status,p);if(h!==void 0)return c?.info({event:"upstream_oauth_unknown_client_rejected",upstreamServerId:e,host:ie(s.url),path:s.url.pathname,status:u.status,providerMessage:ts(h,Li)},"Upstream OAuth provider no longer recognizes the gateway's client; treating it as invalid_client"),oA(u,h)}if(!u.ok&&Fk(u,p)&&Kk({upstreamServerId:e,request:s,response:u,body:p}),!Bk(u,p))return u;try{JSON.parse(p)}catch(h){throw new k({message:`Upstream OAuth fetch ${s.url.origin}${s.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[M]:"upstream_token_exchange_failed"}},{cause:h})}return u}}o(Gy,"createUpstreamOAuthFetch");function Ky(e){se()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ie(e.serverUrl),resourceMetadataHost:ie(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}o(Ky,"logUpstreamOAuthFlowStarted");function Wy(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ie(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),Ae(t,"error",e.error),se()?.warn(t,"Upstream OAuth flow failed before a connection was established")}o(Wy,"logUpstreamOAuthFlowFailed");function Zy(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(Zy,"readAuthorizationRequestScope");async function Yy(e,t){e.applyChallengeScope(t.requestedScope),Ky({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Gy(t.upstreamServerId,t.refreshFailures)},n=Zy(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await lc(e,r)}catch(r){Wy({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=Lk({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(Yy,"runUpstreamOAuth");async function sA(e,t){e.applyChallengeScope(t.requestedScope),Ky({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Gy(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=Zy(e,t);n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await lc(e,r)}catch(s){throw Wy({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(sA,"exchangeUpstreamAuthorizationCode");async function pd(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await G().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Me(r)!=="usable"||!ln(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}o(pd,"adoptPeerCredentialAtResolutionBoundary");async function Xy(e,t){let r=await Yy(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(Xy,"requireUpstreamAuthorizationRedirect");function iA(e,t){let r=t.status===void 0?"did not respond":`answered HTTP ${t.status}`;return new k({message:`The token endpoint for ${e} ${r} while the gateway refreshed a stored connection. The connection was kept; retry the request.`,extensionMembers:{[M]:"upstream_token_refresh_unavailable",[To]:e,[pt]:`${t.url.origin}${t.url.pathname}`,...t.status===void 0?{}:{[lt]:t.status}}},t.cause===void 0?void 0:{cause:t.cause})}o(iA,"buildTransientRefreshProblem");function aA(e){e.log?.warn({event:"upstream_oauth_refresh_unavailable",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:e.connection?.id,host:ie(e.failure.url),path:e.failure.url.pathname,status:e.failure.status},"Upstream token endpoint could not refresh the connection; the connection was kept")}o(aA,"logTransientRefreshFailure");async function Qy(e){let t=Me(e.connection),r=!!e.forceRefresh,n=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=se(),i=s?await un({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={},c=o(u=>{throw aA({log:s,target:e.target,connection:e.connection,connectionFingerprint:i,failure:u}),iA(e.target.upstreamServerId,u)},"rejectTransientRefreshFailure"),d;try{d=await Yy(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,refreshFailures:a,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(u){if(a.failure!==void 0&&!Jy(u)){if(await pd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope}))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};c(a.failure)}if(e.connection===void 0||!Jy(u))throw u;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:u.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 pd({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 md({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(d==="AUTHORIZED"){let u=e.provider.readUsablePeerAdoption(e.requestedScope);return u!==void 0&&await e.provider.adoptConnectionForDirectResolution(u,"cas_loss"),!e.provider.tokenWriteWasPersisted&&u===void 0?{kind:"connect_required",payload:await md({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(d!=="REDIRECT")throw new k({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${d}`,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 pd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:(a.failure!==void 0&&c(a.failure),{kind:"connect_required",payload:await md({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(Qy,"authorizeUpstreamOAuthSession");async function cA(e){let t=await zi(e.stateToken),r=await G().consumeUpstreamOAuthState({id:t.id,now:W(new Date)}),n=dA(r);return uA({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),lA(n),n}o(cA,"consumeStoredCallbackState");function dA(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(dA,"readConsumedCallbackState");function uA(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(uA,"assertStoredCallbackStateMatches");function lA(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}})}o(lA,"assertStoredCallbackStateFresh");async function md(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),Ay(r)}if($t()&&!xy(e.operationId))return se()?.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"),Oy({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),Ni(t)}o(md,"buildOAuthConnectRequiredResponse");async function eS(e){let t=await cA({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Vs(t),[n]=await G().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 Bt(s),a=await sA(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(eS,"finishUpstreamOAuthCallback");import{importPKCS8 as pA,SignJWT as mA}from"jose";var rS=1e4,nS=64*1024,oS=2,hA=300,at=m.string().min(1),fA=m.object({access_token:at,issued_token_type:m.literal(Pa),token_type:m.string().optional(),expires_in:m.number().int().positive().optional(),scope:at.optional()}).passthrough(),gA=m.object({id_token:at,token_type:at.optional(),expires_in:m.number().int().positive().optional(),refresh_token:at.optional(),scope:at.optional()}).passthrough(),yA=m.object({access_token:at,token_type:at,expires_in:m.number().int().positive().optional(),scope:at.optional(),resource:at.optional(),refresh_token:at.optional()}).passthrough();function tS(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(tS,"formEncodeClientCredential");function SA(e){return e.replaceAll("\\n",`
41
+ `)}o(SA,"normalizePem");async function RA(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??hA,n=await pA(SA(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new mA({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(RA,"createPrivateKeyJwtClientAssertion");async function wA(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=tS(e.clientAuth.clientId),r=tS(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",Ks),e.form.set("client_assertion",await RA({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(wA,"appendClientAuthentication");async function hd(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await wA({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(hd,"buildFormRequest");function sS(e){return(t,r)=>Ui(t,r,{context:e,maxRedirects:oS,maxResponseBytes:nS,problemCode:"upstream_token_exchange_failed",timeoutMs:rS})}o(sS,"defaultIdpFetchJson");function _A(e){return(t,r)=>uy(t,r,{context:e,maxRedirects:oS,maxResponseBytes:nS,problemCode:"upstream_token_exchange_failed",timeoutMs:rS})}o(_A,"defaultResourceAsFetchJson");function Hi(e){let t={[M]:e.code,[pt]:e.tokenUrl};return e.response!==void 0&&(t[lt]=e.response.status),new k({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}o(Hi,"runtimeError");function fd(e){if(!e.response.ok)throw Hi({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(fd,"assertTokenEndpointSucceeded");function bA(e){let t=gA.safeParse(e.json);if(!t.success)throw Hi({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(bA,"parseIdpRefreshTokenResponse");function vA(e){let t=fA.safeParse(e.json);if(!t.success)throw Hi({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(vA,"parseIdJagTokenExchangeResponse");function CA(e){let t=yA.safeParse(e.json);if(!t.success)throw Hi({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(CA,"parseAccessTokenResponse");async function iS(e){let t=new URLSearchParams({grant_type:Gs,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??sS(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return fd({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),vA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(iS,"requestIdJag");async function aS(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??sS(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return fd({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),bA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(aS,"refreshIdpSubjectToken");async function cS(e){let t=new URLSearchParams({grant_type:zt,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??_A(e.context),{response:n,json:s}=await r(e.resourceAs.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return fd({response:n,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),CA({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(cS,"exchangeIdJagForAccessToken");function IA(e){return Me(e)==="usable"}o(IA,"hasUsableAccessToken");function TA(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(TA,"assertBearerToken");function dS(e,t){if(t===nn)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(dS,"hasExpiredSubjectToken");async function EA(e){let t=await Ct(e.encryptedSubjectToken);if(e.subjectTokenType!==nn)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await aS({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:Po};let n=await G().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 vt(r.refreshToken),idpSubjectTokenType:nn,idpSubjectTokenExpiresAt:void 0}});return se()?.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 gr(t),newSubjectRefreshTokenFingerprint:await gr(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:n,subjectToken:r.idToken,subjectTokenType:Po}}o(EA,"resolveIdJagSubjectToken");async function uS(e){let t="preloadedConnection"in e?e.preloadedConnection:(await G().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Me(t),n=!!e.forceRefresh,s=!n&&r==="usable",i=se(),a=i?await un({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&&IA(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Ct(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||dS(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&&dS(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=Lt(e.upstreamServerId),p=Qg(e.upstreamServerId,e.authProfileId),h=p.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(p.scopes.length===0?void 0:p.scopes.join(p.scopeDelimiter)),y=await EA({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:p.idp.tokenUrl},clientAuth:p.idp.clientAuth,context:e.context}),b=await iS({idp:{tokenUrl:p.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:p.resourceAs.audience,resource:h,scope:f,clientAuth:p.idp.clientAuth,context:e.context}),w=b.scope??f,S=await cS({resourceAs:{tokenUrl:p.resourceAs.tokenUrl},assertion:b.assertion,resource:h,scope:w,clientAuth:p.resourceAs.clientAuth,context:e.context});if(TA(S),t!==void 0){let v=(S.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],x=S.expiresIn===void 0?void 0:W(new Date(Date.now()+S.expiresIn*1e3)),N=await G().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await vt(S.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:v,expiresAt:x,metadata:y.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:v.length,expiresAt:x},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:S.accessToken}}}o(uS,"authorizeUpstreamIdJagRequest");var Bi=new Map;function kA(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(kA,"normalizeRefreshFlightScope");function AA(e){return ji(new URL(e.callbackPath,ce(e.requestUrl,e.requestHeaders))).toString()}o(AA,"buildGatewayOAuthRedirectUri");async function gd(e){let t=Lt(e.upstreamServerId),r=cn(e.upstreamServerId,e.authProfileId),n=AA({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await G().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:ce(e.request.url,e.request.headers)}}}o(gd,"prepareUpstreamOAuthRequest");async function lS(e){let t=await gd(e),r=new Bt({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Xy(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(lS,"startUpstreamConnect");async function pS(e){let t=await gd(e),r=new Bt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>Qy({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&&Me(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n();let s=Th({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,kA(r.configuredAuthorizationScope??e.requestedScope)]),a=Bi.get(i);if(a!==void 0){se()?.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:p,...h}=e;if(t=await gd(h),r=new Bt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Me(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&&Me(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{Bi.get(i)===d&&Bi.delete(i)}),Bi.set(i,d),c}o(pS,"authorizeUpstreamRequest");async function Fi(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return pS({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 uS({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 Ee(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(Fi,"resolveUpstreamCredentialForRoute");async function mS(e){if(e.connectRequest.authMode==="id-jag")throw new Ee(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await lS({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(mS,"startUpstreamConnectForRequest");async function PA(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 Oi({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(PA,"requireCallbackBrowser");async function hS(e){let t=await zi(e.callbackRequest.state);$t()&&await PA(e,t.browserBinding);let r=t.authProfileId;if(Ai({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Ee(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return eS({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:Lt(e.callbackRequest.upstreamServerId)})}o(hS,"finishUpstreamCallbackForRequest");function xA(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(xA,"buildRouteAuthBaseFromConnection");function fS(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:nh(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(fS,"buildRouteAuthBaseFromPolicyOptions");function Ji(e,t){let n=Ie().byOperationId.get(t);if(!n)throw new re(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(n.connection===void 0)throw new re(`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 re(`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 xA({connection:n.connection,operationId:t})}o(Ji,"resolveRouteAuthBase");function yd(e,t){switch(e){case"user":return tn(t);case"shared":return th()}}o(yd,"buildOwnerForSubject");function mn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:yd("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:yd("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:yd("user",t),initiatedBySubjectId:t}}}o(mn,"resolveRouteAuthForSubject");import{base64url as OA,errors as gS,jwtVerify as MA,SignJWT as UA}from"jose";var Sd="zuplo-connect.",qA=600,yS="mcp_connect_request_state",zA=m.object({purpose:m.literal(yS),binding:m.string().min(1),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),NA=new TextEncoder;async function SS(){return Ze({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"connect-request-state"),"derive")})}o(SS,"getConnectRequestStateKey");async function RS(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",NA.encode(t));return OA.encode(new Uint8Array(r))}o(RS,"digestBinding");function Rd(e){return typeof e=="string"&&e.startsWith(Sd)}o(Rd,"isConnectRequestState");async function wS(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new UA({purpose:yS,binding:await RS(e)}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt(r).setExpirationTime(r+qA).sign(await SS());return`${Sd}${n}`}o(wS,"signConnectRequestState");async function _S(e,t,r=new Date){if(!Rd(e))return"foreign";let n;try{let{payload:s}=await MA(e.slice(Sd.length),await SS(),{algorithms:[be],issuer:fe,audience:_e,currentDate:r,clockTolerance:0});n=zA.parse(s)}catch(s){return s instanceof gS.JWTExpired?"expired":s instanceof gS.JWTClaimValidationFailed||s instanceof m.ZodError?"invalid":"foreign"}return n.binding===await RS(t)?void 0:"mismatch"}o(_S,"verifyConnectRequestState");var jA=new Set(["initialize","ping","logging/setLevel","resources/subscribe","resources/unsubscribe","tasks/list","tasks/result"]);function bS(e){if(!xe()||!jA.has(e.method))return;let t=we(e.message);return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:I.MethodNotFound,message:"Method not found"}}),{status:404})}o(bS,"modernMethodNotFoundResponse");var DA=new Map([["tools/list","tools"],["prompts/list","prompts"],["resources/list","resources"],["resources/templates/list","resourceTemplates"]]),LA=0,$A="private",HA=new Set(["tools/call","prompts/get","resources/read"]);var BA=-32021,FA="Invalid or expired requestState";function yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yr,"isRecord");function JA(e,t){if(!(!te()||!yr(t)||typeof t.method!="string"||!Fr(e,t)))return{message:t,method:t.method}}o(JA,"readModernMcpRequest");async function vS(e,t){return xe()?!te()||!yr(t)||typeof t.method!="string"||!Bs(e.headers,t)||await vm(e.clone(),t,{maxRequestBodySize:Number.MAX_SAFE_INTEGER})?void 0:{message:t,method:t.method}:JA(e.headers,t)}o(vS,"classifyModernMcpRequest");function wd(e){return!Object.hasOwn(e.message,"id")}o(wd,"isModernNotification");function _d(){return new Response(null,{status:202})}o(_d,"acceptedNotificationResponse");function bd(e){let t=e.message.params;return yr(t)?t:void 0}o(bd,"readParams");function CS(e){if(!HA.has(e.method))return;let t=bd(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}o(CS,"readInputRequiredTarget");function IS(e,t,r){return{...e,method:t.method,target:r}}o(IS,"buildBinding");function VA(e){let t=we(e.message);return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:I.InvalidParams,message:FA,data:{reason:"invalid_request_state"}}}))}o(VA,"invalidRequestStateResponse");function GA(e){if(!yr(e))return;let t=e[Jr],r=yr(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}o(GA,"readElicitationAction");function KA(e){let t={...bd(e)};if(delete t.requestState,yr(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(KA,"stripConnectState");async function TS(e){let t=bd(e.request),r=t?.requestState;if(!Rd(r))return{kind:"none"};let n=CS(e.request),s=n===void 0?"mismatch":await _S(r,IS(e.binding,e.request,n),e.now);if(s==="foreign")return{kind:"none"};if(s!==void 0)return{kind:"rejected",reason:s,response:VA(e.request)};let i=KA(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:GA(t?.inputResponses)}}o(TS,"readModernConnectRetry");function WA(e){let t=km(e.message)?.elicitation;return yr(t)&&t.url!==void 0}o(WA,"declaresUrlElicitation");function ZA(e,t){return Response.json(Pe({...e===void 0?{}:{id:e},error:{code:Sc,message:t.message,data:{connectRequired:t}}}))}o(ZA,"connectRequiredErrorResponse");async function ES(e){if(wd(e.request))return _d();let t=we(e.request.message),r=DA.get(e.request.method);if(r!==void 0)return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",[r]:[],ttlMs:LA,cacheScope:$A,_meta:{[Mt]:e.serverInfo}}});let n=CS(e.request),s=e.payload.authUrl;if(n===void 0||s===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return ZA(t,e.payload);if(!WA(e.request))return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:BA,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 i=await wS(IS(e.binding,e.request,n),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:s}}},requestState:i,_meta:{[Mt]:e.serverInfo}}})}o(ES,"modernConnectRequiredResponse");var vd=new WeakMap;function kS(e,t){vd.set(e,t)}o(kS,"setUpstreamAuthRetry");function AS(e){let t=vd.get(e);return vd.delete(e),t}o(AS,"takeUpstreamAuthRetry");var PS=new WeakSet;function xS(e){PS.add(e)}o(xS,"markGatewayUpstreamCredential");function OS(e){return PS.has(e)}o(OS,"sentGatewayUpstreamCredential");async function MS(e){try{return await Fi(e)}catch(t){if(Be(t)==="upstream_token_refresh_unavailable")return{kind:"refresh_unavailable"};throw t}}o(MS,"resolveCredentialOrRefreshUnavailable");function US(e,t){return en(e,t,{code:"upstream_token_refresh_unavailable"})}o(US,"refreshUnavailableResponse");var YA="The upstream connection returned no OAuth tokens.";function qS(e){let t=hc(e);return Response.json(Pe({id:t,error:{code:I.InternalError,message:YA}}),{status:t===void 0?500:200})}o(qS,"noUpstreamTokensJsonRpcResponse");function XA(e,t){return{credentialType:e.type,forceRefresh:t}}o(XA,"buildCredentialResolvedAttributes");function QA(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(QA,"connectRequiredReasonCode");function zS(e){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:XA(e.credential,e.forceRefresh===!0)})}o(zS,"emitCredentialResolvedAnalyticsEvent");function NS(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(ne(e.context,{eventType:Z.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"){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:QA(e.payload.state),reasonClass:"auth",attributes:t})}o(NS,"emitCredentialMissingAnalyticsEvents");function eP(e){let t=e.route.raw();return Js.parse(t?.operationId)}o(eP,"readOperationId");async function tP(e,t,r,n,s){let i=await MS({request:e,context:n,routeAuth:t});if(i.kind==="refresh_unavailable")return i;if(i.kind==="connect_required")return NS({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(zS({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(tP,"buildCredentialHeaders");var rP=new Set(["authorization","cookie","cookie2"]);function jS(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(jS,"parseJsonRequestBody");function nP(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(nP,"readJsonRequestMethod");function oP(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(oP,"isJsonResponse");function Ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ft,"isRecord");function DS(e){return Array.isArray(e)&&e.length>0}o(DS,"hasIconList");function LS(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Ei(Qm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(LS,"readFallbackServerIcons");function sP(e){if(!Ft(e.body))return e.body;let t=e.body.result;if(!Ft(t))return e.body;let r=t.serverInfo;return!Ft(r)||DS(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(sP,"addMissingServerIcons");function iP(e){if(!Ft(e.body))return e.body;let t=e.body.result;if(!Ft(t))return e.body;let r=t._meta;if(!Ft(r))return e.body;let n=r[Mt];return!Ft(n)||DS(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[Mt]:{...n,icons:e.icons}}}}}o(iP,"addMissingDiscoverServerIcons");function aP(e,t){let r=$S(e.headers);for(let n of rP)r.delete(n);for(let[n,s]of t)r.set(n,s);return new xt(e,{headers:r})}o(aP,"applyUpstreamHeaders");function $S(e){let t=new Headers(e);return ku(t),t}o($S,"buildProxyHeaders");async function cP(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(cP,"readRetryBody");function dP(e){return xe()&&e.httpMethod==="POST"?Zf({body:e.requestBody,parsed:jS(e.requestBody),headers:e.headers,payload:e.payload}):Response.json(Rc({id:hc(e.requestBody),payload:e.payload,urlElicitation:!0,fallbackCode:I.InvalidRequest}))}o(dP,"connectRequiredJsonRpcResponse");function uP(e){let t=e.modern;if(t===void 0)return{respond:o(async i=>xe()&&e.httpMethod!=="POST"?await Si(e.request,e.context):dP({requestBody:e.requestBody,httpMethod:e.httpMethod,headers:e.headers,payload:i}),"respond")};let r=o(()=>LS({connection:e.connection,context:e.context}),"readIcons"),n=yi(t.binding.upstreamServerId,$o),s=t.request.method==="server/discover"?async()=>Bf({request:t.request,supportedVersions:n,connection:e.connection,capabilityFilter:lP(e.context),icons:r()}):i=>ES({request:t.request,payload:i,binding:t.binding,previousAction:t.previousAction,serverInfo:gc({connection:e.connection,icons:r()})});return{respond:o(async i=>{let a=Hg({headers:e.headers,message:t.request.message,supportedVersions:n});return a!==void 0?a:wd(t.request)?_d():bS(t.request)??s(i)},"respond")}}o(uP,"createConnectRequiredResponder");function lP(e){return rn()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(lP,"readRouteCapabilityFilter");async function pP(e){let{scope:t}=Nf(e.upstreamResponse),r=await MS({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="refresh_unavailable")return r;if(r.kind==="connect_required")return NS({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(zS({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(pP,"applyRefreshedCredentialHeaders");function mP(e){kS(e.context,{refresh:o(async(t,r)=>{let n=await pP({request:e.request,context:e.context,headers:$S(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:qS(e.requestBody)}:n.kind==="refresh_unavailable"?{kind:"response",response:await US(e.request,e.context)}:n},"refresh")})}o(mP,"registerUpstreamAuthRetry");function hP(e){return e.body!==null&&e.status>=200&&e.status<=299&&We(e.headers.get("content-type"))==="text/event-stream"&&!ht(e.headers)}o(hP,"isRewritableEventStream");function fP(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(fP,"answersRequestId");function gP(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(!(!Ft(r)||"method"in r||!("result"in r||"error"in r)||!fP(r.id,t)))return r}o(gP,"readResponseInEvent");function yP(e){let t=!1;return wi(e.response,r=>{if(t)return;let n=gP(r,e.requestId);if(n===void 0)return;t=!0;let s=e.addMissingIcons({body:n,icons:e.icons});return s===n?void 0:Fo(r,JSON.stringify(s))},{failureMode:"open"})}o(yP,"addMissingIconsToEventStream");function SP(e){let t=nP(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?sP:iP,n=LS({connection:e.connection,context:e.context});if(n===void 0||n.length===0)return;let s=te()?we(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!oP(i))return s!==void 0&&hP(i)?yP({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=Xf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(SP,"installInitializeIconHook");function RP(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new xt(e,{headers:r,body:t})}o(RP,"withRequestBody");async function Cd(e,t,r){let n=Date.now(),s=eP(t),i=e,a=await cP(i),c=jS(a),d=o(async(x,N)=>(await Xg({request:i,context:t,requestJson:c,requestBody:a,response:x,startTime:n,...N===void 0?{}:{outcome:N}}),x),"answer"),u=lr(i.headers,c),p=fS({connection:r,operationId:s}),h=pr(i.user,i.url,i.headers);Ph(t,h);let f=mn(p,h.subjectId),y=await vS(i,c),b={subjectId:h.subjectId,operationId:s,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId},w;if(y!==void 0){let x=await TS({request:y,binding:b});if(x.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:x.reason,upstreamServerId:f.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),d(x.response);x.kind==="accepted"&&(i=RP(i,x.body),a=x.body,c=x.request.message,y=x.request,w=x.action)}let S=uP({request:i,requestBody:a,httpMethod:i.method,headers:i.headers,modern:y===void 0?void 0:{request:y,binding:b,previousAction:w},context:t,connection:r}),R=await tP(i,f,r,t,u);if(R.kind==="connect_required")return d(await S.respond(R.payload));if(R.kind==="no_tokens")return d(qS(a),"no_upstream_tokens");if(R.kind==="refresh_unavailable")return d(await US(i,t),"upstream_token_refresh_unavailable");let v=aP(i,R.headers);return xS(t),mP({request:v,context:t,requestBody:a,connectRequired:S,routeAuth:f,mcpProtocolVersion:u}),SP({context:t,requestJson:c,connection:r,modern:y!==void 0}),v}o(Cd,"mcpTokenExchangePolicy");var Id=class extends Os{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=oh(t,r);super(n,r),this.#e=n}async handler(t,r){return Cd(t,r,this.#e)}};var HS=Symbol("Html");function wP(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(wP,"escapeHtml");function _P(e){return e===null||typeof e!="object"?!1:e[HS]===!0}o(_P,"isHtml");function Vi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Vi).join(""):_P(e)?e.value:wP(String(e))}o(Vi,"renderValue");function Ye(e){return{[HS]:!0,value:e}}o(Ye,"trustedHtml");var Xe=Ye("");function X(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Vi(t[n]),r+=e[n+1]??"";return Ye(r)}o(X,"html");function hn(e,t=Xe){let r=Vi(t),n="",s=!0;for(let i of e)s||(n+=r),n+=Vi(i),s=!1;return Ye(n)}o(hn,"joinHtml");function fn(e){return e.value}o(fn,"renderHtml");function BS(e){return X`<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(BS,"renderBrowserErrorPage");var FS=Ye('<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>'),JS=Ye('<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>'),gn=Ye('*,: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 yn(e){return X`<!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(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};
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(yn,"renderShell");function Gi(e){return X`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?FS:JS}</div>`}o(Gi,"renderStatusIcon");var bP="text/html; charset=utf-8";function Jt(e){try{return new URL(e).host}catch{return""}}o(Jt,"safeHostFromUrl");function Qe(e){let t=e.kind??"authorization_failed",r=CP(t),n=vP(e),s=e.title??r.title;return new Response(fn(yn({title:s,iconHref:"",styles:gn,headerIcon:Gi(t==="access_denied"?"neutral":"error"),heading:s,subhead:X`<p class="card__subtitle">${e.detail}</p>`,body:BS({steps:hn(r.steps.map(i=>X`<li>${i}</li>`)),action:EP(e.action),reference:kP(n),diagnostics:AP({diagnostic:n,detail:e.detail}),upstreamResponse:PP(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":bP,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Qe,"browserErrorPageResponse");function vP(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??IP(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??TP(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(vP,"buildBrowserErrorDiagnostic");function CP(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(CP,"readBrowserErrorPagePresentation");function IP(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_refresh_unavailable":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(IP,"readBrowserErrorStage");function TP(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(TP,"readBrowserErrorSuggestedFix");function EP(e){return e===void 0?Xe:X`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(EP,"renderAction");function Ki(e){if(e.value===void 0||e.value==="")return Xe;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return X`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}o(Ki,"renderRow");function Je(e){return Ki({label:e.label,value:e.value===void 0?void 0:X`<code>${e.value}</code>`})}o(Je,"renderCodeRow");function kP(e){return hn([Ki({label:"Error code",value:X`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Je({label:"Request ID",value:e.requestId}),Je({label:"Time",value:e.timestamp})])}o(kP,"renderReference");function AP(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return hn([Ki({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Ki({label:"Reason",value:r,block:!0}),Je({label:"Stage",value:t.stage}),Je({label:"Gateway route",value:t.routePath}),Je({label:"Operation ID",value:t.operationId}),Je({label:"Upstream",value:t.upstreamServerId}),Je({label:"Auth profile",value:t.authProfileId}),Je({label:"Upstream URL",value:t.upstreamUrl}),Je({label:"Metadata URL",value:t.metadataUrl}),Je({label:"HTTP status",value:t.httpStatus}),Je({label:"Content type",value:t.contentType}),Je({label:"Provider error",value:t.providerError}),Je({label:"Provider error description",value:t.providerErrorDescription})])}o(AP,"renderDiagnostics");function PP(e){return e===void 0?Xe:X`<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(PP,"renderUpstreamHtml");var VS="application/json",xP="application/x-www-form-urlencoded";function Wi(e,t){return new k({message:e,extensionMembers:{[M]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Wi,"invalidRequestError");function OP(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(OP,"normalizeContentType");function MP(e,t){return e===t?!0:t===VS&&e.endsWith("+json")}o(MP,"contentTypeMatches");function UP(e,t){if(!t||t.length===0)return;let r=OP(e.headers.get("content-type"));if(!t.some(n=>MP(r,n)))throw Wi(`Request body must be ${t.join(" or ")}.`)}o(UP,"assertExpectedContentType");function qP(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 Wi(`${r} exceeded the maximum allowed size.`)}o(qP,"assertContentLengthWithinLimit");async function GS(e,t){let r=t.label??"Request body";UP(e,t.expectedContentTypes),qP(e,t.maxBytes,r);let n=await Mi(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Wi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(GS,"readBoundedTextBody");async function KS(e,t){let r=await GS(e,{...t,expectedContentTypes:[VS]});try{return JSON.parse(r)}catch(n){throw Wi("Request body must be valid JSON.",n)}}o(KS,"readBoundedJsonBody");async function WS(e,t){let r=await GS(e,{...t,expectedContentTypes:[xP]});return new URLSearchParams(r)}o(WS,"readBoundedFormUrlEncodedBody");import{errors as YS,jwtVerify as XS,SignJWT as Ed}from"jose";import{base64url as zP}from"jose";var NP="mcp-browser-login-pkce:",jP=new TextEncoder;async function DP(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(DP,"importHmacKey");async function Td(e){let t=await DP(e.signingKey),r=jP.encode(`${NP}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return Kr.parse(zP.encode(new Uint8Array(n)))}o(Td,"deriveBrowserLoginPkceVerifier");async function ZS(e){let t=await Td(e),r=await ei(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Gr}}o(ZS,"deriveBrowserLoginPkceParams");var LP={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},E=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=LP[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var $P=300,QS=m.string().min(1).optional(),HP=m.object({purpose:m.literal("gateway_browser_login"),transactionId:xa,stateId:Ws,binding:Zo,authorizationServerIssuer:QS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),BP=m.object({purpose:m.literal("gateway_browser_login_return"),stateId:Ws,binding:Zo,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),FP=m.discriminatedUnion("purpose",[HP,BP]),JP=m.object({purpose:m.literal("gateway_authorization_setup"),transactionId:xa,stateId:Ws,authorizationServerIssuer:QS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()});async function Sn(){return Ze({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-login"),"derive")})}o(Sn,"getBrowserLoginKey");async function eR(){return Ze({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"authorization-csrf"),"derive")})}o(eR,"getCsrfKey");function tR(e){return{now:e.now??new Date,ttlSeconds:kd()}}o(tR,"readPendingTransactionDependencies");function kd(){return ke().browserLogin.stateTtlSeconds}o(kd,"readBrowserLoginStateTtlSeconds");function VP(e){let t=ge();return He(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o(VP,"isLoopbackDevLoginUrl");async function rR(e){let t=ke().browserLogin,r=ge(),n=new URL(Ut("url")),s=new URL(r.actionPath("/oauth/callback"),qt(e.requestUrl,e.requestHeaders));if(VP(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",Ut("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===Gr){let i=await ZS({stateId:e.stateId,signingKey:await Sn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(rR,"buildBrowserLoginUrl");function GP(e,t){return e.subjectId===t.subjectId}o(GP,"principalsMatch");function nR(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(nR,"toPendingPrincipal");function oR(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:W(e.now),expiresAt:W(gt(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:nR(e.principal)}}o(oR,"createTransactionRecord");async function sR(e){let{id:t,...r}=e.record,n=await G().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 E("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new E("invalid_request","redirect_uri is not registered for the client.")}}o(sR,"startPendingTransaction");async function KP(e){return new Ed({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Sn())}o(KP,"signBrowserLoginState");async function iR(e){return new Ed({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ys(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await eR())}o(iR,"signCsrfToken");async function Ad(e){try{let{payload:t}=await XS(e,await Sn(),{algorithms:[be],issuer:fe,audience:_e}),r=FP.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 YS.JWTExpired?z("oauth_state_expired","Browser login state has expired.",t):z("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Ad,"verifyAnyBrowserLoginStateToken");async function WP(e){let t=await Ad(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(WP,"verifyBrowserLoginStateToken");async function Zi(e){try{let{payload:t}=await XS(e,await eR(),{algorithms:[be],issuer:fe,audience:_e}),r=JP.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof YS.JWTExpired?z("oauth_state_expired","Authorization setup state has expired.",t):z("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Zi,"verifyCsrfToken");function Pd(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Pd,"pendingStateErrorCode");function ZP(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(ZP,"toPendingAuthorizationGetResult");function YP(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(YP,"toPendingAuthorizationAdvanceResult");function xd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Pd(e==="consumed_already"?"consumed_already":e)}o(xd,"setupDecisionErrorCode");async function aR(e){let t=e.now??new Date,r=await Zi(e.csrfToken),n=await G().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:W(t)});if(n.kind!=="marked")throw z(xd(n.kind),"Authorization setup state is invalid, expired, or already used.");return cR({kind:"available",record:n.transaction})}o(aR,"markSetupApproved");function cR(e){if(e.kind!=="available")throw z(Pd(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(cR,"requireAwaitingSetup");function XP(e){if(!GP(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(XP,"requireCurrentPrincipalMatches");async function dR(e){let t=e.now??new Date,r=kd(),n=Oa(),s=Ys(),i=await Xo({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await KP({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=oR({id:n,transaction:e.transaction,currentStateHash:await de(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 sR({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 rR({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(dR,"startAwaitingLogin");async function uR(e){let t=kd(),r=Ys(),n=await Xo({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new Ed({purpose:"gateway_browser_login_return",stateId:r,binding:n.claim}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Sn());return{browserLoginUrl:await rR({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(uR,"startReturnToBrowserLogin");async function lR(e){let{now:t,ttlSeconds:r}=tR(e),n=Oa(),s=await iR({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=oR({id:n,transaction:e.transaction,currentStateHash:await de(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 sR({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(lR,"startAwaitingSetup");async function pR(e){let{now:t,ttlSeconds:r}=tR(e),n=await WP(e.browserLoginStateToken),s=await iR({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=YP(await G().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await de(e.browserLoginStateToken),nextStateHash:await de(s),nextPhase:"awaiting_setup",principal:nR(e.principal),now:W(t)}));if(i.kind!=="advanced")throw z(Pd(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(pR,"completeLogin");async function mR(e){let t=await Od(e);return XP({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(mR,"getSetup");async function Od(e){let t=e.now??new Date,r=await Zi(e.csrfToken);return cR(ZP(await G().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await de(e.csrfToken),now:W(t)})))}o(Od,"getSetupTransaction");async function QP(e){let t=await Zi(e.csrfToken),r=St(),n=W(gt(e.now,$P)),s=await G().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await de(r),authorizationCodeExpiresAt:n,grantId:lh(),now:W(e.now)});if(s.kind!=="approved")throw z(s.kind==="cancelled"?"oauth_state_invalid":xd(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),Yi(i,t.authorizationServerIssuer),i}o(QP,"createAuthorizationCodeRedirectWithDecision");async function ex(e){let t=await Zi(e.csrfToken),r=await G().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:W(e.now)});if(r.kind!=="cancelled")throw z(r.kind==="approved"?"oauth_state_invalid":xd(r.kind),"Authorization setup state is invalid, expired, or already used.");return tx({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(ex,"createCancelRedirectWithDecision");function Yi(e,t){t!==void 0&&te()&&e.searchParams.set("iss",t)}o(Yi,"setAuthorizationResponseIssuer");function tx(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),Yi(t,e.authorizationServerIssuer),t}o(tx,"buildClientCancelRedirect");async function hR(e){let t=e.now??new Date;return QP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(hR,"approve");async function fR(e){let t=e.now??new Date;return ex({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(fR,"cancel");import{createRemoteJWKSet as rx,errors as Rn,jwtVerify as gR,SignJWT as nx}from"jose";var ox="zuplo_mcp_session",sx=m.object({purpose:m.literal("gateway_browser_session"),sub:Eo,browserLoginOrigin:m.string().min(1),roles:m.array(m.string().min(1)).optional(),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),ix=m.object({id_token:m.string().min(1),token_type:m.string().min(1).optional(),expires_in:m.number().optional(),access_token:m.string().min(1).optional(),refresh_token:m.string().min(1).optional(),scope:m.string().min(1).optional()}),ax=m.object({error:m.string().min(1).optional(),error_description:m.string().min(1).optional(),error_uri:m.string().min(1).optional()}),cx=m.object({sub:Eo,nonce:m.string().min(1)}).catchall(m.unknown()),Md;async function yR(){return Ze({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-session"),"derive")})}o(yR,"getBrowserSessionKey");function qd(e,t){let r=xi(e,t);return{name:Qc(ox,r),secure:r}}o(qd,"browserSessionCookieName");function Ud(e,t){let{name:r,secure:n}=qd(e,t);return Yo({name:r,value:"",maxAgeSeconds:0,secure:n})}o(Ud,"buildBrowserSessionEvictionCookie");function dx(e){let{name:t,secure:r}=qd(e.requestUrl,e.requestHeaders);return Yo({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}o(dx,"serializeSessionCookie");function SR(){return new URL(Ut("url")).origin}o(SR,"readBrowserLoginOrigin");function ux(e){let t=ax.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(ux,"readIdpErrorFields");function lx(e){return e instanceof Rn.JWTExpired?"expired":e instanceof Rn.JWTClaimValidationFailed?"claim":e instanceof Rn.JWSSignatureVerificationFailed?"signature":e instanceof Rn.JWKSNoMatchingKey?"jwks_no_match":e instanceof Rn.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(lx,"readJwtFailureKind");function px(e){return e instanceof Error&&"cause"in e?e.cause:e}o(px,"readErrorCause");function mx(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(mx,"readRuntimeGatewayCode");function hx(){if(!Md){let e=ke();Md=rx(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Md}o(hx,"readFederatedJwks");function RR(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return pr(e.user,e.url)}o(RR,"resolveCurrentRequestPrincipal");async function wn(e,t={}){let r=ed(e.headers.get("cookie")).get(qd(e.url,e.headers).name);if(!r)return{};try{let{payload:n}=await gR(r,await yR(),{algorithms:[be],issuer:fe,audience:_e}),s=sx.parse(n);if(s.browserLoginOrigin!==SR())return{evictCookie:Ud(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 Rn.JWTExpired?{evictCookie:Ud(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:Ud(e.url,e.headers)})}}o(wn,"readBrowserSession");async function rs(e){let t=ke().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:SR()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new nx(r).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await yR());return dx({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(rs,"createBrowserSessionCookie");async function fx(e){let t=ke(),r=Ut("tokenUrl"),n=Ut("clientId"),s=Ut("clientSecret"),i=new URL(ge().actionPath("/oauth/callback"),qt(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===Gr){let c=await Td({stateId:e.stateId,signingKey:await Sn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await Ui(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 y=ux(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ie(r),idpStatus:c.status,...y},"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}${y.idpError?` idp_error=${y.idpError}`:""}${y.idpErrorDescription?` idp_error_description=${y.idpErrorDescription}`:""})`)})}let u=ix.parse(d),p;try{({payload:p}=await gR(u.id_token,hx(),{issuer:t.oidc.issuer,audience:n}))}catch(y){let b={};throw Ae(b,"error",y),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:lx(y),idpHost:ie(r),expectedIssuer:t.oidc.issuer,...b},"Federated id_token failed jose verification"),y}if(p.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ie(r),nonceMissingFromIdToken:p.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=cx.parse(p);return{principal:pr({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:Po,expiresAt:typeof p.exp=="number"?W(new Date(p.exp*1e3)):void 0}}}catch(c){let d=Be(c)??mx(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",px(c))}}o(fx,"exchangeFederatedAuthorizationCode");async function zd(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return fx({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await wn(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(zd,"resolveBrowserLoginCallbackIdentity");var gx=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function yx(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(yx,"readScheme");function Sx(e){return e.protocol==="https:"}o(Sx,"isSpecCompliantRedirectUri");function Rx(e){let t=yx(e);return t.length>0&&t!=="http"&&t!=="https"&&!gx.has(t)}o(Rx,"isNativeAppCustomSchemeRedirectUri");var _R=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>Sx(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>He(e),"accepts"),matches:o((e,t)=>He(e)&&He(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>Rx(e),"accepts")}];function bR(e){let t=_R.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(bR,"evaluateBuiltInRedirectUriCompatibility");function wR(e){try{return new URL(e)}catch{return}}o(wR,"parseUrl");function vR(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=wR(e.registeredRedirectUri),r=wR(e.requestedRedirectUri);return t===void 0||r===void 0?!1:_R.some(n=>n.matches?.(t,r))}o(vR,"redirectUriMatchesBuiltInCompatibility");var wx=1e4,_x=5*1024,bx=0,vx=2160*60*60,CR=["authorization_code","refresh_token",Gs,zt],Cx=["authorization_code","refresh_token"],IR=[ch],Ix=["code"],Tx=m.object({client_name:m.string().min(1).optional(),redirect_uris:m.array(m.string().min(1)).min(1),grant_types:m.array(m.enum(CR)).min(1).max(CR.length).optional(),authorization_grant_profiles_supported:m.array(m.enum(IR)).min(1).max(IR.length).optional(),response_types:m.array(m.enum(Ix)).min(1).max(1).optional(),scope:m.literal(he).optional(),token_endpoint_auth_method:uh.optional(),jwks_uri:m.string().min(1).optional()});function Ex(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&He(t))&&t.pathname!=="/"}catch{return!1}}o(Ex,"isCimdClientIdCandidate");function TR(e,t){throw new E("invalid_client",wh({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(TR,"invalidCimdClientError");function _n(e,t="invalid_request"){if(kx(e))throw new E(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new E(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new E(t,"redirect_uris must not include credentials or fragments.");if(bR({url:r}).kind==="rejected")throw new E(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(_n,"assertValidRedirectUri");function kx(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(kx,"hasForbiddenRawRedirectUriCharacter");async function Ax(e){let{response:t,json:r}=await ly(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:bx,maxResponseBytes:_x,timeoutMs:wx});if(!t.ok)throw z("invalid_request","CIMD metadata could not be fetched.");let n=Zs(r);for(let s of n.redirect_uris)_n(s,"invalid_request");if(n.jwks_uri!==void 0&&Oo(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(Ax,"fetchCimdMetadata");async function Px(e){let t=Xs(e),r=await Ax({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(Px,"resolveCimdClient");async function Xi(e,t){let r=yt.parse(e);if(Ex(r)){ke().gateway.downstreamCimdEnabled||TR(r);try{return await Px(r)}catch(s){TR(r,s)}}let n=await G().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=bh(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 E("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=Zs({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 E("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(Xi,"resolveClient");function ER(e,t){if(!e.metadata.redirect_uris.some(r=>vR({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(ER,"assertRedirectRegistered");function xx(e){return e===void 0?[...Cx]:Array.from(new Set(e))}o(xx,"normalizeGrantTypes");function Ox(e){try{Oo(e)}catch(t){throw new E("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(Ox,"assertValidDcrJwksUri");function Mx(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?yt.parse(_h({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):yt.parse(`dcr:${crypto.randomUUID()}`)}o(Mx,"createDcrClientId");function bn(e){if(e===void 0||e===he)return he;throw new E("invalid_request",`Only the ${he} scope is supported.`)}o(bn,"assertSupportedOAuthScope");function Sr(e,t,r){let n;try{n=new URL(t)}catch{throw new E("invalid_target","resource must be an absolute URI.")}if(n.hash)throw new E("invalid_target","resource must not include a fragment.");if(n.protocol!=="https:"&&!He(n))throw new E("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ce(e,r),i=rn(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new E("invalid_target","resource must match a published MCP route.");return a}o(Sr,"resolveResource");async function kR(e){let t;try{t=Tx.parse(e)}catch(y){if(y instanceof m.ZodError){let b=y.issues.some(w=>w.path[0]==="redirect_uris");throw new E(b?"invalid_redirect_uri":"invalid_client_metadata",y.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:y})}throw y}for(let y of t.redirect_uris)_n(y,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new E("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&Ox(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=Mx({tokenEndpointAuthMethod:n,jwksUri:t.jwks_uri}),a=Zs({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=gt(r,vx),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),p={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:xx(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:he,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:W(r),clientExpiresAt:W(c)};if(n==="client_secret_basic"||n==="client_secret_post"){let y=St();h.hashedClientSecret=await de(y),h.clientSecretExpiresAt=W(c),p.client_secret=y,p.client_secret_expires_at=u,p.client_secret_issued_at=d}if((await G().registerClient(h)).kind==="already_exists")throw z("invalid_request","OAuth client is already registered.");return p}o(kR,"registerDownstreamClient");function Ux(e){return e?.metadata?.idpSubjectTokenType!==nn&&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(Ux,"hasStoredIdJagSubjectTokenBinding");async function AR(e){let t=tn(e.principal.subjectId);return(await G().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(AR,"readIdJagSubjectConnection");async function Nd(e){let t=Ie().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await AR({connection:t.connection,principal:e.principal});return!Ux(r)}o(Nd,"requiresIdJagSubjectTokenBinding");async function PR(e){if(e.subjectToken===void 0)return;let t=Ie().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 AR({connection:t.connection,principal:e.principal});return G().upsertUpstreamConnection({id:r?.id??Qs(),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 vt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}o(PR,"bindIdJagSubjectTokenForAuthorizationTransaction");function xR(e){return X`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(xR,"renderShellIcon");function OR(e){return X`<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(OR,"renderActions");var MR=Ye('<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 UR(e){return X`<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(UR,"renderBannerWarning");var N1=Ye('<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>'),j1=Ye('<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 D1=Ye('<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 qx="data:,",qR=X`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);"`,zR=X`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 zx(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(zx,"safeGatewayConnectHref");function Nx(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Nx,"deriveMode");function jx(e){return OR({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:qR,authorizeAttrs:Xe})}o(jx,"renderActions");function jd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=zx(s.connectUrl,t,n);if(i)return i}}o(jd,"firstUserConnectHref");function Dx(e){let t=e.connectHref===void 0?Xe:X`<a class="button button--primary" href="${e.connectHref}" ${zR}>Connect</a>`;return X`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${qR}><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(Dx,"renderSetupActions");function Lx(e){return e?X`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${zR}>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>`:Xe}o(Lx,"renderReconnectAction");function $x(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($x,"isRenderableIconHref");function NR(e){return e?.find(t=>$x(t.src))?.src}o(NR,"readIconHref");function Hx(e){return NR(e.serverIcons)??(e.transportHost===void 0?void 0:Jc(e.transportHost).src)}o(Hx,"readUpstreamIconHref");function Bx(e){let t=NR(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=Hx(r);if(n!==void 0)return n}}o(Bx,"readHeaderIconHref");function Fx(e){let t=e.setupMessage===void 0?Xe:UR({icon:MR,message:e.setupMessage});return X`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}o(Fx,"renderBody");function Dd(e){let t=Nx(e.upstreams),r=jd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),n=jd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=jd(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=Bx({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?X`<footer class="card__footer">${Dx({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:X`<footer class="card__footer">${Lx(s)}${jx({state:e.state,gateway:e.gateway})}</footer>`;return fn(yn({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??qx,styles:gn,headerIcon:c===void 0?Xe:xR({iconHref:c,fallbackIconHref:Ng}),heading:"Authorize access",subhead:Xe,body:Fx({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(Dd,"renderConsentPage");var Jx=1e4,Vx=2e3,Gx=64*1024,jR=1024*1024,VR={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},Ld="mcp-session-id",GR=1,Kx=/^\d{4}-\d{2}-\d{2}$/,Wx;function $d(){return{tools:[],prompts:[],resources:[]}}o($d,"emptyCapabilities");function DR(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ma})}o(DR,"buildReadinessHeaders");async function LR(e){if(e.type==="bearer_token"){let n=DR();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=DR();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(LR,"buildAsyncCredentialHeaders");function Zx(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(cr.parse({jsonrpc:ar,id:GR,method:"initialize",params:{protocolVersion:Ma,capabilities:{},clientInfo:VR}}))})}o(Zx,"buildInitializePreflight");function Yx(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",ur),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:ar,id:1,method:"server/discover",params:{_meta:{[Cm]:ur,[Im]:{},[Tm]:VR}}})})}o(Yx,"buildDiscoverPreflight");async function Xx(e){if(e.status!==400&&e.status!==404)return!1;let t=await KR(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(Xx,"isModernRejectionOfInitialize");async function KR(e,t=Gx){let r=new TextDecoder,n="";return WR(e,t,s=>{if(s===void 0)return n+r.decode();n+=r.decode(s,{stream:!0})})}o(KR,"readBoundedBody");async function WR(e,t,r){let n=e.body?.getReader();if(n===void 0)return;let s,i=new Promise(c=>{s=setTimeout(()=>c("timeout"),Vx)}),a=(async()=>{let c=0;for(;;){let{done:d,value:u}=await n.read();if(d)return r(void 0);if(c+=u.byteLength,c>t)return;let p=r(u);if(p!==void 0)return p}})();try{let c=await Promise.race([a,i]);return c==="timeout"?void 0:c}catch{return}finally{clearTimeout(s),n.cancel().catch(()=>{})}}o(WR,"readBoundedChunks");async function Hd(e){xo(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Jx);try{let n=new Request(e,{redirect:"manual",signal:t.signal});return await wu.fetch(n)}finally{clearTimeout(r)}}o(Hd,"runPreflight");function ns(e){e.body?.cancel().catch(()=>{})}o(ns,"releasePreflightBody");async function ZR(e){if(We(e.headers.get("content-type"))!=="text/event-stream"){let n=await KR(e,jR);return n===void 0?void 0:$R(HR(n))?.result}let t=new fr;return(await WR(e,jR,n=>{let s=n===void 0?t.end():t.push(n);for(let i of s){let a=i.data===void 0?void 0:$R(HR(i.data));if(a!==void 0)return a}}))?.result}o(ZR,"readProbeResult");async function Qx(e){let t=(await ZR(e))?.protocolVersion;return typeof t=="string"&&Kx.test(t)?t:void 0}o(Qx,"readNegotiatedProtocolVersion");function $R(e){if(!(!BR(e)||e.id!==GR))return{result:BR(e.result)?e.result:void 0}}o($R,"probeAnswer");function HR(e){try{return JSON.parse(e)}catch{return}}o(HR,"parseJson");function BR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(BR,"isRecord");async function eO(e){let t=e.response.headers.get(Ld);if(!t)return;let r=new Headers(e.headers);r.set(Ld,t),r.delete("content-type"),e.protocolVersion!==void 0&&r.set("mcp-protocol-version",e.protocolVersion);try{let n=await Hd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));ns(n)}catch{}}o(eO,"terminatePreflightSession");async function YR(e){let{response:t}=e;if(e.discover===!0){let s=await ZR(t),i=fi("server/discover",{result:s});return i!==void 0&&e.upstreamServerId!==void 0&&gi(e.upstreamServerId,i,{modernOnly:!0}),{kind:"ready",upstreamStatus:t.status,capabilities:$d()}}let r=xe()&&t.status>=200&&t.status<300&&t.headers.has(Ld),n=r?await Qx(t):void 0;return r||ns(t),t.status>=200&&t.status<300?(te()&&e.upstreamServerId!==void 0&&Jf(e.upstreamServerId),await eO({...e,protocolVersion:n}),{kind:"ready",upstreamStatus:t.status,capabilities:$d()}):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(YR,"classifyResponse");function FR(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(FR,"connectRequiredResult");async function XR(e){let t=await Hd(Zx(e));if(!te()||!await Xx(t))return{response:t,discover:!1};try{let r=await Hd(Yx(e));if(r.status>=200&&r.status<300)return ns(t),{response:r,discover:!0};ns(r)}catch{}return{response:t,discover:!1}}o(XR,"probeUpstream");async function tO(e){try{let t=await XR(e);return YR({response:t.response,discover:t.discover,upstreamUrl:e.upstreamUrl,headers:e.headers,upstreamServerId:e.upstreamServerId})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}o(tO,"classifyPreflight");async function JR(e){try{return await Fi(e)}catch(t){if(Be(t)!=="upstream_token_refresh_unavailable")throw t;return{kind:"upstream_unavailable",message:"The upstream token endpoint could not refresh the connection. Retry later."}}}o(JR,"resolveReadinessCredential");async function rO(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:$d()};let r=Ji(t.upstreamServerId,e.route.operationId),n=mn(r,e.subjectId),s=e.returnTo===void 0?n:{...n,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await JR({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="upstream_unavailable")return a;if(a.kind==="connect_required")return FR(a.payload);let c=await LR(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 XR({upstreamUrl:t.mcpUrl,headers:c})}catch(f){return{kind:"upstream_unavailable",message:f instanceof Error?f.message:"Upstream MCP server readiness preflight failed."}}let{response:u}=d;if(u.status!==401)return YR({response:u,discover:d.discover,upstreamUrl:t.mcpUrl,headers:c,upstreamServerId:t.upstreamServerId});ns(u);let p=await JR({request:i,routeAuth:s,forceRefresh:!0});if(p.kind==="upstream_unavailable")return p;if(p.kind==="connect_required")return FR(p.payload);let h=await LR(p.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:tO({upstreamUrl:t.mcpUrl,headers:h,upstreamServerId:t.upstreamServerId})}o(rO,"checkUpstreamRouteReadinessImpl");function QR(e){return(Wx??rO)(e)}o(QR,"checkUpstreamRouteReadiness");function nO(e){try{return new URL(e).host}catch{return}}o(nO,"safeUrlHost");function ew(e){return e!==void 0&&e.length>0}o(ew,"hasItems");function oO(e){let t=e.serverInfo?.icons;if(ew(t))return t;let r=Ei(e.mcpUrl);return r===void 0?void 0:[r]}o(oO,"readServerIcons");async function sO(e){let{authConfig:t,authMode:r,description:n,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",p=u&&r!=="id-jag",h=e.readiness??(u?Eh(e.connection):{connected:!0,status:"active"}),f=p?e.readiness?.connectUrl??(e.returnTo!==void 0?await nd({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,y=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:n,transportHost:nO(i),scopesRequested:ew(y)?y:void 0,serverIcons:oO(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(sO,"buildSetupRequirement");function tw(e){let t=Ie().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(tw,"requireRoute");async function Bd(e){let t=tw(e.transaction.operationId),r=tn(e.transaction.principal.subjectId),n=t.connection;if(n===void 0)return[];let i=n.ownerMode==="user"?(await G().batchGetUpstreamConnections([{owner:r,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId}]))[0]:void 0,a=await QR({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 sO({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(Bd,"requirementsForSetup");async function Fd(e){let t=tw(e.transaction.operationId),r=await G().readClient({clientId:e.transaction.clientId}),n=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ce(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(Fd,"consentContext");function Jd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Jd,"hasUnresolvedUserUpstream");var iO=["mcp_user"],aO="dev-browser-user",cO=["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(" "),dO=m.object({response_type:m.literal("code"),client_id:m.string().min(1),redirect_uri:m.string().min(1),resource:m.url(),code_challenge:m.string().min(43),code_challenge_method:Zm,state:m.string().min(1).optional(),scope:m.literal(he).default(he)}),uO=m.enum(["continue","approve","cancel"]).default("continue"),lO=m.object({state:m.string().min(1),decision:uO}),Vt=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 rw(e){return typeof e=="string"&&e.length>0?e:void 0}o(rw,"readQueryString");function pO(e,t){let r=rw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new E("invalid_target",cO)}let n=gh(t,e.url,e.headers);if(r===void 0||r===n)return n;throw new E("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(pO,"requireAuthorizeResource");async function mO(e,t){let r={};t!==void 0&&(r.context=t);let n=await wn(e,r);if(n.principal)return{principal:n.principal};if(!e.user)return n.evictCookie===void 0?{}:{setCookie:n.evictCookie};let s=RR(e);return{principal:s,setCookie:await rs({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o(mO,"resolveBrowserPrincipal");async function hO(e,t){let r={};t!==void 0&&(r.context=t);let n=await wn(e,r);if(!n.principal)throw z("authentication_required","Authorization setup requires a current browser session.");return n.principal}o(hO,"requireSetupPrincipal");function nw(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(nw,"buildSetupReturnTo");async function ow(e){let t=await Bd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:nw(e.csrfToken)}),r=await Fd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),n={kind:"setup_page",html:Dd({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(ow,"renderSetup");function fO(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(fO,"toAuthorizationTransactionClient");async function Vd(e,t={}){let r=dO.parse({...e.query,resource:pO(e,t.operationId),state:rw(e.query.state)}),n=bn(r.scope);_n(r.redirect_uri,"invalid_request");let s=te()?t.operationId===void 0?qt(e.url,e.headers):ph({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=yt.parse(r.client_id),c=await Xi(r.client_id,i);ER(c,r.redirect_uri);try{let d=Sr(e.url,r.resource,e.headers),u=fO(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&&ne(t.context,{eventType:Z.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type}});let p={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 mO(e,t.context),y=h===void 0?!1:await Nd({operationId:d.operationId,principal:h});if(!h||y){let w=await dR({transaction:p,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:w.browserLoginUrl,setCookies:[...f===void 0?[]:[f],w.browserBindingCookie]}}let b=await lR({transaction:p,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&&ne(t.context,{eventType:Z.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type,subjectId:h.subjectId}}),ow({transaction:b.transaction,csrfToken:b.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw gO({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Vd,"authorizeDownstreamClient");function gO(e){if(e.cause instanceof Vt)return e.cause;let t=yO(e.cause);return t?new Vt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(gO,"toDownstreamAuthorizeRedirectError");function yO(e){if(e instanceof E)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof m.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(yO,"mapToOAuthRedirectError");async function sw(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,p=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},...p===void 0?{}:{idpErrorUri:p}},"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 Ad(n),i=await Oi({purpose:"login",claim:s.binding,request:e});if(!i.matched&&$t())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=SO(i.payload),p=await zd(a);return{kind:"redirect",location:new URL(u,ce(e.url,e.headers)),setCookies:[await rs({principal:p.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await zd(a),d=await pR({browserLoginStateToken:n,principal:c.principal});if(await PR({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await Nd({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 ow({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await rs({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}o(sw,"completeBrowserLoginCallback");function SO(e){let t=ko(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(SO,"readConnectReturnTo");async function iw(e){let t=await uR(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(iw,"startConnectBrowserLogin");async function aw(e){let t=ke(),r=new URL(e.url);if(!He(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,ce(e.url)),a=new URL(ce(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:Eo.parse(aO),roles:iO};return{kind:"redirect",location:i,setCookies:[await rs({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(aw,"completeLocalDevBrowserLogin");function RO(e){let t=e.method==="POST"?e.body:e.query;return lO.parse(t)}o(RO,"readSetupContinueRequest");async function cw(e){let{state:t,decision:r}=RO({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await Od({csrfToken:t,now:n}),i=await hO(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await fR({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await mR({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Bd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:nw(t)});if(r==="approve"&&Jd(c)&&await aR({csrfToken:t,currentBrowserPrincipal:i,now:n}),Jd(c)){let d=await Fd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:Dd({state:t,operationId:a.operationId,gateway:ge(),upstreams:c,...d})}}return{kind:"redirect",location:await hR({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(cw,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as OO,decodeJwt as MO,errors as ss,jwtVerify as UO}from"jose";import{createRemoteJWKSet as wO,decodeJwt as _O,decodeProtectedHeader as bO,errors as os,jwtVerify as vO}from"jose";var mw=30,ue=m.string().min(1),CO=m.union([ue,m.array(ue).min(1)]),IO=m.union([ue,m.array(ue).min(1)]),TO=m.object({type:ue,locations:m.array(ue).optional(),actions:m.array(ue).optional(),datatypes:m.array(ue).optional(),identifier:ue.optional(),privileges:m.array(ue).optional()}).passthrough(),EO=m.object({iss:m.url(),sub:ue,aud:CO,client_id:ue,resource:IO.optional(),scope:ue.optional(),authorization_details:m.array(TO).optional(),jti:ue,iat:m.number().int(),nbf:m.number().int().optional(),exp:m.number().int(),tenant:ue.optional(),aud_tenant:ue.optional(),aud_sub:ue.optional(),sub_id:ue.optional(),act:m.unknown().optional(),email:ue.optional(),auth_time:m.number().int().optional(),acr:ue.optional(),amr:m.array(ue).optional(),cnf:m.unknown().optional()}).passthrough();function Ve(e){throw new E("invalid_grant",e)}o(Ve,"throwInvalidGrant");function kO(e){return e instanceof os.JWTExpired?"expired":e instanceof os.JWTClaimValidationFailed?"claim":e instanceof os.JWSSignatureVerificationFailed?"signature":e instanceof os.JWKSNoMatchingKey?"jwks_no_match":e instanceof os.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(kO,"readJwtFailureKind");function AO(e){return Array.isArray(e.aud)?(e.aud.length!==1&&Ve("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}o(AO,"readSingleAudience");function dw(e){try{let t=EO.parse(e);return AO(t),t}catch(t){if(t instanceof E)throw t;Ve("ID-JAG claims are invalid.")}}o(dw,"parseIdJagClaims");function PO(e,t){e.idJag.enabled||Ve("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(n=>n.issuer===t);return r===void 0&&Ve("ID-JAG issuer is not trusted."),r}o(PO,"readTrustedIssuer");function xO(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(xO,"readGrantedAuthorizationDetails");function uw(e){if(e.clientAuth.method==="none")throw new E("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&Ve("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&Ve("ID-JAG client_id is not allowed for this issuer.")}o(uw,"assertClientBinding");function lw(e){e.cnf!==void 0&&Ve("ID-JAG cnf-bound assertions require DPoP support.")}o(lw,"assertProofOfPossessionNotDeferred");function pw(e){let t=Math.floor(e.now.getTime()/1e3)+mw;e.claims.iat>t&&Ve("ID-JAG iat must not be in the future.")}o(pw,"assertIssuedAtNotInFuture");async function hw(e){let t;try{t=bO(e.assertion)}catch{Ve("ID-JAG assertion is malformed.")}t.typ!==Aa&&Ve('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=dw(_O(e.assertion))}catch(c){if(c instanceof E)throw c;Ve("ID-JAG assertion is malformed.")}let n=qt(e.requestUrl,e.requestHeaders),s=[n];e.requestedResource!==void 0&&e.requestedResource!==n&&s.push(e.requestedResource);let i=PO(e.config,r.iss);s.includes(r.iss)&&Ve("ID-JAG issuer must be different from the gateway."),uw({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),lw(r),pw({claims:r,now:e.now});let a;try{let c=wO(new URL(i.jwksUrl)),{payload:d}=await vO(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:mw,typ:Aa});a=dw(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:kO(c)},"OAuth ID-JAG assertion verification failed"),Ve("ID-JAG assertion verification failed.")}return uw({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),lw(a),pw({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:yh({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:xO({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(hw,"verifyIdJagAssertion");var qO=new Set(["authorization_code","refresh_token",zt]),zO=1e4,NO=32*1024,jO=2,DO=3600,Gd=m.object({client_id:m.string().min(1).optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),LO=m.discriminatedUnion("grant_type",[Gd.extend({grant_type:m.literal("authorization_code"),code:m.string().min(1),redirect_uri:m.string().min(1),code_verifier:Kr,resource:m.url().optional(),scope:m.literal(he).optional()}),Gd.extend({grant_type:m.literal("refresh_token"),refresh_token:m.string().min(1),resource:m.url().optional(),scope:m.literal(he).optional()}),Gd.extend({grant_type:m.literal(zt),assertion:m.string().min(1),resource:m.url().optional(),scope:m.literal(he).optional(),authorization_details:m.string().min(1).optional()})]);function $O(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!qO.has(t)))throw new E("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o($O,"assertSupportedGrantType");var HO=m.object({token:m.string().min(1),client_id:m.string().min(1).optional(),token_type_hint:m.string().optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),BO=m.object({keys:m.array(m.record(m.string(),m.unknown())).min(1)}).passthrough();function gw(){return ke().gateway.accessTokenTtlSeconds}o(gw,"readAccessTokenTtlSeconds");function FO(){return ke().gateway.refreshTokenTtlSeconds}o(FO,"readRefreshTokenTtlSeconds");function fw(e,t){let r=gw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,n);return{expiresAt:W(gt(e,s)),expiresIn:s}}o(fw,"calculateAccessTokenExpiresAt");function JO(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 E("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new E("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new E("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}o(JO,"readIdJagResource");function VO(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 E("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}o(VO,"readIdJagGrantedAuthorizationDetails");function GO(e){if(e.claimScope?.split(/\s+/).includes(he)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return he;if(e.claimScope===void 0)throw new E("invalid_grant",`ID-JAG must include ${he} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(he))throw new E("invalid_grant",`ID-JAG scope must include ${he}.`);return he}o(GO,"readIdJagGrantedScope");function KO(e){if(e!==void 0&&e.get("dpop")!==null)throw new E("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}o(KO,"assertNoDpopProofForIdJag");function yw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new E("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new E("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new E("invalid_client","Malformed HTTP Basic client authentication.")}}o(yw,"readBasicClientSecret");function Sw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new E("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=MO(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new E("invalid_client","Malformed private_key_jwt client assertion.")}throw new E("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new E("invalid_client","Client authentication or client_id is required.")}o(Sw,"resolveAuthenticatedClientId");function WO(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new E("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(WO,"resolveClientSecretInput");function ZO(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(ZO,"hasClientAssertion");function YO(e){if(e.requestUrl===void 0)throw new E("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(ge().actionPath(e.pathname),ce(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}o(YO,"buildEndpointAudience");function XO(e){return e instanceof ss.JWTExpired?"expired":e instanceof ss.JWTClaimValidationFailed?"claim":e instanceof ss.JWSSignatureVerificationFailed?"signature":e instanceof ss.JWKSNoMatchingKey?"jwks_no_match":e instanceof ss.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(XO,"readJwtFailureKind");async function QO(e){let{response:t,json:r}=await py(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:jO,maxResponseBytes:NO,timeoutMs:zO});if(!t.ok)throw new E("invalid_client","Client JWKS could not be fetched.");return BO.parse(r)}o(QO,"fetchClientJwks");async function eM(e){if(e.clientAssertionType!==Ks||e.clientAssertion===void 0)throw new E("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=yt.parse(e.clientId),r=await Xi(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new E("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new E("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=YO({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await QO({jwksUri:n,context:e.context}),{payload:a}=await UO(e.clientAssertion,OO(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+DO;if(typeof a.exp!="number"||a.exp>c)throw new E("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:XO(i)},"OAuth private_key_jwt client authentication failed"),new E("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(eM,"verifyPrivateKeyJwtClientAssertion");async function tM(e){let t=yt.parse(e.clientId);if(vh(t))throw new E("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 de(e.clientSecret)}}o(tM,"buildRuntimeHttpClientAuth");async function Rw(e){if(ZO({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new E("invalid_request","Use only one client authentication method per request.");return eM(e)}let t=WO({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return tM({clientId:e.clientId,...t})}o(Rw,"resolveRuntimeHttpClientAuth");async function ww(e){$O(e.body);let t=LO.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await Rw({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 rM({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(ww,"exchangeDownstreamToken");async function rM(e){if(e.parsed.grant_type==="authorization_code"){_n(e.parsed.redirect_uri,"invalid_request"),bn(e.parsed.scope),e.parsed.resource!==void 0&&Sr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=St(),d=St(),u=W(gt(e.now,FO())),p=fw(e.now,u),h=await G().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await de(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await ei(e.parsed.code_verifier),currentRefreshTokenHash:await de(c),accessTokenHash:await de(d),grantExpiresAt:u,accessTokenExpiresAt:p.expiresAt,now:W(e.now)});if(h.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new E("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:p.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===zt){bn(e.parsed.scope),KO(e.requestHeaders);let c=await hw({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:ke()}),d=JO({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=Sr(e.requestUrl??d,d,e.requestHeaders),p=VO({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=GO({claimScope:c.claims.scope,grantedAuthorizationDetails:p}),f=St(),y=W(new Date(c.claims.exp*1e3)),b=fw(e.now,y),w=await G().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await de(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:p,accessTokenExpiresAt:b.expiresAt,now:W(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:y}});if(w.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(w.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:f,token_type:"Bearer",expires_in:b.expiresIn,scope:w.grant.scope,resource:w.grant.resource,...p===void 0?{}:{authorization_details:p}}}bn(e.parsed.scope),e.parsed.resource!==void 0&&Sr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await de(e.parsed.refresh_token),r=e.parsed.refresh_token,n=St(),s=W(gt(e.now,gw())),i=await G().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await de(n),resource:e.parsed.resource,accessTokenExpiresAt:s,now:W(e.now)});if(i.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new E("invalid_grant","Refresh token is invalid, expired, or revoked.");Sr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&ne(e.context,{eventType:Z.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(rM,"exchangeDownstreamTokenWithRuntimeHttp");async function _w(e){let t=HO.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await G().revokeOAuthToken({clientAuth:await Rw({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 de(t.token),now:W(s)})).kind==="invalid_client")throw new E("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&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(_w,"revokeDownstreamToken");var nM=64*1024,oM=16*1024,sM="text/html; charset=utf-8";function iM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(iM,"formDataToObject");async function aM(e){return KS(e,{maxBytes:nM,label:"Request body"})}o(aM,"readJsonBody");async function Wd(e){return iM(await WS(e,{maxBytes:oM,label:"Request body"}))}o(Wd,"readFormBody");async function bw(e,t,r){let n=Be(r),s=r instanceof m.ZodError?Gt(r):void 0,i={code:n??(r instanceof m.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),en(e,t,i)}o(bw,"handleProblem");function vw(e){return e?.requestId}o(vw,"readBrowserRequestId");function Cw(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(Cw,"readUpstreamHtmlError");function vn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(vn,"readRuntimeErrorExtensionString");function cM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(cM,"readRuntimeErrorExtensionNumber");function dM(e){try{return new URL(e.url).pathname}catch{return}}o(dM,"readBrowserRequestPath");function Rr(e){let t={code:e.code,requestId:e.requestId,routePath:dM(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=cM(e.error,lt),t.contentType=vn(e.error,Wr),t.upstreamUrl=vn(e.error,pt),t.upstreamServerId=vn(e.error,To),t.metadataUrl=vn(e.error,Yr),t.providerError=vn(e.error,Xr),t.providerErrorDescription=vn(e.error,Qr)),t}o(Rr,"buildBrowserErrorDiagnostic");function is(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(is,"oauthErrorResponse");function uM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(uM,"readOAuthProtocolHeaders");function lM(e,t){let r=ot("internal_server_error");return is({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:uM(e,t)})}o(lM,"oauthProtocolErrorResponse");function Kd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(Kd,"readZodOAuthErrorCode");function pM(e){let t={error:Kd(e)},r=Gt(e);return r!==void 0&&(t.errorDescription=r),is(t)}o(pM,"oauthZodErrorResponse");function mM(e){let t=Be(e);if(t===void 0)return;let r=ot(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:fM(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,is(n)}o(mM,"oauthGatewayProblemResponse");function hM(){let t={error:"server_error",status:500,errorDescription:ot("internal_server_error").publicDetail};return is(t)}o(hM,"oauthFallbackErrorResponse");function fM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(fM,"readOAuthStatus");function Zd(e,t={}){return e instanceof Vt?Ew(e):e instanceof E?lM(e,t):e instanceof m.ZodError?pM(e):mM(e)??hM()}o(Zd,"oauthProblemResponse");function Yd(e,t,r){let n=Jt(e.url),s=vw(t);if(r instanceof Vt)return Ew(r);if(r instanceof E){let c=ot("internal_server_error");return Qe({host:n,kind:gM(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:Rr({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 m.ZodError)return Qe({host:n,kind:"invalid_request",detail:Gt(r)??"The authorization request was invalid.",developerDetail:Gt(r)??"The authorization request was invalid.",code:Kd(r),diagnostic:Rr({request:e,requestId:s,code:Kd(r),underlyingError:Gt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=Be(r);if(i!==void 0){let c=ot(i);return Qe({host:n,kind:Tw(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:Rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Cw(r),status:c.status})}let a=ot("internal_server_error");return Qe({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:Rr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(Yd,"browserOAuthProblemResponse");function Iw(e,t,r){let n=Jt(e.url),s=vw(t),i=Be(r);if(i!==void 0){let c=ot(i);return Qe({host:n,kind:Tw(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:Rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Cw(r),status:c.status})}if(r instanceof m.ZodError)return Qe({host:n,kind:"invalid_request",detail:Gt(r)??"The authorization request was invalid.",developerDetail:Gt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:Rr({request:e,requestId:s,code:"invalid_request",underlyingError:Gt(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=ot("internal_server_error");return Qe({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:Rr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(Iw,"browserGatewayProblemResponse");function gM(e){return e==="server_error"?"internal_error":"invalid_request"}o(gM,"readOAuthBrowserErrorKind");function Tw(e){if(ot(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":case"upstream_token_refresh_unavailable":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(Tw,"readGatewayBrowserErrorKind");function Tt(e,t,r){let n={event:t},s=!1;if(r instanceof E)n.oauthError=r.errorCode,n.status=r.status,Ae(n,"error",r);else if(r instanceof Vt)n.oauthError=r.errorCode,Ae(n,"error",r);else if(r instanceof m.ZodError){n.code="invalid_request",Ae(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=Be(r);if(i!==void 0){let a=ot(i);n.code=i,n.status=a.status,a.oauthError!==void 0&&(n.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",Ae(n,"error",r)}else s=!0,Ae(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(Tt,"logUnexpectedOAuthHandlerError");function Ew(e){let t;try{t=new URL(e.redirectUri)}catch{return is({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),Yi(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(Ew,"downstreamAuthorizeRedirectErrorResponse");function Gt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Gt,"formatZodErrorDetail");function yM(e,t){let r={event:"browser_login_callback_failed",code:Be(t)??"invalid_request"};Ae(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(yM,"logBrowserLoginCallbackFailure");function kw(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(kw,"redirectResultResponse");function Qi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":sM,"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 kw(e)}o(Qi,"authorizeResultResponse");async function Aw(e,t){try{return Response.json(mh(e.url,e.headers))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),bw(e,t,r)}}o(Aw,"authorizationServerMetadataHandler");async function Pw(e,t){try{let r=Ua(e.params.routePath);return Response.json(hh({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),bw(e,t,r)}}o(Pw,"scopedAuthorizationServerMetadataHandler");async function xw(e,t){try{let r=await kR(await aM(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"),ne(t,{eventType:Z.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 Tt(t,"oauth_register_failed",r),Zd(r)}}o(xw,"registerHandler");async function Ow(e,t){try{return Qi(await Vd(e,{context:t}))}catch(r){return Tt(t,"oauth_authorize_failed",r),Yd(e,t,r)}}o(Ow,"authorizeHandler");async function Mw(e,t){try{let r=Ua(e.params.routePath);return Qi(await Vd(e,{operationId:r.operationId,context:t}))}catch(r){return Tt(t,"oauth_authorize_scoped_failed",r),Yd(e,t,r)}}o(Mw,"scopedAuthorizeHandler");async function Uw(e,t){try{let r=await sw(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 yM(t,r),Iw(e,t,r)}}o(Uw,"callbackHandler");async function qw(e,t){try{return kw(await aw(e))}catch(r){return Tt(t,"oauth_dev_login_failed",r),Yd(e,t,r)}}o(qw,"devLoginHandler");async function zw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await cw({request:e,body:e.method==="POST"?await Wd(e):void 0,context:t});return Qi(r)}catch(r){return Tt(t,"oauth_setup_failed",r),Iw(e,t,r)}}o(zw,"setupHandler");async function Nw(e,t){try{return Response.json(await ww({body:await Wd(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 Tt(t,"oauth_token_failed",r),Zd(r)}}o(Nw,"tokenHandler");async function jw(e,t){try{return await _w({body:await Wd(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 Tt(t,"oauth_revoke_failed",r),Zd(r)}}o(jw,"revokeHandler");var Dw="0.0.0",SM=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function as(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}o(as,"firstNonBlank");function cs(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}o(cs,"clampToCodePoints");function RM(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(RM,"shortHash");function Lw(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${RM(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(Lw,"clampNameSegment");function wM(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(wM,"sanitizeRegistryNameSegment");var _M=/^\d{1,3}(\.\d{1,3}){3}$/u;function bM(e){let t=new URL(e).hostname.toLowerCase();if(_M.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(bM,"buildRegistryNamespaceFromOrigin");function vM(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(vM,"sanitizeWebsiteUrl");function CM(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&&!SM.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(CM,"sanitizeIcons");function IM(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(IM,"localNameFromRoutePath");function $w(e){return e.includes("{")||e.includes(":")}o($w,"isParameterizedRoutePath");var TM=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Hw(e){let t=as(e)??Dw;return TM.test(t)?Dw:cs(t,255)}o(Hw,"sanitizeRegistryVersion");function Bw(e){let t=Lw(bM(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=Lw(wM(c),r),u=d;for(let p=2;n.has(u);p++){let h=`-${p}`;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($w(c.routePath))continue;let d=c.connection,u=d?.serverInfo,p=cs(as(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=as(u?.title,d?.displayName),f=vM(u?.websiteUrl),y=CM(u?.icons);a(c.operationId,{description:p,...h===void 0?{}:{title:cs(h,100)},version:Hw(u?.version),...f===void 0?{}:{websiteUrl:f},...y===void 0?{}:{icons:y},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if($w(c.routePath))continue;let d=c.operationId??IM(c.routePath),u=cs(as(c.summary,c.description,c.serverName,c.operationId,d)??d,100),p=as(c.serverName);a(d,{description:u,...p===void 0?{}:{title:cs(p,100)},version:Hw(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o(Bw,"buildMcpRegistryDirectory");var EM=30,Fw=100;function ct(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(ct,"registryErrorResponse");function Qd(e){return Bw({registry:Ie(),origin:ce(e.url,e.headers)})}o(Qd,"readEntries");function Xd(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}o(Xd,"decodePathParam");function Jw(e,t){return e.find(r=>r.name===t)}o(Jw,"findEntryByName");function kM(e){let t=e.get("limit");return t===null?{ok:!0,value:EM}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Fw)}}o(kM,"parseLimit");function AM(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(AM,"parseCursor");var PM=/^(\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 xM(e){let t=PM.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(xM,"isValidRfc3339Timestamp");async function Vw(e,t){let r=new URL(e.url).searchParams,n=kM(r);if(!n.ok)return ct(400,`Invalid 'limit' parameter: expected a positive integer (max ${Fw}).`);let s=AM(r);if(!s.ok)return ct(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&&!xM(i))return ct(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=Qd(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),p=s.value+n.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...p<d.length?{nextCursor:String(p)}:{}}})}o(Vw,"listMcpRegistryServersHandler");async function Gw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return ct(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Jw(Qd(e),r.value);return n===void 0?ct(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(Gw,"listMcpRegistryServerVersionsHandler");async function Kw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return ct(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Xd(e.params.version);if(!n.ok)return ct(400,"Invalid version: malformed encoding.");let s=Jw(Qd(e),r.value);return s===void 0?ct(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?ct(404,"Server or version not found"):Response.json(s.response)}o(Kw,"getMcpRegistryServerVersionHandler");function ea(e,t){return(r,n)=>ct(e,t)}o(ea,"createWriteNotSupportedHandler");async function Ww(e,t){return ct(404,"Not found")}o(Ww,"mcpRegistryNotFoundHandler");var Zw=ea(501,"Publishing is not supported by this registry"),Yw=ea(501,"Updates are not supported by this registry"),Xw=ea(501,"Deletion is not supported by this registry"),eu=ea(403,"You do not have publish or edit permissions for this server");function Qw(e){return X`<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(Qw,"renderBrowserResult");var OM="text/html; charset=utf-8";function MM(e){return yn({title:e.title,iconHref:Fc(e.host),styles:gn,headerIcon:Gi("success"),heading:e.title,subhead:X`<p class="card__subtitle">${e.detail}</p>`,body:Qw({steps:hn(e.steps.map(t=>X`<li>${t}</li>`))}),footer:""})}o(MM,"browserResultHtml");function UM(e,t=200){return new Response(fn(e),{status:t,headers:{"content-type":OM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(UM,"browserResultResponse");function e_(e){return UM(MM(e))}o(e_,"browserConnectionSuccessResponse");function ta(e,t,r={}){let n=Xm(t);return Qe({host:e,kind:qM(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(ta,"browserConnectionFailureResponse");function qM(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(qM,"readCallbackFailureBrowserErrorKind");var zM={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},t_=Symbol("upstream-request");function ds(e,t){Object.defineProperty(e,t_,{configurable:!0,value:t})}o(ds,"setUpstreamRequestContext");function NM(e){let t=e[t_];if(!t)throw new Ee("Upstream request context has not been set");return t}o(NM,"readUpstreamRequestContext");function jM(e,t){return t.some(r=>r===e)}o(jM,"requestContextMatchesKind");function DM(e){return typeof e=="string"?[e]:e}o(DM,"toExpectedKinds");function us(e,t){let r=NM(e),n=DM(t);if(!jM(r.kind,n)){let s=zM[n[0]];throw new Ee(`${s} request context has not been set`)}return r}o(us,"requireUpstreamRequestContext");function Kt(e){if(typeof e=="string"&&e.length!==0)return e}o(Kt,"readOptionalQueryString");function LM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Ee(`Validated path parameter ${t} is missing`);return $M(r,t)}o(LM,"requirePathString");function $M(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($M,"decodePathString");function HM(e){let t=Kt(e);return t?Js.parse(t):void 0}o(HM,"readOptionalOperationId");function BM(e){let t=Ie().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(BM,"readRegisteredAuthProfileId");function FM(e){let t=HM(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[M]:"invalid_request"}});return t}o(FM,"readRequiredOperationId");async function tu(e){return e.redirect?Qe({host:Jt(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(tu,"browserConnectRefusal");function JM(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(JM,"withSetCookies");async function VM(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(Km(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 tu({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 wn(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return JM(await tu({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=ko(`${d.pathname}${d.search}`);if(u===void 0)throw new Ee("Connect request path is empty");let p=await iw({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:p.location.toString(),"cache-control":"no-store"});for(let f of[...a,p.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 tu({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(VM,"requireTicketOwnerBrowser");async function GM(e,t,r){let n=Ji(r,FM(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=Kt(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=pr(e.user,e.url),u={kind:"connect",...mn(n,d.subjectId),redirect:s},p=ko(Kt(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!i)throw new k({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[M]:"authentication_required"}});let a=await Ey(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($t()){let d=await VM({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await ky(a);let c=Vs(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(GM,"resolveConnectContext");async function KM(e,t,r){let n=eh.parse(LM(e,"connection"));switch(r){case"connect":{let s=await GM(e,t,n);if(s instanceof Response)return s;ds(e,s);return}case"callback":{let s=Kt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Kt(e.query.error_description);d!==void 0&&(c.errorDescription=d),ds(e,c);return}let i=Kt(e.query.code),a=Kt(e.query.state);if(i&&a){let c=Kt(e.query.iss);ds(e,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:a,...c===void 0?{}:{iss:c}});return}ds(e,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":ds(e,{kind:"client_metadata",upstreamServerId:n,authProfileId:BM(n)});return}}o(KM,"resolveUpstreamRequestInbound");async function WM(e,t,r){try{return await KM(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(WM,"applyUpstreamRequestContext");function ra(e,t){return o(async(n,s)=>{let i=await WM(n,s,e);return i||t(n,s)},"wrapped")}o(ra,"withUpstreamRequestContext");var ZM=["callback_authorization_code","callback_provider_error","callback_invalid"];function ru(e){try{return new URL(e.url).pathname}catch{return}}o(ru,"readBrowserRequestPath");function YM(e){return"cause"in e?e.cause:void 0}o(YM,"readErrorCause");function XM(e){return e.stack?.split(`
44
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(XM,"readFirstStackFrame");function r_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=XM(r))}o(r_,"addErrorAttributes");function nu(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[M];return Fs(t)?t:void 0}o(nu,"readRuntimeGatewayCode");function ls(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(ls,"readRuntimeErrorExtensionString");function QM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(QM,"readRuntimeErrorExtensionNumber");function e0(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"),ne(t,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),ta(n,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:ru(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"),ta(n,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:ru(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}o(e0,"requireAuthorizationCallbackRequest");function t0(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(t0,"emitCallbackReceivedAnalyticsEvent");function r0(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(r0,"emitTokenExchangeSucceededAnalyticsEvent");function n0(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return e_({host:Jt(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(n0,"buildSuccessfulCallbackResponse");function o0(e){let t={detail:e instanceof Error?e.message:void 0};return r_(t,"error",e),e instanceof Error&&r_(t,"cause",YM(e)),t}o(o0,"buildTokenExchangeFailureAttributes");function s0(e){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:nu(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:o0(e.error)})}o(s0,"emitTokenExchangeFailedAnalyticsEvent");function i0(e){let t=e.error,r=nu(t),n=Ym(r)?r:"upstream_token_exchange_failed",s={code:n,requestId:e.context.requestId,routePath:ru(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof k?{httpStatus:QM(t,lt),contentType:ls(t,Wr),upstreamUrl:ls(t,pt),metadataUrl:ls(t,Yr),providerError:ls(t,Xr),providerErrorDescription:ls(t,Qr)}:{}};return ta(e.host,n,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:a0(t)})}o(i0,"tokenExchangeFailureResponse");function n_(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(n_,"withSetCookie");function a0(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(a0,"readUpstreamHtmlError");async function ou(e,t){let r=us(e,ZM),n=Jt(e.url),s=e0(e,t,r,n);if(s instanceof Response)return s;t0(t,s);let i;try{let a=await hS({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return r0(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"),n_(n0(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:nu(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return Ae(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),s0({context:t,callbackRequest:s,error:a}),n_(i0({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(ou,"callbackHandler");function c0(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(c0,"clientMetadataProblemDetail");async function o_(e,t){let r=us(e,"connect"),n=r.redirect?await Xo({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:qi/1e3}):void 0,s=await mS({request:e,connectRequest:r,...n===void 0?{}:{browserBinding:n.claim}});if(ne(t,{eventType:Z.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 Ni({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(o_,"connectHandler");async function s_(e,t){let r=us(e,"client_metadata");try{let n=ce(e.url,e.headers),s=Dy(n,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(n){if(!(n instanceof re))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:c0(n)})}}o(s_,"oauthClientMetadataHandler");function d0(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(d0,"resolveInternalRoutePath");var u0={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function l0(){return new Response(null,{status:204,headers:u0})}o(l0,"buildWellKnownPreflightResponse");function p0(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(p0,"withWellKnownCorsHeaders");function wr(e){return async(t,r)=>t.method==="OPTIONS"?l0():p0(await e(t,r))}o(wr,"wrapWellKnownHandler");var i_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:wr(Aw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:wr(Pw),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:wr(fh),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:xw},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Ow},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Mw},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Uw},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:qw},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:zw},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Nw},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:jw},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ra("client_metadata",s_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ra("connect",o_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ra("callback",ou)}],m0=i_.filter(e=>!e.routeName.startsWith("upstream_")),h0=i_.filter(e=>e.routeName.startsWith("upstream_"));function f0(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:wr(Vw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:wr(Gw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:wr(Kw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:Zw},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:Yw},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:Xw},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:eu},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:eu},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:wr(Ww),corsPolicy:"anything-goes"}]}o(f0,"buildMcpRegistryInternalRoutes");function g0(e){let t=sh({routes:e.routes,policies:e.policies,gateway:e.gateway});return ih(t),t}o(g0,"initializeMcpGatewayConnectionRegistry");function y0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(y0,"hasDownstreamOAuthRoutes");function S0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(S0,"hasIdJagDownstreamOAuth");function R0(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 Ee("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 re(`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(R0,"readSingletonDownstreamOAuthConfig");function w0(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(dh(n));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?en(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}o(w0,"readScopedDownstreamOAuthConfig");function _0(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o(_0,"routeUsesScopedOAuthConfig");function su(e,t,r){return async(n,s)=>{if(r){let d=await r(n,s);if(d instanceof Response)return d;d&&Gm(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(su,"wrapInternalHandler");function iu(e,t,r,n){e.addPluginRoute({path:d0(t,r),methods:t.methods,handler:n,processors:[Iu],corsPolicy:t.corsPolicy??"none"})}o(iu,"addInternalRoute");function a_(e,t){let r=g0(t);if(r.gateway.registry.enabled){ut("plugin.mcp-gateway.registry");for(let c of f0(r.gateway.registry))iu(e,c,r.gateway,su(c.routeName,c.handler))}let n=y0(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=R0(r)),i),"readSingletonOAuthConfig");if(n){ut("plugin.mcp-gateway.downstream-oauth"),S0(r)&&ut("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of m0){let d=_0(c)?(u,p)=>w0(r,u,p):a;iu(e,c,r.gateway,su(c.routeName,c.handler,d))}}if(s){ut("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())ut(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of h0)iu(e,c,r.gateway,su(c.routeName,c.handler,n?a:void 0))}}o(a_,"registerMcpGatewayInternalRoutes");var au=class extends Cu{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),ut("plugin.mcp-gateway"),this.#e=Wm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&a_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as U_}from"@opentelemetry/api";var b0="zuplo_mcp_",v0=["__host-","__secure-"];function C0(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of v0)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(b0)}o(C0,"setsGatewayCookie");function c_(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!C0(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(c_,"stripUpstreamOriginStateHeaders");function et(e){return e&&typeof e=="object"?e:void 0}o(et,"readRecord");function ps(e,t){let r=et(e)?.[t];return typeof r=="string"?r:void 0}o(ps,"readStringProperty");function u_(e,t){let r=et(e)?.[t];return typeof r=="number"?r:void 0}o(u_,"readNumberProperty");function d_(e,t){return u_(e,"code")??(t>=400?t:void 0)}o(d_,"readErrorCode");function l_(e){return Array.isArray(e)?e.map(l_).find(t=>t?.method):et(e)}o(l_,"readJsonRpcMessage");function cu(e){let t=l_(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:ps(n,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:ps(n,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=ps(n,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}o(cu,"buildBaseCapabilityInput");function na(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}o(na,"isCapabilityListMethod");function I0(e,t,r){let i=et(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}o(I0,"readItemCount");function p_(e){let t=cu(e);return!t||na(t.mcpMethod)?null:{eventType:Z.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(p_,"buildCapabilityInvokedAnalyticsInput");function T0(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(T0,"readMissingResponseFailure");function m_(e,t,r={}){let n=cu(e);if(!n)return null;let s=et(t.message),i=et(s?.error),a=et(i?.data),c=s?.result,d=n.mcpMethod==="tools/call"&&et(c)?.isError===!0,u=et(c),p=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&et(et(u.inputRequests)?.[Jr])!==void 0;if(et(a?.connectRequired)||p)return{eventType:Z.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...n,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:u_(i,"code"),mcpErrorType:ps(i,"message")};let h=t.status<400?T0(t):void 0;if(h&&!i)return{eventType:na(n.mcpMethod)?Z.MCP_CAPABILITY_LISTED:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,...h};if(na(n.mcpMethod)){let f=t.status>=400?void 0:I0(n.mcpMethod,n.capabilityType,c),y=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:Z.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...n,httpStatusCode:t.status,...y?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:d_(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:d_(i,t.status),mcpErrorType:ps(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:Z.MCP_CAPABILITY_COMPLETED,outcome:"success",...n,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:Z.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...n,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}o(m_,"buildCapabilityFinalAnalyticsInput");function h_(e,t){let r=cu(e);return r?{eventType:na(r.mcpMethod)?Z.MCP_CAPABILITY_LISTED:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}o(h_,"buildCapabilityThrownAnalyticsInput");var du={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},f_={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},g_={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var mu=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),uu=64*1024,hu=1024*1024,E0=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function y_(e,t={}){return e===void 0?uu:E0.has(e)||t.modern===!0&&e==="server/discover"||t.captureToolCallContent===!0&&e==="tools/call"?hu:uu}o(y_,"tapMaxBytesForMethod");function k0(e){let t=We(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(k0,"readTapMode");function A0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(A0,"isPlainObject");function P0(e){return A0(e)&&!("method"in e)&&("result"in e||"error"in e)}o(P0,"isResponseShaped");function x0(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(x0,"isSameJsonRpcIdValue");function S_(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(P0);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>x0(a.id,t));if(i||r)return i}return s[0]}o(S_,"selectResponse");function R_(e){try{return JSON.parse(e)}catch{return}}o(R_,"tryParseJson");var lu=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=S_(R_(new TextDecoder().decode(t)),this.requestId,!1)}},pu=class{constructor(t,r){this.requestId=t;this.#e=new fr({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=S_(R_(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},O0={push(){},end(){},message:void 0,truncated:!1};function M0(e,t,r){switch(e){case"json":return new lu(t,r);case"sse":return new pu(t,r);case"passthrough":return O0}}o(M0,"createObserver");function w_(e,t={}){let r=e.body;if(r===null){let v=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:v,outcome:v}}let n=ht(e.headers)?"passthrough":k0(e),s=M0(n,t.requestId,t.maxBytes??uu),i,a=new Promise(v=>{i=v}),c,d=new Promise(v=>{c=v}),u=!1,p=o(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,y=o((v,x)=>{if(f)return;if(f=!0,v==="complete")try{s.end()}catch{}let N={ended:v,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...n==="passthrough"&&h>0?{uninspected:!0}:{},...x===void 0?{}:{error:x}};i(N),u||(u=!0,c(N))},"settle"),b=r.getReader(),w=new ReadableStream({async pull(v){let x;try{x=await b.read()}catch(N){y("errored",N),v.error(N);return}if(x.done){y("complete"),v.close();return}if(h+=x.value.byteLength,!f)try{s.push(x.value)}catch{}v.enqueue(x.value),p()},async cancel(v){y(v===mu?"released":"cancelled"),await b.cancel(v)}},{highWaterMark:0}),S=Qf(new Headers(e.headers)),R;try{R=new Response(w,{status:e.status,statusText:e.statusText,headers:S})}catch(v){throw b.cancel(v).catch(()=>{}),v}return{response:R,done:a,outcome:d}}o(w_,"tapJsonRpcResponse");function __(e){try{let r=e.route?.handler?.options?.telemetry;return r!==null&&typeof r=="object"&&r.captureToolCallContent===!0}catch{return!1}}o(__,"readCaptureToolCallContent");var U0=-32603,q0="The upstream MCP server ended the response stream without a response to this request.",z0="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function b_(e){return`${typeof e}:${String(e)}`}o(b_,"idKey");function N0(e,t){if(e.delete(b_(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(N0,"clearAnsweredRequest");function oa(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!v_(n)||typeof n.method!="string"||typeof n.id!="string"&&typeof n.id!="number")continue;let s=we(n);s!==void 0&&r.push(s)}return r}o(oa,"readJsonRpcRequestIds");function v_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(v_,"isRecord");function j0(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)v_(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(j0,"readResponseIds");function D0(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(D0,"endOnError");function C_(e,t,r=hu,n){let s=new Map;for(let a of t)s.set(b_(a),a);let i=!1;return Cc(D0(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of j0(a.data))N0(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?z0:q0;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:U0,message:a}})}))},"end")})}o(C_,"answerUnansweredRequests");var L0="The upstream MCP server rejected the gateway's credential.";function I_(e){return e.status===401||e.status===403&&e.headers.has("www-authenticate")}o(I_,"isUpstreamCredentialRejection");function T_(e,t){let r={code:I.InternalError,message:L0,data:{upstreamStatus:t}},n=oa(e);if(n.length===0)return Response.json(Pe({error:r}),{status:502});let s=n.map(i=>Pe({id:i,error:r}));return Response.json(Array.isArray(e)?s:s[0])}o(T_,"upstreamCredentialRejectedResponse");var E_="mcp-session-id";async function $0(e){try{return await e.clone().arrayBuffer()}catch{return}}o($0,"readRequestBody");function gu(e){try{let t=ah(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(gu,"readRouteAnalyticsFields");function H0(e,t,r){if(!te())return;let n=fi(t,r.message);if(n===void 0)return;let s=rn()?.byRoutePath.get(e.route.path)?.connection?.upstreamServerId;s!==void 0&&gi(s,n)}o(H0,"learnUpstreamSupportedVersions");function yu(e){return Sh(e.user,e.url,e.headers)?.subjectId}o(yu,"readRequestSubjectId");function fu(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}o(fu,"readRequestMethod");function k_(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(k_,"readHeader");function Su(e){let t=k_(e.request.headers,E_)??(e.response?k_(e.response.headers,E_):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=lr(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Su,"readMcpProtocolFields");function B0(e){let t=p_(e.requestJson?.value);t&&ne(e.context,{...t,...gu(e.context),...Su({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http"})}o(B0,"emitCapabilityInvokedAnalytics");function F0(e){let t=m_(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&&qa(e.context,{...t,...gu(e.context),...Su(e),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(F0,"emitCapabilityFinalAnalytics");function sa(e){let t=h_(e.requestJson?.value,e.details);t&&(e.late?qa:ne)(e.context,{...t,...gu(e.context),...Su({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(sa,"emitCapabilityThrownAnalytics");async function A_(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 xt(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(A_,"callUpstream");function J0(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(J0,"readClientSignal");function P_(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(P_,"throwIfClientCancelled");function V0(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{xs.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(V0,"watchClientCancelBeforeHeaders");async function ia(e){try{await e.body?.cancel()}catch{}}o(ia,"discardBody");function G0(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(G0,"isClientAbortError");function K0(e,t){try{xs.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(K0,"logErrorAfterClientLeft");async function x_(e){P_(e.clientSignal);let t=await A_(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=AS(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await ia(t);let n=o(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await U_.with(e.refreshContext,n):await n();return P_(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await A_({...e,headers:s.headers}),gatewayAnswered:!1}}o(x_,"forwardToUpstream");function W0(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?x_({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):U_.with(i.client.ctx,()=>x_({request:t,context:r,bodyBytes:n===void 0?void 0:Wg(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(W0,"callUpstreamOperation");function Z0(e,t,r){if(e.body===null||e.status<200||e.status>299||We(e.headers.get("content-type"))!=="text/event-stream"||ht(e.headers))return e;let n=oa(t?.value);if(n.length===0)return e;let s=wt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(C_(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(Z0,"withUnansweredRequestErrors");function Y0(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(X0(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(Y0,"finishModernResponse");function X0(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(X0,"cancelOnClientAbort");function Q0(e,t){Eu.findContextExtensions(e)?.addPipelineExitHook(r=>{let n=t.body;r===t||n===null||r?.body===n||n.locked||n.cancel(mu).catch(()=>{})})}o(Q0,"releaseBodyIfNotSent");function O_(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(O_,"clientClosedResponse");function M_(e){return e instanceof re?g_:f_}o(M_,"thrownDetails");async function eU(e,t){if(ut("handler.mcp-gateway-proxy"),e.method==="GET")return Si(e,t);let r=Date.now(),n=await $0(e),s=Mh(n,{readMetaProtocolVersion:te()});Uh(t,lr(e.headers,s?.value));let i=Zc(e,s,n),a=__(t),c;if(i!==void 0)try{c=Gg({request:e,context:t,parsed:i,captureToolCallContent:a})}catch{c=void 0}B0({context:t,request:e,requestJson:s});let d=te()&&Fr(e.headers,s?.value),u=d&&fu(s)==="subscriptions/listen",p=d?J0(e):void 0,h=p?V0({clientSignal:p,context:t,onCancel:o(()=>{c&&Xc(c),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:d,late:!0})},"onCancel")}):void 0,f={},y,b;try{let R=await W0({request:e,context:t,requestBody:n,parsed:i,spans:c,modern:d,listen:u,clientSignal:p,upstreamTimeout:f});b=R.gatewayAnswered;let v=R.response;!b&&xe()&&OS(t)&&I_(v)&&(t.log.warn({event:"mcp_upstream_credential_rejected",upstreamStatus:v.status},"MCP upstream proxy: upstream rejected the gateway credential"),await ia(v),v=T_(s?.value,v.status),b=!0),y=c_(v)}catch(R){let v=h?.claim()??!0;if(p?.aborted)return G0(R,p)||K0(t,R),v&&(c&&Xc(c),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:d})),O_(e,t);throw c&&Yc(c,R),sa({context:t,request:e,requestJson:s,startedAt:r,details:M_(R),modern:d}),R}if(h&&!h.claim())return await ia(y),O_(e,t);let w,S;try{w=w_(y,{requestId:we(s?.value),maxBytes:y_(fu(s),{modern:d,captureToolCallContent:a})});let R=Z0(w.response,s,f.signal);S=d?Y0(R,{rewritten:R!==w.response,clientSignal:p}):R,Q0(t,S)}catch(R){throw await ia(w?.response??y),c&&Yc(c,R),sa({context:t,request:e,requestJson:s,startedAt:r,details:M_(R),modern:d}),R}return t.waitUntil(w.outcome.then(R=>{b||H0(t,fu(s),R);try{F0({context:t,request:e,requestJson:s,response:y,tapResult:R,startedAt:r,modern:d,gatewayAnswered:b})}finally{c&&i&&Yg({spans:c,method:i.method,response:y,tapResult:R,expectsResponse:i.id!==void 0,gatewayAnswered:b})}}).catch(R=>{try{xs.getLogger(t).error(R,"Error emitting MCP gateway capability analytics")}catch{}})),S}o(eU,"McpProxyHandler");export{V_ as McpAuth0OAuthInboundPolicy,Nc as McpCapabilityFilterInboundPolicy,z_ as McpClerkOAuthInboundPolicy,N_ as McpCognitoOAuthInboundPolicy,j_ as McpEntraOAuthInboundPolicy,au as McpGatewayPlugin,D_ as McpGoogleOAuthInboundPolicy,L_ as McpKeycloakOAuthInboundPolicy,$_ as McpLogtoOAuthInboundPolicy,G_ as McpOAuthInboundPolicy,H_ as McpOktaOAuthInboundPolicy,B_ as McpOneLoginOAuthInboundPolicy,F_ as McpPingOAuthInboundPolicy,eU as McpProxyHandler,Id as McpTokenExchangeInboundPolicy,J_ as McpWorkosOAuthInboundPolicy,Cg as claimsCapabilityResolver};
45
45
  /*! For license information please see index.js.LEGAL.txt */
46
46
  //# sourceMappingURL=index.js.map