@zuplo/runtime 7.14.6 → 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,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as Nr,$a as gl,$b as fa,$c as om,$f as Be,$g as he,Aa as ma,Ab as Bl,Ac as Up,Ad as vm,Ag as nh,Ah as ne,Ba as Ju,Bb as Fl,Bc as ba,Bd as Am,Bg as oh,Bh as qa,C as Iu,Ca as Vu,Cb as Jl,Cc as Ns,Cd as Io,Cg as sh,Ch as ye,Da as Gu,Db as Vl,Dc as js,Dd as Pm,Dg as Ie,Dh as St,E as Os,Ea as Ku,Eb as Gl,Ec as qp,Ed as Ls,Ef as Fm,Eg as ge,Eh as de,Fa as Wu,Fb as Kl,Fc as zp,Fd as $s,Ff as He,Fg as ih,Fh as ei,Ga as Zu,Gb as Wl,Gc as Np,Gd as ur,Gf as Jm,Gg as rn,Gh as Ae,H as Ms,Ha as Yu,Hb as Zl,Hc as jp,Hd as xm,Hf as Vm,Hg as W,Hh as ie,Ia as Xu,Ib as Yl,Ic as Dp,Id as Ca,If as Gm,Ig as gt,Ih as Ah,Ja as Qu,Jb as Xl,Jc as Lp,Jd as Vr,Jf as ce,Jg as qt,Jh as se,Ka as el,Kb as Ql,Kc as $p,Kd as Hs,Kf as Km,Kg as ah,Kh as Ph,La as tl,Lb as ep,Lc as Hp,Ld as Om,Lf as Gr,Lg as zt,Lh as xh,Ma as rl,Mb as tp,Mc as Bp,Md as Mm,Mf as Wm,Mg as Aa,Mh as Oh,N as Tu,Na as nl,Nb as rp,Nc as Fp,Nd as Um,Nf as Kr,Ng as Gs,Nh as Mh,Oa as ol,Ob as np,Oc as Jp,Od as Bs,Of as M,Og as Pa,Oh as B_,Pa as sl,Pb as op,Pc as Vp,Pd as Nm,Pf as Wr,Pg as Ks,Ph as F_,Q as Eu,Qa as il,Qb as sp,Qc as Gp,Qd as jm,Qf as Zr,Qg as Po,Ra as al,Rb as ip,Rc as Kp,Rd as Ia,Rf as ut,Rg as nn,Sa as ha,Sb as ap,Sc as Wp,Sd as Dm,Sf as lt,Sg as ch,T as ku,Ta as cl,Tb as cp,Tc as Zp,Td as Lm,Tf as To,Tg as yt,Ua as dl,Ub as dp,Uc as Yp,Ud as $m,Uf as Yr,Ug as xa,Va as ul,Vb as up,Vc as Xp,Vd as Ta,Vf as Xr,Vg as Ws,Wa as ll,Wb as lp,Wc as Qp,Wd as Hm,Wf as Qr,Wg as dh,Xa as pl,Xb as pp,Xc as em,Xd as Ea,Xf as Fs,Xg as Zs,Ya as ml,Yb as mp,Yc as tm,Yf as Zm,Yg as Oa,Za as hl,Zb as hp,Zc as rm,Zf as ot,Zg as Ys,_ as Us,_a as fl,_b as fp,_c as nm,_f as Ym,_g as uh,aa as jr,ab as yl,ac as gp,ad as sm,ag as z,ah as lh,b as xs,ba as wo,bb as Sl,bc as yp,bd as im,bg as en,bh as ph,ca as Dr,cb as Rl,cc as Sp,cd as am,ce as Bm,cg as ke,ch as mh,da as Lr,db as wl,dc as Rp,dd as cm,dg as Ut,dh as Ma,ea as _o,eb as _l,ec as wp,ed as dm,eg as M_,eh as hh,fa as ir,fb as bl,fc as _p,fd as um,fg as U_,fh,ga as Au,gb as vl,gc as bp,gd as lm,gg as q_,gh as Ua,ha as Pu,hb as Cl,hc as vp,hd as pm,hg as z_,hh as gh,ia as xu,ib as Il,ic as Cp,id as mm,ig as N_,ih as lr,ja as Ou,jb as Tl,jc as Ip,jd as hm,jg as j_,jh as yh,ka as Mu,kb as El,kc as Tp,kd as $r,kg as D_,kh as xo,la as Uu,lb as kl,lc as Ep,ld as Hr,lg as L_,lh as Sh,ma as qu,mb as Al,mc as kp,md as fm,mg as $_,mh as Xs,n as dt,na as zu,nb as Pl,nc as Ap,nd as Br,ng as H_,nh as Oo,oa as Nu,ob as xl,oc as Pp,od as Ot,og as Xm,oh as Rh,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 Js,qh as _h,ra as Lu,rb as Ul,rc as qs,rd as gm,rg as Eo,rh as bh,sa as $u,sb as ql,sc as zs,sd as vo,sg as ko,sh as vh,ta as Hu,tb as zl,tc as ya,td as cr,tg as tn,th as Ch,u as Ne,ua as Bu,ub as Nl,uc as Sa,ud as ym,ug as eh,uh as Ih,v as Cu,va as Fu,vb as jl,vc as Ra,vd as Sm,vg as ka,vh as Th,wa as ar,wb as Dl,wc as Op,wd as Rm,wg as th,wh as Qs,x as Z,xa as la,xb as Ll,xc as wa,xd as wm,xg as Ao,xh as Eh,ya as pa,yb as $l,yc as _a,yd as _m,yg as Vs,yh as kh,za as bo,zb as Hl,zc as Mp,zd as bm,zg as rh,zh as G}from"../chunk-JORDKCQ5.js";import"../chunk-VP5Q3DEN.js";import"../chunk-LDA754KZ.js";import{a as xt,b as te,c as dr,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-AEVCZW3D.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 v,m as g,n as V,o as q,p as da,q as So,r as U,s as K,t as w,u as J,v as ua,w as Ps,y as Ro}from"../chunk-G2O2ZIL3.js";import"../chunk-UKQQD2JN.js";import{$ as zr,a as Ee,aa as wu,c as k,d as re}from"../chunk-VIH2ISEH.js";import{a as o}from"../chunk-TYV53J3B.js";var J_=Object.create,ti=Object.defineProperty,V_=Object.getOwnPropertyDescriptor,G_=Object.getOwnPropertyNames,K_=Object.getPrototypeOf,W_=Object.prototype.hasOwnProperty,Uh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),qh=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"),Z_=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=G_(t),i=0,a=s.length,c;i<a;i++)c=s[i],!W_.call(e,c)&&c!==r&&ti(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=V_(t,c))||n.enumerable});return e},"__copyProps"),zh=o((e,t,r)=>(r=e!=null?J_(K_(e)):{},Z_(t||!e||!e.__esModule?ti(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Y_=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Nh(e){return typeof e=="string"&&Y_.has(e.replace(/#$/,""))}o(Nh,"declares2019Dialect");var $a=Symbol.for("mcp.sdk.errorBrands");function pr(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(pr,"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 Kh 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",pr(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 Kh(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",pr(this,new.target)}},db=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 Wh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Wh,"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 ub="2026-07-28";function Zh(e){return e>=ub}o(Zh,"isModernProtocolVersion");function Yh(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(Yh,"appendTextFallbackForNonObject");var Xh=["task","inputRequests","requestState"];function lb(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Xh.some(t=>t in e)?e:{...e,content:[]}}o(lb,"normalizeContentlessToolResult");function pb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),v(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()}),S=q([l(),A().int()]),b=f.strict(),R=p.extend({requestId:S.optional(),reason:l().optional()}),y=h.extend({method:w("notifications/cancelled"),params:R}),_=g({src:l(),mimeType:l().optional(),sizes:v(l()).optional(),theme:K(["light","dark"]).optional()}),C=g({icons:v(_).optional()}),x=g({name:l(),title:l().optional()}),N=x.extend({...x.shape,...C.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:w("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:w("notifications/initialized"),params:p.optional()}),De=u.extend({method:w("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:w("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()}),Kt=l().refine(Ce=>{try{return atob(Ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),vr=_r.extend({blob:Kt}),ct=K(["user","assistant"]),rt=g({audience:v(ct).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),Wt=g({...x.shape,...C.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:rt.optional(),_meta:J(V({}))}),Cn=g({...x.shape,...C.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:rt.optional(),_meta:J(V({}))}),In=oe.extend({method:w("resources/list")}),Tn=tt.extend({resources:v(Wt)}),Et=oe.extend({method:w("resources/templates/list")}),Cr=tt.extend({resourceTemplates:v(Cn)}),Zt=c.extend({uri:l()}),En=Zt,kn=u.extend({method:w("resources/read"),params:En}),An=f.extend({contents:v(q([br,vr]))}),Pn=h.extend({method:w("notifications/resources/list_changed"),params:p.optional()}),xn=Zt,On=u.extend({method:w("resources/subscribe"),params:xn}),Mn=Zt,Un=u.extend({method:w("resources/unsubscribe"),params:Mn}),qn=p.extend({uri:l()}),zn=h.extend({method:w("notifications/resources/updated"),params:qn}),Nn=g({name:l(),description:J(l()),required:J(D())}),jn=g({...x.shape,...C.shape,description:J(l()),arguments:J(v(Nn)),_meta:J(V({}))}),Dn=oe.extend({method:w("prompts/list")}),Ln=tt.extend({prompts:v(jn)}),$n=c.extend({name:l(),arguments:U(l(),l()).optional()}),Hn=u.extend({method:w("prompts/get"),params:$n}),Yt=g({type:w("text"),text:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Xt=g({type:w("image"),data:Kt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Qt=g({type:w("audio"),data:Kt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Bn=g({type:w("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),kt=g({type:w("resource"),resource:q([br,vr]),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Fn=Wt.extend({type:w("resource_link")}),Ke=q([Yt,Xt,Qt,Fn,kt]),Ir=g({role:ct,content:Ke}),Tr=f.extend({description:l().optional(),messages:v(Ir)}),er=h.extend({method:w("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()}),tr=g({...x.shape,...C.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:U(l(),e).optional(),required:v(l()).optional()}).catchall(F()),outputSchema:g({type:w("object"),properties:U(l(),e).optional(),required:v(l()).optional()}).catchall(F()).optional(),annotations:Jn.optional(),execution:Er.optional(),_meta:U(l(),F()).optional()}),kr=oe.extend({method:w("tools/list")}),Ar=tt.extend({tools:v(tr)}),Pr=f.extend({content:v(Ke),structuredContent:U(l(),F()).optional(),isError:D().optional()}),ve=d.extend({name:l(),arguments:U(l(),F()).optional()}),Vn=u.extend({method:w("tools/call"),params:ve}),ms=h.extend({method:w("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:w("logging/setLevel"),params:Gn}),Wn=p.extend({level:xr,logger:l().optional(),data:F()}),Zn=h.extend({method:w("notifications/message"),params:Wn}),Yn=g({name:l().optional()}),Xn=g({hints:v(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:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:v(Ke),structuredContent:g({}).loose().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),eo=da("type",[Yt,Xt,Qt]),At=da("type",[Yt,Xt,Qt,Bn,hs]),to=g({role:ct,content:q([At,v(At)]),_meta:U(l(),F()).optional()}),ro=d.extend({messages:v(to),modelPreferences:Xn.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:v(l()).optional(),metadata:t.optional(),tools:v(tr).optional(),toolChoice:Qn.optional()}),no=u.extend({method:w("sampling/createMessage"),params:ro}),oo=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens"]).or(l())),role:ct,content:eo}),so=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:ct,content:q([At,v(At)])}),io=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),ao=g({type:w("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:w("string"),title:l().optional(),description:l().optional(),enum:v(l()),default:l().optional()}),lo=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:v(g({const:l(),title:l()})),default:l().optional()}),po=g({type:w("string"),title:l().optional(),description:l().optional(),enum:v(l()),enumNames:v(l()).optional(),default:l().optional()}),mo=q([uo,lo]),rr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:w("string"),enum:v(l())}),default:v(l()).optional()}),nr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:v(g({const:l(),title:l()}))}),default:v(l()).optional()}),fs=q([rr,nr]),gs=q([po,mo,fs]),Le=q([gs,io,ao,co]),$e=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:U(l(),Le),required:v(l()).optional()}).catchall(F())}),ho=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),nt=q([$e,ho]),ys=u.extend({method:w("elicitation/create"),params:nt}),Ss=p.extend({elicitationId:l()}),Rs=h.extend({method:w("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(),v(l())])).optional())}),_s=g({type:w("ref/resource"),uri:l()}),bs=g({type:w("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:w("completion/complete"),params:vs}),Cs=f.extend({completion:V({values:v(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:w("roots/list"),params:c.optional()}),go=f.extend({roots:v(Is)}),Ts=h.extend({method:w("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),or=h.extend({method:w("notifications/tasks/status"),params:ks}),Mr=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),Ur=f.merge(Pt),qr=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),aa=f.loose(),Te=oe.extend({method:w("tasks/list")}),ae=tt.extend({tasks:v(Pt)}),sr=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:p,NotificationSchema:h,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:R,CancelledNotificationSchema:y,IconSchema:_,IconsSchema:C,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:ct,AnnotationsSchema:rt,ResourceSchema:Wt,ResourceTemplateSchema:Cn,ListResourcesRequestSchema:In,ListResourcesResultSchema:Tn,ListResourceTemplatesRequestSchema:Et,ListResourceTemplatesResultSchema:Cr,ResourceRequestParamsSchema:Zt,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:Yt,ImageContentSchema:Xt,AudioContentSchema:Qt,ToolUseContentSchema:Bn,EmbeddedResourceSchema:kt,ResourceLinkSchema:Fn,ContentBlockSchema:Ke,PromptMessageSchema:Ir,GetPromptResultSchema:Tr,PromptListChangedNotificationSchema:er,ToolAnnotationsSchema:Jn,ToolExecutionSchema:Er,ToolSchema:tr,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:rr,TitledMultiSelectEnumSchemaSchema:nr,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:or,GetTaskRequestSchema:Mr,GetTaskResultSchema:Ur,GetTaskPayloadRequestSchema:qr,GetTaskPayloadResultSchema:aa,ListTasksRequestSchema:Te,ListTasksResultSchema:ae,CancelTaskRequestSchema:sr,CancelTaskResultSchema:f.merge(Pt),ClientRequestSchema:q([De,j,fo,Kn,Hn,Dn,In,Et,kn,On,Un,Vn,kr,Mr,qr,Te,sr]),ClientNotificationSchema:q([y,le,Ue,Ts,or]),ClientResultSchema:q([b,oo,so,ws,go,Ur,ae,ze]),ServerRequestSchema:q([De,no,ys,Or,Mr,qr,Te,sr]),ServerNotificationSchema:q([y,le,Zn,zn,Pn,ms,er,or,Rs]),ServerResultSchema:q([b,ee,Cs,Tr,Ln,Tn,Cr,An,Pr,Ar,Ur,ae,ze]),CallToolResultWireSchema:F().superRefine((Ce,O_)=>{if(!(typeof Ce!="object"||Ce===null||Array.isArray(Ce)||Ce.content!==void 0)){for(let Ru of Xh)if(Ru in Ce){O_.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(lb).pipe(Pr)}}o(pb,"build$1");var mb;function Ka(){return mb??=pb()}o(Ka,"buildSchemas2025");function Qh(e){return e.type!=="object"}o(Qh,"isNonObjectJsonSchemaRoot");var hb=new Set(["const","enum","default","examples"]),fb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function jh(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(jh,"establishesNewBase");function gb(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(jh(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Nh(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&&jh(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:hb.has(d)?a[d]=u:fb.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(gb,"wrapOutputSchemaForLegacy");var ef={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},tf={"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},yb={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 Sb(){ai()}o(Sb,"warmRegistryMaps2025");function rf(e){return Object.prototype.hasOwnProperty.call(ef,e)}o(rf,"hasRequestMethod2025");function nf(e){return Object.prototype.hasOwnProperty.call(tf,e)}o(nf,"hasNotificationMethod2025");function Rb(e){return Object.prototype.hasOwnProperty.call(yb,e)}o(Rb,"hasResultMethod");function wb(e){return Rb(e)?ai().resultSchemas[e]:void 0}o(wb,"getResultSchema");function _b(e){return rf(e)?ai().requestSchemas[e]:void 0}o(_b,"getRequestSchema");function bb(e){return nf(e)?ai().notificationSchemas[e]:void 0}o(bb,"getNotificationSchema");var oU=Object.keys(ef),sU=Object.keys(tf);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 Dh={ok:!1,reason:"not-in-era"};function Lh(e){return Ha(e)&&Ha(e.outputSchema)&&Qh(e.outputSchema)}o(Lh,"toolNeedsLegacyWrap");var Wa={era:"2025-11-25",hasRequestMethod:rf,hasNotificationMethod:nf,validateRequest:o((e,t)=>ni(_b(e),t),"validateRequest"),validateResult:o((e,t)=>ni(wb(e),t),"validateResult"),validateNotification:o((e,t)=>ni(bb(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>Dh,"validateInputRequest"),validateInputResponse:o(()=>Dh,"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=Yh(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&Qh(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=>Lh(n))?t:{...t,tools:r.map(n=>Lh(n)?{...n,outputSchema:gb(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function vb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),v(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()}),S=g({_meta:p.optional()}),b=g({method:l(),params:S.loose().optional()}),R=g({src:l(),mimeType:l().optional(),sizes:v(l()).optional(),theme:K(["light","dark"]).optional()}),y=g({icons:v(R).optional()}),_=g({name:l(),title:l().optional()}),C=_.extend({..._.shape,...y.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({...S.shape,...P.shape,progressToken:r}),j=b.extend({method:w("notifications/progress"),params:$}),B=S.extend({level:a,logger:l().optional(),data:F()}),ee=b.extend({method:w("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:v(i).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),le=g({..._.shape,...y.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:Y.optional(),_meta:J(V({}))}),qe=g({..._.shape,...y.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:Y.optional(),_meta:J(V({}))}),oe=b.extend({method:w("notifications/resources/list_changed"),params:S.optional()}),tt=S.extend({uri:l()}),_r=b.extend({method:w("notifications/resources/updated"),params:tt}),br=g({name:l(),description:J(l()),required:J(D())}),Kt=g({..._.shape,...y.shape,description:J(l()),arguments:J(v(br)),_meta:J(V({}))}),vr=b.extend({method:w("notifications/prompts/list_changed"),params:S.optional()}),ct=g({type:w("text"),text:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),rt=g({type:w("image"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Wt=g({type:w("audio"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Cn=g({type:w("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),In=g({type:w("resource"),resource:q([De,Ge]),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Tn=le.extend({type:w("resource_link")}),Et=q([ct,rt,Wt,Tn,In]),Cr=g({role:i,content:Et}),Zt=g({title:l().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),En=b.extend({method:w("notifications/tools/list_changed"),params:S.optional()}),kn=g({name:l().optional()}),An=g({hints:v(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:w("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),On=g({type:w("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:w("string"),title:l().optional(),description:l().optional(),enum:v(l()),default:l().optional()}),qn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:v(g({const:l(),title:l()})),default:l().optional()}),zn=g({type:w("string"),title:l().optional(),description:l().optional(),enum:v(l()),enumNames:v(l()).optional(),default:l().optional()}),Nn=q([Un,qn]),jn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:w("string"),enum:v(l())}),default:v(l()).optional()}),Dn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:v(g({const:l(),title:l()}))}),default:v(l()).optional()}),Ln=q([jn,Dn]),$n=q([zn,Nn,Ln]),Hn=q([$n,xn,On,Mn]),Yt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:U(l(),Hn),required:v(l()).optional()}).catchall(F())}),Xt=g({type:w("ref/resource"),uri:l()}),Qt=g({type:w("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]:C.optional(),[Lr]:Fn,[_o]:a.optional()}),er=g({..._.shape,...y.shape,description:l().optional(),inputSchema:V({$schema:l().optional(),type:w("object")}),outputSchema:V({$schema:l().optional()}).optional(),annotations:Zt.optional(),_meta:U(l(),F()).optional()}),Jn=g({type:w("tool_result"),toolUseId:l(),content:v(Et),structuredContent:F().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),Er=q([ct,rt,Wt,Cn,Jn]),tr=g({role:i,content:q([Er,v(Er)]),_meta:U(l(),F()).optional()}),kr=l(),Ar=V({[Dr]:C.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:v(Et),structuredContent:F().optional(),isError:D().optional()}),Gn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:v(er),nextCursor:n.optional()}),Kn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:v(Kt),nextCursor:n.optional()}),Wn=ve({description:l().optional(),messages:v(Cr)}),Zn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:v(le),nextCursor:n.optional()}),Yn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:v(qe),nextCursor:n.optional()}),Xn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:v(q([De,Ge]))}),Qn=ve({completion:g({values:v(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:v(l()),capabilities:Ir,instructions:l().optional()}),At=g({messages:v(tr),modelPreferences:An.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:v(l()).optional(),metadata:t.optional(),tools:v(er).optional(),toolChoice:Pn.optional()}),to=g({method:w("sampling/createMessage"),params:At}),ro=g({method:w("roots/list"),params:g({_meta:U(l(),F()).optional()}).optional()}),no=g({...tr.shape,model:l(),stopReason:l().optional()}),oo=g({roots:v(Bn)}),so=g({action:K(["accept","decline","cancel"]),content:U(l(),q([l(),A(),D(),v(l())])).optional()}),io=g({mode:w("url"),message:l(),url:l().url()}),ao=q([Yt,io]),co=g({method:w("elicitation/create"),params:ao}),uo=q([to,ro,co]),lo=q([no,oo,so]),po=U(l(),uo),mo=U(l(),lo),rr=ve({inputRequests:po.optional(),requestState:l().optional()}),nr={inputResponses:mo.optional(),requestState:l().optional()},fs=g({_meta:Tr,...nr}),gs=V({progressToken:r.optional()});function Le(ae,sr){return g({method:w(ae),params:g({_meta:Tr,...sr})})}o(Le,"wireRequest");function $e(ae,sr){return g({method:w(ae),params:g({_meta:gs.optional(),...sr}).optional()})}o($e,"dispatchRequest");let ho={name:l(),arguments:U(l(),F()).optional(),...nr},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(),...nr}),_s=Le("resources/list",nt),bs=Le("resources/templates/list",nt),vs=Le("resources/read",{uri:l(),...nr}),fo={ref:q([Qt,Xt]),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:v(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:v(Et),structuredContent:F().optional(),isError:D().optional()}),"tools/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:v(er),nextCursor:n.optional()}),"prompts/get":ze({description:l().optional(),messages:v(Cr)}),"prompts/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:v(Kt),nextCursor:n.optional()}),"resources/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:v(le),nextCursor:n.optional()}),"resources/templates/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:v(qe),nextCursor:n.optional()}),"resources/read":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:v(q([De,Ge]))}),"completion/complete":ze({completion:g({values:v(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:v(l()),capabilities:Ir,instructions:l().optional()}),"subscriptions/listen":ze({})},or=V({"io.modelcontextprotocol/subscriptionId":s.optional()}),Mr=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:or.optional(),notifications:Or})}),Ur=g({_meta:or.optional(),requestId:s,reason:l().optional()}),qr=g({method:w("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:w("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:S,NotificationSchema:b,IconSchema:R,IconsSchema:y,BaseMetadataSchema:_,ImplementationSchema:C,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:Kt,PromptListChangedNotificationSchema:vr,TextContentSchema:ct,ImageContentSchema:rt,AudioContentSchema:Wt,ToolUseContentSchema:Cn,EmbeddedResourceSchema:In,ResourceLinkSchema:Tn,ContentBlockSchema:Et,PromptMessageSchema:Cr,ToolAnnotationsSchema:Zt,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:Yt,ResourceTemplateReferenceSchema:Xt,PromptReferenceSchema:Qt,RootSchema:Bn,ClientCapabilities2026Schema:Fn,ServerCapabilities2026Schema:Ir,RequestMetaEnvelopeSchema:Tr,ToolSchema:er,ToolResultContentSchema:Jn,SamplingMessageContentBlockSchema:Er,SamplingMessageSchema:tr,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:rr,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:or,SubscriptionsAcknowledgedNotificationSchema:Mr,CancelledNotificationParamsSchema:Ur,CancelledNotificationSchema:qr,notificationSchemas2026:aa,JSONRPCResultResponseSchema:Te(Vn),CallToolResultResponseSchema:Te(q([xr,rr])),ListToolsResultResponseSchema:Te(Gn),ListPromptsResultResponseSchema:Te(Kn),GetPromptResultResponseSchema:Te(q([Wn,rr])),ListResourcesResultResponseSchema:Te(Zn),ListResourceTemplatesResultResponseSchema:Te(Yn),ReadResourceResultResponseSchema:Te(q([Xn,rr])),CompleteResultResponseSchema:Te(Qn),DiscoverResultResponseSchema:Te(eo),SubscriptionsListenResultResponseSchema:Te(yo)}}o(vb,"build");var Cb;function Rt(){return Cb??=vb()}o(Rt,"buildSchemas2026");var Ib=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Tb(e){return Ib.includes(e)}o(Tb,"isCacheableResultMethod");var Za=Symbol("modelcontextprotocol.resultCacheHintFallback");function Eb(e){return e[Za]}o(Eb,"cacheHintFallbackOf");function of(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(of,"isValidCacheTtlMs");function sf(e){return e==="public"||e==="private"}o(sf,"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 af 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",pr(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 df({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 cf(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 uf({requiredCapabilities:s.requiredCapabilities},r)}return new af(t,r,n)}},cf=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??[]}},df=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}},uf=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}},kb=0,Ab="private",Pb=["tools/call","prompts/get","resources/read"];function xb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Pb.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(xb,"stampResultType");function Ob(e,t){let r=Eb(t);if(t.resultType!=="complete"||!Tb(e))return r===void 0?t:Nb(t);let n=t,s=of(n.ttlMs)?n.ttlMs:qb(r),i=sf(n.cacheScope)?n.cacheScope:zb(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Za],a}o(Ob,"fillCacheFields");function Mb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Mb,"isPlainObject$4");function Ub(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Dr]:t}}:!Mb(r)||r[Dr]!==void 0?e:{...e,_meta:{...r,[Dr]:t}}}o(Ub,"stampServerInfoMeta");function qb(e){return e!==void 0&&of(e.ttlMs)?e.ttlMs:kb}o(qb,"resolveTtlMs");function zb(e){return e!==void 0&&sf(e.cacheScope)?e.cacheScope:Ab}o(zb,"resolveCacheScope");function Nb(e){let t={...e};return delete t[Za],t}o(Nb,"stripCacheHintFallback");var jb=["elicitation/create","sampling/createMessage","roots/list"],oi;function Ya(){if(oi)return oi;let e=Rt();return oi={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:V({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},oi}o(Ya,"inputSchemaMaps");function Db(){Ya()}o(Db,"warmInputSchemaMaps2026");function lf(e){return jb.includes(e)}o(lf,"isInputRequestMethod2026");function za(e){return lf(e)?Ya().request[e]:void 0}o(za,"getInputRequestSchema2026");function Lb(e){return lf(e)?Ya().response[e]:void 0}o(Lb,"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},pf={"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 mf(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o(mf,"hasRequestMethod2026");function hf(e){return Object.prototype.hasOwnProperty.call(pf,e)}o(hf,"hasNotificationMethod2026");function $b(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o($b,"hasResultMethod2026");function Hb(e){return mf(e)?Rt().dispatchRequestSchemas[e]:void 0}o(Hb,"getRequestSchema2026");function Bb(e){return $b(e)?Rt().dispatchResultSchemas[e]:void 0}o(Bb,"getResultSchema2026");function Fb(e){return hf(e)?Rt().notificationSchemas2026[e]:void 0}o(Fb,"getNotificationSchema2026");var iU=Object.keys(Xa),aU=Object.keys(pf);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 Jb={ok:!1,reason:"not-in-era"},Vb=[jr,Lr];function Gb(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(Gb,"enforceDeletedFields");var Qa={era:"2026-07-28",hasRequestMethod:mf,hasNotificationMethod:hf,hasInputRequestMethod:o(e=>za(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>Mo(Hb(e),t),"validateRequest"),validateResult:o((e,t)=>Mo(Bb(e),t),"validateResult"),validateNotification:o((e,t)=>Mo(Fb(e),t),"validateNotification"),validateInputRequest:o((e,t)=>Mo(za(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>Mo(Lb(e),t),"validateInputResponse"),samplingResultVariant:o(()=>Jb,"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 Vb)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=>Yh(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=ff(),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 Ub(Ob(e,xb(e,Gb(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 ff(){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(ff,"getWireResultSchemas");function Kb(){ff()}o(Kb,"warmWireResultSchemas2026");var ec="2026-07-28";function No(e){return e!==void 0&&Zh(e)?Qa:Wa}o(No,"codecForVersion");function $h(e){return e.revision!==void 0?No(e.revision).era:e.era==="modern"?Qa.era:Wa.era}o($h,"classifiedWireEra");function Na(e){return gf.some(t=>t.hasRequestMethod(e))}o(Na,"isSpecRequestMethod");function ja(e){return gf.some(t=>t.hasNotificationMethod(e))}o(ja,"isSpecNotificationMethod");function Hh(e){return e==="tasks/get"||e==="tasks/cancel"}o(Hh,"isExtensionReusedRequestMethod");var gf=[Wa,Qa],Wb=qh({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(()=>ar,"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 yf=o(e=>ar.safeParse(e).success,"isJSONRPCRequest"),Sf=o(e=>la.safeParse(e).success,"isJSONRPCNotification"),Ba=o(e=>pa.safeParse(e).success,"isJSONRPCResultResponse"),Rf=o(e=>bo.safeParse(e).success,"isJSONRPCErrorResponse");var zo=-32020,cU=[{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."}],dU={[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 Bh=!1,Ja="draft-2020-12";function Zb(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().");Bh||(Bh=!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:wf(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(Zb,"standardSchemaToJsonSchema");function wf(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"||wf(n)))}return!1}o(wf,"isProvablyObjectShapedRoot");function Yb(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(Yb,"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=>Yb(n)).join(", ")}:{success:!0,data:r.value}}o(Da,"validateStandardSchema");function Xb(e){let t=ca(e,{target:Ja,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(Xb,"zodEmittedPattern");var Qb=/\\\.\\d\{(\d+)\}/;function ev(e){let t=Qb.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(ev,"datetimeReferenceSchemas");function tv(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=ev(t);break}return new Set(r.map(n=>Xb(n)).filter(n=>n!==void 0))}o(tv,"referencePatternsForFormat");function rv(e,t,r){return r!=="zod"?!0:tv(e,t).has(t)}o(rv,"isLibraryFormatPattern");function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(jo,"isJsonObject");function nv(e){try{return Zb(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(nv,"convertStandardElicitationSchema");var ov=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function rc(e){return ov.has(e)||e.startsWith("x-")}o(rc,"isAnnotationOnlyJsonSchemaKeyword");var sv=new Set(["$schema",...Object.keys(Ns.shape.requestedSchema.shape)]),Fh={string:Uo([qs,ya,Sa,Ra]),number:Uo([zs]),integer:Uo([zs]),boolean:Uo([ga]),array:Uo([wa,_a])},iv=new Set(qs.shape.format.unwrap().options);function av(e,t,r,n){if(!jo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Fh,e.type)?Fh[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"?iv.has(e.format)?(typeof c!="string"||!rv(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(av,"walkProperty");function cv(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,av(c,`properties.${a}`,t,n)])):sv.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(cv,"walkRequestedSchema");function dv(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(dv,"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 uv(e){if(!Fa(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=cv(nv(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): ${dv(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(uv,"normalizeElicitInputParams");function lv(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(lv,"buildInputRequired");var uU=Object.assign(lv,{elicit(e){try{return{method:"elicitation/create",params:uv(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 pv=["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"],mv={IdJagTokenExchangeResponseSchema:va,OAuthClientInformationFullSchema:cr,OAuthClientInformationSchema:vo,OAuthClientMetadataSchema:gm,OAuthClientRegistrationErrorSchema:ym,OAuthErrorResponseSchema:Ds,OAuthMetadataSchema:Hr,OAuthProtectedResourceMetadataSchema:$r,OAuthTokenRevocationRequestSchema:Sm,OAuthTokensSchema:Ot,OpenIdProviderDiscoveryMetadataSchema:Br,OpenIdProviderMetadataSchema:fm},_f={},bf={};function vf(e,t){let r=e.slice(0,-6);_f[r]=t,bf[r]=n=>t.safeParse(n).success}o(vf,"register");for(let e of pv)vf(e,Wb[e]);for(let[e,t]of Object.entries(mv))vf(e,t);var hv=Object.freeze(_f),fv=Object.freeze(bf);function gv(e){switch(e){case"initialize":case"notifications/initialized":return No(void 0);case"server/discover":return No(ec);default:return}}o(gv,"bootstrapOutboundCodec");var Cf=6e4,yv=[jr,wo,Lr,_o],Sv=["inputResponses","requestState"];function Jh(e,t){let r=e.params;if(!La(r))return{message:e,lifted:{}};let n=r._meta,s=La(n)?yv.filter(d=>d in n):[],i=t==="request"?Sv.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(Jh,"liftWireOnlyMaterial");function Vh(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(Vh,"codecResultValidator");function If(e){return()=>e}o(If,"requestStateAccessor");var Rv=If(void 0),wv,_v=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{wv=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)||Rf(s)?this._onresponse(s):yf(s)?this._onrequest(s,i):Sf(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}=Jh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=$h(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}=Jh(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((R,y,_)=>{let C={jsonrpc:"2.0",id:r.id,error:{code:R,message:y,..._!==void 0&&{data:_}}};i?.send(C).catch(x=>this._onerror(new Error(`Failed to send an error response: ${x}`)))},"sendErrorResponse");if(t?.classification!==void 0){let R=$h(t.classification);if(R!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${R} but this instance serves ${s.era}`));let y=t.classification.revision??R;a(I.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(Na(r.method)&&!s.hasRequestMethod(r.method)&&!(Hh(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((R,y)=>this._notificationViaCodec(this._resolveOutboundCodec(R.method),R,{...y,relatedRequestId:r.id}),"sendNotification"),p=o((R,y,_)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(R.method),R,y,{..._,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:bv(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?Rv:If(n.requestState),signal:h.signal,send:o(((R,y,_)=>{let C=this._resolveOutboundCodec(R.method);if(this._assertOutboundRequestInEra(C,R.method),Fa(y))return p(R,y,_);let x=Vh(C,R.method);if(x===void 0)throw new TypeError(`'${R.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(R,x,y)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>c(r,b)).then(async R=>{if(h.signal.aborted)return;let y;try{y=s.encodeResult(r.method,R,this._outboundServerInfo())}catch(C){this._onerror(new Error(`Failed to encode result for ${r.method}: ${C}`)),a(I.InternalError,"Internal error");return}let _={result:y,jsonrpc:"2.0",id:r.id};await i?.send(_)},async R=>{if(h.signal.aborted)return;let y=Number.isSafeInteger(R.code)?R.code:I.InternalError,_={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(y),message:R.message??"Internal error",...R.data!==void 0&&{data:R.data}}};await i?.send(_)}).catch(R=>this._onerror(new Error(`Failed to send response: ${R}`))).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 Hh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=Vh(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=gv(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 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 pe?O:new pe(Se.RequestTimeout,String(O))}let b=e.era===ec&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,R=this._requestMessageId++;p=R;let y={...t,jsonrpc:"2.0",id:R};n?.onprogress&&(this._progressHandlers.set(R,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:R}});let _=this._envelopeOutbound(y),C=!1,x=o(O=>{C||(this._progressHandlers.delete(R),b===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:R,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(R,O=>{if(n?.signal?.aborted)return;if(C=!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(vv(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??Cf,T=o(()=>x(new pe(Se.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(R,N,n?.maxTotalTimeout,T,n?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:b?.signal}).catch(O=>{this._progressHandlers.delete(R),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 Gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Gh,"isPlainObject");function bv(e){let t={},r=[];if(!Gh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!Gh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(bv,"partitionInputResponses");function vv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(vv,"manualInputRequiredValue");var Cv=Uh((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,S,b;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(),b=S[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")})),lU=zh(Cv(),1);var Iv=10*1024*1024;var Tv=new Set([301,302,303,307,308]),Ev=5;function kv(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(kv,"isWithinOrigin");function Av(e,t){let r=Tv.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Av,"redirectTarget");var Pv=new WeakSet;function di(e){return Pv.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=Av(s,a);if(!c||i===Ev)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||!kv(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(di,"fetchWithinOrigin");function nc(){Ka(),Rt(),Sb(),Db(),Kb()}o(nc,"preloadSchemas");var vU=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 xv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ov=[0,31,28,31,30,31,30,31,31,30,31,30,31],Mv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Uv=/^(?=.{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,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,zv=/^(?:(?:[^\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,Nv=/^(?:(?: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,jv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Dv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Lv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,$v=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Hv=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"),Bv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Fv=/^((([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,Jv=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 pt(e){return e.test.bind(e)}o(pt,"bind");var CU={date:Tf,time:Ef.bind(void 0,!1),"date-time":Kv,duration:Jv,uri:Yv,"uri-reference":pt(qv),"uri-template":pt(zv),url:pt(Nv),email:Hv,hostname:pt(Uv),ipv4:pt(Bv),ipv6:pt(Fv),regex:Qv,uuid:pt(jv),"json-pointer":pt(Dv),"json-pointer-uri-fragment":pt(Lv),"relative-json-pointer":pt($v)};function Vv(e){return e%4===0&&(e%100!==0||e%400===0)}o(Vv,"isLeapYear");function Tf(e){let t=e.match(xv);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&Vv(r)?29:Ov[n])}o(Tf,"date");function Ef(e,t){let r=t.match(Mv);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(Ef,"time");var Gv=/t|\s/i;function Kv(e){let t=e.split(Gv);return t.length==2&&Tf(t[0])&&Ef(!0,t[1])}o(Kv,"date_time");var Wv=/\/|:/,Zv=/^(?:[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 Yv(e){return Wv.test(e)&&Zv.test(e)}o(Yv,"uri");var Xv=/[^\\]\\Z/;function Qv(e){if(Xv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(Qv,"regex");nc();var kf=!1;var oc;oc=globalThis.crypto;async function tC(e){return(await oc).getRandomValues(new Uint8Array(e))}o(tC,"getRandomValues");async function rC(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await tC(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(rC,"random");async function nC(e){return await rC(e)}o(nC,"generateVerifier");async function oC(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(oC,"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 nC(e),r=await oC(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,pr(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}},mq=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}):Of(e.issuer,t)?e:void 0}o(dc,"discardIfIssuerMismatch");function Of(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(Of,"issuersMatch");var hq=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",pr(this,new.target)}};function Mf(e){return e?.authorization_response_iss_parameter_supported===!0}o(Mf,"isIssParameterSupported");function Uf({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(Uf,"validateAuthorizationResponseIssuer");function sC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(sC,"isClientAuthMethod");var ic="code",ac="S256";function iC(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&sC(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(iC,"selectClientAuthMethod");function aC(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":cC(s,i,r);return;case"client_secret_post":dC(s,i,n);return;case"none":uC(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(aC,"applyClientAuthentication");function cC(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(cC,"applyBasicAuth");function dC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(dC,"applyPostAuth");function uC(e,t){t.set("client_id",e)}o(uC,"applyPublicAuth");function qf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(qf,"isLoopbackHost");function lC(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!qf(t.hostname))throw new pi(t.href);return t}o(lC,"assertSecureTokenEndpoint");function pC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||qf(r.hostname))return"native"}return"web"}o(pC,"deriveApplicationType");function mC(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??pC(t.redirect_uris)}}o(mC,"resolveClientMetadata");async function Af(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(Af,"parseErrorResponse");function Pf(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(Pf,"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 Pf(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 Pf(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await cc(e,t)}throw r}}o(lc,"auth");function hC(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(hC,"determineScope");async function cc(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=mC(e),p=await e.discoveryState?.(),h,f,S,b,R=i;if(!R&&p?.resourceMetadataUrl&&(R=new URL(p.resourceMetadataUrl)),p?.authorizationServerUrl){if(f=p.authorizationServerUrl,h=p.resourceMetadata,S=p.authorizationServerMetadata??await Df(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await Nf(t,{resourceMetadataUrl:R},a)}catch(B){if(B instanceof TypeError)throw B}(S!==p.authorizationServerMetadata||h!==p.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:R?.toString(),resourceMetadata:h,authorizationServerMetadata:S})}else{let B=await _C(t,{resourceMetadataUrl:R,fetchFn:a,skipIssuerMetadataValidation:c});f=B.authorizationServerUrl,S=B.authorizationServerMetadata,h=B.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:R?.toString(),resourceMetadata:h,authorizationServerMetadata:S}}let y=S?.issuer??String(f),_={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),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",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(!Of(B,y))throw new li(B,y)}b&&await e.saveDiscoveryState?.(b);let C=await fC(t,e,h),x=C&&h&&!e.validateResourceURL?h.resource:C;x&&await e.saveResourceUrl?.(mc(x));let N=hC({requestedScope:s,resourceMetadata:h,authServerMetadata:S,clientMetadata:e.clientMetadata}),T=await Promise.resolve(e.clientInformation(_)),O=dc(T,y,{canPersistStamp:e.saveClientInformation!==void 0});if(O===void 0&&T?.issuer&&e.saveClientInformation===void 0)throw new li(T.issuer,y);if(O&&O.issuer===void 0&&(O={...O,issuer:y},await e.saveClientInformation?.(O,_)),!O){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let B=S?.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:y},await e.saveClientInformation?.(O,_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");O={...await TC(f,{metadata:S,clientMetadata:u,scope:N,fetchFn:a}),issuer:y},await e.saveClientInformation(O,_)}}let L=!e.redirectUrl;if(r!==void 0||L){r!==void 0&&Uf({iss:n,expectedIssuer:S?.issuer,issParameterSupported:Mf(S)});let B=await IC(e,f,{metadata:S,resource:x,authorizationCode:r,iss:n,scope:N,fetchFn:a});return await e.saveTokens({...B,issuer:y},_),"AUTHORIZED"}let Q=dc(await e.tokens(_),y);if(Q&&Q.issuer===void 0&&(Q={...Q,issuer:y},await e.saveTokens(Q,_)),Q?.refresh_token&&!d){let B;try{B=await CC(f,{metadata:S,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:y},_),"AUTHORIZED"}let P=e.state?await e.state():void 0,{authorizationUrl:$,codeVerifier:j}=await bC(f,{metadata:S,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 fC(e,t,r){let n=Wh(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(fC,"selectResourceURL");var gC=new Set(["bearer","dpop"]);function zf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!gC.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(zf,"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 Nf(e,t,r=fetch){let n=await RC(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(Nf,"discoverOAuthProtectedResourceMetadata");async function jf(e,t,r=fetch){let n=di(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!kf)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(jf,"fetchWithCorsRetry");function yC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(yC,"buildWellKnownPath");async function xf(e,t,r=fetch){return await jf(e,{"MCP-Protocol-Version":t},r)}o(xf,"tryMetadataDiscovery");function SC(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(SC,"shouldAttemptFallback");async function RC(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=yC(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await xf(a,i,r);return!n?.metadataUrl&&SC(c,s.pathname)&&(c=await xf(new URL(`/.well-known/${t}`,s),i,r)),c}o(RC,"discoverMetadataWithFallback");function wC(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(wC,"buildDiscoveryUrls");async function Df(e,{fetchFn:t=fetch,protocolVersion:r=Us,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=wC(e);for(let{url:a,type:c}of i){let d=await jf(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(Df,"discoverAuthorizationServerMetadata");async function _C(e,t){let r,n;try{r=await Nf(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 Df(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(_C,"discoverOAuthServerInfo");function mc(e){return typeof e=="string"?e:e.href}o(mc,"resourceIndicatorToString");async function bC(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(bC,"startAuthorization");function vC(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(vC,"prepareAuthorizationCodeRequest");async function Lf(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=lC(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&&aC(iC(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let p=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})),di(c??fetch)(d,{method:"POST",headers:S,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 Af(h);let f=await h.json();try{return Ot.parse(Ga(f))}catch(S){throw typeof f=="object"&&f!==null&&"error"in f?await Af(JSON.stringify(f)):S}}o(Lf,"executeTokenRequest");async function CC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await Lf(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(CC,"refreshAuthorization");async function IC(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&Uf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Mf(r)});let d=r?.issuer??String(t),u=o(async()=>{let S=await e.clientInformation({issuer:d}),b=dc(S,d,{canPersistStamp:!1});if(S&&b===void 0)throw new li(String(S.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=vC(s,await e.codeVerifier(),e.redirectUrl)}return p??=await u(),Lf(t,{metadata:r,tokenRequestParams:f,clientInformation:p,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(IC,"fetchToken");async function TC(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 cr.parse(Ga(await c.json()))}o(TC,"registerClient");var fq=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,pr(this,new.target)}};function we(e){let t=ar.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:ir,...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 $f(e){return new ci([js.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o($f,"urlElicitationRequiredError");var fc=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],$o=[dr,...fc],EC=0,kC="private",AC="0.0.0";function PC(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(PC,"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??AC,...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 Hf(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:PC(e.capabilityFilter),_meta:{[Mt]:gc({connection:e.connection,icons:e.icons})},ttlMs:EC,cacheScope:kC}})}o(Hf,"gatewayDiscoverResponse");var xC=/^\d{4}-\d{2}-\d{2}$/;var hi="2026-07-28",Ho;function OC(){return Ho??=new Map,Ho}o(OC,"store");function mi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(mi,"isRecord");function Bf(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string"&&xC.test(r)))].slice(0,32);return t.length===0?void 0:t}o(Bf,"readVersionList");function fi(e,t){if(!mi(t))return;if(e==="server/discover"&&mi(t.result))return Bf(t.result.supportedVersions);let r=t.error;if(mi(r)&&r.code===-32022&&mi(r.data))return Bf(r.data.supported)}o(fi,"readUpstreamSupportedVersions");function gi(e,t,r={}){let n=OC(),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 Ff(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(Ff,"recordUpstreamAcceptsInitialize");var MC=-32e3,UC="2025-11-25",qC=/^\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 zC(e,t){return typeof e=="string"&&qC.test(e)&&e>=t}o(zC,"isAtLeast");function NC(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 zC(s,UC)&&!Co(s)&&yc(n)&&n.url!==void 0}o(NC,"acceptsUrlElicitation");function Rc(e){let{payload:t}=e,r=t.authUrl===void 0||!e.urlElicitation?void 0:$f({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 Jf(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(Jf,"classifyMessage");function on(e,t){return Response.json(Pe({error:{code:e,message:t}}),{status:400})}o(on,"unidentifiedError");function Vf(){return new Response(null,{status:202})}o(Vf,"acceptedResponse");function jC(e,t){return te()?jm(e,t):void 0}o(jC,"modernBatchVersion");function DC(e,t){let r=e.get("mcp-protocol-version"),n=jC(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(DC,"batchRefusal");function Gf(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(MC,`Bad Request: Unsupported protocol version: ${s} (supported versions: ${r.listed.join(", ")})`)}o(Gf,"transportVersionRefusal");function Kf(e,t){return Gf(e,t,{accepted:o(r=>Nr.includes(r),"accepted"),listed:Nr})}o(Kf,"handlerTransportVersionRefusal");function LC(e,t,r){let n=yi(r,te()?$o:fc);return Gf(e,t,{accepted:o(s=>n.includes(s)||te()&&s===dr,"accepted"),listed:n})}o(LC,"gatewayTransportVersionRefusal");function $C(e){return{jsonrpc:"2.0",id:e,result:{}}}o($C,"pingResult");function Wf(e){if(e.parsed===void 0)return on(I.ParseError,"Parse error: Invalid JSON");let t=Array.isArray(e.parsed)?DC(e.headers,e.parsed):void 0;if(t!==void 0)return t;let r=LC(e.headers,e.parsed,e.payload.upstreamServerId);if(r!==void 0)return r;let n=o(i=>i.message.method==="ping"?$C(i.id):Rc({id:i.id,payload:e.payload,urlElicitation:NC(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)=>Jf(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?Vf():Response.json(a)}let s=Jf(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"):Vf();case"invalid":return Response.json(s.error,{status:400})}}o(Wf,"legacyConnectRequiredResponse");function xe(){return zr.instance.build.COMPATIBILITY_FLAGS.mcpGatewaySpecCompliance===!0}o(xe,"isMcpGatewaySpecComplianceEnabled");var HC={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."},HC)}o(Si,"gatewayMethodNotAllowed");function We(e){return(e??"").split(";")[0].trim().toLowerCase()}o(We,"mediaTypeEssence");var BC=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function wt(e){for(let t of BC)e.delete(t);return e}o(wt,"deleteEncodedBodyHeaders");function Zf(){let e=zr.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(Zf,"currentRuntime");var FC=new Set(["gzip","x-gzip","deflate","br","zstd"]);function mt(e,t=Zf()){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=>FC.has(n.trim()))}}o(mt,"isBodyStillEncoded");function Yf(e){return mt(e)?e:wt(e)}o(Yf,"deleteEncodedBodyHeadersIfDecoded");function Xf(e,t=Zf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?mt(e,t):e.has("content-length"))?e:wt(e)}o(Xf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var eg=10*1024*1024,JC=1024,VC=32,GC=64,mr=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")}},KC=10;function WC(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o(WC,"handleRejection");function tg(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(tg,"fieldName");var hr=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??eg;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)===KC&&(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>=GC&&(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 mr(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>JC&&(this.#g+=Math.max(0,VC-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(`
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
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}
@@ -32,15 +32,15 @@ ${r}`),e.terminated?`${r}
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(_c,"serializeSseEvent");var ZC=new Set(["data","event","id","retry"]);function rg(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!ZC.has(tg(t)))}o(rg,"hasUnknownSseFields");function Fo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>tg(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
36
- `)}}o(Fo,"replaceSseData");var ng=Symbol("sse.terminate");function vc(...e){return{[ng]:!0,events:e}}o(vc,"terminateSse");function YC(e){return typeof e=="object"&&e!==null&&ng in e}o(YC,"isTerminate");var XC=64,Qf=new Uint8Array(0),bc=class{static{o(this,"SseRawEventBytes")}#e=Qf;#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>=XC&&this.#l())}take(){let t;return this.#r===0?t=rI(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=Qf,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,QC=[239,187,191];function eI(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(eI,"splitLines");function tI(e){let t=e[e.length-1];return t===Bo||t===Ri}o(tI,"endsLine");function Cc(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??eg,a=new hr(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,S=0,b=new bc,R=0,y=!1,_,C,x=o(P=>{h=!0,d.abort(P),p.cancel(P).catch(()=>{})},"stop"),N=o((P,$)=>{try{WC(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,$)=>YC(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 mr&&T(j),j}let $=[];for(let j of eI(P)){if(y&&(y=!1,j[0]===Bo)){a.push(j),S+=j.length,$.push({raw:j,atStart:!1});continue}let B=a.discardedEvents,ee=a.discardedComments,Ue=a.discarding;!Ue&&b.length===0&&(R=S),S+=j.length;for(let De of a.push(j))$.push({event:De});Ue?($.push({raw:j,atStart:!1}),y=!a.discarding&&j[j.length-1]===Ri):a.discardedEvents>B?(T(new mr(i,a.discardedComments>ee)),b.push(j),$.push({raw:b.take(),atStart:R===0}),y=!a.discarding&&j[j.length-1]===Ri):tI(j)&&a.idle?b.clear():b.push(j)}return $},"parse");return new ReadableStream({async pull(P){if(C!==void 0){P.error(C.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 mr&&T(oe),oe}for(let oe of qe)oe.terminated?j.push({event:oe}):B=!0;a.discardedEvents>Y&&b.length>0&&(T(new mr(i,a.discardedComments>le)),j.push({raw:b.take(),atStart:R===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&&QC.every((oe,tt)=>Y.raw[tt]===oe)&&Ge(`
37
- `),De(Y.raw.slice()),_=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(_===Bo?`
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
- `),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?C={error:$}:P.error($))}},cancel(P){if(!h)return h=!0,d.abort(P),p.cancel(P)}},{highWaterMark:0})}o(Cc,"rewriteSseStream");function rI(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(rI,"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 ig=new Set(["jsonrpc","method","id","params"]),Ec=new Set(["name","uri","ref"]),ag=new Set(["type","name","uri"]),nI="subscriptions/listen",kc="notifications",cg="resourceSubscriptions",oI=new Set([...Ec,_t(kc)]),sI=new Set([_t(cg)]),iI=/[^\u0000-\u007f]/,aI=34,cI=92,og=123,dI=125,uI=91,lI=93,pI=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 sg(e,t){let r=_t(t);return Object.keys(e).some(n=>n!==t&&_t(n)===r)}o(sg,"hasCaseVariantOf");function mI(e,t){let r=o(a=>{switch(a.role){case"member":return ig;case"params":return t.has(a.member)?oI:Ec;case"ref":return ag;case"notifications":return sI;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===aI){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let p=0;for(;e.charCodeAt(d-1-p)===cI;)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(iI.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===og||c===uI){let d=c===og,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===dI||c===lI)s>0?s--:n.pop();else if(s===0&&(c===pI||c===Ic)){let d=n.at(-1);d?.isObject?d.expectKey=c===Ic:d?.role==="batch"&&c===Ic&&d.member++}}return!1}o(mI,"hasUnsafeKeyInText");function dg(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(Jo(s)){if(Tc(s,ig)||e.checksListen===!0&&s.method===nI&&(t.add(r),Jo(s.params)&&(sg(s.params,kc)||Jo(s.params.notifications)&&sg(s.params.notifications,cg))))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,ag)))return!0}}return mI(e.text,t)}o(dg,"hasAmbiguousIdentifyingKeys");var hI=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),fI=47,ug=44,gI=38,Ac=o(e=>e!==fI&&e!==ug,"VALUE"),yI=o(e=>!hI(e),"ANY"),SI=o(e=>e!==gI,"QUERY_VALUE"),RI=["+","#",".","/","?","&"],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===ug,"test"),to:n}),this.edges[n].push({test:Ac,to:r})}};function lg(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=RI.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(SI)});break;case"+":case"#":t.plus(yI);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(lg,"compileUriTemplate");function pg(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(pg,"matchesUriTemplate");var Ii=m.record(m.string(),m.unknown()),wI=m.record(m.string(),m.unknown()),jt=m.array(m.string().min(1)).min(1).optional(),_I=m.object({name:m.string().min(1),description:m.string().min(1).optional(),annotations:wI.optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),bI=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(),vI=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(),CI=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(),II=m.array(m.union([m.string(),_I])),TI=m.array(m.union([m.string(),bI])),EI=m.array(m.union([m.string(),vI])),kI=m.array(m.union([m.string(),CI])),AI=m.object({module:m.unknown(),export:m.string().min(1)}).strict(),PI=m.object({mode:m.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:m.string().min(1).optional(),groupClaim:m.string().min(1).optional(),identifier:AI.optional()}).strict(),xI=m.object({tools:II.optional(),prompts:TI.optional(),resources:EI.optional(),resourceTemplates:kI.optional(),accessControl:PI.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 OI(e,t){return Jm(xI,e,`MCP capability filter policy "${t}"`)}o(OI,"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 bg(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(bg,"createReplyIdMatcher");function mg(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(mg,"asStringArray");function hg(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(hg,"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:mg(e.roles),groups:mg(e.groups),public:e.public===!0}}o(jc,"normalizeEntry");function MI(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(MI,"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&&MI(a,r,n)&&s.push(a.key)}return s}o(_i,"allowedKeys");var vg=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(hg(e.user?.data,n)),a=new Set(hg(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 UI(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(UI,"assertNoConflictingMarkup");function qI(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(qI,"assertNoMarkup");function zI(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(zI,"buildCustomResolver");function NI(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 zI(r,t)}if(n==="rolesAndGroups")return UI(e,t),vg;qI(e,t)}o(NI,"buildCapabilityResolver");function jI(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=aT(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o(jI,"buildProjectionMaps");function Cg(e){return e===void 0?void 0:bt.find(t=>t.listMethod===e)}o(Cg,"findListRule");function Dc(e){return e===void 0?void 0:bt.find(t=>t.directMethods.includes(e))}o(Dc,"findDirectRule");var Ti="completion/complete",Ig=["prompts","resources","resourceTemplates"];function Tg(e){return e===Ti||Dc(e)!==void 0}o(Tg,"isCapabilityMethod");var Ci="subscriptions/listen",DI=[...bt.flatMap(e=>[e.listMethod,...e.directMethods]),Ti,Ci];function LI(e){let t=_t(e.trim()),r=DI.find(n=>_t(n)===t);return r!==void 0&&r!==e?r:void 0}o(LI,"methodVariantOf");function fg(e,[t,r]){return{code:I.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(fg,"invalidParams");function Lc(e){return t=>({code:I.InvalidParams,message:`${e} "${$s(t)}" not found`})}o(Lc,"namedNotFound");function $I(e,t){return{code:Am(t),message:"Resource not found",data:{uri:Ls(e,Pm)}}}o($I,"resourceNotFound");var HI={legacy:Lc("Tool"),modern:Io.tool},xc={legacy:Lc("Prompt"),modern:Io.prompt},BI={legacy:$I,modern:Io.resource},FI={legacy:Lc("Resource template"),modern:Io.resourceTemplate};function JI(e){let t=je(e);if(t===void 0||!Tg(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:BI}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?HI: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&&VI(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:FI}]}let c=H(r)?H(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Ig,target:void 0,issue:c,notFound:xc}]}o(JI,"capabilityAccesses");function VI(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 GI(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(VI,"hasTemplateExpression");function GI(e){return e>32&&e<127?!1:KI.test(String.fromCharCode(e))}o(GI,"isWhitespaceCode");var KI=/\s/;function WI(e){return e.type==="invalid"&&(!H(e.raw)||e.raw.jsonrpc!=="2.0")}o(WI,"isNonJsonRpcMember");function ZI(e){return H(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(ZI,"hasNonStringMethod");function Eg(e){return e.type==="request"||e.type==="invalid"&&je(e)!==void 0}o(Eg,"awaitsReply");function YI(e){return H(e.raw)&&H(e.raw.params)?e.raw.params:void 0}o(YI,"rawParams");function XI(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:te()&&Fr(e.headers,r.raw)}o(XI,"isModernRequest");var gg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Oc="=?base64?",Mc="?=",QI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function eT(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(QI.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(eT,"decodeMcpHeaderValue");var tT=-32020;function rT(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(gg,r)?gg[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let p=eT(d);if(p===void 0)return bi(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=YI(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(rT,"headerMismatchResponse");function bi(e,t,r){return st(400,{code:tT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(bi,"mismatchResponse");var nT={code:I.MethodNotFound,message:"Method not found"},yg={code:I.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},oT={code:I.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},sT="2025-06-18";function Ko(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(Ko,"isValidRequestId");function kg(e){return H(e.raw)&&!Object.hasOwn(e.raw,"id")}o(kg,"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(kg(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 Sg=-32e3;function iT(e,t){let r=e.headers.get("accept");if(r===null||!/application\/json/i.test(r))return st(406,{code:Sg,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:Sg,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 Kf(e.headers,t.shape==="batch"?t.messages.map(n=>n.raw):t.messages[0]?.raw)}}o(iT,"legacyTransportRefusal");function Rg(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>=sT)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"||kg(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)??oT).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(Rg,"refusalResponse");function aT(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(aT,"buildProjection");function wg(e){let t=e.base[e.property],r=e.overlay[e.property];return H(r)?H(t)?{...t,...r}:r:t}o(wg,"mergeRecordProperty");function cT(e,t){let r={...e,...t.overlay},n=wg({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=wg({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(cT,"applyProjection");var Oe=Symbol("unreadable"),sn=Symbol("dropped");function dT(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?[]:[cT(d,p)]})}}}o(dT,"filterAndProjectItems");var Ag="resources/read";function uT(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(uT,"withPrivateReadScope");function Pg(e,t){let r=Cg(je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(Pg,"listTargetOf");function lT(e,t,r){return H(e)&&bt.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(lT,"carriesUnfilteredList");function pT(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(y=>Pg(y,r),"listTarget"),d=t.messages.filter(Eg),u=new Map;for(let y of d){let _=Go(y.id);_!==void 0&&!u.get(_)&&u.set(_,c(y))}let p=bg(d.map(y=>y.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&je(h)===Ag,S=o(y=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let _=p(y);return _===void 0?void 0:u.get(_)},"targetForReply"),b=o(y=>{if(!H(y))return Oe;if(!("result"in y))return"method"in y&&!("error"in y)?R(y):"error"in y||"method"in y?y:Oe;let _=S(y.id);return _===void 0||lT(y.result,_,r)?Oe:_===null?f?uT(y):y:dT(y,_.rule,_.projections,n?.[_.rule.option],s)},"filterMessage"),R=o(y=>{if(a===void 0)return y;if(y.method==="notifications/resources/updated"){let _=H(y.params)?y.params.uri:void 0;return typeof _=="string"&&!a(_)?sn:y}if(y.method==="notifications/subscriptions/acknowledged"){let _=Mg(y.params,a);return _===void 0?y:{...y,params:_}}return y},"filterServerMessage");return y=>{if(!Array.isArray(y))return b(y);if(t.shape!=="batch")return Oe;let _=y.map(b);if(_.includes(Oe))return Oe;let C=_.filter(x=>x!==sn);return C.length===_.length?_:C.length===0?sn:C}}o(pT,"createReplyFilter");function mT(e){return We(e.headers.get("content-type")).includes("json")}o(mT,"isJsonResponse");function hT(e){return We(e.headers.get("content-type"))==="text/event-stream"}o(hT,"isEventStreamResponse");var fT=10*1024*1024,gT=/^[\w.~:/+=-]{0,256}$/;function yT(e){if(rg(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"&&gT.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(yT,"inspectSseLines");var xg="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",ST="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(Eg),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),Pg(u,t)!==null&&s.add(h))}let i=bg(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)?xg:ST}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(zc,"createReplyTracker");function Og(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(Og,"filterBatchMembers");function RT(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=yT(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 b=a.keyOf(S);if(b!==void 0&&a.hasFailed(b))return null;let R=s(S);if(R===sn)return null;if(R===Oe&&r.shape==="batch"&&Array.isArray(S)){let{replies:y,dropped:_}=Og(S,s,a);if(_>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),y.length===0)return null;let C=Fo(f,JSON.stringify(y));return p()?vc(C):C}if(R===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 y=u(a.fail([b]));return p()?vc(...y):y}for(let y of Array.isArray(R)?R:[R])a.answer(a.keyOf(y));return R===S?f:Fo(f,JSON.stringify(R))},{maxEventChars:fT,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(RT,"filterEventStream");function $c(e){return je(e)===Ci}o($c,"isListenRequest");function wT(e){return te()&&e.messages.some($c)}o(wT,"filtersListen");function Mg(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(Mg,"narrowSubscriptionParams");function _T(e,t,r){let n=!1,s=t.messages.map(a=>{if(!$c(a)||!H(a.raw))return a.raw;let c=Mg(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(_T,"narrowListenSubscriptions");var qc=Symbol("access unresolved"),_g=10*1024*1024,Ug="the request body could not be read";async function bT(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(bT,"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 vT(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)>_g)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: ${Ug}`}),"unreadable"),c;try{c=await bT(e,_g,!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(vT,"refuseUninspectable");var Nc=class extends Os{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=OI(t,r);super(n,r),this.#r=r,this.#e=jI(n),this.#t=NI(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,lg(i)]))}async handler(t,r){let n=await zm(t);if(n===null)return await vT(t,r)??t;let s=XI(t,n);if(s){let T=n.messages[0],O=T===void 0?void 0:rT(t,T);if(O!==void 0)return O}let i=n.messages.findIndex(WI);if(i!==-1)return vi(`batch member ${i}: ${Hc(n.messages[i].raw)}`);let a=n.messages.findIndex(ZI);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: ${Ug}`})}if(dg({envelope:n,text:c,isCapabilityMethod:Tg,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:LI(O);L!==void 0&&this.#u(L)&&d.set(T,nT)}let u=wT(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)?yg: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()?iT(t,n):void 0)??Rg(n,d,s,!s&&f)}if(p===qc)return Rg(n,new Map(n.messages.map(T=>[T,yg])),s);let S=u||s?this.#l(p):void 0,b=S===void 0?t:_T(t,n,S),R=s&&this.#t!==void 0,y=R&&this.#p();if(!this.#h(n,u,y))return b;let _=pT({envelope:n,projectionMaps:this.#e,allowedSets:p,privateScope:R,privateReadScope:y,isResourceVisible:S}),C=o(T=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${T}`),"warn"),x=o((T,O)=>{C(`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:xg})),{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&&mt(T.headers))return O?T:x("its body is still content-encoded",T);if(hT(T))return RT({response:T,envelope:n,projectionMaps:this.#e,filterReply:_,warn:C});if(!mT(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=_(L);if(Q===Oe&&n.shape==="batch"&&Array.isArray(L)){let $=zc(n,this.#e),{replies:j,dropped:B}=Og(L,_,$);B>0&&j.push(...$.fail($.pendingKeys())),j.length>0&&(C("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 JI(t)){if(!(d.refusedBy??d.options).some(a))continue;let{target:u}=d;if(u===void 0)return fg(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,S=i&&h!==void 0?Mm(h,H(f)?f:void 0):void 0;return S!==void 0&&h!==void 0?fg(h,S):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||!pg(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?Ig.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)===Ag)return!0;let i=Cg(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",CT=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),IT=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function qg(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(qg,"s2FaviconHref");function TT(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(TT,"strictFaviconHref");var zg=qg(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")?qg(Bc):TT(e)}o(Fc,"resolveIconHref");function ET(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(ET,"hostnameFromHost");function kT(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(kT,"isLocalOrAddressHost");function AT(e){let t=ET(e).toLowerCase().replace(/\.$/,"");if(kT(t)||IT.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=CT.has(n)?3:2;return r.slice(-s).join(".")}o(AT,"inferFaviconDomain");function Jc(e){return{src:Fc(AT(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 PT=-32020,Vc="(missing)",xT=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"]),Ng={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},jg="=?base64?",Dg="?=",OT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function MT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(MT,"isRecord");function Lg(e){return e===" "||e===" "}o(Lg,"isHttpOws");function UT(e){let t=0,r=e.length;for(;t<r&&Lg(e[t]);)t++;for(;r>t&&Lg(e[r-1]);)r--;return e.slice(t,r)}o(UT,"stripHttpOws");function an(e,t){return e.get(t)??void 0}o(an,"readHeader");function qT(e){if(!e.startsWith(jg)||!e.endsWith(Dg))return e;let t=e.slice(jg.length,e.length-Dg.length);if(OT.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(qT,"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:PT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(Wo,"headerMismatchResponse");function zT(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(Ng,n))return;let s=Ng[n],i=MT(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=UT(c),u=qT(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(zT,"standardHeadersResponse");function $g(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 xT.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"?zT(t,r,s):void 0}o($g,"validateModernGatewayRequest");function Gc(e,t){return t===void 0?{}:{[e]:t}}o(Gc,"optionalHeader");import{context as NT,TraceFlags as jT,trace as DT}from"@opentelemetry/api";var Hg="mcp-session-id",LT=256*1024;function ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(ht,"isPlainObject");function Bg(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Bg,"isJsonContentType");function Zc(e,t,r){if(t===void 0||r===void 0||r.byteLength>Ph||!Bg(e))return;let n=t.value;if(!ht(n)||typeof n.method!="string"||n.params!==void 0&&!ht(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 $T(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($T,"readCapability");function Fg(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Fg,"readHeader");function HT(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(HT,"readUpstreamServer");function Jg(e,t){let r=ur(e.headers,t.message),n=Fg(e.headers,Hg),s={methodName:t.method,...$T(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??Dm,params:t.params},requestedProtocolVersion:r}}o(Jg,"readServerSpanInput");function Vg(e){let{request:t,context:r,parsed:n}=e,{common:s,server:i,requestedProtocolVersion:a}=Jg(t,n),c=Ta(i),d;try{Ms(c.span);let u=c.span.isRecording()||$m()?HT(t,r):{};return d=NT.with(c.ctx,()=>Hm({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Ms(d.span),Ca(r,c.span.spanContext()),{server:c,client:d}}catch(u){throw ki(d===void 0?[c]:[d,c]),u}}o(Vg,"startMcpProxySpans");var BT=["content-digest","repr-digest","digest","content-md5"];function FT(e){return BT.some(t=>e.has(t))}o(FT,"hasBodyIntegrityHeader");function Gg(e,t,r,n){let s=DT.getSpanContext(t.client.ctx);if(r.byteLength>LT||n!==void 0&&FT(n)||s===void 0||(s.traceFlags&jT.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!ht(i))return r;try{let a=Ea(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!xh(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(Gg,"injectTraceContextIntoBody");function Kg(e,t){if(e){if(ht(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(ht(e.result)&&e.result.isError===!0)return{isError:!0}}}o(Kg,"readSpanResponse");function JT(e,t,r){let n=Fg(t.headers,Hg),s=r?.result,i=xm(ht(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);fr(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(JT,"recordInitializeResult");function Wg(e){let{spans:t}=e,r=[t.client,t.server];try{VT(r,e)}catch{}finally{ki(r)}}o(Wg,"finishMcpProxySpans");function VT(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&JT(e,n,s.message);let i=Kg(s.message,n.status);i?fr(e,a=>a.setResponse(i)):s.ended==="errored"?fr(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?fr(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?fr(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?fr(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&&fr(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(VT,"recordOutcome");function fr(e,t){for(let r of e)try{t(r)}catch{}}o(fr,"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 GT(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(GT,"gatewayAnswerMessage");var KT=64*1024;async function WT(e){if(e.body===null||!Bg(e))return;let t=await e.clone().text();if(t.length>KT)return;let r=JSON.parse(t);return ht(r)?r:void 0}o(WT,"readGatewayAnswer");function ZT(e){return ht(e.error)?ht(e.error.data)&&e.error.data.connectRequired!==void 0:ht(e.result)&&e.result.resultType==="input_required"}o(ZT,"isConnectRequiredAnswer");async function Zg(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}=Jg(e.request,r);t=Ta({...n,startTime:e.startTime}),Ms(t.span),Ca(e.context,t.span.spanContext());let s;try{s=await WT(e.response)}catch{}let i=Kg(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&&ZT(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,GT(a))}catch{}finally{t&&ki([t])}}o(Zg,"recordGatewayAnsweredMcpSpan");function Dt(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(Dt,"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 Yg(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(Yg,"requireUpstreamIdJagConfig");import{base64url as Pi}from"jose";var YT="__Host-",XT=16,QT=32,Qg=".",eE=!1;function Lt(){return eE}o(Lt,"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?`${YT}${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 Xg(e){return Pi.encode(crypto.getRandomValues(new Uint8Array(e)))}o(Xg,"randomBase64url");async function ey(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Pi.encode(new Uint8Array(t))}o(ey,"hashNonce");function tE(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(tE,"constantTimeEqual");function ty(e,t,r){return Qc(`zuplo_mcp_${e}_${t}`,r)}o(ty,"bindingCookieName");async function Xo(e){let t=Xg(XT),r=Xg(QT),n=xi(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${Qg}${Pi.encode(e.payload)}`;return{claim:{id:t,hash:await ey(r)},setCookie:Yo({name:ty(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=ty(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(Qg),a=i<0?s:s.slice(0,i);if(!tE(await ey(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 ry(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(ry,"mergeAbortSignals");async function rE(e){try{await e.cancel()}catch{}}o(rE,"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 rE(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 nE=2,oE=1024*1024,sE=1e4,iE=new Set([301,302,303,307,308]),aE=["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 cE(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(cE,"assertContentLengthWithinLimit");async function dE(e,t,r){return cE(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(dE,"readBoundedResponseBody");function uE(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(uE,"responseFromBufferedBody");function lE(e,t){if(!iE.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(lE,"resolveRedirectUrl");function ny(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(ny,"validateOutboundUrl");var oy=new WeakSet;function sy(e){return e instanceof k&&oy.has(e)}o(sy,"isOutboundTransportFailure");function iy(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 oy.add(r),r}o(iy,"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 pE(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()}}),iy(d,s)}}o(pE,"fetchWithNormalizedError");function mE(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(mE,"assertRedirectAllowed");function hE(e,t){let r=new Headers(e);for(let n of aE)r.delete(n);for(let n of t)r.delete(n);return r}o(hE,"stripCrossOriginHeaders");function fE(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=hE(e.headers,s)),i}o(fE,"buildRedirectInit");function gE(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(gE,"buildInitialRequestInit");function yE(e){let t=dn(e.currentInput,e.currentInit);mE({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ny(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:fE(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(yE,"followRedirect");async function rd(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??nE,i=r.maxResponseBytes??oE,a=r.timeoutMs??sE,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,p=new AbortController,h=ry(p,t.signal),f=!1,S=setTimeout(()=>{f=!0,p.abort()},a),b=e,R=gE(e,t,p.signal),y;try{y=ny(td(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(C){throw Qo(u,{event:"outbound_url_blocked",problemCode:n,method:dn(e,t),host:ie(td(e)),error:C}),clearTimeout(S),h?.(),C}let _=0;try{for(;;){let C=await pE(u,c,b,R,n,y,()=>f?`timeout_after_${a}ms`:void 0),x=lE(C,y);if(x!==void 0)try{let N=yE({currentInput:b,currentInit:R,currentUrl:y,redirectUrl:x,redirects:_,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});b=N.currentInput,R=N.currentInit,y=N.currentUrl,_=N.redirects;continue}catch(N){throw Qo(u,{event:"outbound_redirect_blocked",problemCode:n,method:dn(b,R),host:ie(y),error:N,extra:{redirects:_,maxRedirects:s,redirectTargetHost:ie(x)}}),N}try{return uE(C,await dE(C,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,R),host:ie(y),error:N,extra:{maxResponseBytes:i,status:C.status}}),iy(N,n)}}}finally{clearTimeout(S),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 ay(e,t={},r={}){return rd(e,t,{...r,validateUrl:xo})}o(ay,"fetchConfiguredOutbound");function cy(e,t={},r={}){return es(e,t,{...r,validateUrl:xo})}o(cy,"fetchConfiguredOutboundJson");function Ui(e,t={},r={}){return es(e,t,{...r,validateUrl:Sh})}o(Ui,"fetchIdentityProviderJson");function dy(e,t={},r={}){return es(e,t,{...r,validateUrl:Xs})}o(dy,"fetchCimdClientMetadataJson");function uy(e,t={},r={}){return es(e,t,{...r,validateUrl:Oo})}o(uy,"fetchCimdClientJwksJson");import{errors as gy,jwtVerify as yy,SignJWT as Sy}from"jose";var fe="zuplo-mcp-gateway",_e=fe,be="HS256";import{base64url as SE}from"jose";var RE=new TextEncoder,wE="MCP gateway could not initialize secure key material.",_E=32,ly=new Map,py=new Map,bE;function vE(){return bE??zr.instance.authPrivateKey}o(vE,"readAuthPrivateKey");function my(e){return new Ee(wE,e===void 0?void 0:{cause:e})}o(my,"createGeneratedKeyMaterialError");function hy(e,t){let r=SE.decode(t);if(r.byteLength!==_E)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(hy,"decodeJwkKeyField");function CE(e){let t=vE();if(!t)throw my();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=hy("d",r.d);hy("x",r.x);let s=RE.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 my(r)}}o(CE,"decodeGeneratedKeyMaterial");function IE(e){let t=ly.get(e);return t||(t=CE(e),ly.set(e,t)),t}o(IE,"getMasterKeyMaterial");async function Ze(e){let t=py.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(IE(e.keyMaterialPurpose));return py.set(e.purpose,r),r}o(Ze,"readCachedDerivedKey");var TE="SHA-256",EE=32,kE="zuplo-mcp-gateway:",AE=new TextEncoder,fy=new WeakMap;async function ft(e,t){let r=fy.get(e);r||(r=new Map,fy.set(e,r));let n=r.get(t);if(n)return n;let s=await PE(e,t);return r.set(t,s),s}o(ft,"deriveGatewaySigningKey");async function PE(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=AE.encode(`${kE}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:TE,salt:new Uint8Array,info:ye(s)},n,EE*8);return new Uint8Array(i)}o(PE,"hkdfExpand");var Ry=900,xE=900,OE=th.extend({id:vh,browserBinding:Zo.optional()}),ME=OE.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),wy=ka.extend({id:Ch,purpose:m.literal("browser_connect")}),UE=ka.extend({purpose:m.literal("browser_connect")}),qE=wy.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),qi=Ry*1e3;async function _y(){return Ze({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"oauth-state"),"derive")})}o(_y,"getOAuthStateKey");async function by(){return Ze({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-connect"),"derive")})}o(by,"getBrowserConnectKey");async function vy(e){let t=Math.floor(Date.now()/1e3)+Ry;return new Sy(e).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await _y())}o(vy,"signOAuthState");async function zi(e){try{let{payload:t}=await yy(e,await _y(),{algorithms:[be],issuer:fe,audience:_e});return ME.parse(t)}catch(t){throw t instanceof gy.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 Cy(e){let t=Math.floor(Date.now()/1e3)+xE,r=UE.parse(e),n=wy.parse({...r,id:kh()});return new Sy(n).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await by())}o(Cy,"signBrowserConnectTicket");async function Iy(e){try{let{payload:t}=await yy(e,await by(),{algorithms:[be],issuer:fe,audience:_e});return qE.parse(t)}catch(t){throw t instanceof gy.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(Iy,"verifyBrowserConnectTicket");async function Ty(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(Ty,"consumeBrowserConnectTicket");function zE(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(zE,"buildConnectRequiredMessage");async function NE(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 Cy({...Ao(e),purpose:"browser_connect"})),r.toString()}o(NE,"buildGatewayBrowserTicketUrl");function jE(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(jE,"buildGatewayConnectPath");async function nd(e){return NE({...e,path:jE(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:zE(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ni,"buildRedirectConnectRequiredResponse");function Ey(e){return ky({...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(Ey,"buildAdminConnectRequiredResponse");function ky(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(ky,"buildAdminSetupRequiredResponse");function Ay(e){return Ie().byOperationId.get(e)?.downstreamOAuth!==void 0}o(Ay,"routeSupportsBrowserConnect");function Py(e){return ky({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o(Py,"buildBrowserConnectUnavailableResponse");var xy=12;async function Oy(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(Oy,"sha256Hex");async function gr(e){if(e)return(await Oy(e)).slice(0,xy)}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 Oy(t)).slice(0,xy)}o(un,"fingerprintConnectionIdentity");var DE=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()+DE)return"near_expiry"}return"usable"}o(Me,"describeAccessTokenState");var My=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function LE(e,t){return e&&e.length>0?e.join(t):void 0}o(LE,"joinOAuthScopes");function $E(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of My)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o($E,"sanitizeAuthorizationServerMetadata");function Uy(e){let t=$E(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(Uy,"sanitizeOAuthDiscoveryState");function qy(e){let t=new URL(e);for(let r of My){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(qy,"dedupeSingletonAuthorizationRequestParams");function ji(e){let t=new URL(e);return He(t)&&Fm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(ji,"normalizeLoopbackOAuthRedirectUri");function zy(e){return LE(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(zy,"readProtectedResourceMetadataScope");function HE(e){return`Zuplo MCP Gateway - ${e}`}o(HE,"buildGatewayOAuthClientName");function BE(e,t){return e&&e.length>0?e.join(t):void 0}o(BE,"joinOAuthScopeList");function FE(e){if(e.clientRegistration.mode!=="auto")return BE(e.scopes,e.scopeDelimiter)}o(FE,"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=Dt(e.upstreamServerId);return{client_name:HE(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 Ny(e,t,r){let n=cn(t,r),s=FE(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(Ny,"buildOAuthClientMetadataDocument");import{base64url as $t}from"jose";var JE="SHA-256",pn="AES-GCM",VE=12,ad="zuplo-secret",cd=1,jy="generated:auth_private_key:token-encryption",GE=m.object({version:m.literal(cd),keyId:m.literal(jy),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(JE,ye(e));return crypto.subtle.importKey("raw",t,{name:pn},!1,["encrypt","decrypt"])},"derive")})}o(id,"getEncryptionKey");function Dy(e){return ye(new TextEncoder().encode(`${ad}:v${e.version}:${e.keyId}`))}o(Dy,"getAssociatedData");function KE(e){return`${ad}:v${e.version}:${$t.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(KE,"encodeEnvelope");function WE(e){let t=`${ad}:v${cd}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode($t.decode(r));return GE.parse(JSON.parse(n))}o(WE,"decodeEnvelope");async function vt(e){let t=await id(),r=crypto.getRandomValues(new Uint8Array(VE)),n={version:cd,keyId:jy},s=await crypto.subtle.encrypt({name:pn,iv:r,additionalData:Dy(n)},t,new TextEncoder().encode(e));return KE({...n,algorithm:pn,iv:$t.encode(r),ciphertext:$t.encode(new Uint8Array(s))})}o(vt,"encryptSecret");async function Ct(e){let t=WE(e);if(t){let a=await id(),c=await crypto.subtle.decrypt({name:pn,iv:ye($t.decode(t.iv)),additionalData:Dy(t)},a,ye($t.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($t.decode(r))},s,ye($t.decode(n)));return new TextDecoder().decode(i)}o(Ct,"decryptSecret");var Ly={issuer:m.string().min(1).optional()},ZE=m.union([cr.extend(Ly),vo.extend(Ly)]),$y=m.object({authorizationServerUrl:m.url(),resourceMetadataUrl:m.url().optional(),resourceMetadata:$r.optional(),authorizationServerMetadata:m.union([Hr,Br]).optional()}).passthrough(),YE="Bearer",XE="__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 QE(e){return Kr.parse(e)}o(QE,"parsePkceCodeVerifier");function ek(e){if(typeof e.expires_in=="number")return W(new Date(Date.now()+e.expires_in*1e3))}o(ek,"readTokenExpiry");async function ld(e){if(e!==void 0)return vt(JSON.stringify(e))}o(ld,"encryptJson");async function Hy(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(Hy,"decryptJson");function tk(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(tk,"clientInformationAllowsRedirectUri");function rk(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(rk,"clientInformationMatchesCurrentClientMetadataUrl");function nk(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(nk,"isUrlBasedClientInformation");function ok(e,t){return t===void 0?e:{...e,scope:t}}o(ok,"applyOAuthClientMetadataScope");function sk(e,t){return zy({state:e,delimiter:t})}o(sk,"readResourceMetadataScope");function ik(e,t){return e&&e.length>0?e.join(t):void 0}o(ik,"joinOAuthScopeList");function ak(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 cr.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(ak,"buildManualOAuthClientInformation");function ck(e,t){let r=od({origin:new URL(t).origin,upstreamServerId:e});return pc(r)?r:void 0}o(ck,"buildClientMetadataUrl");function dk(e){for(let t of e)if(t!==void 0)return t}o(dk,"firstDefined");function uk(e){let t=cn(e.target.upstreamServerId,e.target.authProfileId),r=ik(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:ak({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=ck(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(uk,"buildInitialOAuthClientSetup");function lk(e,t){if(t===void 0)return dk([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(lk,"readEncryptedClientInformation");function pk(e){return e.pendingState?.encryptedDiscoveryState}o(pk,"readEncryptedDiscoveryState");function Di(e,t){return t===void 0?e:{...e,issuer:t}}o(Di,"applyIssuerStamp");var Ht=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=uk({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=lk(t,this.configuredClientInformation),this.encryptedDiscoveryState=pk(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 ok(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return vy({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"),!nk({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=Uy($y.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=sk(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:ek(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,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};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: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,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=qy(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:QE(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:Eh(),...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 Hy(this.encryptedClientInformation,ZE)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!tk(r,this.redirectUriValue)||!rk({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 Hy(this.encryptedDiscoveryState,$y)}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??XE,token_type:YE,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 mk=3e4,hk=256*1024,fk=2,gk="does not support dynamic client registration",yk=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Sk=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],Rk=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],wk="Protected resource ",_k=" does not match expected ",bk=["HTTP 403 Forbidden","Access Denied","permission to access"],vk=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function Ck(e){return e instanceof Error&&e.message.includes(gk)}o(Ck,"isDynamicClientRegistrationUnsupported");function Ik(e){return e instanceof Error&&yk.some(t=>e.message.includes(t))}o(Ik,"isProtectedResourceMetadataUnavailable");function Tk(e){return e instanceof Error&&Sk.some(t=>e.message.includes(t))}o(Tk,"isAuthorizationServerMetadataUnavailable");function Ek(e){return e instanceof Error&&Rk.some(t=>e.message.includes(t))}o(Ek,"isAuthorizationServerIncompatible");function kk(e){return e instanceof Error&&e.message.includes(wk)&&e.message.includes(_k)}o(kk,"isProtectedResourceMismatch");function Ak(e){return e instanceof Error&&bk.some(t=>e.message.includes(t))}o(Ak,"isUpstreamProviderAccessDenied");function By(e){return e instanceof Nt&&vk.has(e.code)}o(By,"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?{}:{[lt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[ut]:t.httpStatus},...t.providerError===void 0?{}:{[Xr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Qr]:t.providerErrorDescription}}},{cause:e.cause})}o(It,"buildUpstreamSetupProblem");function Pk(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(Pk,"describeIssuerMetadataMismatch");var xk=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 Ok(e){let{error:t,errorDescription:r}=$i(e.body),n=ts(t,xk),s=ts(r,Li);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(Ok,"readRegistrationRejectionDiagnostics");function Mk(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(Mk,"describeRegistrationRejection");function Uk(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(Uk,"readDiscoveryEndpointUrl");function qk(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(Ck(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=Ok(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 (${Mk(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:Pk(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(Ek(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(Tk(e.error)){let r=Uk(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(kk(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(Ik(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(Ak(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(qk,"mapUpstreamOAuthSetupError");function zk(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(zk,"readOAuthFetchRequest");function Nk(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Nk,"readOAuthFetchMethod");function jk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(jk,"responseLooksJson");function Dk(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(Dk,"responseLooksHtml");var Lk=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function $k(e){return Lk.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o($k,"isMetadataDiscoveryRequest");function Hk(e,t,r){return e!=="GET"||!$k(t)?!1:r>=400&&r<500||r===502}o(Hk,"sdkRetriesDiscoveryCandidate");function Bk(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,[Wr]:r,[lt]:e.request.url.toString(),[Zr]:e.body}})}o(Bk,"throwUpstreamHtmlError");var Fk=["message","error_message","detail","title"];function Fy(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}o(Fy,"readStringField");function Jk(e){for(let r of Fk){let n=Fy(e,r);if(n!==void 0)return n}let t=e.error;if(typeof t=="object"&&t!==null)return Fy(t,"message")}o(Jk,"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?Jk(r):void 0}}catch{return{}}}o($i,"readUpstreamOAuthErrorBody");function Vk(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(Vk,"logUpstreamOAuthHttpError");function Gk(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(Gk,"isRefreshTokenGrant");var Kk=new Set([void 0,me.ServerError,me.TemporarilyUnavailable]);function Wk(e,t){return e.status<500&&e.status!==429?!1:Kk.has($i(t).error)}o(Wk,"isTransientTokenEndpointResponse");var Zk=[/\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 Yk(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}o(Yk,"isTokenEndpointRequest");function Xk(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:n}=$i(t);if(!(r!==void 0||n===void 0))return Zk.some(s=>s.test(n))?n:void 0}o(Xk,"readUnknownClientRejection");function Qk(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(Qk,"rewriteUnknownClientRejection");function Jy(e,t){return async(r,n)=>{let s=zk(r),i=Nk(r,n),a=t!==void 0&&Gk(i,n),c=se(),d=Date.now(),u;try{u=await ay(r,n,{maxRedirects:fk,maxResponseBytes:hk,problemCode:"upstream_token_exchange_failed",timeoutMs:mk})}catch(h){throw a&&sy(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||Vk({log:c,upstreamServerId:e,method:i,request:s,response:u,body:p}),a&&Wk(u,p)&&(t.failure={url:s.url,status:u.status}),Hk(i,s.url,u.status))return u;if(Yk(i,n)){let h=Xk(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"),Qk(u,h)}if(!u.ok&&Dk(u,p)&&Bk({upstreamServerId:e,request:s,response:u,body:p}),!jk(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(Jy,"createUpstreamOAuthFetch");function Vy(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(Vy,"logUpstreamOAuthFlowStarted");function Gy(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(Gy,"logUpstreamOAuthFlowFailed");function Ky(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(Ky,"readAuthorizationRequestScope");async function Wy(e,t){e.applyChallengeScope(t.requestedScope),Vy({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Jy(t.upstreamServerId,t.refreshFailures)},n=Ky(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await lc(e,r)}catch(r){Gy({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=qk({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(Wy,"runUpstreamOAuth");async function eA(e,t){e.applyChallengeScope(t.requestedScope),Vy({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Jy(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=Ky(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 Gy({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(eA,"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 Zy(e,t){let r=await Wy(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(Zy,"requireUpstreamAuthorizationRedirect");function tA(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,[lt]:`${t.url.origin}${t.url.pathname}`,...t.status===void 0?{}:{[ut]:t.status}}},t.cause===void 0?void 0:{cause:t.cause})}o(tA,"buildTransientRefreshProblem");function rA(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(rA,"logTransientRefreshFailure");async function Yy(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 rA({log:s,target:e.target,connection:e.connection,connectionFingerprint:i,failure:u}),tA(e.target.upstreamServerId,u)},"rejectTransientRefreshFailure"),d;try{d=await Wy(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&&!By(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||!By(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(Yy,"authorizeUpstreamOAuthSession");async function nA(e){let t=await zi(e.stateToken),r=await G().consumeUpstreamOAuthState({id:t.id,now:W(new Date)}),n=oA(r);return sA({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),iA(n),n}o(nA,"consumeStoredCallbackState");function oA(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(oA,"readConsumedCallbackState");function sA(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(sA,"assertStoredCallbackStateMatches");function iA(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}})}o(iA,"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),Ey(r)}if(Lt()&&!Ay(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"),Py({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 Xy(e){let t=await nA({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 Ht(s),a=await eA(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(Xy,"finishUpstreamOAuthCallback");import{importPKCS8 as aA,SignJWT as cA}from"jose";var eS=1e4,tS=64*1024,rS=2,dA=300,it=m.string().min(1),uA=m.object({access_token:it,issued_token_type:m.literal(Pa),token_type:m.string().optional(),expires_in:m.number().int().positive().optional(),scope:it.optional()}).passthrough(),lA=m.object({id_token:it,token_type:it.optional(),expires_in:m.number().int().positive().optional(),refresh_token:it.optional(),scope:it.optional()}).passthrough(),pA=m.object({access_token:it,token_type:it,expires_in:m.number().int().positive().optional(),scope:it.optional(),resource:it.optional(),refresh_token:it.optional()}).passthrough();function Qy(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(Qy,"formEncodeClientCredential");function mA(e){return e.replaceAll("\\n",`
41
- `)}o(mA,"normalizePem");async function hA(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??dA,n=await aA(mA(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new cA({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(hA,"createPrivateKeyJwtClientAssertion");async function fA(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=Qy(e.clientAuth.clientId),r=Qy(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 hA({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(fA,"appendClientAuthentication");async function hd(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await fA({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(hd,"buildFormRequest");function nS(e){return(t,r)=>Ui(t,r,{context:e,maxRedirects:rS,maxResponseBytes:tS,problemCode:"upstream_token_exchange_failed",timeoutMs:eS})}o(nS,"defaultIdpFetchJson");function gA(e){return(t,r)=>cy(t,r,{context:e,maxRedirects:rS,maxResponseBytes:tS,problemCode:"upstream_token_exchange_failed",timeoutMs:eS})}o(gA,"defaultResourceAsFetchJson");function Hi(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(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 yA(e){let t=lA.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(yA,"parseIdpRefreshTokenResponse");function SA(e){let t=uA.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(SA,"parseIdJagTokenExchangeResponse");function RA(e){let t=pA.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(RA,"parseAccessTokenResponse");async function oS(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??nS(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"}),SA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(oS,"requestIdJag");async function sS(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??nS(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"}),yA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(sS,"refreshIdpSubjectToken");async function iS(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??gA(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"}),RA({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(iS,"exchangeIdJagForAccessToken");function wA(e){return Me(e)==="usable"}o(wA,"hasUsableAccessToken");function _A(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(_A,"assertBearerToken");function aS(e,t){if(t===nn)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(aS,"hasExpiredSubjectToken");async function bA(e){let t=await Ct(e.encryptedSubjectToken);if(e.subjectTokenType!==nn)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await sS({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(bA,"resolveIdJagSubjectToken");async function cS(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&&wA(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||aS(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&&aS(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=Dt(e.upstreamServerId),p=Yg(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)),S=await bA({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:p.idp.tokenUrl},clientAuth:p.idp.clientAuth,context:e.context}),b=await oS({idp:{tokenUrl:p.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:p.resourceAs.audience,resource:h,scope:f,clientAuth:p.idp.clientAuth,context:e.context}),R=b.scope??f,y=await iS({resourceAs:{tokenUrl:p.resourceAs.tokenUrl},assertion:b.assertion,resource:h,scope:R,clientAuth:p.resourceAs.clientAuth,context:e.context});if(_A(y),t!==void 0){let C=(y.scope??R)?.split(/[,\s]+/).filter(Boolean)??[],x=y.expiresIn===void 0?void 0:W(new Date(Date.now()+y.expiresIn*1e3)),N=await G().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 vt(y.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:C,expiresAt:x,metadata:S.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:C.length,expiresAt:x},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}o(cS,"authorizeUpstreamIdJagRequest");var Bi=new Map;function vA(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(vA,"normalizeRefreshFlightScope");function CA(e){return ji(new URL(e.callbackPath,ce(e.requestUrl,e.requestHeaders))).toString()}o(CA,"buildGatewayOAuthRedirectUri");async function gd(e){let t=Dt(e.upstreamServerId),r=cn(e.upstreamServerId,e.authProfileId),n=CA({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 dS(e){let t=await gd(e),r=new Ht({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Zy(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(dS,"startUpstreamConnect");async function uS(e){let t=await gd(e),r=new Ht({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>Yy({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=Ih({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,vA(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 Ht({...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(uS,"authorizeUpstreamRequest");async function Fi(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return uS({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 cS({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 lS(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 dS({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(lS,"startUpstreamConnectForRequest");async function IA(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(IA,"requireCallbackBrowser");async function pS(e){let t=await zi(e.callbackRequest.state);Lt()&&await IA(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 Xy({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:Dt(e.callbackRequest.upstreamServerId)})}o(pS,"finishUpstreamCallbackForRequest");function TA(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(TA,"buildRouteAuthBaseFromConnection");function mS(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:rh(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(mS,"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 TA({connection:n.connection,operationId:t})}o(Ji,"resolveRouteAuthBase");function yd(e,t){switch(e){case"user":return tn(t);case"shared":return eh()}}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 EA,errors as hS,jwtVerify as kA,SignJWT as AA}from"jose";var Sd="zuplo-connect.",PA=600,fS="mcp_connect_request_state",xA=m.object({purpose:m.literal(fS),binding:m.string().min(1),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),OA=new TextEncoder;async function gS(){return Ze({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"connect-request-state"),"derive")})}o(gS,"getConnectRequestStateKey");async function yS(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",OA.encode(t));return EA.encode(new Uint8Array(r))}o(yS,"digestBinding");function Rd(e){return typeof e=="string"&&e.startsWith(Sd)}o(Rd,"isConnectRequestState");async function SS(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new AA({purpose:fS,binding:await yS(e)}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt(r).setExpirationTime(r+PA).sign(await gS());return`${Sd}${n}`}o(SS,"signConnectRequestState");async function RS(e,t,r=new Date){if(!Rd(e))return"foreign";let n;try{let{payload:s}=await kA(e.slice(Sd.length),await gS(),{algorithms:[be],issuer:fe,audience:_e,currentDate:r,clockTolerance:0});n=xA.parse(s)}catch(s){return s instanceof hS.JWTExpired?"expired":s instanceof hS.JWTClaimValidationFailed||s instanceof m.ZodError?"invalid":"foreign"}return n.binding===await yS(t)?void 0:"mismatch"}o(RS,"verifyConnectRequestState");var MA=new Set(["initialize","ping","logging/setLevel","resources/subscribe","resources/unsubscribe","tasks/list","tasks/result"]);function wS(e){if(!xe()||!MA.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(wS,"modernMethodNotFoundResponse");var UA=new Map([["tools/list","tools"],["prompts/list","prompts"],["resources/list","resources"],["resources/templates/list","resourceTemplates"]]),qA=0,zA="private",NA=new Set(["tools/call","prompts/get","resources/read"]);var jA=-32021,DA="Invalid or expired requestState";function yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yr,"isRecord");function LA(e,t){if(!(!te()||!yr(t)||typeof t.method!="string"||!Fr(e,t)))return{message:t,method:t.method}}o(LA,"readModernMcpRequest");async function _S(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}:LA(e.headers,t)}o(_S,"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 bS(e){if(!NA.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(bS,"readInputRequiredTarget");function vS(e,t,r){return{...e,method:t.method,target:r}}o(vS,"buildBinding");function $A(e){let t=we(e.message);return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:I.InvalidParams,message:DA,data:{reason:"invalid_request_state"}}}))}o($A,"invalidRequestStateResponse");function HA(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(HA,"readElicitationAction");function BA(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(BA,"stripConnectState");async function CS(e){let t=bd(e.request),r=t?.requestState;if(!Rd(r))return{kind:"none"};let n=bS(e.request),s=n===void 0?"mismatch":await RS(r,vS(e.binding,e.request,n),e.now);if(s==="foreign")return{kind:"none"};if(s!==void 0)return{kind:"rejected",reason:s,response:$A(e.request)};let i=BA(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:HA(t?.inputResponses)}}o(CS,"readModernConnectRetry");function FA(e){let t=km(e.message)?.elicitation;return yr(t)&&t.url!==void 0}o(FA,"declaresUrlElicitation");function JA(e,t){return Response.json(Pe({...e===void 0?{}:{id:e},error:{code:Sc,message:t.message,data:{connectRequired:t}}}))}o(JA,"connectRequiredErrorResponse");async function IS(e){if(wd(e.request))return _d();let t=we(e.request.message),r=UA.get(e.request.method);if(r!==void 0)return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",[r]:[],ttlMs:qA,cacheScope:zA,_meta:{[Mt]:e.serverInfo}}});let n=bS(e.request),s=e.payload.authUrl;if(n===void 0||s===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return JA(t,e.payload);if(!FA(e.request))return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:jA,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 SS(vS(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(IS,"modernConnectRequiredResponse");var vd=new WeakMap;function TS(e,t){vd.set(e,t)}o(TS,"setUpstreamAuthRetry");function ES(e){let t=vd.get(e);return vd.delete(e),t}o(ES,"takeUpstreamAuthRetry");var kS=new WeakSet;function AS(e){kS.add(e)}o(AS,"markGatewayUpstreamCredential");function PS(e){return kS.has(e)}o(PS,"sentGatewayUpstreamCredential");async function xS(e){try{return await Fi(e)}catch(t){if(Be(t)==="upstream_token_refresh_unavailable")return{kind:"refresh_unavailable"};throw t}}o(xS,"resolveCredentialOrRefreshUnavailable");function OS(e,t){return en(e,t,{code:"upstream_token_refresh_unavailable"})}o(OS,"refreshUnavailableResponse");var VA="The upstream connection returned no OAuth tokens.";function MS(e){let t=hc(e);return Response.json(Pe({id:t,error:{code:I.InternalError,message:VA}}),{status:t===void 0?500:200})}o(MS,"noUpstreamTokensJsonRpcResponse");function GA(e,t){return{credentialType:e.type,forceRefresh:t}}o(GA,"buildCredentialResolvedAttributes");function KA(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(KA,"connectRequiredReasonCode");function US(e){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:GA(e.credential,e.forceRefresh===!0)})}o(US,"emitCredentialResolvedAnalyticsEvent");function qS(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:KA(e.payload.state),reasonClass:"auth",attributes:t})}o(qS,"emitCredentialMissingAnalyticsEvents");function WA(e){let t=e.route.raw();return Js.parse(t?.operationId)}o(WA,"readOperationId");async function ZA(e,t,r,n,s){let i=await xS({request:e,context:n,routeAuth:t});if(i.kind==="refresh_unavailable")return i;if(i.kind==="connect_required")return qS({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(US({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(ZA,"buildCredentialHeaders");var YA=new Set(["authorization","cookie","cookie2"]);function zS(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(zS,"parseJsonRequestBody");function XA(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(XA,"readJsonRequestMethod");function QA(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(QA,"isJsonResponse");function Bt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Bt,"isRecord");function NS(e){return Array.isArray(e)&&e.length>0}o(NS,"hasIconList");function jS(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Ei(Xm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(jS,"readFallbackServerIcons");function eP(e){if(!Bt(e.body))return e.body;let t=e.body.result;if(!Bt(t))return e.body;let r=t.serverInfo;return!Bt(r)||NS(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(eP,"addMissingServerIcons");function tP(e){if(!Bt(e.body))return e.body;let t=e.body.result;if(!Bt(t))return e.body;let r=t._meta;if(!Bt(r))return e.body;let n=r[Mt];return!Bt(n)||NS(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[Mt]:{...n,icons:e.icons}}}}}o(tP,"addMissingDiscoverServerIcons");function rP(e,t){let r=DS(e.headers);for(let n of YA)r.delete(n);for(let[n,s]of t)r.set(n,s);return new xt(e,{headers:r})}o(rP,"applyUpstreamHeaders");function DS(e){let t=new Headers(e);return ku(t),t}o(DS,"buildProxyHeaders");async function nP(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(nP,"readRetryBody");function oP(e){return xe()&&e.httpMethod==="POST"?Wf({body:e.requestBody,parsed:zS(e.requestBody),headers:e.headers,payload:e.payload}):Response.json(Rc({id:hc(e.requestBody),payload:e.payload,urlElicitation:!0,fallbackCode:I.InvalidRequest}))}o(oP,"connectRequiredJsonRpcResponse");function sP(e){let t=e.modern;if(t===void 0)return{respond:o(async i=>xe()&&e.httpMethod!=="POST"?await Si(e.request,e.context):oP({requestBody:e.requestBody,httpMethod:e.httpMethod,headers:e.headers,payload:i}),"respond")};let r=o(()=>jS({connection:e.connection,context:e.context}),"readIcons"),n=yi(t.binding.upstreamServerId,$o),s=t.request.method==="server/discover"?async()=>Hf({request:t.request,supportedVersions:n,connection:e.connection,capabilityFilter:iP(e.context),icons:r()}):i=>IS({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=$g({headers:e.headers,message:t.request.message,supportedVersions:n});return a!==void 0?a:wd(t.request)?_d():wS(t.request)??s(i)},"respond")}}o(sP,"createConnectRequiredResponder");function iP(e){return rn()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(iP,"readRouteCapabilityFilter");async function aP(e){let{scope:t}=zf(e.upstreamResponse),r=await xS({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 qS({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(US({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(aP,"applyRefreshedCredentialHeaders");function cP(e){TS(e.context,{refresh:o(async(t,r)=>{let n=await aP({request:e.request,context:e.context,headers:DS(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:MS(e.requestBody)}:n.kind==="refresh_unavailable"?{kind:"response",response:await OS(e.request,e.context)}:n},"refresh")})}o(cP,"registerUpstreamAuthRetry");function dP(e){return e.body!==null&&e.status>=200&&e.status<=299&&We(e.headers.get("content-type"))==="text/event-stream"&&!mt(e.headers)}o(dP,"isRewritableEventStream");function uP(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(uP,"answersRequestId");function lP(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(!(!Bt(r)||"method"in r||!("result"in r||"error"in r)||!uP(r.id,t)))return r}o(lP,"readResponseInEvent");function pP(e){let t=!1;return wi(e.response,r=>{if(t)return;let n=lP(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(pP,"addMissingIconsToEventStream");function mP(e){let t=XA(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?eP:tP,n=jS({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(!QA(i))return s!==void 0&&dP(i)?pP({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=Yf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(mP,"installInitializeIconHook");function hP(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new xt(e,{headers:r,body:t})}o(hP,"withRequestBody");async function Cd(e,t,r){let n=Date.now(),s=WA(t),i=e,a=await nP(i),c=zS(a),d=o(async(x,N)=>(await Zg({request:i,context:t,requestJson:c,requestBody:a,response:x,startTime:n,...N===void 0?{}:{outcome:N}}),x),"answer"),u=ur(i.headers,c),p=mS({connection:r,operationId:s}),h=lr(i.user,i.url,i.headers);Ah(t,h);let f=mn(p,h.subjectId),S=await _S(i,c),b={subjectId:h.subjectId,operationId:s,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId},R;if(S!==void 0){let x=await CS({request:S,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=hP(i,x.body),a=x.body,c=x.request.message,S=x.request,R=x.action)}let y=sP({request:i,requestBody:a,httpMethod:i.method,headers:i.headers,modern:S===void 0?void 0:{request:S,binding:b,previousAction:R},context:t,connection:r}),_=await ZA(i,f,r,t,u);if(_.kind==="connect_required")return d(await y.respond(_.payload));if(_.kind==="no_tokens")return d(MS(a),"no_upstream_tokens");if(_.kind==="refresh_unavailable")return d(await OS(i,t),"upstream_token_refresh_unavailable");let C=rP(i,_.headers);return AS(t),cP({request:C,context:t,requestBody:a,connectRequired:y,routeAuth:f,mcpProtocolVersion:u}),mP({context:t,requestJson:c,connection:r,modern:S!==void 0}),C}o(Cd,"mcpTokenExchangePolicy");var Id=class extends Os{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=nh(t,r);super(n,r),this.#e=n}async handler(t,r){return Cd(t,r,this.#e)}};var LS=Symbol("Html");function fP(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(fP,"escapeHtml");function gP(e){return e===null||typeof e!="object"?!1:e[LS]===!0}o(gP,"isHtml");function Vi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Vi).join(""):gP(e)?e.value:fP(String(e))}o(Vi,"renderValue");function Ye(e){return{[LS]:!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 $S(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($S,"renderBrowserErrorPage");var HS=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>'),BS=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>
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(yn,"renderShell");function Gi(e){return X`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?HS:BS}</div>`}o(Gi,"renderStatusIcon");var yP="text/html; charset=utf-8";function Ft(e){try{return new URL(e).host}catch{return""}}o(Ft,"safeHostFromUrl");function Qe(e){let t=e.kind??"authorization_failed",r=RP(t),n=SP(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:$S({steps:hn(r.steps.map(i=>X`<li>${i}</li>`)),action:bP(e.action),reference:vP(n),diagnostics:CP({diagnostic:n,detail:e.detail}),upstreamResponse:IP(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":yP,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Qe,"browserErrorPageResponse");function SP(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??wP(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??_P(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(SP,"buildBrowserErrorDiagnostic");function RP(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(RP,"readBrowserErrorPagePresentation");function wP(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(wP,"readBrowserErrorStage");function _P(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(_P,"readBrowserErrorSuggestedFix");function bP(e){return e===void 0?Xe:X`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(bP,"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 vP(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(vP,"renderReference");function CP(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(CP,"renderDiagnostics");function IP(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(IP,"renderUpstreamHtml");var FS="application/json",TP="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 EP(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(EP,"normalizeContentType");function kP(e,t){return e===t?!0:t===FS&&e.endsWith("+json")}o(kP,"contentTypeMatches");function AP(e,t){if(!t||t.length===0)return;let r=EP(e.headers.get("content-type"));if(!t.some(n=>kP(r,n)))throw Wi(`Request body must be ${t.join(" or ")}.`)}o(AP,"assertExpectedContentType");function PP(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(PP,"assertContentLengthWithinLimit");async function JS(e,t){let r=t.label??"Request body";AP(e,t.expectedContentTypes),PP(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(JS,"readBoundedTextBody");async function VS(e,t){let r=await JS(e,{...t,expectedContentTypes:[FS]});try{return JSON.parse(r)}catch(n){throw Wi("Request body must be valid JSON.",n)}}o(VS,"readBoundedJsonBody");async function GS(e,t){let r=await JS(e,{...t,expectedContentTypes:[TP]});return new URLSearchParams(r)}o(GS,"readBoundedFormUrlEncodedBody");import{errors as WS,jwtVerify as ZS,SignJWT as Ed}from"jose";import{base64url as xP}from"jose";var OP="mcp-browser-login-pkce:",MP=new TextEncoder;async function UP(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(UP,"importHmacKey");async function Td(e){let t=await UP(e.signingKey),r=MP.encode(`${OP}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return Kr.parse(xP.encode(new Uint8Array(n)))}o(Td,"deriveBrowserLoginPkceVerifier");async function KS(e){let t=await Td(e),r=await ei(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Gr}}o(KS,"deriveBrowserLoginPkceParams");var qP={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=qP[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var zP=300,YS=m.string().min(1).optional(),NP=m.object({purpose:m.literal("gateway_browser_login"),transactionId:xa,stateId:Ws,binding:Zo,authorizationServerIssuer:YS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),jP=m.object({purpose:m.literal("gateway_browser_login_return"),stateId:Ws,binding:Zo,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),DP=m.discriminatedUnion("purpose",[NP,jP]),LP=m.object({purpose:m.literal("gateway_authorization_setup"),transactionId:xa,stateId:Ws,authorizationServerIssuer:YS,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 XS(){return Ze({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"authorization-csrf"),"derive")})}o(XS,"getCsrfKey");function QS(e){return{now:e.now??new Date,ttlSeconds:kd()}}o(QS,"readPendingTransactionDependencies");function kd(){return ke().browserLogin.stateTtlSeconds}o(kd,"readBrowserLoginStateTtlSeconds");function $P(e){let t=ge();return He(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o($P,"isLoopbackDevLoginUrl");async function eR(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($P(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 KS({stateId:e.stateId,signingKey:await Sn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(eR,"buildBrowserLoginUrl");function HP(e,t){return e.subjectId===t.subjectId}o(HP,"principalsMatch");function tR(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(tR,"toPendingPrincipal");function rR(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:tR(e.principal)}}o(rR,"createTransactionRecord");async function nR(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(nR,"startPendingTransaction");async function BP(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(BP,"signBrowserLoginState");async function oR(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 XS())}o(oR,"signCsrfToken");async function Ad(e){try{let{payload:t}=await ZS(e,await Sn(),{algorithms:[be],issuer:fe,audience:_e}),r=DP.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 WS.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 FP(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(FP,"verifyBrowserLoginStateToken");async function Zi(e){try{let{payload:t}=await ZS(e,await XS(),{algorithms:[be],issuer:fe,audience:_e}),r=LP.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof WS.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 JP(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(JP,"toPendingAuthorizationGetResult");function VP(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(VP,"toPendingAuthorizationAdvanceResult");function xd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Pd(e==="consumed_already"?"consumed_already":e)}o(xd,"setupDecisionErrorCode");async function sR(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 iR({kind:"available",record:n.transaction})}o(sR,"markSetupApproved");function iR(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(iR,"requireAwaitingSetup");function GP(e){if(!HP(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(GP,"requireCurrentPrincipalMatches");async function aR(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 BP({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=rR({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 nR({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 eR({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(aR,"startAwaitingLogin");async function cR(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 eR({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(cR,"startReturnToBrowserLogin");async function dR(e){let{now:t,ttlSeconds:r}=QS(e),n=Oa(),s=await oR({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=rR({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 nR({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(dR,"startAwaitingSetup");async function uR(e){let{now:t,ttlSeconds:r}=QS(e),n=await FP(e.browserLoginStateToken),s=await oR({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=VP(await G().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await de(e.browserLoginStateToken),nextStateHash:await de(s),nextPhase:"awaiting_setup",principal:tR(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(uR,"completeLogin");async function lR(e){let t=await Od(e);return GP({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(lR,"getSetup");async function Od(e){let t=e.now??new Date,r=await Zi(e.csrfToken);return iR(JP(await G().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await de(e.csrfToken),now:W(t)})))}o(Od,"getSetupTransaction");async function KP(e){let t=await Zi(e.csrfToken),r=St(),n=W(gt(e.now,zP)),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:uh(),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(KP,"createAuthorizationCodeRedirectWithDecision");async function WP(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 ZP({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(WP,"createCancelRedirectWithDecision");function Yi(e,t){t!==void 0&&te()&&e.searchParams.set("iss",t)}o(Yi,"setAuthorizationResponseIssuer");function ZP(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(ZP,"buildClientCancelRedirect");async function pR(e){let t=e.now??new Date;return KP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(pR,"approve");async function mR(e){let t=e.now??new Date;return WP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(mR,"cancel");import{createRemoteJWKSet as YP,errors as Rn,jwtVerify as hR,SignJWT as XP}from"jose";var QP="zuplo_mcp_session",ex=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()}),tx=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()}),rx=m.object({error:m.string().min(1).optional(),error_description:m.string().min(1).optional(),error_uri:m.string().min(1).optional()}),nx=m.object({sub:Eo,nonce:m.string().min(1)}).catchall(m.unknown()),Md;async function fR(){return Ze({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-session"),"derive")})}o(fR,"getBrowserSessionKey");function qd(e,t){let r=xi(e,t);return{name:Qc(QP,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 ox(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(ox,"serializeSessionCookie");function gR(){return new URL(Ut("url")).origin}o(gR,"readBrowserLoginOrigin");function sx(e){let t=rx.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(sx,"readIdpErrorFields");function ix(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(ix,"readJwtFailureKind");function ax(e){return e instanceof Error&&"cause"in e?e.cause:e}o(ax,"readErrorCause");function cx(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(cx,"readRuntimeGatewayCode");function dx(){if(!Md){let e=ke();Md=YP(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Md}o(dx,"readFederatedJwks");function yR(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return lr(e.user,e.url)}o(yR,"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 hR(r,await fR(),{algorithms:[be],issuer:fe,audience:_e}),s=ex.parse(n);if(s.browserLoginOrigin!==gR())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:gR()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new XP(r).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await fR());return ox({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(rs,"createBrowserSessionCookie");async function ux(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 S=sx(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ie(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=tx.parse(d),p;try{({payload:p}=await hR(u.id_token,dx(),{issuer:t.oidc.issuer,audience:n}))}catch(S){let b={};throw Ae(b,"error",S),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:ix(S),idpHost:ie(r),expectedIssuer:t.oidc.issuer,...b},"Federated id_token failed jose verification"),S}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=nx.parse(p);return{principal:lr({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)??cx(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",ax(c))}}o(ux,"exchangeFederatedAuthorizationCode");async function zd(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return ux({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 lx=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function px(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(px,"readScheme");function mx(e){return e.protocol==="https:"}o(mx,"isSpecCompliantRedirectUri");function hx(e){let t=px(e);return t.length>0&&t!=="http"&&t!=="https"&&!lx.has(t)}o(hx,"isNativeAppCustomSchemeRedirectUri");var RR=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>mx(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=>hx(e),"accepts")}];function wR(e){let t=RR.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(wR,"evaluateBuiltInRedirectUriCompatibility");function SR(e){try{return new URL(e)}catch{return}}o(SR,"parseUrl");function _R(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=SR(e.registeredRedirectUri),r=SR(e.requestedRedirectUri);return t===void 0||r===void 0?!1:RR.some(n=>n.matches?.(t,r))}o(_R,"redirectUriMatchesBuiltInCompatibility");var fx=1e4,gx=5*1024,yx=0,Sx=2160*60*60,bR=["authorization_code","refresh_token",Gs,zt],Rx=["authorization_code","refresh_token"],vR=[ah],wx=["code"],_x=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(bR)).min(1).max(bR.length).optional(),authorization_grant_profiles_supported:m.array(m.enum(vR)).min(1).max(vR.length).optional(),response_types:m.array(m.enum(wx)).min(1).max(1).optional(),scope:m.literal(he).optional(),token_endpoint_auth_method:dh.optional(),jwks_uri:m.string().min(1).optional()});function bx(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&He(t))&&t.pathname!=="/"}catch{return!1}}o(bx,"isCimdClientIdCandidate");function CR(e,t){throw new E("invalid_client",Rh({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(CR,"invalidCimdClientError");function _n(e,t="invalid_request"){if(vx(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(wR({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 vx(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(vx,"hasForbiddenRawRedirectUriCharacter");async function Cx(e){let{response:t,json:r}=await dy(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:yx,maxResponseBytes:gx,timeoutMs:fx});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(Cx,"fetchCimdMetadata");async function Ix(e){let t=Xs(e),r=await Cx({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(Ix,"resolveCimdClient");async function Xi(e,t){let r=yt.parse(e);if(bx(r)){ke().gateway.downstreamCimdEnabled||CR(r);try{return await Ix(r)}catch(s){CR(r,s)}}let n=await G().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=_h(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 IR(e,t){if(!e.metadata.redirect_uris.some(r=>_R({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(IR,"assertRedirectRegistered");function Tx(e){return e===void 0?[...Rx]:Array.from(new Set(e))}o(Tx,"normalizeGrantTypes");function Ex(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(Ex,"assertValidDcrJwksUri");function kx(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?yt.parse(wh({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):yt.parse(`dcr:${crypto.randomUUID()}`)}o(kx,"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 TR(e){let t;try{t=_x.parse(e)}catch(S){if(S instanceof m.ZodError){let b=S.issues.some(R=>R.path[0]==="redirect_uris");throw new E(b?"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)_n(S,"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&&Ex(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=kx({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,Sx),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:Tx(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 S=St();h.hashedClientSecret=await de(S),h.clientSecretExpiresAt=W(c),p.client_secret=S,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(TR,"registerDownstreamClient");function Ax(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(Ax,"hasStoredIdJagSubjectTokenBinding");async function ER(e){let t=tn(e.principal.subjectId);return(await G().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(ER,"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 ER({connection:t.connection,principal:e.principal});return!Ax(r)}o(Nd,"requiresIdJagSubjectTokenBinding");async function kR(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 ER({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(kR,"bindIdJagSubjectTokenForAuthorizationTransaction");function AR(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(AR,"renderShellIcon");function PR(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(PR,"renderActions");var xR=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 OR(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(OR,"renderBannerWarning");var O1=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>'),M1=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 U1=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 Px="data:,",MR=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);"`,UR=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 xx(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(xx,"safeGatewayConnectHref");function Ox(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Ox,"deriveMode");function Mx(e){return PR({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:MR,authorizeAttrs:Xe})}o(Mx,"renderActions");function jd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=xx(s.connectUrl,t,n);if(i)return i}}o(jd,"firstUserConnectHref");function Ux(e){let t=e.connectHref===void 0?Xe:X`<a class="button button--primary" href="${e.connectHref}" ${UR}>Connect</a>`;return X`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${MR}><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(Ux,"renderSetupActions");function qx(e){return e?X`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${UR}>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(qx,"renderReconnectAction");function zx(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(zx,"isRenderableIconHref");function qR(e){return e?.find(t=>zx(t.src))?.src}o(qR,"readIconHref");function Nx(e){return qR(e.serverIcons)??(e.transportHost===void 0?void 0:Jc(e.transportHost).src)}o(Nx,"readUpstreamIconHref");function jx(e){let t=qR(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=Nx(r);if(n!==void 0)return n}}o(jx,"readHeaderIconHref");function Dx(e){let t=e.setupMessage===void 0?Xe:OR({icon:xR,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(Dx,"renderBody");function Dd(e){let t=Ox(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=jx({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?X`<footer class="card__footer">${Ux({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:X`<footer class="card__footer">${qx(s)}${Mx({state:e.state,gateway:e.gateway})}</footer>`;return fn(yn({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??Px,styles:gn,headerIcon:c===void 0?Xe:AR({iconHref:c,fallbackIconHref:zg}),heading:"Authorize access",subhead:Xe,body:Dx({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(Dd,"renderConsentPage");var Lx=1e4,$x=2e3,Hx=64*1024,zR=1024*1024,FR={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},Ld="mcp-session-id",JR=1,Bx=/^\d{4}-\d{2}-\d{2}$/,Fx;function $d(){return{tools:[],prompts:[],resources:[]}}o($d,"emptyCapabilities");function NR(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ma})}o(NR,"buildReadinessHeaders");async function jR(e){if(e.type==="bearer_token"){let n=NR();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=NR();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(jR,"buildAsyncCredentialHeaders");function Jx(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(ar.parse({jsonrpc:ir,id:JR,method:"initialize",params:{protocolVersion:Ma,capabilities:{},clientInfo:FR}}))})}o(Jx,"buildInitializePreflight");function Vx(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",dr),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:ir,id:1,method:"server/discover",params:{_meta:{[Cm]:dr,[Im]:{},[Tm]:FR}}})})}o(Vx,"buildDiscoverPreflight");async function Gx(e){if(e.status!==400&&e.status!==404)return!1;let t=await VR(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(Gx,"isModernRejectionOfInitialize");async function VR(e,t=Hx){let r=new TextDecoder,n="";return GR(e,t,s=>{if(s===void 0)return n+r.decode();n+=r.decode(s,{stream:!0})})}o(VR,"readBoundedBody");async function GR(e,t,r){let n=e.body?.getReader();if(n===void 0)return;let s,i=new Promise(c=>{s=setTimeout(()=>c("timeout"),$x)}),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(GR,"readBoundedChunks");async function Hd(e){xo(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Lx);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 KR(e){if(We(e.headers.get("content-type"))!=="text/event-stream"){let n=await VR(e,zR);return n===void 0?void 0:DR(LR(n))?.result}let t=new hr;return(await GR(e,zR,n=>{let s=n===void 0?t.end():t.push(n);for(let i of s){let a=i.data===void 0?void 0:DR(LR(i.data));if(a!==void 0)return a}}))?.result}o(KR,"readProbeResult");async function Kx(e){let t=(await KR(e))?.protocolVersion;return typeof t=="string"&&Bx.test(t)?t:void 0}o(Kx,"readNegotiatedProtocolVersion");function DR(e){if(!(!$R(e)||e.id!==JR))return{result:$R(e.result)?e.result:void 0}}o(DR,"probeAnswer");function LR(e){try{return JSON.parse(e)}catch{return}}o(LR,"parseJson");function $R(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o($R,"isRecord");async function Wx(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(Wx,"terminatePreflightSession");async function WR(e){let{response:t}=e;if(e.discover===!0){let s=await KR(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 Kx(t):void 0;return r||ns(t),t.status>=200&&t.status<300?(te()&&e.upstreamServerId!==void 0&&Ff(e.upstreamServerId),await Wx({...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(WR,"classifyResponse");function HR(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(HR,"connectRequiredResult");async function ZR(e){let t=await Hd(Jx(e));if(!te()||!await Gx(t))return{response:t,discover:!1};try{let r=await Hd(Vx(e));if(r.status>=200&&r.status<300)return ns(t),{response:r,discover:!0};ns(r)}catch{}return{response:t,discover:!1}}o(ZR,"probeUpstream");async function Zx(e){try{let t=await ZR(e);return WR({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(Zx,"classifyPreflight");async function BR(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(BR,"resolveReadinessCredential");async function Yx(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 BR({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="upstream_unavailable")return a;if(a.kind==="connect_required")return HR(a.payload);let c=await jR(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 ZR({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 WR({response:u,discover:d.discover,upstreamUrl:t.mcpUrl,headers:c,upstreamServerId:t.upstreamServerId});ns(u);let p=await BR({request:i,routeAuth:s,forceRefresh:!0});if(p.kind==="upstream_unavailable")return p;if(p.kind==="connect_required")return HR(p.payload);let h=await jR(p.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Zx({upstreamUrl:t.mcpUrl,headers:h,upstreamServerId:t.upstreamServerId})}o(Yx,"checkUpstreamRouteReadinessImpl");function YR(e){return(Fx??Yx)(e)}o(YR,"checkUpstreamRouteReadiness");function Xx(e){try{return new URL(e).host}catch{return}}o(Xx,"safeUrlHost");function XR(e){return e!==void 0&&e.length>0}o(XR,"hasItems");function Qx(e){let t=e.serverInfo?.icons;if(XR(t))return t;let r=Ei(e.mcpUrl);return r===void 0?void 0:[r]}o(Qx,"readServerIcons");async function eO(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?Th(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,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:Xx(i),scopesRequested:XR(S)?S:void 0,serverIcons:Qx(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(eO,"buildSetupRequirement");function QR(e){let t=Ie().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(QR,"requireRoute");async function Bd(e){let t=QR(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 YR({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 eO({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=QR(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 tO=["mcp_user"],rO="dev-browser-user",nO=["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(" "),oO=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:Wm,state:m.string().min(1).optional(),scope:m.literal(he).default(he)}),sO=m.enum(["continue","approve","cancel"]).default("continue"),iO=m.object({state:m.string().min(1),decision:sO}),Jt=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 ew(e){return typeof e=="string"&&e.length>0?e:void 0}o(ew,"readQueryString");function aO(e,t){let r=ew(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new E("invalid_target",nO)}let n=fh(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(aO,"requireAuthorizeResource");async function cO(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=yR(e);return{principal:s,setCookie:await rs({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o(cO,"resolveBrowserPrincipal");async function dO(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(dO,"requireSetupPrincipal");function tw(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(tw,"buildSetupReturnTo");async function rw(e){let t=await Bd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:tw(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(rw,"renderSetup");function uO(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(uO,"toAuthorizationTransactionClient");async function Vd(e,t={}){let r=oO.parse({...e.query,resource:aO(e,t.operationId),state:ew(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):lh({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);IR(c,r.redirect_uri);try{let d=Sr(e.url,r.resource,e.headers),u=uO(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 cO(e,t.context),S=h===void 0?!1:await Nd({operationId:d.operationId,principal:h});if(!h||S){let R=await aR({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:R.browserLoginUrl,setCookies:[...f===void 0?[]:[f],R.browserBindingCookie]}}let b=await dR({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}}),rw({transaction:b.transaction,csrfToken:b.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw lO({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Vd,"authorizeDownstreamClient");function lO(e){if(e.cause instanceof Jt)return e.cause;let t=pO(e.cause);return t?new Jt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(lO,"toDownstreamAuthorizeRedirectError");function pO(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(pO,"mapToOAuthRedirectError");async function nw(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&&Lt())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=mO(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 uR({browserLoginStateToken:n,principal:c.principal});if(await kR({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 rw({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(nw,"completeBrowserLoginCallback");function mO(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(mO,"readConnectReturnTo");async function ow(e){let t=await cR(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(ow,"startConnectBrowserLogin");async function sw(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(rO),roles:tO};return{kind:"redirect",location:i,setCookies:[await rs({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(sw,"completeLocalDevBrowserLogin");function hO(e){let t=e.method==="POST"?e.body:e.query;return iO.parse(t)}o(hO,"readSetupContinueRequest");async function iw(e){let{state:t,decision:r}=hO({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await Od({csrfToken:t,now:n}),i=await dO(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await mR({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await lR({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Bd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:tw(t)});if(r==="approve"&&Jd(c)&&await sR({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 pR({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(iw,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as EO,decodeJwt as kO,errors as ss,jwtVerify as AO}from"jose";import{createRemoteJWKSet as fO,decodeJwt as gO,decodeProtectedHeader as yO,errors as os,jwtVerify as SO}from"jose";var lw=30,ue=m.string().min(1),RO=m.union([ue,m.array(ue).min(1)]),wO=m.union([ue,m.array(ue).min(1)]),_O=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(),bO=m.object({iss:m.url(),sub:ue,aud:RO,client_id:ue,resource:wO.optional(),scope:ue.optional(),authorization_details:m.array(_O).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 vO(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(vO,"readJwtFailureKind");function CO(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(CO,"readSingleAudience");function aw(e){try{let t=bO.parse(e);return CO(t),t}catch(t){if(t instanceof E)throw t;Ve("ID-JAG claims are invalid.")}}o(aw,"parseIdJagClaims");function IO(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(IO,"readTrustedIssuer");function TO(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(TO,"readGrantedAuthorizationDetails");function cw(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(cw,"assertClientBinding");function dw(e){e.cnf!==void 0&&Ve("ID-JAG cnf-bound assertions require DPoP support.")}o(dw,"assertProofOfPossessionNotDeferred");function uw(e){let t=Math.floor(e.now.getTime()/1e3)+lw;e.claims.iat>t&&Ve("ID-JAG iat must not be in the future.")}o(uw,"assertIssuedAtNotInFuture");async function pw(e){let t;try{t=yO(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=aw(gO(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=IO(e.config,r.iss);s.includes(r.iss)&&Ve("ID-JAG issuer must be different from the gateway."),cw({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),dw(r),uw({claims:r,now:e.now});let a;try{let c=fO(new URL(i.jwksUrl)),{payload:d}=await SO(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:lw,typ:Aa});a=aw(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:vO(c)},"OAuth ID-JAG assertion verification failed"),Ve("ID-JAG assertion verification failed.")}return cw({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),dw(a),uw({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:gh({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:TO({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(pw,"verifyIdJagAssertion");var PO=new Set(["authorization_code","refresh_token",zt]),xO=1e4,OO=32*1024,MO=2,UO=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()}),qO=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 zO(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!PO.has(t)))throw new E("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(zO,"assertSupportedGrantType");var NO=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()}),jO=m.object({keys:m.array(m.record(m.string(),m.unknown())).min(1)}).passthrough();function hw(){return ke().gateway.accessTokenTtlSeconds}o(hw,"readAccessTokenTtlSeconds");function DO(){return ke().gateway.refreshTokenTtlSeconds}o(DO,"readRefreshTokenTtlSeconds");function mw(e,t){let r=hw(),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(mw,"calculateAccessTokenExpiresAt");function LO(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(LO,"readIdJagResource");function $O(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($O,"readIdJagGrantedAuthorizationDetails");function HO(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(HO,"readIdJagGrantedScope");function BO(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(BO,"assertNoDpopProofForIdJag");function fw(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(fw,"readBasicClientSecret");function gw(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=kO(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(gw,"resolveAuthenticatedClientId");function FO(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(FO,"resolveClientSecretInput");function JO(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(JO,"hasClientAssertion");function VO(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(VO,"buildEndpointAudience");function GO(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(GO,"readJwtFailureKind");async function KO(e){let{response:t,json:r}=await uy(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:MO,maxResponseBytes:OO,timeoutMs:xO});if(!t.ok)throw new E("invalid_client","Client JWKS could not be fetched.");return jO.parse(r)}o(KO,"fetchClientJwks");async function WO(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=VO({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await KO({jwksUri:n,context:e.context}),{payload:a}=await AO(e.clientAssertion,EO(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+UO;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:GO(i)},"OAuth private_key_jwt client authentication failed"),new E("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(WO,"verifyPrivateKeyJwtClientAssertion");async function ZO(e){let t=yt.parse(e.clientId);if(bh(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(ZO,"buildRuntimeHttpClientAuth");async function yw(e){if(JO({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 WO(e)}let t=FO({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return ZO({clientId:e.clientId,...t})}o(yw,"resolveRuntimeHttpClientAuth");async function Sw(e){zO(e.body);let t=qO.parse(e.body),r=fw(e.authorizationHeader),n=gw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await yw({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 YO({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(Sw,"exchangeDownstreamToken");async function YO(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,DO())),p=mw(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),BO(e.requestHeaders);let c=await pw({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=LO({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=Sr(e.requestUrl??d,d,e.requestHeaders),p=$O({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=HO({claimScope:c.claims.scope,grantedAuthorizationDetails:p}),f=St(),S=W(new Date(c.claims.exp*1e3)),b=mw(e.now,S),R=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:S}});if(R.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(R.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:R.grant.scope,resource:R.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,hw())),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(YO,"exchangeDownstreamTokenWithRuntimeHttp");async function Rw(e){let t=NO.parse(e.body),r=fw(e.authorizationHeader),n=gw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await G().revokeOAuthToken({clientAuth:await yw({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(Rw,"revokeDownstreamToken");var XO=64*1024,QO=16*1024,eM="text/html; charset=utf-8";function tM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(tM,"formDataToObject");async function rM(e){return VS(e,{maxBytes:XO,label:"Request body"})}o(rM,"readJsonBody");async function Wd(e){return tM(await GS(e,{maxBytes:QO,label:"Request body"}))}o(Wd,"readFormBody");async function ww(e,t,r){let n=Be(r),s=r instanceof m.ZodError?Vt(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(ww,"handleProblem");function _w(e){return e?.requestId}o(_w,"readBrowserRequestId");function bw(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(bw,"readUpstreamHtmlError");function vn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(vn,"readRuntimeErrorExtensionString");function nM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(nM,"readRuntimeErrorExtensionNumber");function oM(e){try{return new URL(e.url).pathname}catch{return}}o(oM,"readBrowserRequestPath");function Rr(e){let t={code:e.code,requestId:e.requestId,routePath:oM(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=nM(e.error,ut),t.contentType=vn(e.error,Wr),t.upstreamUrl=vn(e.error,lt),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 sM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(sM,"readOAuthProtocolHeaders");function iM(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:sM(e,t)})}o(iM,"oauthProtocolErrorResponse");function Kd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(Kd,"readZodOAuthErrorCode");function aM(e){let t={error:Kd(e)},r=Vt(e);return r!==void 0&&(t.errorDescription=r),is(t)}o(aM,"oauthZodErrorResponse");function cM(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:uM(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(cM,"oauthGatewayProblemResponse");function dM(){let t={error:"server_error",status:500,errorDescription:ot("internal_server_error").publicDetail};return is(t)}o(dM,"oauthFallbackErrorResponse");function uM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(uM,"readOAuthStatus");function Zd(e,t={}){return e instanceof Jt?Iw(e):e instanceof E?iM(e,t):e instanceof m.ZodError?aM(e):cM(e)??dM()}o(Zd,"oauthProblemResponse");function Yd(e,t,r){let n=Ft(e.url),s=_w(t);if(r instanceof Jt)return Iw(r);if(r instanceof E){let c=ot("internal_server_error");return Qe({host:n,kind:lM(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:Vt(r)??"The authorization request was invalid.",developerDetail:Vt(r)??"The authorization request was invalid.",code:Kd(r),diagnostic:Rr({request:e,requestId:s,code:Kd(r),underlyingError:Vt(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:Cw(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:bw(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 vw(e,t,r){let n=Ft(e.url),s=_w(t),i=Be(r);if(i!==void 0){let c=ot(i);return Qe({host:n,kind:Cw(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:bw(r),status:c.status})}if(r instanceof m.ZodError)return Qe({host:n,kind:"invalid_request",detail:Vt(r)??"The authorization request was invalid.",developerDetail:Vt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:Rr({request:e,requestId:s,code:"invalid_request",underlyingError:Vt(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(vw,"browserGatewayProblemResponse");function lM(e){return e==="server_error"?"internal_error":"invalid_request"}o(lM,"readOAuthBrowserErrorKind");function Cw(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(Cw,"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 Jt)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 Iw(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(Iw,"downstreamAuthorizeRedirectErrorResponse");function Vt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Vt,"formatZodErrorDetail");function pM(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(pM,"logBrowserLoginCallbackFailure");function Tw(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(Tw,"redirectResultResponse");function Qi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":eM,"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 Tw(e)}o(Qi,"authorizeResultResponse");async function Ew(e,t){try{return Response.json(ph(e.url,e.headers))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),ww(e,t,r)}}o(Ew,"authorizationServerMetadataHandler");async function kw(e,t){try{let r=Ua(e.params.routePath);return Response.json(mh({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),ww(e,t,r)}}o(kw,"scopedAuthorizationServerMetadataHandler");async function Aw(e,t){try{let r=await TR(await rM(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(Aw,"registerHandler");async function Pw(e,t){try{return Qi(await Vd(e,{context:t}))}catch(r){return Tt(t,"oauth_authorize_failed",r),Yd(e,t,r)}}o(Pw,"authorizeHandler");async function xw(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(xw,"scopedAuthorizeHandler");async function Ow(e,t){try{let r=await nw(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 pM(t,r),vw(e,t,r)}}o(Ow,"callbackHandler");async function Mw(e,t){try{return Tw(await sw(e))}catch(r){return Tt(t,"oauth_dev_login_failed",r),Yd(e,t,r)}}o(Mw,"devLoginHandler");async function Uw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await iw({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),vw(e,t,r)}}o(Uw,"setupHandler");async function qw(e,t){try{return Response.json(await Sw({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(qw,"tokenHandler");async function zw(e,t){try{return await Rw({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(zw,"revokeHandler");var Nw="0.0.0",mM=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 hM(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(hM,"shortHash");function jw(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${hM(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(jw,"clampNameSegment");function fM(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(fM,"sanitizeRegistryNameSegment");var gM=/^\d{1,3}(\.\d{1,3}){3}$/u;function yM(e){let t=new URL(e).hostname.toLowerCase();if(gM.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(yM,"buildRegistryNamespaceFromOrigin");function SM(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(SM,"sanitizeWebsiteUrl");function RM(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&&!mM.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(RM,"sanitizeIcons");function wM(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(wM,"localNameFromRoutePath");function Dw(e){return e.includes("{")||e.includes(":")}o(Dw,"isParameterizedRoutePath");var _M=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Lw(e){let t=as(e)??Nw;return _M.test(t)?Nw:cs(t,255)}o(Lw,"sanitizeRegistryVersion");function $w(e){let t=jw(yM(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=jw(fM(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(Dw(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=SM(u?.websiteUrl),S=RM(u?.icons);a(c.operationId,{description:p,...h===void 0?{}:{title:cs(h,100)},version:Lw(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(Dw(c.routePath))continue;let d=c.operationId??wM(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:Lw(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o($w,"buildMcpRegistryDirectory");var bM=30,Hw=100;function at(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(at,"registryErrorResponse");function Qd(e){return $w({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 Bw(e,t){return e.find(r=>r.name===t)}o(Bw,"findEntryByName");function vM(e){let t=e.get("limit");return t===null?{ok:!0,value:bM}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Hw)}}o(vM,"parseLimit");function CM(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(CM,"parseCursor");var IM=/^(\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 TM(e){let t=IM.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(TM,"isValidRfc3339Timestamp");async function Fw(e,t){let r=new URL(e.url).searchParams,n=vM(r);if(!n.ok)return at(400,`Invalid 'limit' parameter: expected a positive integer (max ${Hw}).`);let s=CM(r);if(!s.ok)return at(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&&!TM(i))return at(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(Fw,"listMcpRegistryServersHandler");async function Jw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return at(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Bw(Qd(e),r.value);return n===void 0?at(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(Jw,"listMcpRegistryServerVersionsHandler");async function Vw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return at(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 at(400,"Invalid version: malformed encoding.");let s=Bw(Qd(e),r.value);return s===void 0?at(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?at(404,"Server or version not found"):Response.json(s.response)}o(Vw,"getMcpRegistryServerVersionHandler");function ea(e,t){return(r,n)=>at(e,t)}o(ea,"createWriteNotSupportedHandler");async function Gw(e,t){return at(404,"Not found")}o(Gw,"mcpRegistryNotFoundHandler");var Kw=ea(501,"Publishing is not supported by this registry"),Ww=ea(501,"Updates are not supported by this registry"),Zw=ea(501,"Deletion is not supported by this registry"),eu=ea(403,"You do not have publish or edit permissions for this server");function Yw(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(Yw,"renderBrowserResult");var EM="text/html; charset=utf-8";function kM(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:Yw({steps:hn(e.steps.map(t=>X`<li>${t}</li>`))}),footer:""})}o(kM,"browserResultHtml");function AM(e,t=200){return new Response(fn(e),{status:t,headers:{"content-type":EM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(AM,"browserResultResponse");function Xw(e){return AM(kM(e))}o(Xw,"browserConnectionSuccessResponse");function ta(e,t,r={}){let n=Ym(t);return Qe({host:e,kind:PM(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(ta,"browserConnectionFailureResponse");function PM(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(PM,"readCallbackFailureBrowserErrorKind");var xM={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Qw=Symbol("upstream-request");function ds(e,t){Object.defineProperty(e,Qw,{configurable:!0,value:t})}o(ds,"setUpstreamRequestContext");function OM(e){let t=e[Qw];if(!t)throw new Ee("Upstream request context has not been set");return t}o(OM,"readUpstreamRequestContext");function MM(e,t){return t.some(r=>r===e)}o(MM,"requestContextMatchesKind");function UM(e){return typeof e=="string"?[e]:e}o(UM,"toExpectedKinds");function us(e,t){let r=OM(e),n=UM(t);if(!MM(r.kind,n)){let s=xM[n[0]];throw new Ee(`${s} request context has not been set`)}return r}o(us,"requireUpstreamRequestContext");function Gt(e){if(typeof e=="string"&&e.length!==0)return e}o(Gt,"readOptionalQueryString");function qM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Ee(`Validated path parameter ${t} is missing`);return zM(r,t)}o(qM,"requirePathString");function zM(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(zM,"decodePathString");function NM(e){let t=Gt(e);return t?Js.parse(t):void 0}o(NM,"readOptionalOperationId");function jM(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(jM,"readRegisteredAuthProfileId");function DM(e){let t=NM(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[M]:"invalid_request"}});return t}o(DM,"readRequiredOperationId");async function tu(e){return e.redirect?Qe({host:Ft(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 LM(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(LM,"withSetCookies");async function $M(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(Gm(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 LM(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 ow({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($M,"requireTicketOwnerBrowser");async function HM(e,t,r){let n=Ji(r,DM(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=Gt(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=lr(e.user,e.url),u={kind:"connect",...mn(n,d.subjectId),redirect:s},p=ko(Gt(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 Iy(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(Lt()){let d=await $M({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await Ty(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(HM,"resolveConnectContext");async function BM(e,t,r){let n=Qm.parse(qM(e,"connection"));switch(r){case"connect":{let s=await HM(e,t,n);if(s instanceof Response)return s;ds(e,s);return}case"callback":{let s=Gt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Gt(e.query.error_description);d!==void 0&&(c.errorDescription=d),ds(e,c);return}let i=Gt(e.query.code),a=Gt(e.query.state);if(i&&a){let c=Gt(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:jM(n)});return}}o(BM,"resolveUpstreamRequestInbound");async function FM(e,t,r){try{return await BM(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(FM,"applyUpstreamRequestContext");function ra(e,t){return o(async(n,s)=>{let i=await FM(n,s,e);return i||t(n,s)},"wrapped")}o(ra,"withUpstreamRequestContext");var JM=["callback_authorization_code","callback_provider_error","callback_invalid"];function ru(e){try{return new URL(e.url).pathname}catch{return}}o(ru,"readBrowserRequestPath");function VM(e){return"cause"in e?e.cause:void 0}o(VM,"readErrorCause");function GM(e){return e.stack?.split(`
44
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(GM,"readFirstStackFrame");function e_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=GM(r))}o(e_,"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 KM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(KM,"readRuntimeErrorExtensionNumber");function WM(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(WM,"requireAuthorizationCallbackRequest");function ZM(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(ZM,"emitCallbackReceivedAnalyticsEvent");function YM(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(YM,"emitTokenExchangeSucceededAnalyticsEvent");function XM(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Xw({host:Ft(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(XM,"buildSuccessfulCallbackResponse");function QM(e){let t={detail:e instanceof Error?e.message:void 0};return e_(t,"error",e),e instanceof Error&&e_(t,"cause",VM(e)),t}o(QM,"buildTokenExchangeFailureAttributes");function e0(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:QM(e.error)})}o(e0,"emitTokenExchangeFailedAnalyticsEvent");function t0(e){let t=e.error,r=nu(t),n=Zm(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:KM(t,ut),contentType:ls(t,Wr),upstreamUrl:ls(t,lt),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:r0(t)})}o(t0,"tokenExchangeFailureResponse");function t_(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(t_,"withSetCookie");function r0(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(r0,"readUpstreamHtmlError");async function ou(e,t){let r=us(e,JM),n=Ft(e.url),s=WM(e,t,r,n);if(s instanceof Response)return s;ZM(t,s);let i;try{let a=await pS({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return YM(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"),t_(XM(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"),e0({context:t,callbackRequest:s,error:a}),t_(t0({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(ou,"callbackHandler");function n0(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(n0,"clientMetadataProblemDetail");async function r_(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 lS({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(r_,"connectHandler");async function n_(e,t){let r=us(e,"client_metadata");try{let n=ce(e.url,e.headers),s=Ny(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:n0(n)})}}o(n_,"oauthClientMetadataHandler");function o0(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(o0,"resolveInternalRoutePath");var s0={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function i0(){return new Response(null,{status:204,headers:s0})}o(i0,"buildWellKnownPreflightResponse");function a0(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(a0,"withWellKnownCorsHeaders");function wr(e){return async(t,r)=>t.method==="OPTIONS"?i0():a0(await e(t,r))}o(wr,"wrapWellKnownHandler");var o_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:wr(Ew),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:wr(kw),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:wr(hh),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Aw},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Pw},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:xw},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Ow},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Mw},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Uw},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:qw},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:zw},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ra("client_metadata",n_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ra("connect",r_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ra("callback",ou)}],c0=o_.filter(e=>!e.routeName.startsWith("upstream_")),d0=o_.filter(e=>e.routeName.startsWith("upstream_"));function u0(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:wr(Fw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:wr(Jw),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(Vw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:Kw},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:Ww},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:Zw},{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(Gw),corsPolicy:"anything-goes"}]}o(u0,"buildMcpRegistryInternalRoutes");function l0(e){let t=oh({routes:e.routes,policies:e.policies,gateway:e.gateway});return sh(t),t}o(l0,"initializeMcpGatewayConnectionRegistry");function p0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(p0,"hasDownstreamOAuthRoutes");function m0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(m0,"hasIdJagDownstreamOAuth");function h0(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(h0,"readSingletonDownstreamOAuthConfig");function f0(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(ch(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(f0,"readScopedDownstreamOAuthConfig");function g0(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o(g0,"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&&Vm(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:o0(t,r),methods:t.methods,handler:n,processors:[Iu],corsPolicy:t.corsPolicy??"none"})}o(iu,"addInternalRoute");function s_(e,t){let r=l0(t);if(r.gateway.registry.enabled){dt("plugin.mcp-gateway.registry");for(let c of u0(r.gateway.registry))iu(e,c,r.gateway,su(c.routeName,c.handler))}let n=p0(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=h0(r)),i),"readSingletonOAuthConfig");if(n){dt("plugin.mcp-gateway.downstream-oauth"),m0(r)&&dt("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of c0){let d=g0(c)?(u,p)=>f0(r,u,p):a;iu(e,c,r.gateway,su(c.routeName,c.handler,d))}}if(s){dt("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())dt(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of d0)iu(e,c,r.gateway,su(c.routeName,c.handler,n?a:void 0))}}o(s_,"registerMcpGatewayInternalRoutes");var au=class extends Cu{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),dt("plugin.mcp-gateway"),this.#e=Km(t)}registerRoutes(t){let r=t.parsedRouteData;r&&s_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as x_}from"@opentelemetry/api";var y0="zuplo_mcp_",S0=["__host-","__secure-"];function R0(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of S0)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(y0)}o(R0,"setsGatewayCookie");function i_(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!R0(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(i_,"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 c_(e,t){let r=et(e)?.[t];return typeof r=="number"?r:void 0}o(c_,"readNumberProperty");function a_(e,t){return c_(e,"code")??(t>=400?t:void 0)}o(a_,"readErrorCode");function d_(e){return Array.isArray(e)?e.map(d_).find(t=>t?.method):et(e)}o(d_,"readJsonRpcMessage");function cu(e){let t=d_(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 w0(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(w0,"readItemCount");function u_(e){let t=cu(e);return!t||na(t.mcpMethod)?null:{eventType:Z.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(u_,"buildCapabilityInvokedAnalyticsInput");function _0(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(_0,"readMissingResponseFailure");function l_(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:c_(i,"code"),mcpErrorType:ps(i,"message")};let h=t.status<400?_0(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:w0(n.mcpMethod,n.capabilityType,c),S=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,...S?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:a_(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:a_(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(l_,"buildCapabilityFinalAnalyticsInput");function p_(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(p_,"buildCapabilityThrownAnalyticsInput");var du={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},m_={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},h_={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,b0=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function f_(e,t={}){return e===void 0?uu:b0.has(e)||t.modern===!0&&e==="server/discover"?hu:uu}o(f_,"tapMaxBytesForMethod");function v0(e){let t=We(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(v0,"readTapMode");function C0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(C0,"isPlainObject");function I0(e){return C0(e)&&!("method"in e)&&("result"in e||"error"in e)}o(I0,"isResponseShaped");function T0(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(T0,"isSameJsonRpcIdValue");function g_(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(I0);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>T0(a.id,t));if(i||r)return i}return s[0]}o(g_,"selectResponse");function y_(e){try{return JSON.parse(e)}catch{return}}o(y_,"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=g_(y_(new TextDecoder().decode(t)),this.requestId,!1)}},pu=class{constructor(t,r){this.requestId=t;this.#e=new hr({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=g_(y_(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},E0={push(){},end(){},message:void 0,truncated:!1};function k0(e,t,r){switch(e){case"json":return new lu(t,r);case"sse":return new pu(t,r);case"passthrough":return E0}}o(k0,"createObserver");function S_(e,t={}){let r=e.body;if(r===null){let C=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:C,outcome:C}}let n=mt(e.headers)?"passthrough":v0(e),s=k0(n,t.requestId,t.maxBytes??uu),i,a=new Promise(C=>{i=C}),c,d=new Promise(C=>{c=C}),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,S=o((C,x)=>{if(f)return;if(f=!0,C==="complete")try{s.end()}catch{}let N={ended:C,...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(),R=new ReadableStream({async pull(C){let x;try{x=await b.read()}catch(N){S("errored",N),C.error(N);return}if(x.done){S("complete"),C.close();return}if(h+=x.value.byteLength,!f)try{s.push(x.value)}catch{}C.enqueue(x.value),p()},async cancel(C){S(C===mu?"released":"cancelled"),await b.cancel(C)}},{highWaterMark:0}),y=Xf(new Headers(e.headers)),_;try{_=new Response(R,{status:e.status,statusText:e.statusText,headers:y})}catch(C){throw b.cancel(C).catch(()=>{}),C}return{response:_,done:a,outcome:d}}o(S_,"tapJsonRpcResponse");var A0=-32603,P0="The upstream MCP server ended the response stream without a response to this request.",x0="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function R_(e){return`${typeof e}:${String(e)}`}o(R_,"idKey");function O0(e,t){if(e.delete(R_(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(O0,"clearAnsweredRequest");function oa(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!w_(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 w_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(w_,"isRecord");function M0(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)w_(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(M0,"readResponseIds");function U0(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(U0,"endOnError");function __(e,t,r=hu,n){let s=new Map;for(let a of t)s.set(R_(a),a);let i=!1;return Cc(U0(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of M0(a.data))O0(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?x0:P0;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:A0,message:a}})}))},"end")})}o(__,"answerUnansweredRequests");var q0="The upstream MCP server rejected the gateway's credential.";function b_(e){return e.status===401||e.status===403&&e.headers.has("www-authenticate")}o(b_,"isUpstreamCredentialRejection");function v_(e,t){let r={code:I.InternalError,message:q0,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(v_,"upstreamCredentialRejectedResponse");var C_="mcp-session-id";async function z0(e){try{return await e.clone().arrayBuffer()}catch{return}}o(z0,"readRequestBody");function gu(e){try{let t=ih(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 N0(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(N0,"learnUpstreamSupportedVersions");function yu(e){return yh(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 I_(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(I_,"readHeader");function Su(e){let t=I_(e.request.headers,C_)??(e.response?I_(e.response.headers,C_):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=ur(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Su,"readMcpProtocolFields");function j0(e){let t=u_(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(j0,"emitCapabilityInvokedAnalytics");function D0(e){let t=l_(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(D0,"emitCapabilityFinalAnalytics");function sa(e){let t=p_(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 T_(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 Bm(n,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}o(T_,"callUpstream");function L0(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(L0,"readClientSignal");function E_(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(E_,"throwIfClientCancelled");function $0(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($0,"watchClientCancelBeforeHeaders");async function ia(e){try{await e.body?.cancel()}catch{}}o(ia,"discardBody");function H0(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(H0,"isClientAbortError");function B0(e,t){try{xs.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(B0,"logErrorAfterClientLeft");async function k_(e){E_(e.clientSignal);let t=await T_(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=ES(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 x_.with(e.refreshContext,n):await n();return E_(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await T_({...e,headers:s.headers}),gatewayAnswered:!1}}o(k_,"forwardToUpstream");function F0(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?k_({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):x_.with(i.client.ctx,()=>k_({request:t,context:r,bodyBytes:n===void 0?void 0:Gg(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(F0,"callUpstreamOperation");function J0(e,t,r){if(e.body===null||e.status<200||e.status>299||We(e.headers.get("content-type"))!=="text/event-stream"||mt(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(__(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(J0,"withUnansweredRequestErrors");function V0(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(G0(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(V0,"finishModernResponse");function G0(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(G0,"cancelOnClientAbort");function K0(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(K0,"releaseBodyIfNotSent");function A_(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(A_,"clientClosedResponse");function P_(e){return e instanceof re?h_:m_}o(P_,"thrownDetails");async function W0(e,t){if(dt("handler.mcp-gateway-proxy"),e.method==="GET")return Si(e,t);let r=Date.now(),n=await z0(e),s=Oh(n,{readMetaProtocolVersion:te()});Mh(t,ur(e.headers,s?.value));let i=Zc(e,s,n),a;if(i!==void 0)try{a=Vg({request:e,context:t,parsed:i})}catch{a=void 0}j0({context:t,request:e,requestJson:s});let c=te()&&Fr(e.headers,s?.value),d=c&&fu(s)==="subscriptions/listen",u=c?L0(e):void 0,p=u?$0({clientSignal:u,context:t,onCancel:o(()=>{a&&Xc(a),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:c,late:!0})},"onCancel")}):void 0,h={},f,S;try{let y=await F0({request:e,context:t,requestBody:n,parsed:i,spans:a,modern:c,listen:d,clientSignal:u,upstreamTimeout:h});S=y.gatewayAnswered;let _=y.response;!S&&xe()&&PS(t)&&b_(_)&&(t.log.warn({event:"mcp_upstream_credential_rejected",upstreamStatus:_.status},"MCP upstream proxy: upstream rejected the gateway credential"),await ia(_),_=v_(s?.value,_.status),S=!0),f=i_(_)}catch(y){let _=p?.claim()??!0;if(u?.aborted)return H0(y,u)||B0(t,y),_&&(a&&Xc(a),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:c})),A_(e,t);throw a&&Yc(a,y),sa({context:t,request:e,requestJson:s,startedAt:r,details:P_(y),modern:c}),y}if(p&&!p.claim())return await ia(f),A_(e,t);let b,R;try{b=S_(f,{requestId:we(s?.value),maxBytes:f_(fu(s),{modern:c})});let y=J0(b.response,s,h.signal);R=c?V0(y,{rewritten:y!==b.response,clientSignal:u}):y,K0(t,R)}catch(y){throw await ia(b?.response??f),a&&Yc(a,y),sa({context:t,request:e,requestJson:s,startedAt:r,details:P_(y),modern:c}),y}return t.waitUntil(b.outcome.then(y=>{S||N0(t,fu(s),y);try{D0({context:t,request:e,requestJson:s,response:f,tapResult:y,startedAt:r,modern:c,gatewayAnswered:S})}finally{a&&i&&Wg({spans:a,method:i.method,response:f,tapResult:y,expectsResponse:i.id!==void 0})}}).catch(y=>{try{xs.getLogger(t).error(y,"Error emitting MCP gateway capability analytics")}catch{}})),R}o(W0,"McpProxyHandler");export{B_ as McpAuth0OAuthInboundPolicy,Nc as McpCapabilityFilterInboundPolicy,M_ as McpClerkOAuthInboundPolicy,U_ as McpCognitoOAuthInboundPolicy,q_ as McpEntraOAuthInboundPolicy,au as McpGatewayPlugin,z_ as McpGoogleOAuthInboundPolicy,N_ as McpKeycloakOAuthInboundPolicy,j_ as McpLogtoOAuthInboundPolicy,F_ as McpOAuthInboundPolicy,D_ as McpOktaOAuthInboundPolicy,L_ as McpOneLoginOAuthInboundPolicy,$_ as McpPingOAuthInboundPolicy,W0 as McpProxyHandler,Id as McpTokenExchangeInboundPolicy,H_ as McpWorkosOAuthInboundPolicy,vg 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