@zuplo/runtime 7.14.0 → 7.14.2

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.
Files changed (34) hide show
  1. package/out/esm/chunk-7RNZS3GX.js +26 -0
  2. package/out/esm/chunk-7RNZS3GX.js.map +1 -0
  3. package/out/esm/chunk-AENEWA54.js +26 -0
  4. package/out/esm/chunk-AENEWA54.js.map +1 -0
  5. package/out/esm/chunk-C32OTSKW.js +91 -0
  6. package/out/esm/chunk-C32OTSKW.js.map +1 -0
  7. package/out/esm/chunk-MUDGPSWL.js +414 -0
  8. package/out/esm/chunk-MUDGPSWL.js.map +1 -0
  9. package/out/esm/chunk-UFTMOJ7K.js +37 -0
  10. package/out/esm/chunk-UFTMOJ7K.js.map +1 -0
  11. package/out/esm/index.js +1 -1
  12. package/out/esm/index.js.map +1 -1
  13. package/out/esm/mcp/messages/index.js +1 -1
  14. package/out/esm/mcp-gateway/index.js +12 -12
  15. package/out/esm/mcp-gateway/index.js.map +1 -1
  16. package/out/esm/mocks/index.js +1 -1
  17. package/out/esm/mocks/index.js.map +1 -1
  18. package/out/esm/sdks/aws/index.js +1 -1
  19. package/out/esm/sdks/aws/index.js.map +1 -1
  20. package/out/types/index.d.ts +120 -0
  21. package/out/types/internal/index.d.ts +64 -0
  22. package/out/types/mcp/messages/index.d.ts +78 -0
  23. package/out/types/mcp-gateway/index.d.ts +3 -2
  24. package/package.json +1 -1
  25. package/out/esm/chunk-4SVXBKXH.js +0 -414
  26. package/out/esm/chunk-4SVXBKXH.js.map +0 -1
  27. package/out/esm/chunk-7FFIW3HF.js +0 -26
  28. package/out/esm/chunk-7FFIW3HF.js.map +0 -1
  29. package/out/esm/chunk-QGAJTUPE.js +0 -26
  30. package/out/esm/chunk-QGAJTUPE.js.map +0 -1
  31. package/out/esm/chunk-WUZE2HKB.js +0 -102
  32. package/out/esm/chunk-WUZE2HKB.js.map +0 -1
  33. /package/out/esm/{chunk-4SVXBKXH.js.LEGAL.txt → chunk-MUDGPSWL.js.LEGAL.txt} +0 -0
  34. /package/out/esm/{chunk-WUZE2HKB.js.LEGAL.txt → chunk-UFTMOJ7K.js.LEGAL.txt} +0 -0
@@ -22,25 +22,25 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as Zn,$a as Wd,$b as Ku,$c as Nl,$f as fs,$g as Np,Aa as vd,Ab as bu,Ac as as,Af as We,Ag as Ss,Ba as Cd,Bb as vu,Bc as cs,Bf as ap,Bg as Rp,C as nd,Ca as Id,Cb as Cu,Cc as pl,Cf as ot,Cg as _s,Da as Td,Db as Iu,Dc as ml,Df as M,Dg as qi,E as ns,Ea as Ed,Eb as Tu,Ec as hl,Ef as ms,Eg as ws,Fa as kd,Fb as Eu,Fc as fl,Fd as Ql,Ff as ve,Fg as bp,Ga as Ad,Gb as ku,Gc as gl,Gf as bt,Gg as ue,Ha as Pd,Hb as Au,Hc as yl,Hf as VS,Hg as vp,Ia as xd,Ib as Pu,Ic as Sl,If as KS,Ig as Cp,Ja as Od,Jb as xu,Jc as _l,Jf as WS,Jg as zi,Ka as Ud,Kb as Ou,Kc as wl,Kf as ZS,Kg as Ip,La as Md,Lb as Uu,Lc as Rl,Lf as YS,Lg as Tp,Ma as qd,Mb as Mu,Mc as bl,Mf as XS,Mg as Ni,Na as zd,Nb as qu,Nc as vl,Nf as QS,Ng as Ep,O as od,Oa as Nd,Ob as zu,Oc as Cl,Of as e_,Og as Yt,Pa as jd,Pb as Nu,Pc as Il,Pf as t_,Pg as kp,Qa as Ri,Qb as ju,Qc as Tl,Qf as r_,Qg as so,R as sd,Ra as Dd,Rb as Du,Rc as El,Rf as cp,Rg as Ap,Sa as $d,Sb as $u,Sc as kl,Sf as dp,Sg as Rs,Ta as Ld,Tb as Lu,Tc as Al,Tf as hs,Tg as io,Ua as Hd,Ub as Hu,Uc as Pl,Uf as to,Ug as Pp,Va as Bd,Vb as Bu,Vc as xl,Vf as ro,Vg as xp,Wa as Jd,Wb as Ju,Wc as Ol,Wf as Mr,Wg as Op,Xa as Fd,Xb as Fu,Xc as Ul,Xf as up,Xg as Up,Y as os,Ya as Gd,Yb as Gu,Yc as Ml,Yf as xi,Yg as Mp,Z as yi,Za as Vd,Zb as bi,Zc as ql,Zf as lp,Zg as qp,_ as wr,_a as Kd,_b as Vu,_c as zl,_f as no,_g as zp,aa as Rr,ab as Zd,ac as Wu,ad as jl,ag as pp,ah as bs,b as td,ba as br,bb as Yd,bc as Zu,bd as Dl,bg as mp,bh as jp,ca as Yn,cb as Xd,cc as Yu,cd as $l,cg as hp,ch as Dp,da as vr,db as Qd,dc as Xu,dd as Ll,dg as fp,dh as H,ea as id,eb as eu,ec as Qu,ed as Hl,eg as _e,eh as X,fa as ad,fb as tu,fc as el,fd as Bl,ff as ep,fg as me,fh as $p,ga as cd,gb as ru,gc as tl,gd as Jl,gf as qe,gg as gp,gh as he,ha as dd,hb as nu,hc as rl,hd as Fl,hf as tp,hg as yp,hh as at,ia as ud,ib as ou,ic as nl,id as Cr,if as rp,ig as J,ih as oe,ja as ld,jb as su,jc as ol,jd as Ir,jf as np,jg as st,jh as vs,ka as pd,kb as iu,kc as sl,kd as Gl,kf as ne,kg as qr,kh as Lp,la as md,lb as au,lc as il,ld as Tr,lf as op,lg as Ce,lh as n_,ma as hd,mb as cu,mc as al,md as Rt,mf as Er,mg as ce,mh as o_,n as Qe,na as fd,nb as du,nc as cl,nd as Pi,nf as sp,ng as Sp,oa as gd,ob as uu,oc as vi,od as ds,of as kr,og as te,pa as yd,pb as lu,pc as ss,pd as Vl,pf as E,pg as _p,qa as Sd,qb as pu,qc as is,qd as Qn,qf as Ar,qg as vt,ra as _d,rb as mu,rc as Ci,rd as Zt,rf as Pr,rg as Oi,sa as wd,sb as hu,sc as Ii,sd as Kl,sf as rt,sg as gs,ta as Rd,tb as fu,tc as Ti,td as Wl,tf as nt,tg as Ui,u as He,ua as Wt,ub as gu,uc as dl,ud as eo,uf as ls,ug as ys,v as rd,va as Si,vb as yu,vc as Ei,vd as Zl,vf as xr,vg as oo,wa as _i,wb as Su,wc as ki,wd as Yl,wf as Or,wg as zr,x as F,xa as Xn,xb as _u,xc as ul,xd as Xl,xf as Ur,xg as wp,ya as wi,yb as wu,yc as ll,yd as us,yf as ps,yg as it,za as bd,zb as Ru,zc as Ai,zf as ip,zg as Mi}from"../chunk-4SVXBKXH.js";import"../chunk-VP5Q3DEN.js";import{a as Hp,b as Bp}from"../chunk-7FFIW3HF.js";import{a as _r}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{$ as es,Ba as p,a as be,aa as Yc,c as T,ca as hi,d as Y,da as Xc,ea as u,fa as Qc,ga as ed,ha as C,ia as z,ja as ts,la as D,ma as b,na as g,oa as L,pa as U,qa as fi,ra as Kn,sa as P,ta as B,ua as _,va as $,wa as gi,xa as rs,za as Wn}from"../chunk-WUZE2HKB.js";import"../chunk-UKQQD2JN.js";import{a as n}from"../chunk-TYV53J3B.js";var s_=Object.create,Cs=Object.defineProperty,i_=Object.getOwnPropertyDescriptor,a_=Object.getOwnPropertyNames,c_=Object.getPrototypeOf,d_=Object.prototype.hasOwnProperty,Jp=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),Fp=n((e,t)=>{let r={};for(var o in e)Cs(r,o,{get:e[o],enumerable:!0});return t&&Cs(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),u_=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=a_(t),i=0,a=s.length,c;i<a;i++)c=s[i],!d_.call(e,c)&&c!==r&&Cs(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(o=i_(t,c))||o.enumerable});return e},"__copyProps"),Gp=n((e,t,r)=>(r=e!=null?s_(c_(e)):{},u_(t||!e||!e.__esModule?Cs(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var l_=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Vp(e){return typeof e=="string"&&l_.has(e.replace(/#$/,""))}n(Vp,"declares2019Dialect");var Bi=Symbol.for("mcp.sdk.errorBrands");function Xt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let s=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof s=="string"&&r.add(s),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,Bi,{value:r,enumerable:!1,configurable:!0})}n(Xt,"stampErrorBrands");function ze(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Bi)){let r=t[Bi];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(ze,"brandedHasInstance");var le=(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})({}),Ct=class om extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return ze(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 ze(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",Xt(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 om(t.error,t.error_description??t.error,t.error_uri)}},fe=(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})({}),de=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return ze(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 ze(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",Xt(this,new.target)}},v_=class extends de{static{n(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function sm(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(sm,"resourceUrlFromServerUrl");function Wi(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}n(Wi,"withoutIssuer");function As({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(i)}n(As,"checkResourceAllowed");var C_="2026-07-28";function im(e){return e>=C_}n(im,"isModernProtocolVersion");function am(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)}]}}n(am,"appendTextFallbackForNonObject");var cm=["task","inputRequests","requestState"];function I_(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||cm.some(t=>t in e)?e:{...e,content:[]}}n(I_,"normalizeContentlessToolResult");function T_(){let e=gi(()=>U([u(),C(),z(),ts(),P(u(),e),b(e)])),t=P(u(),e),r=U([u(),C().int()]),o=u(),s=g({ttl:C().optional()}),i=g({taskId:u()}),a=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),l=g({method:u(),params:c.loose().optional()}),m=g({_meta:a.optional()}),h=g({method:u(),params:m.loose().optional()}),y=L({_meta:a.optional()}),f=U([u(),C().int()]),R=y.strict(),S=m.extend({requestId:f.optional(),reason:u().optional()}),w=h.extend({method:_("notifications/cancelled"),params:S}),x=g({src:u(),mimeType:u().optional(),sizes:b(u()).optional(),theme:B(["light","dark"]).optional()}),I=g({icons:b(x).optional()}),O=g({name:u(),title:u().optional()}),N=O.extend({...O.shape,...I.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),we=Kn(g({applyDefaults:z().optional()}),t),q=rs(Se=>Se&&typeof Se=="object"&&!Array.isArray(Se)&&Object.keys(Se).length===0?{form:{}}:Se,Kn(g({form:we.optional(),url:t.optional()}),t.optional())),ie=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),pe=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),A=g({experimental:P(u(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:q.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:ie.optional(),extensions:P(u(),t).optional()}),K=c.extend({protocolVersion:u(),capabilities:A,clientInfo:N}),j=l.extend({method:_("initialize"),params:K}),W=g({experimental:P(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:z().optional()}).optional(),resources:g({subscribe:z().optional(),listChanged:z().optional()}).optional(),tools:g({listChanged:z().optional()}).optional(),tasks:pe.optional(),extensions:P(u(),t).optional()}),Z=y.extend({protocolVersion:u(),capabilities:W,serverInfo:N,instructions:u().optional()}),De=h.extend({method:_("notifications/initialized"),params:m.optional()}),Oe=l.extend({method:_("ping"),params:c.optional()}),$e=g({progress:C(),total:$(C()),message:$(u())}),G=g({...m.shape,...$e.shape,progressToken:r}),ae=h.extend({method:_("notifications/progress"),params:G}),ke=c.extend({cursor:o.optional()}),ee=l.extend({params:ke.optional()}),Ge=y.extend({nextCursor:o.optional()}),or=g({uri:u(),mimeType:$(u()),_meta:P(u(),D()).optional()}),sr=or.extend({text:u()}),Nt=u().refine(Se=>{try{return atob(Se),!0}catch{return!1}},{message:"Invalid Base64 string"}),ir=or.extend({blob:Nt}),Xe=B(["user","assistant"]),Ve=g({audience:b(Xe).optional(),priority:C().min(0).max(1).optional(),lastModified:Wn.datetime({offset:!0}).optional()}),jt=g({...O.shape,...I.shape,uri:u(),description:$(u()),mimeType:$(u()),size:$(C()),annotations:Ve.optional(),_meta:$(L({}))}),en=g({...O.shape,...I.shape,uriTemplate:u(),description:$(u()),mimeType:$(u()),annotations:Ve.optional(),_meta:$(L({}))}),tn=ee.extend({method:_("resources/list")}),rn=Ge.extend({resources:b(jt)}),yt=ee.extend({method:_("resources/templates/list")}),ar=Ge.extend({resourceTemplates:b(en)}),Dt=c.extend({uri:u()}),nn=Dt,on=l.extend({method:_("resources/read"),params:nn}),sn=y.extend({contents:b(U([sr,ir]))}),an=h.extend({method:_("notifications/resources/list_changed"),params:m.optional()}),cn=Dt,dn=l.extend({method:_("resources/subscribe"),params:cn}),un=Dt,ln=l.extend({method:_("resources/unsubscribe"),params:un}),pn=m.extend({uri:u()}),mn=h.extend({method:_("notifications/resources/updated"),params:pn}),hn=g({name:u(),description:$(u()),required:$(z())}),fn=g({...O.shape,...I.shape,description:$(u()),arguments:$(b(hn)),_meta:$(L({}))}),gn=ee.extend({method:_("prompts/list")}),yn=Ge.extend({prompts:b(fn)}),Sn=c.extend({name:u(),arguments:P(u(),u()).optional()}),_n=l.extend({method:_("prompts/get"),params:Sn}),$t=g({type:_("text"),text:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Lt=g({type:_("image"),data:Nt,mimeType:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Ht=g({type:_("audio"),data:Nt,mimeType:u(),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),wn=g({type:_("tool_use"),name:u(),id:u(),input:P(u(),D()),_meta:P(u(),D()).optional()}),St=g({type:_("resource"),resource:U([sr,ir]),annotations:Ve.optional(),_meta:P(u(),D()).optional()}),Rn=jt.extend({type:_("resource_link")}),Le=U([$t,Lt,Ht,Rn,St]),cr=g({role:Xe,content:Le}),dr=y.extend({description:u().optional(),messages:b(cr)}),Bt=h.extend({method:_("notifications/prompts/list_changed"),params:m.optional()}),bn=g({title:u().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),ur=g({taskSupport:B(["required","optional","forbidden"]).optional()}),Jt=g({...O.shape,...I.shape,description:u().optional(),inputSchema:g({type:_("object"),properties:P(u(),e).optional(),required:b(u()).optional()}).catchall(D()),outputSchema:g({type:_("object"),properties:P(u(),e).optional(),required:b(u()).optional()}).catchall(D()).optional(),annotations:bn.optional(),execution:ur.optional(),_meta:P(u(),D()).optional()}),lr=ee.extend({method:_("tools/list")}),pr=Ge.extend({tools:b(Jt)}),mr=y.extend({content:b(Le),structuredContent:P(u(),D()).optional(),isError:z().optional()}),ye=d.extend({name:u(),arguments:P(u(),D()).optional()}),vn=l.extend({method:_("tools/call"),params:ye}),jo=h.extend({method:_("notifications/tools/list_changed"),params:m.optional()}),hr=B(["debug","info","notice","warning","error","critical","alert","emergency"]),Cn=c.extend({level:hr}),In=l.extend({method:_("logging/setLevel"),params:Cn}),Tn=m.extend({level:hr,logger:u().optional(),data:D()}),En=h.extend({method:_("notifications/message"),params:Tn}),kn=g({name:u().optional()}),An=g({hints:b(kn).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Pn=g({mode:B(["auto","required","none"]).optional()}),Do=g({type:_("tool_result"),toolUseId:u().describe("The unique identifier for the corresponding tool call."),content:b(Le),structuredContent:g({}).loose().optional(),isError:z().optional(),_meta:P(u(),D()).optional()}),xn=fi("type",[$t,Lt,Ht]),_t=fi("type",[$t,Lt,Ht,wn,Do]),On=g({role:Xe,content:U([_t,b(_t)]),_meta:P(u(),D()).optional()}),Un=d.extend({messages:b(On),modelPreferences:An.optional(),systemPrompt:u().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:b(u()).optional(),metadata:t.optional(),tools:b(Jt).optional(),toolChoice:Pn.optional()}),Mn=l.extend({method:_("sampling/createMessage"),params:Un}),qn=y.extend({model:u(),stopReason:$(B(["endTurn","stopSequence","maxTokens"]).or(u())),role:Xe,content:xn}),zn=y.extend({model:u(),stopReason:$(B(["endTurn","stopSequence","maxTokens","toolUse"]).or(u())),role:Xe,content:U([_t,b(_t)])}),Nn=g({type:_("boolean"),title:u().optional(),description:u().optional(),default:z().optional()}),jn=g({type:_("string"),title:u().optional(),description:u().optional(),minLength:C().optional(),maxLength:C().optional(),format:B(["email","uri","date","date-time"]).optional(),default:u().optional()}),Dn=g({type:B(["number","integer"]),title:u().optional(),description:u().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),$n=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),default:u().optional()}),Ln=g({type:_("string"),title:u().optional(),description:u().optional(),oneOf:b(g({const:u(),title:u()})),default:u().optional()}),Hn=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),enumNames:b(u()).optional(),default:u().optional()}),Bn=U([$n,Ln]),Ft=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({type:_("string"),enum:b(u())}),default:b(u()).optional()}),Gt=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({anyOf:b(g({const:u(),title:u()}))}),default:b(u()).optional()}),$o=U([Ft,Gt]),Lo=U([Hn,Bn,$o]),Ue=U([Lo,Nn,jn,Dn]),Me=d.extend({mode:_("form").optional(),message:u(),requestedSchema:g({type:_("object"),properties:P(u(),Ue),required:b(u()).optional()}).catchall(D())}),Jn=d.extend({mode:_("url"),message:u(),elicitationId:u(),url:u().url()}),Ke=U([Me,Jn]),Ho=l.extend({method:_("elicitation/create"),params:Ke}),Bo=m.extend({elicitationId:u()}),Jo=h.extend({method:_("notifications/elicitation/complete"),params:Bo}),Fo=y.extend({action:B(["accept","decline","cancel"]),content:rs(Se=>Se===null?void 0:Se,P(u(),U([u(),C(),z(),b(u())])).optional())}),Go=g({type:_("ref/resource"),uri:u()}),Vo=g({type:_("ref/prompt"),name:u()}),Ko=c.extend({ref:U([Vo,Go]),argument:g({name:u(),value:u()}),context:g({arguments:P(u(),u()).optional()}).optional()}),Fn=l.extend({method:_("completion/complete"),params:Ko}),Wo=y.extend({completion:L({values:b(u()).max(100),total:$(C().int()),hasMore:$(z())})}),Zo=g({uri:u().startsWith("file://"),name:u().optional(),_meta:P(u(),D()).optional()}),fr=l.extend({method:_("roots/list"),params:c.optional()}),Gn=y.extend({roots:b(Zo)}),Yo=h.extend({method:_("notifications/roots/list_changed"),params:m.optional()}),Xo=L({ttl:C().optional(),pollInterval:C().optional()}),Vn=B(["working","input_required","completed","failed","cancelled"]),wt=g({taskId:u(),status:Vn,ttl:U([C(),ts()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:$(C()),statusMessage:$(u())}),Ae=y.extend({task:wt}),Qo=m.merge(wt),Vt=h.extend({method:_("notifications/tasks/status"),params:Qo}),gr=l.extend({method:_("tasks/get"),params:c.extend({taskId:u()})}),yr=y.merge(wt),Sr=l.extend({method:_("tasks/result"),params:c.extend({taskId:u()})}),mi=y.loose(),Re=ee.extend({method:_("tasks/list")}),re=Ge.extend({tasks:b(wt)}),Kt=l.extend({method:_("tasks/cancel"),params:c.extend({taskId:u()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:l,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:y,RequestIdSchema:f,EmptyResultSchema:R,CancelledNotificationParamsSchema:S,CancelledNotificationSchema:w,IconSchema:x,IconsSchema:I,BaseMetadataSchema:O,ImplementationSchema:N,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:pe,ClientCapabilitiesSchema:A,InitializeRequestParamsSchema:K,InitializeRequestSchema:j,ServerCapabilitiesSchema:W,InitializeResultSchema:Z,InitializedNotificationSchema:De,PingRequestSchema:Oe,ProgressSchema:$e,ProgressNotificationParamsSchema:G,ProgressNotificationSchema:ae,PaginatedRequestParamsSchema:ke,PaginatedRequestSchema:ee,PaginatedResultSchema:Ge,ResourceContentsSchema:or,TextResourceContentsSchema:sr,BlobResourceContentsSchema:ir,RoleSchema:Xe,AnnotationsSchema:Ve,ResourceSchema:jt,ResourceTemplateSchema:en,ListResourcesRequestSchema:tn,ListResourcesResultSchema:rn,ListResourceTemplatesRequestSchema:yt,ListResourceTemplatesResultSchema:ar,ResourceRequestParamsSchema:Dt,ReadResourceRequestParamsSchema:nn,ReadResourceRequestSchema:on,ReadResourceResultSchema:sn,ResourceListChangedNotificationSchema:an,SubscribeRequestParamsSchema:cn,SubscribeRequestSchema:dn,UnsubscribeRequestParamsSchema:un,UnsubscribeRequestSchema:ln,ResourceUpdatedNotificationParamsSchema:pn,ResourceUpdatedNotificationSchema:mn,PromptArgumentSchema:hn,PromptSchema:fn,ListPromptsRequestSchema:gn,ListPromptsResultSchema:yn,GetPromptRequestParamsSchema:Sn,GetPromptRequestSchema:_n,TextContentSchema:$t,ImageContentSchema:Lt,AudioContentSchema:Ht,ToolUseContentSchema:wn,EmbeddedResourceSchema:St,ResourceLinkSchema:Rn,ContentBlockSchema:Le,PromptMessageSchema:cr,GetPromptResultSchema:dr,PromptListChangedNotificationSchema:Bt,ToolAnnotationsSchema:bn,ToolExecutionSchema:ur,ToolSchema:Jt,ListToolsRequestSchema:lr,ListToolsResultSchema:pr,CallToolResultSchema:mr,CallToolRequestParamsSchema:ye,CallToolRequestSchema:vn,ToolListChangedNotificationSchema:jo,LoggingLevelSchema:hr,SetLevelRequestParamsSchema:Cn,SetLevelRequestSchema:In,LoggingMessageNotificationParamsSchema:Tn,LoggingMessageNotificationSchema:En,ModelHintSchema:kn,ModelPreferencesSchema:An,ToolChoiceSchema:Pn,ToolResultContentSchema:Do,SamplingContentSchema:xn,SamplingMessageContentBlockSchema:_t,SamplingMessageSchema:On,CreateMessageRequestParamsSchema:Un,CreateMessageRequestSchema:Mn,CreateMessageResultSchema:qn,CreateMessageResultWithToolsSchema:zn,BooleanSchemaSchema:Nn,StringSchemaSchema:jn,NumberSchemaSchema:Dn,UntitledSingleSelectEnumSchemaSchema:$n,TitledSingleSelectEnumSchemaSchema:Ln,LegacyTitledEnumSchemaSchema:Hn,SingleSelectEnumSchemaSchema:Bn,UntitledMultiSelectEnumSchemaSchema:Ft,TitledMultiSelectEnumSchemaSchema:Gt,MultiSelectEnumSchemaSchema:$o,EnumSchemaSchema:Lo,PrimitiveSchemaDefinitionSchema:Ue,ElicitRequestFormParamsSchema:Me,ElicitRequestURLParamsSchema:Jn,ElicitRequestParamsSchema:Ke,ElicitRequestSchema:Ho,ElicitationCompleteNotificationParamsSchema:Bo,ElicitationCompleteNotificationSchema:Jo,ElicitResultSchema:Fo,ResourceTemplateReferenceSchema:Go,PromptReferenceSchema:Vo,CompleteRequestParamsSchema:Ko,CompleteRequestSchema:Fn,CompleteResultSchema:Wo,RootSchema:Zo,ListRootsRequestSchema:fr,ListRootsResultSchema:Gn,RootsListChangedNotificationSchema:Yo,TaskCreationParamsSchema:Xo,TaskStatusSchema:Vn,TaskSchema:wt,CreateTaskResultSchema:Ae,TaskStatusNotificationParamsSchema:Qo,TaskStatusNotificationSchema:Vt,GetTaskRequestSchema:gr,GetTaskResultSchema:yr,GetTaskPayloadRequestSchema:Sr,GetTaskPayloadResultSchema:mi,ListTasksRequestSchema:Re,ListTasksResultSchema:re,CancelTaskRequestSchema:Kt,CancelTaskResultSchema:y.merge(wt),ClientRequestSchema:U([Oe,j,Fn,In,_n,gn,tn,yt,on,dn,ln,vn,lr,gr,Sr,Re,Kt]),ClientNotificationSchema:U([w,ae,De,Yo,Vt]),ClientResultSchema:U([R,qn,zn,Fo,Gn,yr,re,Ae]),ServerRequestSchema:U([Oe,Mn,Ho,fr,gr,Sr,Re,Kt]),ServerNotificationSchema:U([w,ae,En,mn,an,jo,Bt,Vt,Jo]),ServerResultSchema:U([R,Z,Wo,dr,yn,rn,ar,sn,mr,pr,yr,re,Ae]),CallToolResultWireSchema:D().superRefine((Se,GS)=>{if(!(typeof Se!="object"||Se===null||Array.isArray(Se)||Se.content!==void 0)){for(let Zc of cm)if(Zc in Se){GS.addIssue({code:"custom",message:`content is required when the body carries '${Zc}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(I_).pipe(mr)}}n(T_,"build$1");var E_;function Zi(){return E_??=T_()}n(Zi,"buildSchemas2025");function dm(e){return e.type!=="object"}n(dm,"isNonObjectJsonSchemaRoot");var k_=new Set(["const","enum","default","examples"]),A_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Kp(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(Kp,"establishesNewBase");function P_(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Kp(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Vp(e.$schema)&&e.$recursiveAnchor!==!0,o=n((s,i)=>{if(Array.isArray(s))return s.map(d=>o(d,!1));if(s===null||typeof s!="object"||!i&&Kp(s.$id))return s;let a={},c=!1;for(let[d,l]of Object.entries(s))i?a[d]=o(l,!1):(d==="$ref"||d==="$dynamicRef")&&typeof l=="string"?a[d]=l==="#"?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:d==="$recursiveRef"&&l==="#"&&r?c=!0:k_.has(d)?a[d]=l:A_.has(d)?a[d]=o(l,!0):a[d]=o(l,!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:o(e,!1)},required:["result"]}}n(P_,"wrapOutputSchemaForLegacy");var um={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},lm={"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},x_={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},Is;function Ps(){if(Is)return Is;let e=Zi();return Is={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}},Is}n(Ps,"registryMaps");function O_(){Ps()}n(O_,"warmRegistryMaps2025");function pm(e){return Object.prototype.hasOwnProperty.call(um,e)}n(pm,"hasRequestMethod2025");function mm(e){return Object.prototype.hasOwnProperty.call(lm,e)}n(mm,"hasNotificationMethod2025");function U_(e){return Object.prototype.hasOwnProperty.call(x_,e)}n(U_,"hasResultMethod");function M_(e){return U_(e)?Ps().resultSchemas[e]:void 0}n(M_,"getResultSchema");function q_(e){return pm(e)?Ps().requestSchemas[e]:void 0}n(q_,"getRequestSchema");function z_(e){return mm(e)?Ps().notificationSchemas[e]:void 0}n(z_,"getNotificationSchema");var NP=Object.keys(um),jP=Object.keys(lm);function Ji(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ji,"isPlainObject$5");function Ts(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)}}n(Ts,"triState$1");var Wp={ok:!1,reason:"not-in-era"};function Zp(e){return Ji(e)&&Ji(e.outputSchema)&&dm(e.outputSchema)}n(Zp,"toolNeedsLegacyWrap");var Yi={era:"2025-11-25",hasRequestMethod:pm,hasNotificationMethod:mm,validateRequest:n((e,t)=>Ts(q_(e),t),"validateRequest"),validateResult:n((e,t)=>Ts(M_(e),t),"validateResult"),validateNotification:n((e,t)=>Ts(z_(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>Wp,"validateInputRequest"),validateInputResponse:n(()=>Wp,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=Zi();return Ts(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=am(e),o=r.structuredContent;if(o===void 0)return r;let s=typeof o!="object"||o===null||Array.isArray(o),i=t!==void 0&&dm(t);return!s&&!i?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(Ji(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(o=>Zp(o))?t:{...t,tools:r.map(o=>Zp(o)?{...o,outputSchema:P_(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function N_(){let e=gi(()=>U([u(),C(),z(),ts(),P(u(),e),b(e)])),t=P(u(),e),r=U([u(),C().int()]),o=u(),s=U([u(),C().int()]),i=B(["user","assistant"]),a=B(["debug","info","notice","warning","error","critical","alert","emergency"]),c=u().refine(re=>{try{return atob(re),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:C().optional()}),l=g({taskId:u()}),m=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=g({_meta:m.optional()}),y=h.extend({task:d.optional()}),f=g({_meta:m.optional()}),R=g({method:u(),params:f.loose().optional()}),S=g({src:u(),mimeType:u().optional(),sizes:b(u()).optional(),theme:B(["light","dark"]).optional()}),w=g({icons:b(S).optional()}),x=g({name:u(),title:u().optional()}),I=x.extend({...x.shape,...w.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),O=Kn(g({applyDefaults:z().optional()}),t),N=rs(re=>re&&typeof re=="object"&&!Array.isArray(re)&&Object.keys(re).length===0?{form:{}}:re,Kn(g({form:O.optional(),url:t.optional()}),t.optional())),we=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),q=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),ie=g({experimental:P(u(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:we.optional(),extensions:P(u(),t).optional()}),pe=g({experimental:P(u(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:z().optional()}).optional(),resources:g({subscribe:z().optional(),listChanged:z().optional()}).optional(),tools:g({listChanged:z().optional()}).optional(),tasks:q.optional(),extensions:P(u(),t).optional()}),A=g({progress:C(),total:$(C()),message:$(u())}),K=g({...f.shape,...A.shape,progressToken:r}),j=R.extend({method:_("notifications/progress"),params:K}),W=f.extend({level:a,logger:u().optional(),data:D()}),Z=R.extend({method:_("notifications/message"),params:W}),De=g({uri:u(),mimeType:$(u()),_meta:P(u(),D()).optional()}),Oe=De.extend({text:u()}),$e=De.extend({blob:c}),G=g({audience:b(i).optional(),priority:C().min(0).max(1).optional(),lastModified:Wn.datetime({offset:!0}).optional()}),ae=g({...x.shape,...w.shape,uri:u(),description:$(u()),mimeType:$(u()),size:$(C()),annotations:G.optional(),_meta:$(L({}))}),ke=g({...x.shape,...w.shape,uriTemplate:u(),description:$(u()),mimeType:$(u()),annotations:G.optional(),_meta:$(L({}))}),ee=R.extend({method:_("notifications/resources/list_changed"),params:f.optional()}),Ge=f.extend({uri:u()}),or=R.extend({method:_("notifications/resources/updated"),params:Ge}),sr=g({name:u(),description:$(u()),required:$(z())}),Nt=g({...x.shape,...w.shape,description:$(u()),arguments:$(b(sr)),_meta:$(L({}))}),ir=R.extend({method:_("notifications/prompts/list_changed"),params:f.optional()}),Xe=g({type:_("text"),text:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),Ve=g({type:_("image"),data:c,mimeType:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),jt=g({type:_("audio"),data:c,mimeType:u(),annotations:G.optional(),_meta:P(u(),D()).optional()}),en=g({type:_("tool_use"),name:u(),id:u(),input:P(u(),D()),_meta:P(u(),D()).optional()}),tn=g({type:_("resource"),resource:U([Oe,$e]),annotations:G.optional(),_meta:P(u(),D()).optional()}),rn=ae.extend({type:_("resource_link")}),yt=U([Xe,Ve,jt,rn,tn]),ar=g({role:i,content:yt}),Dt=g({title:u().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),nn=R.extend({method:_("notifications/tools/list_changed"),params:f.optional()}),on=g({name:u().optional()}),sn=g({hints:b(on).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),an=g({mode:B(["auto","required","none"]).optional()}),cn=g({type:_("boolean"),title:u().optional(),description:u().optional(),default:z().optional()}),dn=g({type:_("string"),title:u().optional(),description:u().optional(),minLength:C().optional(),maxLength:C().optional(),format:B(["email","uri","date","date-time"]).optional(),default:u().optional()}),un=g({type:B(["number","integer"]),title:u().optional(),description:u().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),ln=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),default:u().optional()}),pn=g({type:_("string"),title:u().optional(),description:u().optional(),oneOf:b(g({const:u(),title:u()})),default:u().optional()}),mn=g({type:_("string"),title:u().optional(),description:u().optional(),enum:b(u()),enumNames:b(u()).optional(),default:u().optional()}),hn=U([ln,pn]),fn=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({type:_("string"),enum:b(u())}),default:b(u()).optional()}),gn=g({type:_("array"),title:u().optional(),description:u().optional(),minItems:C().optional(),maxItems:C().optional(),items:g({anyOf:b(g({const:u(),title:u()}))}),default:b(u()).optional()}),yn=U([fn,gn]),Sn=U([mn,hn,yn]),_n=U([Sn,cn,dn,un]),$t=y.extend({mode:_("form").optional(),message:u(),requestedSchema:g({type:_("object"),properties:P(u(),_n),required:b(u()).optional()}).catchall(D())}),Lt=g({type:_("ref/resource"),uri:u()}),Ht=g({type:_("ref/prompt"),name:u()}),wn=g({uri:u().startsWith("file://"),name:u().optional(),_meta:P(u(),D()).optional()}),St=ie.shape,Rn=g({experimental:St.experimental,sampling:St.sampling,elicitation:St.elicitation,roots:St.roots,extensions:St.extensions}),Le=pe.shape,cr=g({experimental:Le.experimental,logging:Le.logging,completions:Le.completions,prompts:Le.prompts,resources:Le.resources,tools:Le.tools,extensions:Le.extensions}),dr=L({progressToken:r.optional(),[wr]:u(),[Zn]:I.optional(),[br]:Rn,[Yn]:a.optional()}),Bt=g({...x.shape,...w.shape,description:u().optional(),inputSchema:L({$schema:u().optional(),type:_("object")}),outputSchema:L({$schema:u().optional()}).optional(),annotations:Dt.optional(),_meta:P(u(),D()).optional()}),bn=g({type:_("tool_result"),toolUseId:u(),content:b(yt),structuredContent:D().optional(),isError:z().optional(),_meta:P(u(),D()).optional()}),ur=U([Xe,Ve,jt,en,bn]),Jt=g({role:i,content:U([ur,b(ur)]),_meta:P(u(),D()).optional()}),lr=u(),pr=L({[Rr]:I.optional().catch(void 0)}),mr=pr.optional();function ye(re){return L({_meta:mr,resultType:lr.default("complete"),...re})}n(ye,"wireResult");let vn=ye({}),jo=ye({nextCursor:o.optional()}),hr=ye({content:b(yt),structuredContent:D().optional(),isError:z().optional()}),Cn=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),tools:b(Bt),nextCursor:o.optional()}),In=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),prompts:b(Nt),nextCursor:o.optional()}),Tn=ye({description:u().optional(),messages:b(ar)}),En=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resources:b(ae),nextCursor:o.optional()}),kn=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:b(ke),nextCursor:o.optional()}),An=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),contents:b(U([Oe,$e]))}),Pn=ye({completion:g({values:b(u()).max(100),total:C().int().optional(),hasMore:z().optional()}).loose()}),Do=ye({ttlMs:C().int().min(0),cacheScope:B(["public","private"])}),xn=ye({ttlMs:C().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:b(u()),capabilities:cr,instructions:u().optional()}),_t=g({messages:b(Jt),modelPreferences:sn.optional(),systemPrompt:u().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:b(u()).optional(),metadata:t.optional(),tools:b(Bt).optional(),toolChoice:an.optional()}),On=g({method:_("sampling/createMessage"),params:_t}),Un=g({method:_("roots/list"),params:g({_meta:P(u(),D()).optional()}).optional()}),Mn=g({...Jt.shape,model:u(),stopReason:u().optional()}),qn=g({roots:b(wn)}),zn=g({action:B(["accept","decline","cancel"]),content:P(u(),U([u(),C(),z(),b(u())])).optional()}),Nn=g({mode:_("url"),message:u(),url:u().url()}),jn=U([$t,Nn]),Dn=g({method:_("elicitation/create"),params:jn}),$n=U([On,Un,Dn]),Ln=U([Mn,qn,zn]),Hn=P(u(),$n),Bn=P(u(),Ln),Ft=ye({inputRequests:Hn.optional(),requestState:u().optional()}),Gt={inputResponses:Bn.optional(),requestState:u().optional()},$o=g({_meta:dr,...Gt}),Lo=L({progressToken:r.optional()});function Ue(re,Kt){return g({method:_(re),params:g({_meta:dr,...Kt})})}n(Ue,"wireRequest");function Me(re,Kt){return g({method:_(re),params:g({_meta:Lo.optional(),...Kt}).optional()})}n(Me,"dispatchRequest");let Jn={name:u(),arguments:P(u(),D()).optional(),...Gt},Ke={cursor:o.optional()},Ho=Ue("tools/call",Jn),Bo=Ue("tools/list",Ke),Jo=Ue("prompts/list",Ke),Fo=Ue("prompts/get",{name:u(),arguments:P(u(),u()).optional(),...Gt}),Go=Ue("resources/list",Ke),Vo=Ue("resources/templates/list",Ke),Ko=Ue("resources/read",{uri:u(),...Gt}),Fn={ref:U([Ht,Lt]),argument:g({name:u(),value:u()}),context:g({arguments:P(u(),u()).optional()}).optional()},Wo=Ue("completion/complete",Fn),Zo=Ue("server/discover",{}),fr=g({toolsListChanged:z().optional(),promptsListChanged:z().optional(),resourcesListChanged:z().optional(),resourceSubscriptions:b(u()).optional()}),Gn={notifications:fr},Yo=Ue("subscriptions/listen",Gn),Xo=pr.extend({"io.modelcontextprotocol/subscriptionId":s}),Vn=L({_meta:Xo,resultType:lr.default("complete")}),wt={"tools/call":Me("tools/call",Jn),"tools/list":Me("tools/list",Ke),"prompts/get":Me("prompts/get",{name:u(),arguments:P(u(),u()).optional()}),"prompts/list":Me("prompts/list",Ke),"resources/list":Me("resources/list",Ke),"resources/templates/list":Me("resources/templates/list",Ke),"resources/read":Me("resources/read",{uri:u()}),"completion/complete":Me("completion/complete",Fn),"server/discover":Me("server/discover",{}),"subscriptions/listen":Me("subscriptions/listen",Gn)};function Ae(re){return L({_meta:mr,...re})}n(Ae,"liftedResult");let Qo={"tools/call":Ae({content:b(yt),structuredContent:D().optional(),isError:z().optional()}),"tools/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),tools:b(Bt),nextCursor:o.optional()}),"prompts/get":Ae({description:u().optional(),messages:b(ar)}),"prompts/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),prompts:b(Nt),nextCursor:o.optional()}),"resources/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resources:b(ae),nextCursor:o.optional()}),"resources/templates/list":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:b(ke),nextCursor:o.optional()}),"resources/read":Ae({ttlMs:C().int().min(0),cacheScope:B(["public","private"]),contents:b(U([Oe,$e]))}),"completion/complete":Ae({completion:g({values:b(u()).max(100),total:C().int().optional(),hasMore:z().optional()}).loose()}),"server/discover":Ae({ttlMs:C().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:b(u()),capabilities:cr,instructions:u().optional()}),"subscriptions/listen":Ae({})},Vt=L({"io.modelcontextprotocol/subscriptionId":s.optional()}),gr=g({method:_("notifications/subscriptions/acknowledged"),params:g({_meta:Vt.optional(),notifications:fr})}),yr=g({_meta:Vt.optional(),requestId:s,reason:u().optional()}),Sr=g({method:_("notifications/cancelled"),params:yr}),mi={"notifications/cancelled":Sr,"notifications/progress":j,"notifications/message":Z,"notifications/resources/updated":or,"notifications/resources/list_changed":ee,"notifications/tools/list_changed":nn,"notifications/prompts/list_changed":ir,"notifications/subscriptions/acknowledged":gr},Re=n(re=>g({jsonrpc:_("2.0"),id:U([u(),C().int()]),result:re}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:l,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:f,NotificationSchema:R,IconSchema:S,IconsSchema:w,BaseMetadataSchema:x,ImplementationSchema:I,ClientTasksCapabilitySchema:we,ServerTasksCapabilitySchema:q,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:pe,ProgressSchema:A,ProgressNotificationParamsSchema:K,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:W,LoggingMessageNotificationSchema:Z,ResourceContentsSchema:De,TextResourceContentsSchema:Oe,BlobResourceContentsSchema:$e,AnnotationsSchema:G,ResourceSchema:ae,ResourceTemplateSchema:ke,ResourceListChangedNotificationSchema:ee,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:or,PromptArgumentSchema:sr,PromptSchema:Nt,PromptListChangedNotificationSchema:ir,TextContentSchema:Xe,ImageContentSchema:Ve,AudioContentSchema:jt,ToolUseContentSchema:en,EmbeddedResourceSchema:tn,ResourceLinkSchema:rn,ContentBlockSchema:yt,PromptMessageSchema:ar,ToolAnnotationsSchema:Dt,ToolListChangedNotificationSchema:nn,ModelHintSchema:on,ModelPreferencesSchema:sn,ToolChoiceSchema:an,BooleanSchemaSchema:cn,StringSchemaSchema:dn,NumberSchemaSchema:un,UntitledSingleSelectEnumSchemaSchema:ln,TitledSingleSelectEnumSchemaSchema:pn,LegacyTitledEnumSchemaSchema:mn,SingleSelectEnumSchemaSchema:hn,UntitledMultiSelectEnumSchemaSchema:fn,TitledMultiSelectEnumSchemaSchema:gn,MultiSelectEnumSchemaSchema:yn,EnumSchemaSchema:Sn,PrimitiveSchemaDefinitionSchema:_n,ElicitRequestFormParamsSchema:$t,ResourceTemplateReferenceSchema:Lt,PromptReferenceSchema:Ht,RootSchema:wn,ClientCapabilities2026Schema:Rn,ServerCapabilities2026Schema:cr,RequestMetaEnvelopeSchema:dr,ToolSchema:Bt,ToolResultContentSchema:bn,SamplingMessageContentBlockSchema:ur,SamplingMessageSchema:Jt,ResultTypeSchema:lr,ResultMetaSchema:pr,ResultSchema:vn,PaginatedResultSchema:jo,CallToolResultSchema:hr,ListToolsResultSchema:Cn,ListPromptsResultSchema:In,GetPromptResultSchema:Tn,ListResourcesResultSchema:En,ListResourceTemplatesResultSchema:kn,ReadResourceResultSchema:An,CompleteResultSchema:Pn,CacheableResultSchema:Do,DiscoverResultSchema:xn,CreateMessageRequestParamsSchema:_t,CreateMessageRequestSchema:On,ListRootsRequestSchema:Un,CreateMessageResultSchema:Mn,ListRootsResultSchema:qn,ElicitResultSchema:zn,ElicitRequestURLParamsSchema:Nn,ElicitRequestParamsSchema:jn,ElicitRequestSchema:Dn,InputRequestSchema:$n,InputResponseSchema:Ln,InputRequestsSchema:Hn,InputResponsesSchema:Bn,InputRequiredResultSchema:Ft,InputResponseRequestParamsSchema:$o,CallToolRequestSchema:Ho,ListToolsRequestSchema:Bo,ListPromptsRequestSchema:Jo,GetPromptRequestSchema:Fo,ListResourcesRequestSchema:Go,ListResourceTemplatesRequestSchema:Vo,ReadResourceRequestSchema:Ko,CompleteRequestSchema:Wo,DiscoverRequestSchema:Zo,SubscriptionFilterSchema:fr,SubscriptionsListenRequestSchema:Yo,SubscriptionsListenResultMetaSchema:Xo,SubscriptionsListenResultSchema:Vn,dispatchRequestSchemas:wt,dispatchResultSchemas:Qo,NotificationMetaSchema:Vt,SubscriptionsAcknowledgedNotificationSchema:gr,CancelledNotificationParamsSchema:yr,CancelledNotificationSchema:Sr,notificationSchemas2026:mi,JSONRPCResultResponseSchema:Re(vn),CallToolResultResponseSchema:Re(U([hr,Ft])),ListToolsResultResponseSchema:Re(Cn),ListPromptsResultResponseSchema:Re(In),GetPromptResultResponseSchema:Re(U([Tn,Ft])),ListResourcesResultResponseSchema:Re(En),ListResourceTemplatesResultResponseSchema:Re(kn),ReadResourceResultResponseSchema:Re(U([An,Ft])),CompleteResultResponseSchema:Re(Pn),DiscoverResultResponseSchema:Re(xn),SubscriptionsListenResultResponseSchema:Re(Vn)}}n(N_,"build");var j_;function ct(){return j_??=N_()}n(ct,"buildSchemas2026");var D_=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $_(e){return D_.includes(e)}n($_,"isCacheableResultMethod");var Xi=Symbol("modelcontextprotocol.resultCacheHintFallback");function L_(e){return e[Xi]}n(L_,"cacheHintFallbackOf");function hm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(hm,"isValidCacheTtlMs");function fm(e){return e==="public"||e==="private"}n(fm,"isValidCacheScope");var k=(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})({}),ge=class gm extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return ze(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 ze(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",Xt(this,new.target)}static fromError(t,r,o){if(t===k.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new xs(s.elicitations,r)}if(t===k.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Sm({supported:s.supported,requested:s.requested},r)}if(t===k.InvalidParams||t===k.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===k.ResourceNotFound||Object.keys(s).length===1))return new ym(s.uri,r)}if(t===k.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new _m({requiredCapabilities:s.requiredCapabilities},r)}return new gm(t,r,o)}},ym=class extends ge{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(k.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},xs=class extends ge{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(k.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Sm=class extends ge{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(k.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},_m=class extends ge{static{n(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(k.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},H_=0,B_="private",J_=["tools/call","prompts/get","resources/read"];function F_(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||J_.includes(e))return t;throw new ge(k.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(F_,"stampResultType");function G_(e,t){let r=L_(t);if(t.resultType!=="complete"||!$_(e))return r===void 0?t:Y_(t);let o=t,s=hm(o.ttlMs)?o.ttlMs:W_(r),i=fm(o.cacheScope)?o.cacheScope:Z_(r),a={...o,ttlMs:s,cacheScope:i};return delete a[Xi],a}n(G_,"fillCacheFields");function V_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(V_,"isPlainObject$4");function K_(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Rr]:t}}:!V_(r)||r[Rr]!==void 0?e:{...e,_meta:{...r,[Rr]:t}}}n(K_,"stampServerInfoMeta");function W_(e){return e!==void 0&&hm(e.ttlMs)?e.ttlMs:H_}n(W_,"resolveTtlMs");function Z_(e){return e!==void 0&&fm(e.cacheScope)?e.cacheScope:B_}n(Z_,"resolveCacheScope");function Y_(e){let t={...e};return delete t[Xi],t}n(Y_,"stripCacheHintFallback");var X_=["elicitation/create","sampling/createMessage","roots/list"],Es;function Qi(){if(Es)return Es;let e=ct();return Es={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:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Es}n(Qi,"inputSchemaMaps");function Q_(){Qi()}n(Q_,"warmInputSchemaMaps2026");function wm(e){return X_.includes(e)}n(wm,"isInputRequestMethod2026");function ji(e){return wm(e)?Qi().request[e]:void 0}n(ji,"getInputRequestSchema2026");function ew(e){return wm(e)?Qi().response[e]:void 0}n(ew,"getInputResponseSchema2026");var ea={"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},Rm={"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 bm(e){return Object.prototype.hasOwnProperty.call(ea,e)}n(bm,"hasRequestMethod2026");function vm(e){return Object.prototype.hasOwnProperty.call(Rm,e)}n(vm,"hasNotificationMethod2026");function tw(e){return Object.prototype.hasOwnProperty.call(ea,e)}n(tw,"hasResultMethod2026");function rw(e){return bm(e)?ct().dispatchRequestSchemas[e]:void 0}n(rw,"getRequestSchema2026");function nw(e){return tw(e)?ct().dispatchResultSchemas[e]:void 0}n(nw,"getResultSchema2026");function ow(e){return vm(e)?ct().notificationSchemas2026[e]:void 0}n(ow,"getNotificationSchema2026");var DP=Object.keys(ea),$P=Object.keys(Rm);function uo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(uo,"isPlainObject$3");function ao(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)}}n(ao,"triState");var sw={ok:!1,reason:"not-in-era"},iw=[wr,br];function aw(e,t){let r=t,o=!1,s=n(()=>(o||(r={...r},o=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>uo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!uo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(uo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}n(aw,"enforceDeletedFields");var ta={era:"2026-07-28",hasRequestMethod:bm,hasNotificationMethod:vm,hasInputRequestMethod:n(e=>ji(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>ao(rw(e),t),"validateRequest"),validateResult:n((e,t)=>ao(nw(e),t),"validateResult"),validateNotification:n((e,t)=>ao(ow(e),t),"validateNotification"),validateInputRequest:n((e,t)=>ao(ji(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>ao(ew(e),t),"validateInputResponse"),samplingResultVariant:n(()=>sw,"samplingResultVariant"),outboundEnvelope(e){return{[wr]:e.protocolVersion,[Zn]:e.clientInfo,[br]:e.clientCapabilities,...e.logLevel!==void 0&&{[Yn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of iw)o in e||t.push({key:o,problem:"missing"});let r=ct().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let s=o.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:o.message})}return t},projectCallToolResult:n(e=>am(e),"projectCallToolResult"),inputRequestSchema:ji,decodeResult(e,t){if(!uo(t))return{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new de(fe.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 de(fe.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=uo(a)?a:{},d=t.requestState,l=t._meta===void 0?void 0:ct().ResultMetaSchema.safeParse(t._meta),m=l?.success?l.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new de(fe.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new de(fe.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Cm(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new de(fe.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 K_(G_(e,F_(e,aw(e,t))),r)},encodeErrorCode:n(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=ct().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},ks;function Cm(){if(ks)return ks;let e=ct();return ks={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},ks}n(Cm,"getWireResultSchemas");function cw(){Cm()}n(cw,"warmWireResultSchemas2026");var ra="2026-07-28";function po(e){return e!==void 0&&im(e)?ta:Yi}n(po,"codecForVersion");function Yp(e){return e.revision!==void 0?po(e.revision).era:e.era==="modern"?ta.era:Yi.era}n(Yp,"classifiedWireEra");function Di(e){return Im.some(t=>t.hasRequestMethod(e))}n(Di,"isSpecRequestMethod");function $i(e){return Im.some(t=>t.hasNotificationMethod(e))}n($i,"isSpecNotificationMethod");function Xp(e){return e==="tasks/get"||e==="tasks/cancel"}n(Xp,"isExtensionReusedRequestMethod");var Im=[Yi,ta],dw=Fp({AnnotationsSchema:n(()=>Zd,"AnnotationsSchema"),AudioContentSchema:n(()=>Au,"AudioContentSchema"),BaseMetadataSchema:n(()=>kd,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>hd,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>Kd,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>vi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>Ju,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Fu,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Hu,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>jl,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>Dl,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Cd,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Id,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Od,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>Ll,"ClientNotificationSchema"),ClientRequestSchema:n(()=>$l,"ClientRequestSchema"),ClientResultSchema:n(()=>Hl,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Pd,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>Bu,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>_l,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>wl,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Rl,"CompleteResultSchema"),ContentBlockSchema:n(()=>Uu,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>sl,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>il,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>al,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>cl,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Al,"CreateTaskResultSchema"),CursorSchema:n(()=>ud,"CursorSchema"),DiscoverRequestSchema:n(()=>jd,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>Ri,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>as,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>pl,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>ml,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>cs,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>gl,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>hl,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>fl,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>xu,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>vd,"EmptyResultSchema"),EnumSchemaSchema:n(()=>ll,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Iu,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Tu,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>qu,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>Ml,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>ql,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Ol,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>Ul,"GetTaskResultSchema"),IconSchema:n(()=>Td,"IconSchema"),IconsSchema:n(()=>Ed,"IconsSchema"),ImageContentSchema:n(()=>ku,"ImageContentSchema"),ImplementationSchema:n(()=>Ad,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>Ud,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>Md,"InitializeRequestSchema"),InitializeResultSchema:n(()=>zd,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>Nd,"InitializedNotificationSchema"),JSONArraySchema:n(()=>cd,"JSONArraySchema"),JSONObjectSchema:n(()=>ad,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>Xn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>wi,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>Si,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Wt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>bd,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>_i,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>id,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Ti,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>bi,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>vu,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Cu,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>tu,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>ru,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Qd,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>eu,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>vl,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Cl,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>zl,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>Nl,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>$u,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>Lu,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>Vu,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Zu,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>Yu,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Xu,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Qu,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>ul,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>Sd,"NotificationSchema"),NotificationsParamsSchema:n(()=>yd,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>is,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>Bd,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>Jd,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Fd,"PaginatedResultSchema"),PingRequestSchema:n(()=>Dd,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>Ai,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>Ld,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Hd,"ProgressNotificationSchema"),ProgressSchema:n(()=>$d,"ProgressSchema"),ProgressTokenSchema:n(()=>dd,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Ru,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>zu,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>Mu,"PromptMessageSchema"),PromptReferenceSchema:n(()=>Sl,"PromptReferenceSchema"),PromptSchema:n(()=>bu,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>ou,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>su,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>iu,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>pd,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Rd,"RequestIdSchema"),RequestMetaSchema:n(()=>md,"RequestMetaSchema"),RequestSchema:n(()=>gd,"RequestSchema"),ResourceContentsSchema:n(()=>Gd,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Ou,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>au,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>nu,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>Yd,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>yl,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Xd,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>_u,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>wu,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>_d,"ResultMetaObjectSchema"),ResultSchema:n(()=>wd,"ResultSchema"),RoleSchema:n(()=>Wd,"RoleSchema"),RootSchema:n(()=>bl,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Il,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>rl,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>nl,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>ol,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>qd,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>Jl,"ServerNotificationSchema"),ServerRequestSchema:n(()=>Bl,"ServerRequestSchema"),ServerResultSchema:n(()=>Fl,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>xd,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>Ku,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>Wu,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>dl,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>ss,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>cu,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>du,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>pu,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>fu,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>gu,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>mu,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>hu,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>yu,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>Su,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>fd,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Tl,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>ld,"TaskMetadataSchema"),TaskSchema:n(()=>kl,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Pl,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>xl,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>El,"TaskStatusSchema"),TextContentSchema:n(()=>Eu,"TextContentSchema"),TextResourceContentsSchema:n(()=>Vd,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>ki,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>Ii,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>Nu,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>el,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>ju,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>Gu,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>tl,"ToolResultContentSchema"),ToolSchema:n(()=>Du,"ToolSchema"),ToolUseContentSchema:n(()=>Pu,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>uu,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>lu,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ei,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>Ci,"UntitledSingleSelectEnumSchemaSchema")});var Tm=n(e=>Wt.safeParse(e).success,"isJSONRPCRequest"),Em=n(e=>Si.safeParse(e).success,"isJSONRPCNotification"),Fi=n(e=>_i.safeParse(e).success,"isJSONRPCResultResponse"),km=n(e=>Xn.safeParse(e).success,"isJSONRPCErrorResponse");var lo=-32020,LP=[{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:[k.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:[lo,k.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:[k.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:[k.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:[k.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:[lo],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:[k.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:[lo],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."}],HP={[k.ParseError]:400,[k.InvalidRequest]:400,[k.MethodNotFound]:404,[k.UnsupportedProtocolVersion]:400,[k.MissingRequiredClientCapability]:400,[lo]:400};function na(e,t){return Xc(e,t)}n(na,"parseSchema");function co(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(co,"shapeKeys");function Gi(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}n(Gi,"isStandardSchema");var Qp=!1,Vi="draft-2020-12";function uw(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:Vi});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().");Qp||(Qp=!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.")),o=hi(e,{target:Vi,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 o.type!==void 0?o:Am(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}n(uw,"standardSchemaToJsonSchema");function Am(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(o=>o!==null&&typeof o=="object"&&(o.type==="object"||Am(o)))}return!1}n(Am,"isProvablyObjectShapedRoot");function lw(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(lw,"formatIssue");async function Li(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>lw(o)).join(", ")}:{success:!0,data:r.value}}n(Li,"validateStandardSchema");function pw(e){let t=hi(e,{target:Vi,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(pw,"zodEmittedPattern");var mw=/\\\.\\d\{(\d+)\}/;function hw(e){let t=mw.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(s=>r.map(i=>Wn.datetime({local:o,offset:s,precision:i}))))}n(hw,"datetimeReferenceSchemas");function fw(e,t){let r;switch(e){case"email":r=[Qc()];break;case"uri":r=[ed()];break;case"date":r=[Wn.date()];break;case"date-time":r=hw(t);break}return new Set(r.map(o=>pw(o)).filter(o=>o!==void 0))}n(fw,"referencePatternsForFormat");function gw(e,t,r){return r!=="zod"?!0:fw(e,t).has(t)}n(gw,"isLibraryFormatPattern");function mo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(mo,"isJsonObject");function yw(e){try{return uw(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ge(k.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(yw,"convertStandardElicitationSchema");var Sw=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function oa(e){return Sw.has(e)||e.startsWith("x-")}n(oa,"isAnnotationOnlyJsonSchemaKeyword");var _w=new Set(["$schema",...Object.keys(as.shape.requestedSchema.shape)]),em={string:co([ss,Ci,Ii,Ti]),number:co([is]),integer:co([is]),boolean:co([vi]),array:co([Ei,ki])},ww=new Set(ss.shape.format.unwrap().options);function Rw(e,t,r,o){if(!mo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(em,e.type)?em[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||oa(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?ww.has(e.format)?(typeof c!="string"||!gw(e.format,c,r))&&o.push(`${t}.${a}`):i[a]=c:o.push(`${t}.${a}`);return i}n(Rw,"walkProperty");function bw(e,t){let r={},o=[];for(let[s,i]of Object.entries(e))s==="properties"&&mo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Rw(c,`properties.${a}`,t,o)])):_w.has(s)?r[s]=i:oa(s)||o.push(s);if(o.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(bw,"walkRequestedSchema");function vw(e,t){if(!mo(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!na(Ai,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(vw,"describeUnsupportedProperties");function Ki(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Ki(o,t[s],`${r}[${s}]`)):!mo(e)||!mo(t)?[]:Object.entries(e).flatMap(([o,s])=>{let i=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Ki(s,t[o],i):oa(o)?[]:[i]})}n(Ki,"findDroppedConstraintPaths");function Cw(e){if(!Gi(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=bw(yw(e.requestedSchema),t),o=na(as.shape.requestedSchema,r);if(!o.success)throw new ge(k.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${vw(r,o.error.message)}`);let s=Ki(r,o.data);if(s.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(o.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(o.data.properties,a));if(i.length>0)throw new ge(k.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Cw,"normalizeElicitInputParams");function Iw(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}}}n(Iw,"buildInputRequired");var BP=Object.assign(Iw,{elicit(e){try{return{method:"elicitation/create",params:Cw(e)}}catch(t){throw t instanceof ge?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 Tw=["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"],Ew={IdJagTokenExchangeResponseSchema:Pi,OAuthClientInformationFullSchema:Zt,OAuthClientInformationSchema:Qn,OAuthClientMetadataSchema:Vl,OAuthClientRegistrationErrorSchema:Kl,OAuthErrorResponseSchema:ds,OAuthMetadataSchema:Ir,OAuthProtectedResourceMetadataSchema:Cr,OAuthTokenRevocationRequestSchema:Wl,OAuthTokensSchema:Rt,OpenIdProviderDiscoveryMetadataSchema:Tr,OpenIdProviderMetadataSchema:Gl},Pm={},xm={};function Om(e,t){let r=e.slice(0,-6);Pm[r]=t,xm[r]=o=>t.safeParse(o).success}n(Om,"register");for(let e of Tw)Om(e,dw[e]);for(let[e,t]of Object.entries(Ew))Om(e,t);var kw=Object.freeze(Pm),Aw=Object.freeze(xm);function Pw(e){switch(e){case"initialize":case"notifications/initialized":return po(void 0);case"server/discover":return po(ra);default:return}}n(Pw,"bootstrapOutboundCodec");var Um=6e4,xw=[wr,Zn,br,Yn],Ow=["inputResponses","requestState"];function tm(e,t){let r=e.params;if(!Hi(r))return{message:e,lifted:{}};let o=r._meta,s=Hi(o)?xw.filter(d=>d in o):[],i=t==="request"?Ow.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&Hi(o)){let d={},l={...o};for(let m of s)d[m]=o[m],delete l[m];a.envelope=d,Object.keys(l).length>0?c._meta=l: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}}n(tm,"liftWireOnlyMaterial");function rm(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(o){let s=e.validateResult(t,o);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}n(rm,"codecResultValidator");function Mm(e){return()=>e}n(Mm,"requestStateAccessor");var Uw=Mm(void 0),Mw,qw=class{static{n(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{Mw=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??yi,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 de(fe.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,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_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 de(fe.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 o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Fi(s)||km(s)?this._onresponse(s):Tm(s)?this._onrequest(s,i):Em(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 o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new de(fe.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=tm(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Yp(t.classification);if(a!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${o.era}`));return}}if($i(r.method)&&!o.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,o)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:o}=tm(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=n((S,w,x)=>{let I={jsonrpc:"2.0",id:r.id,error:{code:S,message:w,...x!==void 0&&{data:x}}};i?.send(I).catch(O=>this._onerror(new Error(`Failed to send an error response: ${O}`)))},"sendErrorResponse");if(t?.classification!==void 0){let S=Yp(t.classification);if(S!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${S} but this instance serves ${s.era}`));let w=t.classification.revision??S;a(k.UnsupportedProtocolVersion,`Unsupported protocol version: ${w}`,{supported:this._supportedProtocolVersions,requested:w});return}}if(Di(r.method)&&!s.hasRequestMethod(r.method)&&!(Xp(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(k.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(k.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(o);if(d!==void 0){a(k.InvalidParams,d);return}let l=n((S,w)=>this._notificationViaCodec(this._resolveOutboundCodec(S.method),S,{...w,relatedRequestId:r.id}),"sendNotification"),m=n((S,w,x)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(S.method),S,w,{...x,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let y=o.inputResponses===void 0?void 0:zw(o.inputResponses),f={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:o.requestState===void 0?Uw:Mm(o.requestState),signal:h.signal,send:n(((S,w,x)=>{let I=this._resolveOutboundCodec(S.method);if(this._assertOutboundRequestInEra(I,S.method),Gi(w))return m(S,w,x);let O=rm(I,S.method);if(O===void 0)throw new TypeError(`'${S.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(S,O,w)}),"send"),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},R=this.buildContext(f,t);Promise.resolve().then(()=>c(r,R)).then(async S=>{if(h.signal.aborted)return;let w;try{w=s.encodeResult(r.method,S,this._outboundServerInfo())}catch(I){this._onerror(new Error(`Failed to encode result for ${r.method}: ${I}`)),a(k.InternalError,"Internal error");return}let x={result:w,jsonrpc:"2.0",id:r.id};await i?.send(x)},async S=>{if(h.signal.aborted)return;let w=Number.isSafeInteger(S.code)?S.code:k.InternalError,x={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(w),message:S.message??"Internal error",...S.data!==void 0&&{data:S.data}}};await i?.send(x)}).catch(S=>this._onerror(new Error(`Failed to send response: ${S}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),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),Fi(e)?r(e):r(ge.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 o=this._resolveOutboundCodec(e.method);if(Gi(t))return Xp(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let s=rm(o,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(o,e,s,t)}_negotiatedWireCodec(){return po(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Pw(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Di(t)&&!e.hasRequestMethod(t))throw new de(fe.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 o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=o??{},d=Date.now(),l,m;return new Promise((h,y)=>{let f=n(q=>{y(q)},"earlyReject");if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(q){f(q);return}if(o?.signal?.aborted){let q=o.signal.reason;throw q instanceof de?q:new de(fe.RequestTimeout,String(q))}let R=e.era===ra&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,S=this._requestMessageId++;m=S;let w={...t,jsonrpc:"2.0",id:S};o?.onprogress&&(this._progressHandlers.set(S,o.onprogress),w.params={...t.params,_meta:{...t.params?._meta,progressToken:S}});let x=this._envelopeOutbound(w),I=!1,O=n(q=>{I||(this._progressHandlers.delete(S),R===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(q)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(ie=>this._onerror(new Error(`Failed to send cancellation: ${ie}`))):R.abort(),y(q instanceof de?q:new de(fe.RequestTimeout,String(q))))},"cancel");this._responseHandlers.set(S,q=>{if(o?.signal?.aborted)return;if(I=!0,q instanceof Error)return y(q);let ie;try{ie=e.decodeResult(t.method,q.result)}catch(A){return y(A instanceof Error?A:new Error(String(A)))}if(ie.kind==="invalid")return y(ie.error);if(ie.kind==="input_required"){if(o?.allowInputRequired===!0)return h(Nw(ie));let A={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:d,retry:n((K,j)=>this._requestWithSchemaViaCodec(e,K===void 0?{method:t.method}:{method:t.method,params:K},r,j),"retry")};return h(this._resolveNonCompleteResult(ie,A))}let pe=ie.result;Li(r,pe).then(A=>{A.success?h(A.data):y(new de(fe.InvalidResult,`Invalid result for ${t.method}: ${A.error}`))},y)}),l=n(()=>O(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",l,{once:!0});let N=o?.timeout??Um,we=n(()=>O(new de(fe.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(S,N,o?.maxTotalTimeout,we,o?.resetTimeoutOnProgress??!1),this._transport.send(x,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:R?.signal}).catch(q=>{this._progressHandlers.delete(S),y(q)})}).finally(()=>{l&&o?.signal?.removeEventListener("abort",l),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new de(fe.NotConnected,"Not connected");if($i(t.method)&&!e.hasNotificationMethod(t.method))throw new de(fe.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 o=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(o,r).catch(s=>this._onerror(s))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!Di(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((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 ge(k.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)o=n(async(s,i)=>{let a=await Li(t.params,{...s.params});if(!a.success)throw new ge(k.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,o))}_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(!$i(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,s)=>{let i=s.validateNotification(e,o);if(!i.ok)throw i.reason==="not-in-era"?new ge(k.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 o=>{let s=await Li(t.params,{...o.params});if(!s.success)throw new ge(k.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Hi,"isPlainObject$1");function nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(nm,"isPlainObject");function zw(e){let t={},r=[];if(!nm(e))return{accepted:t,droppedKeys:r};for(let[o,s]of Object.entries(e)){if(!nm(s)||"method"in s||"result"in s){r.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:r}}n(zw,"partitionInputResponses");function Nw(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}n(Nw,"manualInputRequiredValue");var jw=Jp((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,o=/^[!#$%&'*+.^_`|~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 l=d.indexOf(";"),m=l!==-1?d.slice(0,l).trim():d.trim();if(!o.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(l!==-1){var y,f,R;for(t.lastIndex=l;f=t.exec(d);){if(f.index!==l)throw new TypeError("invalid parameter format");l+=f[0].length,y=f[1].toLowerCase(),R=f[2],R.charCodeAt(0)===34&&(R=R.slice(1,-1),R.indexOf("\\")!==-1&&(R=R.replace(r,"$1"))),h.parameters[y]=R}if(l!==d.length)throw new TypeError("invalid parameter format")}return h}n(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}n(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}n(a,"ContentType")})),JP=Gp(jw(),1);var Dw=10*1024*1024;var $w=new Set([301,302,303,307,308]),Lw=5;function Hw(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}n(Hw,"isWithinOrigin");function Bw(e,t){let r=$w.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}n(Bw,"redirectTarget");var Jw=new WeakSet;function Os(e){return Jw.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Bw(s,a);if(!c||i===Lw)return a;let d=new URL(s),l=o==="GET"||a.status===307||a.status===308,m=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!l||!m||!Hw(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}n(Os,"fetchWithinOrigin");function sa(){Zi(),ct(),O_(),Q_(),cw()}n(sa,"preloadSchemas");var rx=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 Fw=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Gw=[0,31,28,31,30,31,30,31,31,30,31,30,31],Vw=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Kw=/^(?=.{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,Ww=/^(?:[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,Zw=/^(?:(?:[^\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,Yw=/^(?:(?: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,Xw=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Qw=/^(?:\/(?:[^~/]|~0|~1)*)*$/,eR=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,tR=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,rR=n(e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.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"),nR=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,oR=/^((([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,sR=n(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 et(e){return e.test.bind(e)}n(et,"bind");var nx={date:qm,time:zm.bind(void 0,!1),"date-time":cR,duration:sR,uri:lR,"uri-reference":et(Ww),"uri-template":et(Zw),url:et(Yw),email:rR,hostname:et(Kw),ipv4:et(nR),ipv6:et(oR),regex:mR,uuid:et(Xw),"json-pointer":et(Qw),"json-pointer-uri-fragment":et(eR),"relative-json-pointer":et(tR)};function iR(e){return e%4===0&&(e%100!==0||e%400===0)}n(iR,"isLeapYear");function qm(e){let t=e.match(Fw);if(!t)return!1;let r=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o==2&&iR(r)?29:Gw[o])}n(qm,"date");function zm(e,t){let r=t.match(Vw);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(o<=23&&s<=59&&i<=59||o==23&&s==59&&i==60)&&(!e||a)}n(zm,"time");var aR=/t|\s/i;function cR(e){let t=e.split(aR);return t.length==2&&qm(t[0])&&zm(!0,t[1])}n(cR,"date_time");var dR=/\/|:/,uR=/^(?:[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 lR(e){return dR.test(e)&&uR.test(e)}n(lR,"uri");var pR=/[^\\]\\Z/;function mR(e){if(pR.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(mR,"regex");sa();var Nm=!1;var ia;ia=globalThis.crypto;async function fR(e){return(await ia).getRandomValues(new Uint8Array(e))}n(fR,"getRandomValues");async function gR(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let s=await fR(e-o.length);for(let i of s)i<r&&(o+=t[i%t.length])}return o}n(gR,"random");async function yR(e){return await gR(e)}n(yR,"generateVerifier");async function SR(e){let t=await(await ia).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(SR,"generateChallenge");async function aa(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await yR(e),r=await SR(t);return{code_verifier:t,code_challenge:r}}n(aa,"pkceChallenge");var fo=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return ze(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 ze(this,e)}constructor(e){super(e),this.name=new.target.name,Xt(this,new.target)}},ho=class extends fo{static{n(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}},pa=class extends fo{static{n(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}},qs=class extends fo{static{n(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}},Ms=class extends fo{static{n(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}},Gx=class extends fo{static{n(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 la(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}):Lm(e.issuer,t)?e:void 0}n(la,"discardIfIssuerMismatch");function Lm(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(Lm,"issuersMatch");var Vx=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return ze(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 ze(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Xt(this,new.target)}};function Hm(e){return e?.authorization_response_iss_parameter_supported===!0}n(Hm,"isIssParameterSupported");function Bm({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new ho("authorization_response",t,void 0);return}if(e!==t)throw new ho("authorization_response",t,e)}}n(Bm,"validateAuthorizationResponseIssuer");function _R(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(_R,"isClientAuthMethod");var ca="code",da="S256";function wR(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_R(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"}n(wR,"selectClientAuthMethod");function RR(e,t,r,o){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":bR(s,i,r);return;case"client_secret_post":vR(s,i,o);return;case"none":CR(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(RR,"applyClientAuthentication");function bR(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(bR,"applyBasicAuth");function vR(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(vR,"applyPostAuth");function CR(e,t){t.set("client_id",e)}n(CR,"applyPublicAuth");function Jm(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Jm,"isLoopbackHost");function IR(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Jm(t.hostname))throw new qs(t.href);return t}n(IR,"assertSecureTokenEndpoint");function TR(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Jm(r.hostname))return"native"}return"web"}n(TR,"deriveApplicationType");function ER(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??TR(t.redirect_uris)}}n(ER,"resolveClientMetadata");async function jm(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=ds.parse(JSON.parse(r));return Ct.fromResponse(o)}catch(o){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Ct(le.ServerError,s)}}n(jm,"parseErrorResponse");function Dm(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${o}. Cause: ${JSON.stringify(t.message)}`)}n(Dm,"warnCredentialInvalidation");async function ma(e,t){try{return await ua(e,t)}catch(r){if(r instanceof Ct){if(r.code===le.InvalidClient||r.code===le.UnauthorizedClient)return Dm(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ua(e,t);if(r.code===le.InvalidGrant||r.code===le.InvalidDpopProof)return Dm(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await ua(e,t)}throw r}}n(ma,"auth");function kR(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}n(kR,"determineScope");async function ua(e,{serverUrl:t,authorizationCode:r,iss:o,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let l=ER(e),m=await e.discoveryState?.(),h,y,f,R,S=i;if(!S&&m?.resourceMetadataUrl&&(S=new URL(m.resourceMetadataUrl)),m?.authorizationServerUrl){if(y=m.authorizationServerUrl,h=m.resourceMetadata,f=m.authorizationServerMetadata??await Km(y,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await Gm(t,{resourceMetadataUrl:S},a)}catch(W){if(W instanceof TypeError)throw W}(f!==m.authorizationServerMetadata||h!==m.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:S?.toString(),resourceMetadata:h,authorizationServerMetadata:f})}else{let W=await qR(t,{resourceMetadataUrl:S,fetchFn:a,skipIssuerMetadataValidation:c});y=W.authorizationServerUrl,f=W.authorizationServerMetadata,h=W.resourceMetadata,R={authorizationServerUrl:String(y),resourceMetadataUrl:S?.toString(),resourceMetadata:h,authorizationServerMetadata:f}}let w=f?.issuer??String(y),x={issuer:w};if(await e.saveAuthorizationServerUrl?.(w),r!==void 0){let W=m?.authorizationServerMetadata?.issuer??m?.authorizationServerUrl;if(W===void 0){if(e.saveDiscoveryState!==void 0)throw new Ms("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",w);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(!Lm(W,w))throw new Ms(W,w)}R&&await e.saveDiscoveryState?.(R);let I=await AR(t,e,h),O=I&&h&&!e.validateResourceURL?h.resource:I;O&&await e.saveResourceUrl?.(fa(O));let N=kR({requestedScope:s,resourceMetadata:h,authServerMetadata:f,clientMetadata:e.clientMetadata}),we=await Promise.resolve(e.clientInformation(x)),q=la(we,w,{canPersistStamp:e.saveClientInformation!==void 0});if(q===void 0&&we?.issuer&&e.saveClientInformation===void 0)throw new Ms(we.issuer,w);if(q&&q.issuer===void 0&&(q={...q,issuer:w},await e.saveClientInformation?.(q,x)),!q){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let W=f?.client_id_metadata_document_supported===!0,Z=e.clientMetadataUrl;if(Z&&!ha(Z))throw new Ct(le.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Z}`);if(W&&Z)q={client_id:Z,issuer:w},await e.saveClientInformation?.(q,x);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");q={...await $R(y,{metadata:f,clientMetadata:l,scope:N,fetchFn:a}),issuer:w},await e.saveClientInformation(q,x)}}let ie=!e.redirectUrl;if(r!==void 0||ie){r!==void 0&&Bm({iss:o,expectedIssuer:f?.issuer,issParameterSupported:Hm(f)});let W=await DR(e,y,{metadata:f,resource:O,authorizationCode:r,iss:o,scope:N,fetchFn:a});return await e.saveTokens({...W,issuer:w},x),"AUTHORIZED"}let pe=la(await e.tokens(x),w);if(pe&&pe.issuer===void 0&&(pe={...pe,issuer:w},await e.saveTokens(pe,x)),pe?.refresh_token&&!d){let W;try{W=await jR(y,{metadata:f,clientInformation:q,refreshToken:pe.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(Z){if(Z instanceof qs)throw Z;if(!(Z instanceof Ct)||Z.code===le.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(Z instanceof Error?Z.message:String(Z))}`);else throw Z}if(W)return await e.saveTokens({...W,issuer:w},x),"AUTHORIZED"}let A=e.state?await e.state():void 0,{authorizationUrl:K,codeVerifier:j}=await zR(y,{metadata:f,clientInformation:q,state:A,redirectUrl:e.redirectUrl,scope:N,resource:O});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(K),"REDIRECT"}n(ua,"authInternal");function ha(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(ha,"isHttpsUrl");async function AR(e,t,r){let o=sm(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!As({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(AR,"selectResourceURL");var PR=new Set(["bearer","dpop"]);function Fm(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!PR.has(r.toLowerCase())||!o)return{};let s=Us(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=Us(e,"scope")||void 0,c=Us(e,"error")||void 0,d=Us(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}n(Fm,"extractWWWAuthenticateParams");function Us(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(o);if(s){let i=s[1]||s[2];if(i)return i}return null}n(Us,"extractFieldFromWwwAuth");async function Gm(e,t,r=fetch){let o=await UR(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Cr.parse(await o.json())}n(Gm,"discoverOAuthProtectedResourceMetadata");async function Vm(e,t,r=fetch){let o=Os(r);try{return await o(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Nm)throw s;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(Vm,"fetchWithCorsRetry");function xR(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(xR,"buildWellKnownPath");async function $m(e,t,r=fetch){return await Vm(e,{"MCP-Protocol-Version":t},r)}n($m,"tryMetadataDiscovery");function OR(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}n(OR,"shouldAttemptFallback");async function UR(e,t,r,o){let s=new URL(e),i=o?.protocolVersion??os,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let d=xR(t,s.pathname);a=new URL(d,o?.metadataServerUrl??s),a.search=s.search}let c=await $m(a,i,r);return!o?.metadataUrl&&OR(c,s.pathname)&&(c=await $m(new URL(`/.well-known/${t}`,s),i,r)),c}n(UR,"discoverMetadataWithFallback");function MR(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),o.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"}),o}n(MR,"buildDiscoveryUrls");async function Km(e,{fetchFn:t=fetch,protocolVersion:r=os,skipIssuerValidation:o=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=MR(e);for(let{url:a,type:c}of i){let d=await Vm(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 l=c==="oauth"?Ir.parse(await d.json()):Tr.parse(await d.json());if(!o){let m=typeof e=="string"?e:e.href;if(!(l.issuer===m||m.endsWith("/")&&l.issuer===m.slice(0,-1)))throw new ho("metadata",m,l.issuer)}return l}}n(Km,"discoverAuthorizationServerMetadata");async function qR(e,t){let r,o;try{r=await Gm(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}o||(o=String(new URL("/",e)));let s=await Km(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:s,resourceMetadata:r}}n(qR,"discoverOAuthServerInfo");function fa(e){return typeof e=="string"?e:e.href}n(fa,"resourceIndicatorToString");async function zR(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ca))throw new Error(`Incompatible auth server: does not support response type ${ca}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(da))throw new Error(`Incompatible auth server: does not support code challenge method ${da}`)}else c=new URL("/authorize",e);let d=await aa(),l=d.code_verifier,m=d.code_challenge;return c.searchParams.set("response_type",ca),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",da),c.searchParams.set("redirect_uri",String(o)),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",fa(a)),{authorizationUrl:c,codeVerifier:l}}n(zR,"startAuthorization");function NR(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(NR,"prepareAuthorizationCodeRequest");async function Wm(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=IR(t?.token_endpoint??new URL("/token",e)),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",fa(i)),!s&&o&&RR(wR(o,t?.token_endpoint_auth_methods_supported??[]),o,l,r);let m=n(async()=>{let f=new Headers(l);return s&&await s(f,r,d,t),a&&f.set("DPoP",await a.buildProof({htm:"POST",htu:d})),Os(c??fetch)(d,{method:"POST",headers:f,body:r})},"requestOnce"),h=await m();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===le.UseDpopNonce&&(a.observeNonce(h,d),h=await m()),a?.observeNonce(h,d),!h.ok)throw await jm(h);let y=await h.json();try{return Rt.parse(Wi(y))}catch(f){throw typeof y=="object"&&y!==null&&"error"in y?await jm(JSON.stringify(y)):f}}n(Wm,"executeTokenRequest");async function jR(e,{metadata:t,clientInformation:r,refreshToken:o,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:o,...await Wm(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}n(jR,"refreshAuthorization");async function DR(e,t,{metadata:r,resource:o,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&Bm({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Hm(r)});let d=r?.issuer??String(t),l=n(async()=>{let f=await e.clientInformation({issuer:d}),R=la(f,d,{canPersistStamp:!1});if(f&&R===void 0)throw new Ms(String(f.issuer),d);return R},"readClientInformation"),m=await l(),h=a??e.clientMetadata.scope,y;if(e.prepareTokenRequest&&(y=await e.prepareTokenRequest(h)),!y){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");y=NR(s,await e.codeVerifier(),e.redirectUrl)}return m??=await l(),Wm(t,{metadata:r,tokenRequestParams:y,clientInformation:m,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:c})}n(DR,"fetchToken");async function $R(e,{metadata:t,clientMetadata:r,scope:o,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,...o===void 0?{}:{scope:o}},c=await Os(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new pa({status:c.status,body:await c.text(),submittedMetadata:a});return Zt.parse(Wi(await c.json()))}n($R,"registerClient");var Kx=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return ze(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 ze(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Xt(this,new.target)}};function go(e){let t=Wt.safeParse(e);return t.success?t.data.id:void 0}n(go,"parseJsonRpcRequestId");function ga(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return go(t)}catch{return}}n(ga,"readJsonRpcRequestIdFromBody");function ya(e){return Xn.parse({jsonrpc:vr,...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}}})}n(ya,"jsonRpcErrorResponse");function Zm(e){return new xs([cs.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Zm,"urlElicitationRequiredError");function It(e){return(e??"").split(";")[0].trim().toLowerCase()}n(It,"mediaTypeEssence");var LR=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function dt(e){for(let t of LR)e.delete(t);return e}n(dt,"deleteEncodedBodyHeaders");function Ym(){let e=es.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}n(Ym,"currentRuntime");var HR=new Set(["gzip","x-gzip","deflate","br","zstd"]);function Tt(e,t=Ym()){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(o=>HR.has(o.trim()))}}n(Tt,"isBodyStillEncoded");function Xm(e){return Tt(e)?e:dt(e)}n(Xm,"deleteEncodedBodyHeadersIfDecoded");function Qm(e,t=Ym()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?Tt(e,t):e.has("content-length"))?e:dt(e)}n(Qm,"deleteEncodedBodyHeadersIfRuntimeDecoded");var th=10*1024*1024,BR=1024,JR=32,FR=64,Qt=class extends Error{constructor(r,o=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=o;this.name="SseEventTooLargeError"}maxEventChars;comment;static{n(this,"SseEventTooLargeError")}},GR=10;function VR(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}n(VR,"handleRejection");function rh(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}n(rh,"fieldName");var yo=class{static{n(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#d=!1;#g=/\r\n|\r|\n/g;#s="";#u=[];#o=[];#c=0;#l=!1;#p=!1;#y=!1;#i=!1;#m=!1;#S=0;#C=0;#a=[];#h=0;#f=[];#_;#w;#R;#b=[];constructor(t={}){let r=t.maxEventChars??th;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.#i||this.#m}get idle(){return this.#c===0&&!this.#l&&!this.#i&&this.#a.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.#c>0||this.#l)&&this.#A(t,!1),this.#i||this.#P(t,!1),this.#i=!1,t}#I(t){return this.#d||t===""?t:(this.#d=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let o=0;this.#y&&(this.#y=!1,t.charCodeAt(0)===GR&&(o=1));let s=this.#g;s.lastIndex=o;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(o,i.index)),this.#A(r),o=i.index+i[0].length,i[0]==="\r"&&o===t.length&&(this.#y=!0),i=s.exec(t);this.#E(t.slice(o))}#E(t){if(t!==""){if(this.#i||this.#m){this.#l=!0;return}if(this.#c===0?this.#s=t:(this.#o.push(t),this.#o.length>=FR&&(this.#u.push(this.#o.join("")),this.#o=[])),this.#c+=t.length,this.#h+this.#c>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#m=!0,this.#S++,this.#C++):this.#k(r),this.#l=!0}}}#O(){return this.#t&&this.#a.length===0&&this.#s.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new Qt(this.#e,t);this.#x(),this.#p=!1,this.#v(),this.#i=!0,this.#S++}#v(){this.#s="",this.#u.length>0&&(this.#u=[]),this.#o.length>0&&(this.#o=[]),this.#c=0}#A(t,r=!0){let o=this.#u.length===0&&this.#o.length===0?this.#s:this.#s+this.#u.join("")+this.#o.join(""),s=o===""&&!this.#l;if(this.#v(),this.#l=!1,this.#m){this.#m=!1,this.#p=!0;return}if(s){this.#i?this.#i=!1:this.#p&&this.#a.length===0?(this.#p=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#p=!1,this.#P(t,!0));return}if(this.#i)return;if(this.#t&&r&&this.#a.length===0&&o.charCodeAt(0)===58){t.push({lines:[o],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[o.slice(1)],terminated:!0,lone:!0}),this.#p=!0;return}if(this.#h+=o.length,this.#a.push(o),this.#a.length>BR&&(this.#h+=Math.max(0,JR-o.length),this.#h>this.#e)){this.#k();return}if(o.charCodeAt(0)===58){this.#b.push(o.slice(1));return}let i=o.indexOf(":"),a=i===-1?o:o.slice(0,i),c=i===-1?"":o.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#f.push(c);break;case"event":this.#_=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#R=Number(c));break;default:break}}#P(t,r){this.#a.length>0&&t.push({lines:this.#a,data:this.#f.length>0?this.#f.join(`
26
- `):void 0,event:this.#_,id:this.#w,retry:this.#R,comments:this.#b,terminated:r}),this.#x()}#x(){this.#a=[],this.#h=0,this.#f=[],this.#_=void 0,this.#w=void 0,this.#R=void 0,this.#b=[]}};function Sa(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}n(Sa,"assertSingleLine");function _a(e){if("lines"in e){for(let o of e.lines){if(/[\r\n]/.test(o))throw new TypeError("SSE event line must not contain a line break");if(o==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(o=>`${o}
25
+ import{$ as Wi,$a as Wu,$b as ea,$c as Np,$f as Kw,$g as Bm,Aa as Xi,Ab as bl,Ac as mp,Ad as tm,Af as Rm,Ag as Mm,Ah as Xw,Ba as Cu,Bb as vl,Bc as aa,Bd as xs,Bf as Dr,Bg as oe,C as ou,Ca as Iu,Cb as Cl,Cc as ks,Cd as Os,Cf as O,Cg as Um,Da as Tu,Db as Il,Dc as As,Dd as sr,Df as Lr,Dg as Ot,E as Cs,Ea as Eu,Eb as Tl,Ec as hp,Ed as rm,Ef as $r,Eg as la,Fa as ku,Fb as El,Fc as fp,Fd as nm,Ff as dt,Fg as $s,Ga as Au,Gb as kl,Gc as gp,Gd as um,Gf as ut,Gg as pa,H as Ki,Ha as Pu,Hb as Al,Hc as yp,Hd as lm,Hf as qs,Hg as Hs,Ia as xu,Ib as Pl,Ic as Sp,Id as pm,If as Hr,Ig as bo,Ja as Ou,Jb as xl,Jc as _p,Jd as mm,Jf as Br,Jg as Vr,Ka as Mu,Kb as Ol,Kc as wp,Kd as hm,Kf as Fr,Kg as qm,La as Uu,Lb as Ml,Lc as Rp,Ld as da,Lf as zs,Lg as mt,Ma as qu,Mb as Ul,Mc as bp,Mf as bm,Mg as ma,N as su,Na as zu,Nb as ql,Nc as vp,Nf as et,Ng as Bs,Oa as Nu,Ob as zl,Oc as Cp,Of as vm,Og as zm,Pa as ju,Pb as Nl,Pc as Ip,Pf as lt,Pg as Fs,Q as iu,Qa as Du,Qb as jl,Qc as Tp,Qf as z,Qg as ha,Ra as Lu,Rb as Dl,Rc as Ep,Rf as Ns,Rg as Js,Sa as Qi,Sb as Ll,Sc as kp,Sd as fm,Sf as Ee,Sg as Nm,T as au,Ta as $u,Tb as $l,Tc as Ap,Tf as Pt,Tg as pe,Ua as Hu,Ub as Hl,Uc as Pp,Uf as $w,Ug as jm,Va as Bu,Vb as Bl,Vc as xp,Vf as Hw,Vg as Dm,Wa as Fu,Wb as Fl,Wc as Op,Wf as Bw,Wg as Lm,Xa as Ju,Xb as Jl,Xc as Mp,Xf as Fw,Xg as fa,Ya as Vu,Yb as Vl,Yc as Up,Yf as Jw,Yg as $m,Za as Gu,Zb as Gl,Zc as qp,Zf as Vw,Zg as Hm,_ as Is,_a as Ku,_b as Kl,_c as zp,_f as Gw,_g as ga,aa as Pr,ab as Zu,ac as Wl,ad as jp,ag as Ww,ah as ar,b as vs,ba as mo,bb as Yu,bc as Zl,bd as Dp,bg as Zw,bh as Fm,ca as xr,cb as Xu,cc as Yl,cd as Lp,cg as Cm,ch as vo,da as Or,db as Qu,dc as Xl,dd as $p,dg as Im,dh as Jm,ea as ho,eb as el,ec as Ql,ed as Hp,eg as js,eh as Vs,fa as rr,fb as tl,fc as ep,fd as Bp,fg as _o,fh as Co,ga as cu,gb as rl,gc as tp,gd as Fp,gg as wo,gh as Vm,ha as du,hb as nl,hc as rp,hd as Jp,hg as Jr,hh as Gm,ia as uu,ib as ol,ic as np,id as Vp,ig as Tm,ih as Km,ja as lu,jb as sl,jc as op,jd as Gp,jg as ua,jh as Wm,ka as pu,kb as il,kc as sp,kd as Mr,kg as Em,kh as Zm,la as mu,lb as al,lc as ip,ld as Ur,lg as Ro,lh as Ym,ma as hu,mb as cl,mc as ap,md as Kp,mg as Ds,mh as Xm,n as ot,na as fu,nb as dl,nc as cp,nd as qr,ng as km,nh as Qm,oa as gu,ob as ul,oc as dp,od as At,og as Am,oh as Gs,pa as yu,pb as ll,pc as up,pd as ca,pg as Pm,ph as eh,qa as Su,qb as pl,qc as ta,qd as Ps,qg as xm,qh as th,ra as _u,rb as ml,rc as Ts,rd as Wp,rg as Ce,rh as H,sa as wu,sb as hl,sc as Es,sd as go,sf as gm,sg as ge,sh as te,ta as Ru,tb as fl,tc as ra,td as or,tf as je,tg as Om,th as ya,u as Ne,ua as bu,ub as gl,uc as na,ud as Zp,uf as ym,ug as Ls,uh as ye,v as nu,va as vu,vb as yl,vc as oa,vd as Yp,vf as Sm,vg as J,vh as ht,wa as nr,wb as Sl,wc as lp,wd as Xp,wf as _m,wg as pt,wh as ae,x as V,xa as Zi,xb as _l,xc as sa,xd as Qp,xf as ie,xg as xt,xh as Ks,ya as Yi,yb as wl,yc as ia,yd as em,yf as wm,yg as ke,yh as rh,za as fo,zb as Rl,zc as pp,zd as yo,zf as jr,zg as ue,zh as Yw}from"../chunk-MUDGPSWL.js";import"../chunk-VP5Q3DEN.js";import"../chunk-AENEWA54.js";import{a as kt,b as fe,c as So,d as Ms,e as om,f as sm,g as ir,h as Us,i as im,j as am,k as zr,l as Nr,s as cm,t as dm}from"../chunk-7RNZS3GX.js";import"../chunk-A3QGJZO7.js";import{A as p,b as Ji,c as eu,d as l,e as tu,f as ru,g as E,h as N,i as Rs,k as D,l as C,m as g,n as $,o as q,p as Vi,q as lo,r as M,s as F,t as w,u as L,v as Gi,w as bs,y as po}from"../chunk-C32OTSKW.js";import"../chunk-UKQQD2JN.js";import{$ as ws,a as Te,aa as Qd,c as k,d as ee}from"../chunk-UFTMOJ7K.js";import{a as o}from"../chunk-TYV53J3B.js";var Qw=Object.create,Ws=Object.defineProperty,eR=Object.getOwnPropertyDescriptor,tR=Object.getOwnPropertyNames,rR=Object.getPrototypeOf,nR=Object.prototype.hasOwnProperty,nh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),oh=o((e,t)=>{let r={};for(var n in e)Ws(r,n,{get:e[n],enumerable:!0});return t&&Ws(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),oR=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=tR(t),i=0,a=s.length,c;i<a;i++)c=s[i],!nR.call(e,c)&&c!==r&&Ws(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=eR(t,c))||n.enumerable});return e},"__copyProps"),sh=o((e,t,r)=>(r=e!=null?Qw(rR(e)):{},oR(t||!e||!e.__esModule?Ws(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var sR=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function ih(e){return typeof e=="string"&&sR.has(e.replace(/#$/,""))}o(ih,"declares2019Dialect");var va=Symbol.for("mcp.sdk.errorBrands");function cr(e,t){let r=new Set,n=t;for(;typeof n=="function";){let s=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof s=="string"&&r.add(s),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,va,{value:r,enumerable:!1,configurable:!0})}o(cr,"stampErrorBrands");function De(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,va)){let r=t[va];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}o(De,"brandedHasInstance");var me=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Mt=class yh extends Error{static{o(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",cr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new yh(t.error,t.error_description??t.error,t.error_uri)}},Se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),le=class extends Error{static{o(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",cr(this,new.target)}},yR=class extends le{static{o(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,n){super(e,t,r,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Sh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Sh,"resourceUrlFromServerUrl");function Aa(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}o(Aa,"withoutIssuer");function ei({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(i)}o(ei,"checkResourceAllowed");var SR="2026-07-28";function _h(e){return e>=SR}o(_h,"isModernProtocolVersion");function wh(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}o(wh,"appendTextFallbackForNonObject");var Rh=["task","inputRequests","requestState"];function _R(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Rh.some(t=>t in e)?e:{...e,content:[]}}o(_R,"normalizeContentlessToolResult");function wR(){let e=Gi(()=>q([l(),E(),N(),Rs(),M(l(),e),C(e)])),t=M(l(),e),r=q([l(),E().int()]),n=l(),s=g({ttl:E().optional()}),i=g({taskId:l()}),a=$({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),m=g({_meta:a.optional()}),h=g({method:l(),params:m.loose().optional()}),f=$({_meta:a.optional()}),S=q([l(),E().int()]),R=f.strict(),_=m.extend({requestId:S.optional(),reason:l().optional()}),y=h.extend({method:w("notifications/cancelled"),params:_}),b=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),I=g({icons:C(b).optional()}),U=g({name:l(),title:l().optional()}),v=U.extend({...U.shape,...I.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),Y=lo(g({applyDefaults:N().optional()}),t),x=bs(ve=>ve&&typeof ve=="object"&&!Array.isArray(ve)&&Object.keys(ve).length===0?{form:{}}:ve,lo(g({form:Y.optional(),url:t.optional()}),t.optional())),Z=$({list:t.optional(),cancel:t.optional(),requests:$({sampling:$({createMessage:t.optional()}).optional(),elicitation:$({create:t.optional()}).optional()}).optional()}),re=$({list:t.optional(),cancel:t.optional(),requests:$({tools:$({call:t.optional()}).optional()}).optional()}),P=g({experimental:M(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:x.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Z.optional(),extensions:M(l(),t).optional()}),B=c.extend({protocolVersion:l(),capabilities:P,clientInfo:v}),j=u.extend({method:w("initialize"),params:B}),X=g({experimental:M(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:re.optional(),extensions:M(l(),t).optional()}),Q=f.extend({protocolVersion:l(),capabilities:X,serverInfo:v,instructions:l().optional()}),He=h.extend({method:w("notifications/initialized"),params:m.optional()}),Ue=u.extend({method:w("ping"),params:c.optional()}),Be=g({progress:E(),total:L(E()),message:L(l())}),K=g({...m.shape,...Be.shape,progressToken:r}),de=h.extend({method:w("notifications/progress"),params:K}),xe=c.extend({cursor:n.optional()}),ne=u.extend({params:xe.optional()}),Ye=f.extend({nextCursor:n.optional()}),fr=g({uri:l(),mimeType:L(l()),_meta:M(l(),D()).optional()}),gr=fr.extend({text:l()}),Ft=l().refine(ve=>{try{return atob(ve),!0}catch{return!1}},{message:"Invalid Base64 string"}),yr=fr.extend({blob:Ft}),nt=F(["user","assistant"]),Xe=g({audience:C(nt).optional(),priority:E().min(0).max(1).optional(),lastModified:po.datetime({offset:!0}).optional()}),Jt=g({...U.shape,...I.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(E()),annotations:Xe.optional(),_meta:L($({}))}),yn=g({...U.shape,...I.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:Xe.optional(),_meta:L($({}))}),Sn=ne.extend({method:w("resources/list")}),_n=Ye.extend({resources:C(Jt)}),Ct=ne.extend({method:w("resources/templates/list")}),Sr=Ye.extend({resourceTemplates:C(yn)}),Vt=c.extend({uri:l()}),wn=Vt,Rn=u.extend({method:w("resources/read"),params:wn}),bn=f.extend({contents:C(q([gr,yr]))}),vn=h.extend({method:w("notifications/resources/list_changed"),params:m.optional()}),Cn=Vt,In=u.extend({method:w("resources/subscribe"),params:Cn}),Tn=Vt,En=u.extend({method:w("resources/unsubscribe"),params:Tn}),kn=m.extend({uri:l()}),An=h.extend({method:w("notifications/resources/updated"),params:kn}),Pn=g({name:l(),description:L(l()),required:L(N())}),xn=g({...U.shape,...I.shape,description:L(l()),arguments:L(C(Pn)),_meta:L($({}))}),On=ne.extend({method:w("prompts/list")}),Mn=Ye.extend({prompts:C(xn)}),Un=c.extend({name:l(),arguments:M(l(),l()).optional()}),qn=u.extend({method:w("prompts/get"),params:Un}),Gt=g({type:w("text"),text:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Kt=g({type:w("image"),data:Ft,mimeType:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Wt=g({type:w("audio"),data:Ft,mimeType:l(),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),zn=g({type:w("tool_use"),name:l(),id:l(),input:M(l(),D()),_meta:M(l(),D()).optional()}),It=g({type:w("resource"),resource:q([gr,yr]),annotations:Xe.optional(),_meta:M(l(),D()).optional()}),Nn=Jt.extend({type:w("resource_link")}),Fe=q([Gt,Kt,Wt,Nn,It]),_r=g({role:nt,content:Fe}),wr=f.extend({description:l().optional(),messages:C(_r)}),Zt=h.extend({method:w("notifications/prompts/list_changed"),params:m.optional()}),jn=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Rr=g({taskSupport:F(["required","optional","forbidden"]).optional()}),Yt=g({...U.shape,...I.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:M(l(),e).optional(),required:C(l()).optional()}).catchall(D()),outputSchema:g({type:w("object"),properties:M(l(),e).optional(),required:C(l()).optional()}).catchall(D()).optional(),annotations:jn.optional(),execution:Rr.optional(),_meta:M(l(),D()).optional()}),br=ne.extend({method:w("tools/list")}),vr=Ye.extend({tools:C(Yt)}),Cr=f.extend({content:C(Fe),structuredContent:M(l(),D()).optional(),isError:N().optional()}),be=d.extend({name:l(),arguments:M(l(),D()).optional()}),Dn=u.extend({method:w("tools/call"),params:be}),os=h.extend({method:w("notifications/tools/list_changed"),params:m.optional()}),Ir=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Ln=c.extend({level:Ir}),$n=u.extend({method:w("logging/setLevel"),params:Ln}),Hn=m.extend({level:Ir,logger:l().optional(),data:D()}),Bn=h.extend({method:w("notifications/message"),params:Hn}),Fn=g({name:l().optional()}),Jn=g({hints:C(Fn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Vn=g({mode:F(["auto","required","none"]).optional()}),ss=g({type:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Fe),structuredContent:g({}).loose().optional(),isError:N().optional(),_meta:M(l(),D()).optional()}),Gn=Vi("type",[Gt,Kt,Wt]),Tt=Vi("type",[Gt,Kt,Wt,zn,ss]),Kn=g({role:nt,content:q([Tt,C(Tt)]),_meta:M(l(),D()).optional()}),Wn=d.extend({messages:C(Kn),modelPreferences:Jn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Yt).optional(),toolChoice:Vn.optional()}),Zn=u.extend({method:w("sampling/createMessage"),params:Wn}),Yn=f.extend({model:l(),stopReason:L(F(["endTurn","stopSequence","maxTokens"]).or(l())),role:nt,content:Gn}),Xn=f.extend({model:l(),stopReason:L(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:nt,content:q([Tt,C(Tt)])}),Qn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),eo=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),to=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),ro=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),no=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),oo=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),so=q([ro,no]),Xt=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),Qt=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),is=q([Xt,Qt]),as=q([oo,so,is]),qe=q([as,Qn,eo,to]),ze=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:M(l(),qe),required:C(l()).optional()}).catchall(D())}),io=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),Qe=q([ze,io]),cs=u.extend({method:w("elicitation/create"),params:Qe}),ds=m.extend({elicitationId:l()}),us=h.extend({method:w("notifications/elicitation/complete"),params:ds}),ls=f.extend({action:F(["accept","decline","cancel"]),content:bs(ve=>ve===null?void 0:ve,M(l(),q([l(),E(),N(),C(l())])).optional())}),ps=g({type:w("ref/resource"),uri:l()}),ms=g({type:w("ref/prompt"),name:l()}),hs=c.extend({ref:q([ms,ps]),argument:g({name:l(),value:l()}),context:g({arguments:M(l(),l()).optional()}).optional()}),ao=u.extend({method:w("completion/complete"),params:hs}),fs=f.extend({completion:$({values:C(l()).max(100),total:L(E().int()),hasMore:L(N())})}),gs=g({uri:l().startsWith("file://"),name:l().optional(),_meta:M(l(),D()).optional()}),Tr=u.extend({method:w("roots/list"),params:c.optional()}),co=f.extend({roots:C(gs)}),ys=h.extend({method:w("notifications/roots/list_changed"),params:m.optional()}),Ss=$({ttl:E().optional(),pollInterval:E().optional()}),uo=F(["working","input_required","completed","failed","cancelled"]),Et=g({taskId:l(),status:uo,ttl:q([E(),Rs()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:L(E()),statusMessage:L(l())}),Oe=f.extend({task:Et}),_s=m.merge(Et),er=h.extend({method:w("notifications/tasks/status"),params:_s}),Er=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),kr=f.merge(Et),Ar=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),Fi=f.loose(),Ie=ne.extend({method:w("tasks/list")}),se=Ye.extend({tasks:C(Et)}),tr=u.extend({method:w("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:m,NotificationSchema:h,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:R,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:y,IconSchema:b,IconsSchema:I,BaseMetadataSchema:U,ImplementationSchema:v,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:P,InitializeRequestParamsSchema:B,InitializeRequestSchema:j,ServerCapabilitiesSchema:X,InitializeResultSchema:Q,InitializedNotificationSchema:He,PingRequestSchema:Ue,ProgressSchema:Be,ProgressNotificationParamsSchema:K,ProgressNotificationSchema:de,PaginatedRequestParamsSchema:xe,PaginatedRequestSchema:ne,PaginatedResultSchema:Ye,ResourceContentsSchema:fr,TextResourceContentsSchema:gr,BlobResourceContentsSchema:yr,RoleSchema:nt,AnnotationsSchema:Xe,ResourceSchema:Jt,ResourceTemplateSchema:yn,ListResourcesRequestSchema:Sn,ListResourcesResultSchema:_n,ListResourceTemplatesRequestSchema:Ct,ListResourceTemplatesResultSchema:Sr,ResourceRequestParamsSchema:Vt,ReadResourceRequestParamsSchema:wn,ReadResourceRequestSchema:Rn,ReadResourceResultSchema:bn,ResourceListChangedNotificationSchema:vn,SubscribeRequestParamsSchema:Cn,SubscribeRequestSchema:In,UnsubscribeRequestParamsSchema:Tn,UnsubscribeRequestSchema:En,ResourceUpdatedNotificationParamsSchema:kn,ResourceUpdatedNotificationSchema:An,PromptArgumentSchema:Pn,PromptSchema:xn,ListPromptsRequestSchema:On,ListPromptsResultSchema:Mn,GetPromptRequestParamsSchema:Un,GetPromptRequestSchema:qn,TextContentSchema:Gt,ImageContentSchema:Kt,AudioContentSchema:Wt,ToolUseContentSchema:zn,EmbeddedResourceSchema:It,ResourceLinkSchema:Nn,ContentBlockSchema:Fe,PromptMessageSchema:_r,GetPromptResultSchema:wr,PromptListChangedNotificationSchema:Zt,ToolAnnotationsSchema:jn,ToolExecutionSchema:Rr,ToolSchema:Yt,ListToolsRequestSchema:br,ListToolsResultSchema:vr,CallToolResultSchema:Cr,CallToolRequestParamsSchema:be,CallToolRequestSchema:Dn,ToolListChangedNotificationSchema:os,LoggingLevelSchema:Ir,SetLevelRequestParamsSchema:Ln,SetLevelRequestSchema:$n,LoggingMessageNotificationParamsSchema:Hn,LoggingMessageNotificationSchema:Bn,ModelHintSchema:Fn,ModelPreferencesSchema:Jn,ToolChoiceSchema:Vn,ToolResultContentSchema:ss,SamplingContentSchema:Gn,SamplingMessageContentBlockSchema:Tt,SamplingMessageSchema:Kn,CreateMessageRequestParamsSchema:Wn,CreateMessageRequestSchema:Zn,CreateMessageResultSchema:Yn,CreateMessageResultWithToolsSchema:Xn,BooleanSchemaSchema:Qn,StringSchemaSchema:eo,NumberSchemaSchema:to,UntitledSingleSelectEnumSchemaSchema:ro,TitledSingleSelectEnumSchemaSchema:no,LegacyTitledEnumSchemaSchema:oo,SingleSelectEnumSchemaSchema:so,UntitledMultiSelectEnumSchemaSchema:Xt,TitledMultiSelectEnumSchemaSchema:Qt,MultiSelectEnumSchemaSchema:is,EnumSchemaSchema:as,PrimitiveSchemaDefinitionSchema:qe,ElicitRequestFormParamsSchema:ze,ElicitRequestURLParamsSchema:io,ElicitRequestParamsSchema:Qe,ElicitRequestSchema:cs,ElicitationCompleteNotificationParamsSchema:ds,ElicitationCompleteNotificationSchema:us,ElicitResultSchema:ls,ResourceTemplateReferenceSchema:ps,PromptReferenceSchema:ms,CompleteRequestParamsSchema:hs,CompleteRequestSchema:ao,CompleteResultSchema:fs,RootSchema:gs,ListRootsRequestSchema:Tr,ListRootsResultSchema:co,RootsListChangedNotificationSchema:ys,TaskCreationParamsSchema:Ss,TaskStatusSchema:uo,TaskSchema:Et,CreateTaskResultSchema:Oe,TaskStatusNotificationParamsSchema:_s,TaskStatusNotificationSchema:er,GetTaskRequestSchema:Er,GetTaskResultSchema:kr,GetTaskPayloadRequestSchema:Ar,GetTaskPayloadResultSchema:Fi,ListTasksRequestSchema:Ie,ListTasksResultSchema:se,CancelTaskRequestSchema:tr,CancelTaskResultSchema:f.merge(Et),ClientRequestSchema:q([Ue,j,ao,$n,qn,On,Sn,Ct,Rn,In,En,Dn,br,Er,Ar,Ie,tr]),ClientNotificationSchema:q([y,de,He,ys,er]),ClientResultSchema:q([R,Yn,Xn,ls,co,kr,se,Oe]),ServerRequestSchema:q([Ue,Zn,cs,Tr,Er,Ar,Ie,tr]),ServerNotificationSchema:q([y,de,Bn,An,vn,os,Zt,er,us]),ServerResultSchema:q([R,Q,fs,wr,Mn,_n,Sr,bn,Cr,vr,kr,se,Oe]),CallToolResultWireSchema:D().superRefine((ve,Lw)=>{if(!(typeof ve!="object"||ve===null||Array.isArray(ve)||ve.content!==void 0)){for(let Xd of Rh)if(Xd in ve){Lw.addIssue({code:"custom",message:`content is required when the body carries '${Xd}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(_R).pipe(Cr)}}o(wR,"build$1");var RR;function Pa(){return RR??=wR()}o(Pa,"buildSchemas2025");function bh(e){return e.type!=="object"}o(bh,"isNonObjectJsonSchemaRoot");var bR=new Set(["const","enum","default","examples"]),vR=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ah(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(ah,"establishesNewBase");function CR(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ah(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=ih(e.$schema)&&e.$recursiveAnchor!==!0,n=o((s,i)=>{if(Array.isArray(s))return s.map(d=>n(d,!1));if(s===null||typeof s!="object"||!i&&ah(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=n(u,!1):(d==="$ref"||d==="$dynamicRef")&&typeof u=="string"?a[d]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:d==="$recursiveRef"&&u==="#"&&r?c=!0:bR.has(d)?a[d]=u:vR.has(d)?a[d]=n(u,!0):a[d]=n(u,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}o(CR,"wrapOutputSchemaForLegacy");var vh={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ch={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},IR={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Zs;function ti(){if(Zs)return Zs;let e=Pa();return Zs={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Zs}o(ti,"registryMaps");function TR(){ti()}o(TR,"warmRegistryMaps2025");function Ih(e){return Object.prototype.hasOwnProperty.call(vh,e)}o(Ih,"hasRequestMethod2025");function Th(e){return Object.prototype.hasOwnProperty.call(Ch,e)}o(Th,"hasNotificationMethod2025");function ER(e){return Object.prototype.hasOwnProperty.call(IR,e)}o(ER,"hasResultMethod");function kR(e){return ER(e)?ti().resultSchemas[e]:void 0}o(kR,"getResultSchema");function AR(e){return Ih(e)?ti().requestSchemas[e]:void 0}o(AR,"getRequestSchema");function PR(e){return Th(e)?ti().notificationSchemas[e]:void 0}o(PR,"getNotificationSchema");var GM=Object.keys(vh),KM=Object.keys(Ch);function Ca(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ca,"isPlainObject$5");function Ys(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Ys,"triState$1");var ch={ok:!1,reason:"not-in-era"};function dh(e){return Ca(e)&&Ca(e.outputSchema)&&bh(e.outputSchema)}o(dh,"toolNeedsLegacyWrap");var xa={era:"2025-11-25",hasRequestMethod:Ih,hasNotificationMethod:Th,validateRequest:o((e,t)=>Ys(AR(e),t),"validateRequest"),validateResult:o((e,t)=>Ys(kR(e),t),"validateResult"),validateNotification:o((e,t)=>Ys(PR(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>ch,"validateInputRequest"),validateInputResponse:o(()=>ch,"validateInputResponse"),samplingResultVariant:o(((e,t)=>{let r=Pa();return Ys(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:o(e=>{},"outboundEnvelope"),validateEnvelopeMeta:o(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=wh(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&bh(t);return!s&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ca(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>dh(n))?t:{...t,tools:r.map(n=>dh(n)?{...n,outputSchema:CR(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function xR(){let e=Gi(()=>q([l(),E(),N(),Rs(),M(l(),e),C(e)])),t=M(l(),e),r=q([l(),E().int()]),n=l(),s=q([l(),E().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(se=>{try{return atob(se),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:E().optional()}),u=g({taskId:l()}),m=$({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:m.optional()}),f=h.extend({task:d.optional()}),S=g({_meta:m.optional()}),R=g({method:l(),params:S.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),y=g({icons:C(_).optional()}),b=g({name:l(),title:l().optional()}),I=b.extend({...b.shape,...y.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),U=lo(g({applyDefaults:N().optional()}),t),v=bs(se=>se&&typeof se=="object"&&!Array.isArray(se)&&Object.keys(se).length===0?{form:{}}:se,lo(g({form:U.optional(),url:t.optional()}),t.optional())),Y=$({list:t.optional(),cancel:t.optional(),requests:$({sampling:$({createMessage:t.optional()}).optional(),elicitation:$({create:t.optional()}).optional()}).optional()}),x=$({list:t.optional(),cancel:t.optional(),requests:$({tools:$({call:t.optional()}).optional()}).optional()}),Z=g({experimental:M(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:v.optional(),roots:g({listChanged:N().optional()}).optional(),tasks:Y.optional(),extensions:M(l(),t).optional()}),re=g({experimental:M(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:N().optional()}).optional(),resources:g({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:g({listChanged:N().optional()}).optional(),tasks:x.optional(),extensions:M(l(),t).optional()}),P=g({progress:E(),total:L(E()),message:L(l())}),B=g({...S.shape,...P.shape,progressToken:r}),j=R.extend({method:w("notifications/progress"),params:B}),X=S.extend({level:a,logger:l().optional(),data:D()}),Q=R.extend({method:w("notifications/message"),params:X}),He=g({uri:l(),mimeType:L(l()),_meta:M(l(),D()).optional()}),Ue=He.extend({text:l()}),Be=He.extend({blob:c}),K=g({audience:C(i).optional(),priority:E().min(0).max(1).optional(),lastModified:po.datetime({offset:!0}).optional()}),de=g({...b.shape,...y.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(E()),annotations:K.optional(),_meta:L($({}))}),xe=g({...b.shape,...y.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:K.optional(),_meta:L($({}))}),ne=R.extend({method:w("notifications/resources/list_changed"),params:S.optional()}),Ye=S.extend({uri:l()}),fr=R.extend({method:w("notifications/resources/updated"),params:Ye}),gr=g({name:l(),description:L(l()),required:L(N())}),Ft=g({...b.shape,...y.shape,description:L(l()),arguments:L(C(gr)),_meta:L($({}))}),yr=R.extend({method:w("notifications/prompts/list_changed"),params:S.optional()}),nt=g({type:w("text"),text:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),Xe=g({type:w("image"),data:c,mimeType:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),Jt=g({type:w("audio"),data:c,mimeType:l(),annotations:K.optional(),_meta:M(l(),D()).optional()}),yn=g({type:w("tool_use"),name:l(),id:l(),input:M(l(),D()),_meta:M(l(),D()).optional()}),Sn=g({type:w("resource"),resource:q([Ue,Be]),annotations:K.optional(),_meta:M(l(),D()).optional()}),_n=de.extend({type:w("resource_link")}),Ct=q([nt,Xe,Jt,_n,Sn]),Sr=g({role:i,content:Ct}),Vt=g({title:l().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),wn=R.extend({method:w("notifications/tools/list_changed"),params:S.optional()}),Rn=g({name:l().optional()}),bn=g({hints:C(Rn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),vn=g({mode:F(["auto","required","none"]).optional()}),Cn=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:N().optional()}),In=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:E().optional(),maxLength:E().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),Tn=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),En=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),kn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),An=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),Pn=q([En,kn]),xn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),On=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:E().optional(),maxItems:E().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),Mn=q([xn,On]),Un=q([An,Pn,Mn]),qn=q([Un,Cn,In,Tn]),Gt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:M(l(),qn),required:C(l()).optional()}).catchall(D())}),Kt=g({type:w("ref/resource"),uri:l()}),Wt=g({type:w("ref/prompt"),name:l()}),zn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:M(l(),D()).optional()}),It=Z.shape,Nn=g({experimental:It.experimental,sampling:It.sampling,elicitation:It.elicitation,roots:It.roots,extensions:It.extensions}),Fe=re.shape,_r=g({experimental:Fe.experimental,logging:Fe.logging,completions:Fe.completions,prompts:Fe.prompts,resources:Fe.resources,tools:Fe.tools,extensions:Fe.extensions}),wr=$({progressToken:r.optional(),[Pr]:l(),[mo]:I.optional(),[Or]:Nn,[ho]:a.optional()}),Zt=g({...b.shape,...y.shape,description:l().optional(),inputSchema:$({$schema:l().optional(),type:w("object")}),outputSchema:$({$schema:l().optional()}).optional(),annotations:Vt.optional(),_meta:M(l(),D()).optional()}),jn=g({type:w("tool_result"),toolUseId:l(),content:C(Ct),structuredContent:D().optional(),isError:N().optional(),_meta:M(l(),D()).optional()}),Rr=q([nt,Xe,Jt,yn,jn]),Yt=g({role:i,content:q([Rr,C(Rr)]),_meta:M(l(),D()).optional()}),br=l(),vr=$({[xr]:I.optional().catch(void 0)}),Cr=vr.optional();function be(se){return $({_meta:Cr,resultType:br.default("complete"),...se})}o(be,"wireResult");let Dn=be({}),os=be({nextCursor:n.optional()}),Ir=be({content:C(Ct),structuredContent:D().optional(),isError:N().optional()}),Ln=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Zt),nextCursor:n.optional()}),$n=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Ft),nextCursor:n.optional()}),Hn=be({description:l().optional(),messages:C(Sr)}),Bn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(de),nextCursor:n.optional()}),Fn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),Jn=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),Vn=be({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),ss=be({ttlMs:E().int().min(0),cacheScope:F(["public","private"])}),Gn=be({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:_r,instructions:l().optional()}),Tt=g({messages:C(Yt),modelPreferences:bn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Zt).optional(),toolChoice:vn.optional()}),Kn=g({method:w("sampling/createMessage"),params:Tt}),Wn=g({method:w("roots/list"),params:g({_meta:M(l(),D()).optional()}).optional()}),Zn=g({...Yt.shape,model:l(),stopReason:l().optional()}),Yn=g({roots:C(zn)}),Xn=g({action:F(["accept","decline","cancel"]),content:M(l(),q([l(),E(),N(),C(l())])).optional()}),Qn=g({mode:w("url"),message:l(),url:l().url()}),eo=q([Gt,Qn]),to=g({method:w("elicitation/create"),params:eo}),ro=q([Kn,Wn,to]),no=q([Zn,Yn,Xn]),oo=M(l(),ro),so=M(l(),no),Xt=be({inputRequests:oo.optional(),requestState:l().optional()}),Qt={inputResponses:so.optional(),requestState:l().optional()},is=g({_meta:wr,...Qt}),as=$({progressToken:r.optional()});function qe(se,tr){return g({method:w(se),params:g({_meta:wr,...tr})})}o(qe,"wireRequest");function ze(se,tr){return g({method:w(se),params:g({_meta:as.optional(),...tr}).optional()})}o(ze,"dispatchRequest");let io={name:l(),arguments:M(l(),D()).optional(),...Qt},Qe={cursor:n.optional()},cs=qe("tools/call",io),ds=qe("tools/list",Qe),us=qe("prompts/list",Qe),ls=qe("prompts/get",{name:l(),arguments:M(l(),l()).optional(),...Qt}),ps=qe("resources/list",Qe),ms=qe("resources/templates/list",Qe),hs=qe("resources/read",{uri:l(),...Qt}),ao={ref:q([Wt,Kt]),argument:g({name:l(),value:l()}),context:g({arguments:M(l(),l()).optional()}).optional()},fs=qe("completion/complete",ao),gs=qe("server/discover",{}),Tr=g({toolsListChanged:N().optional(),promptsListChanged:N().optional(),resourcesListChanged:N().optional(),resourceSubscriptions:C(l()).optional()}),co={notifications:Tr},ys=qe("subscriptions/listen",co),Ss=vr.extend({"io.modelcontextprotocol/subscriptionId":s}),uo=$({_meta:Ss,resultType:br.default("complete")}),Et={"tools/call":ze("tools/call",io),"tools/list":ze("tools/list",Qe),"prompts/get":ze("prompts/get",{name:l(),arguments:M(l(),l()).optional()}),"prompts/list":ze("prompts/list",Qe),"resources/list":ze("resources/list",Qe),"resources/templates/list":ze("resources/templates/list",Qe),"resources/read":ze("resources/read",{uri:l()}),"completion/complete":ze("completion/complete",ao),"server/discover":ze("server/discover",{}),"subscriptions/listen":ze("subscriptions/listen",co)};function Oe(se){return $({_meta:Cr,...se})}o(Oe,"liftedResult");let _s={"tools/call":Oe({content:C(Ct),structuredContent:D().optional(),isError:N().optional()}),"tools/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),tools:C(Zt),nextCursor:n.optional()}),"prompts/get":Oe({description:l().optional(),messages:C(Sr)}),"prompts/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),prompts:C(Ft),nextCursor:n.optional()}),"resources/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resources:C(de),nextCursor:n.optional()}),"resources/templates/list":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(xe),nextCursor:n.optional()}),"resources/read":Oe({ttlMs:E().int().min(0),cacheScope:F(["public","private"]),contents:C(q([Ue,Be]))}),"completion/complete":Oe({completion:g({values:C(l()).max(100),total:E().int().optional(),hasMore:N().optional()}).loose()}),"server/discover":Oe({ttlMs:E().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:_r,instructions:l().optional()}),"subscriptions/listen":Oe({})},er=$({"io.modelcontextprotocol/subscriptionId":s.optional()}),Er=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:er.optional(),notifications:Tr})}),kr=g({_meta:er.optional(),requestId:s,reason:l().optional()}),Ar=g({method:w("notifications/cancelled"),params:kr}),Fi={"notifications/cancelled":Ar,"notifications/progress":j,"notifications/message":Q,"notifications/resources/updated":fr,"notifications/resources/list_changed":ne,"notifications/tools/list_changed":wn,"notifications/prompts/list_changed":yr,"notifications/subscriptions/acknowledged":Er},Ie=o(se=>g({jsonrpc:w("2.0"),id:q([l(),E().int()]),result:se}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:m,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:R,IconSchema:_,IconsSchema:y,BaseMetadataSchema:b,ImplementationSchema:I,ClientTasksCapabilitySchema:Y,ServerTasksCapabilitySchema:x,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:re,ProgressSchema:P,ProgressNotificationParamsSchema:B,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:X,LoggingMessageNotificationSchema:Q,ResourceContentsSchema:He,TextResourceContentsSchema:Ue,BlobResourceContentsSchema:Be,AnnotationsSchema:K,ResourceSchema:de,ResourceTemplateSchema:xe,ResourceListChangedNotificationSchema:ne,ResourceUpdatedNotificationParamsSchema:Ye,ResourceUpdatedNotificationSchema:fr,PromptArgumentSchema:gr,PromptSchema:Ft,PromptListChangedNotificationSchema:yr,TextContentSchema:nt,ImageContentSchema:Xe,AudioContentSchema:Jt,ToolUseContentSchema:yn,EmbeddedResourceSchema:Sn,ResourceLinkSchema:_n,ContentBlockSchema:Ct,PromptMessageSchema:Sr,ToolAnnotationsSchema:Vt,ToolListChangedNotificationSchema:wn,ModelHintSchema:Rn,ModelPreferencesSchema:bn,ToolChoiceSchema:vn,BooleanSchemaSchema:Cn,StringSchemaSchema:In,NumberSchemaSchema:Tn,UntitledSingleSelectEnumSchemaSchema:En,TitledSingleSelectEnumSchemaSchema:kn,LegacyTitledEnumSchemaSchema:An,SingleSelectEnumSchemaSchema:Pn,UntitledMultiSelectEnumSchemaSchema:xn,TitledMultiSelectEnumSchemaSchema:On,MultiSelectEnumSchemaSchema:Mn,EnumSchemaSchema:Un,PrimitiveSchemaDefinitionSchema:qn,ElicitRequestFormParamsSchema:Gt,ResourceTemplateReferenceSchema:Kt,PromptReferenceSchema:Wt,RootSchema:zn,ClientCapabilities2026Schema:Nn,ServerCapabilities2026Schema:_r,RequestMetaEnvelopeSchema:wr,ToolSchema:Zt,ToolResultContentSchema:jn,SamplingMessageContentBlockSchema:Rr,SamplingMessageSchema:Yt,ResultTypeSchema:br,ResultMetaSchema:vr,ResultSchema:Dn,PaginatedResultSchema:os,CallToolResultSchema:Ir,ListToolsResultSchema:Ln,ListPromptsResultSchema:$n,GetPromptResultSchema:Hn,ListResourcesResultSchema:Bn,ListResourceTemplatesResultSchema:Fn,ReadResourceResultSchema:Jn,CompleteResultSchema:Vn,CacheableResultSchema:ss,DiscoverResultSchema:Gn,CreateMessageRequestParamsSchema:Tt,CreateMessageRequestSchema:Kn,ListRootsRequestSchema:Wn,CreateMessageResultSchema:Zn,ListRootsResultSchema:Yn,ElicitResultSchema:Xn,ElicitRequestURLParamsSchema:Qn,ElicitRequestParamsSchema:eo,ElicitRequestSchema:to,InputRequestSchema:ro,InputResponseSchema:no,InputRequestsSchema:oo,InputResponsesSchema:so,InputRequiredResultSchema:Xt,InputResponseRequestParamsSchema:is,CallToolRequestSchema:cs,ListToolsRequestSchema:ds,ListPromptsRequestSchema:us,GetPromptRequestSchema:ls,ListResourcesRequestSchema:ps,ListResourceTemplatesRequestSchema:ms,ReadResourceRequestSchema:hs,CompleteRequestSchema:fs,DiscoverRequestSchema:gs,SubscriptionFilterSchema:Tr,SubscriptionsListenRequestSchema:ys,SubscriptionsListenResultMetaSchema:Ss,SubscriptionsListenResultSchema:uo,dispatchRequestSchemas:Et,dispatchResultSchemas:_s,NotificationMetaSchema:er,SubscriptionsAcknowledgedNotificationSchema:Er,CancelledNotificationParamsSchema:kr,CancelledNotificationSchema:Ar,notificationSchemas2026:Fi,JSONRPCResultResponseSchema:Ie(Dn),CallToolResultResponseSchema:Ie(q([Ir,Xt])),ListToolsResultResponseSchema:Ie(Ln),ListPromptsResultResponseSchema:Ie($n),GetPromptResultResponseSchema:Ie(q([Hn,Xt])),ListResourcesResultResponseSchema:Ie(Bn),ListResourceTemplatesResultResponseSchema:Ie(Fn),ReadResourceResultResponseSchema:Ie(q([Jn,Xt])),CompleteResultResponseSchema:Ie(Vn),DiscoverResultResponseSchema:Ie(Gn),SubscriptionsListenResultResponseSchema:Ie(uo)}}o(xR,"build");var OR;function ft(){return OR??=xR()}o(ft,"buildSchemas2026");var MR=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function UR(e){return MR.includes(e)}o(UR,"isCacheableResultMethod");var Oa=Symbol("modelcontextprotocol.resultCacheHintFallback");function qR(e){return e[Oa]}o(qR,"cacheHintFallbackOf");function Eh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(Eh,"isValidCacheTtlMs");function kh(e){return e==="public"||e==="private"}o(kh,"isValidCacheScope");var A=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),_e=class Ah extends Error{static{o(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return De(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",cr(this,new.target)}static fromError(t,r,n){if(t===A.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ri(s.elicitations,r)}if(t===A.UnsupportedProtocolVersion&&n){let s=n;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new xh({supported:s.supported,requested:s.requested},r)}if(t===A.InvalidParams||t===A.ResourceNotFound){let s=n;if(typeof s?.uri=="string"&&(t===A.ResourceNotFound||Object.keys(s).length===1))return new Ph(s.uri,r)}if(t===A.MissingRequiredClientCapability&&n){let s=n;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new Oh({requiredCapabilities:s.requiredCapabilities},r)}return new Ah(t,r,n)}},Ph=class extends _e{static{o(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(A.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ri=class extends _e{static{o(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},xh=class extends _e{static{o(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(A.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Oh=class extends _e{static{o(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(A.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},zR=0,NR="private",jR=["tools/call","prompts/get","resources/read"];function DR(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||jR.includes(e))return t;throw new _e(A.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}o(DR,"stampResultType");function LR(e,t){let r=qR(t);if(t.resultType!=="complete"||!UR(e))return r===void 0?t:JR(t);let n=t,s=Eh(n.ttlMs)?n.ttlMs:BR(r),i=kh(n.cacheScope)?n.cacheScope:FR(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Oa],a}o(LR,"fillCacheFields");function $R(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o($R,"isPlainObject$4");function HR(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[xr]:t}}:!$R(r)||r[xr]!==void 0?e:{...e,_meta:{...r,[xr]:t}}}o(HR,"stampServerInfoMeta");function BR(e){return e!==void 0&&Eh(e.ttlMs)?e.ttlMs:zR}o(BR,"resolveTtlMs");function FR(e){return e!==void 0&&kh(e.cacheScope)?e.cacheScope:NR}o(FR,"resolveCacheScope");function JR(e){let t={...e};return delete t[Oa],t}o(JR,"stripCacheHintFallback");var VR=["elicitation/create","sampling/createMessage","roots/list"],Xs;function Ma(){if(Xs)return Xs;let e=ft();return Xs={request:{"elicitation/create":g({method:w("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:w("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:w("roots/list"),params:$({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Xs}o(Ma,"inputSchemaMaps");function GR(){Ma()}o(GR,"warmInputSchemaMaps2026");function Mh(e){return VR.includes(e)}o(Mh,"isInputRequestMethod2026");function Sa(e){return Mh(e)?Ma().request[e]:void 0}o(Sa,"getInputRequestSchema2026");function KR(e){return Mh(e)?Ma().response[e]:void 0}o(KR,"getInputResponseSchema2026");var Ua={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Uh={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function qh(e){return Object.prototype.hasOwnProperty.call(Ua,e)}o(qh,"hasRequestMethod2026");function zh(e){return Object.prototype.hasOwnProperty.call(Uh,e)}o(zh,"hasNotificationMethod2026");function WR(e){return Object.prototype.hasOwnProperty.call(Ua,e)}o(WR,"hasResultMethod2026");function ZR(e){return qh(e)?ft().dispatchRequestSchemas[e]:void 0}o(ZR,"getRequestSchema2026");function YR(e){return WR(e)?ft().dispatchResultSchemas[e]:void 0}o(YR,"getResultSchema2026");function XR(e){return zh(e)?ft().notificationSchemas2026[e]:void 0}o(XR,"getNotificationSchema2026");var WM=Object.keys(Ua),ZM=Object.keys(Uh);function Eo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Eo,"isPlainObject$3");function Io(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Io,"triState");var QR={ok:!1,reason:"not-in-era"},eb=[Pr,Or];function tb(e,t){let r=t,n=!1,s=o(()=>(n||(r={...r},n=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>Eo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!Eo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(Eo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}o(tb,"enforceDeletedFields");var qa={era:"2026-07-28",hasRequestMethod:qh,hasNotificationMethod:zh,hasInputRequestMethod:o(e=>Sa(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>Io(ZR(e),t),"validateRequest"),validateResult:o((e,t)=>Io(YR(e),t),"validateResult"),validateNotification:o((e,t)=>Io(XR(e),t),"validateNotification"),validateInputRequest:o((e,t)=>Io(Sa(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>Io(KR(e),t),"validateInputResponse"),samplingResultVariant:o(()=>QR,"samplingResultVariant"),outboundEnvelope(e){return{[Pr]:e.protocolVersion,[mo]:e.clientInfo,[Or]:e.clientCapabilities,...e.logLevel!==void 0&&{[ho]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of eb)n in e||t.push({key:n,problem:"missing"});let r=ft().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let s=n.path.map(String),i=s.length>0?s.join("."):"_meta";s.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:o(e=>wh(e),"projectCallToolResult"),inputRequestSchema:Sa,decodeResult(e,t){if(!Eo(t))return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Eo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:ft().ResultMetaSchema.safeParse(t._meta),m=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new le(Se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=Nh(),s=Object.hasOwn(n,e)?n[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new le(Se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return HR(LR(e,DR(e,tb(e,t))),r)},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=ft().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Qs;function Nh(){if(Qs)return Qs;let e=ft();return Qs={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Qs}o(Nh,"getWireResultSchemas");function rb(){Nh()}o(rb,"warmWireResultSchemas2026");var za="2026-07-28";function Ao(e){return e!==void 0&&_h(e)?qa:xa}o(Ao,"codecForVersion");function uh(e){return e.revision!==void 0?Ao(e.revision).era:e.era==="modern"?qa.era:xa.era}o(uh,"classifiedWireEra");function _a(e){return jh.some(t=>t.hasRequestMethod(e))}o(_a,"isSpecRequestMethod");function wa(e){return jh.some(t=>t.hasNotificationMethod(e))}o(wa,"isSpecNotificationMethod");function lh(e){return e==="tasks/get"||e==="tasks/cancel"}o(lh,"isExtensionReusedRequestMethod");var jh=[xa,qa],nb=oh({AnnotationsSchema:o(()=>Xu,"AnnotationsSchema"),AudioContentSchema:o(()=>xl,"AudioContentSchema"),BaseMetadataSchema:o(()=>Pu,"BaseMetadataSchema"),BaseRequestParamsSchema:o(()=>gu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:o(()=>Zu,"BlobResourceContentsSchema"),BooleanSchemaSchema:o(()=>ta,"BooleanSchemaSchema"),CallToolRequestParamsSchema:o(()=>Vl,"CallToolRequestParamsSchema"),CallToolRequestSchema:o(()=>Gl,"CallToolRequestSchema"),CallToolResultSchema:o(()=>Fl,"CallToolResultSchema"),CancelTaskRequestSchema:o(()=>Lp,"CancelTaskRequestSchema"),CancelTaskResultSchema:o(()=>$p,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:o(()=>Tu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:o(()=>Eu,"CancelledNotificationSchema"),ClientCapabilitiesSchema:o(()=>Uu,"ClientCapabilitiesSchema"),ClientNotificationSchema:o(()=>Bp,"ClientNotificationSchema"),ClientRequestSchema:o(()=>Hp,"ClientRequestSchema"),ClientResultSchema:o(()=>Fp,"ClientResultSchema"),ClientTasksCapabilitySchema:o(()=>Ou,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:o(()=>Jl,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:o(()=>Rp,"CompleteRequestParamsSchema"),CompleteRequestSchema:o(()=>bp,"CompleteRequestSchema"),CompleteResultSchema:o(()=>vp,"CompleteResultSchema"),ContentBlockSchema:o(()=>ql,"ContentBlockSchema"),CreateMessageRequestParamsSchema:o(()=>ap,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:o(()=>cp,"CreateMessageRequestSchema"),CreateMessageResultSchema:o(()=>dp,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:o(()=>up,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:o(()=>xp,"CreateTaskResultSchema"),CursorSchema:o(()=>pu,"CursorSchema"),DiscoverRequestSchema:o(()=>Lu,"DiscoverRequestSchema"),DiscoverResultSchema:o(()=>Qi,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:o(()=>ks,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:o(()=>hp,"ElicitRequestParamsSchema"),ElicitRequestSchema:o(()=>fp,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:o(()=>As,"ElicitRequestURLParamsSchema"),ElicitResultSchema:o(()=>Sp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:o(()=>gp,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:o(()=>yp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:o(()=>Ml,"EmbeddedResourceSchema"),EmptyResultSchema:o(()=>Iu,"EmptyResultSchema"),EnumSchemaSchema:o(()=>mp,"EnumSchemaSchema"),GetPromptRequestParamsSchema:o(()=>El,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:o(()=>kl,"GetPromptRequestSchema"),GetPromptResultSchema:o(()=>Nl,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:o(()=>zp,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:o(()=>Np,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:o(()=>Up,"GetTaskRequestSchema"),GetTaskResultSchema:o(()=>qp,"GetTaskResultSchema"),IconSchema:o(()=>ku,"IconSchema"),IconsSchema:o(()=>Au,"IconsSchema"),ImageContentSchema:o(()=>Pl,"ImageContentSchema"),ImplementationSchema:o(()=>xu,"ImplementationSchema"),InitializeRequestParamsSchema:o(()=>qu,"InitializeRequestParamsSchema"),InitializeRequestSchema:o(()=>zu,"InitializeRequestSchema"),InitializeResultSchema:o(()=>ju,"InitializeResultSchema"),InitializedNotificationSchema:o(()=>Du,"InitializedNotificationSchema"),JSONArraySchema:o(()=>uu,"JSONArraySchema"),JSONObjectSchema:o(()=>du,"JSONObjectSchema"),JSONRPCErrorResponseSchema:o(()=>fo,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:o(()=>Xi,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:o(()=>Zi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:o(()=>nr,"JSONRPCRequestSchema"),JSONRPCResponseSchema:o(()=>Cu,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:o(()=>Yi,"JSONRPCResultResponseSchema"),JSONValueSchema:o(()=>cu,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:o(()=>oa,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:o(()=>ea,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:o(()=>Il,"ListPromptsRequestSchema"),ListPromptsResultSchema:o(()=>Tl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:o(()=>nl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:o(()=>ol,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:o(()=>tl,"ListResourcesRequestSchema"),ListResourcesResultSchema:o(()=>rl,"ListResourcesResultSchema"),ListRootsRequestSchema:o(()=>Ip,"ListRootsRequestSchema"),ListRootsResultSchema:o(()=>Tp,"ListRootsResultSchema"),ListTasksRequestSchema:o(()=>jp,"ListTasksRequestSchema"),ListTasksResultSchema:o(()=>Dp,"ListTasksResultSchema"),ListToolsRequestSchema:o(()=>Hl,"ListToolsRequestSchema"),ListToolsResultSchema:o(()=>Bl,"ListToolsResultSchema"),LoggingLevelSchema:o(()=>Wl,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:o(()=>Xl,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:o(()=>Ql,"LoggingMessageNotificationSchema"),ModelHintSchema:o(()=>ep,"ModelHintSchema"),ModelPreferencesSchema:o(()=>tp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:o(()=>pp,"MultiSelectEnumSchemaSchema"),NotificationSchema:o(()=>wu,"NotificationSchema"),NotificationsParamsSchema:o(()=>_u,"NotificationsParamsSchema"),NumberSchemaSchema:o(()=>Es,"NumberSchemaSchema"),PaginatedRequestParamsSchema:o(()=>Ju,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:o(()=>Vu,"PaginatedRequestSchema"),PaginatedResultSchema:o(()=>Gu,"PaginatedResultSchema"),PingRequestSchema:o(()=>$u,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:o(()=>aa,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:o(()=>Bu,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:o(()=>Fu,"ProgressNotificationSchema"),ProgressSchema:o(()=>Hu,"ProgressSchema"),ProgressTokenSchema:o(()=>lu,"ProgressTokenSchema"),PromptArgumentSchema:o(()=>vl,"PromptArgumentSchema"),PromptListChangedNotificationSchema:o(()=>jl,"PromptListChangedNotificationSchema"),PromptMessageSchema:o(()=>zl,"PromptMessageSchema"),PromptReferenceSchema:o(()=>wp,"PromptReferenceSchema"),PromptSchema:o(()=>Cl,"PromptSchema"),ReadResourceRequestParamsSchema:o(()=>il,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:o(()=>al,"ReadResourceRequestSchema"),ReadResourceResultSchema:o(()=>cl,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:o(()=>hu,"RelatedTaskMetadataSchema"),RequestIdSchema:o(()=>vu,"RequestIdSchema"),RequestMetaSchema:o(()=>fu,"RequestMetaSchema"),RequestSchema:o(()=>Su,"RequestSchema"),ResourceContentsSchema:o(()=>Ku,"ResourceContentsSchema"),ResourceLinkSchema:o(()=>Ul,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:o(()=>dl,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:o(()=>sl,"ResourceRequestParamsSchema"),ResourceSchema:o(()=>Qu,"ResourceSchema"),ResourceTemplateReferenceSchema:o(()=>_p,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:o(()=>el,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:o(()=>Rl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:o(()=>bl,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:o(()=>Ru,"ResultMetaObjectSchema"),ResultSchema:o(()=>bu,"ResultSchema"),RoleSchema:o(()=>Yu,"RoleSchema"),RootSchema:o(()=>Cp,"RootSchema"),RootsListChangedNotificationSchema:o(()=>Ep,"RootsListChangedNotificationSchema"),SamplingContentSchema:o(()=>op,"SamplingContentSchema"),SamplingMessageContentBlockSchema:o(()=>sp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:o(()=>ip,"SamplingMessageSchema"),ServerCapabilitiesSchema:o(()=>Nu,"ServerCapabilitiesSchema"),ServerNotificationSchema:o(()=>Vp,"ServerNotificationSchema"),ServerRequestSchema:o(()=>Jp,"ServerRequestSchema"),ServerResultSchema:o(()=>Gp,"ServerResultSchema"),ServerTasksCapabilitySchema:o(()=>Mu,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:o(()=>Zl,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:o(()=>Yl,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:o(()=>lp,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:o(()=>Ts,"StringSchemaSchema"),SubscribeRequestParamsSchema:o(()=>ul,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:o(()=>ll,"SubscribeRequestSchema"),SubscriptionFilterSchema:o(()=>hl,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:o(()=>yl,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:o(()=>Sl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:o(()=>fl,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:o(()=>gl,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:o(()=>_l,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:o(()=>wl,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:o(()=>yu,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:o(()=>kp,"TaskCreationParamsSchema"),TaskMetadataSchema:o(()=>mu,"TaskMetadataSchema"),TaskSchema:o(()=>Pp,"TaskSchema"),TaskStatusNotificationParamsSchema:o(()=>Op,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:o(()=>Mp,"TaskStatusNotificationSchema"),TaskStatusSchema:o(()=>Ap,"TaskStatusSchema"),TextContentSchema:o(()=>Al,"TextContentSchema"),TextResourceContentsSchema:o(()=>Wu,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:o(()=>ia,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:o(()=>na,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:o(()=>Dl,"ToolAnnotationsSchema"),ToolChoiceSchema:o(()=>rp,"ToolChoiceSchema"),ToolExecutionSchema:o(()=>Ll,"ToolExecutionSchema"),ToolListChangedNotificationSchema:o(()=>Kl,"ToolListChangedNotificationSchema"),ToolResultContentSchema:o(()=>np,"ToolResultContentSchema"),ToolSchema:o(()=>$l,"ToolSchema"),ToolUseContentSchema:o(()=>Ol,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:o(()=>pl,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:o(()=>ml,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:o(()=>sa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:o(()=>ra,"UntitledSingleSelectEnumSchemaSchema")});var Dh=o(e=>nr.safeParse(e).success,"isJSONRPCRequest"),Lh=o(e=>Zi.safeParse(e).success,"isJSONRPCNotification"),Ia=o(e=>Yi.safeParse(e).success,"isJSONRPCResultResponse"),$h=o(e=>fo.safeParse(e).success,"isJSONRPCErrorResponse");var ko=-32020,YM=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[A.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[ko,A.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[A.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[A.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[A.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[ko],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[A.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[ko],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],XM={[A.ParseError]:400,[A.InvalidRequest]:400,[A.MethodNotFound]:404,[A.UnsupportedProtocolVersion]:400,[A.MissingRequiredClientCapability]:400,[ko]:400};function Na(e,t){return eu(e,t)}o(Na,"parseSchema");function To(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}o(To,"shapeKeys");function Ta(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}o(Ta,"isStandardSchema");var ph=!1,Ea="draft-2020-12";function ob(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Ea});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");ph||(ph=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=Ji(e,{target:Ea,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Hh(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}o(ob,"standardSchemaToJsonSchema");function Hh(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Hh(n)))}return!1}o(Hh,"isProvablyObjectShapedRoot");function sb(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(sb,"formatIssue");async function Ra(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>sb(n)).join(", ")}:{success:!0,data:r.value}}o(Ra,"validateStandardSchema");function ib(e){let t=Ji(e,{target:Ea,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(ib,"zodEmittedPattern");var ab=/\\\.\\d\{(\d+)\}/;function cb(e){let t=ab.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(s=>r.map(i=>po.datetime({local:n,offset:s,precision:i}))))}o(cb,"datetimeReferenceSchemas");function db(e,t){let r;switch(e){case"email":r=[tu()];break;case"uri":r=[ru()];break;case"date":r=[po.date()];break;case"date-time":r=cb(t);break}return new Set(r.map(n=>ib(n)).filter(n=>n!==void 0))}o(db,"referencePatternsForFormat");function ub(e,t,r){return r!=="zod"?!0:db(e,t).has(t)}o(ub,"isLibraryFormatPattern");function Po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Po,"isJsonObject");function lb(e){try{return ob(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new _e(A.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}o(lb,"convertStandardElicitationSchema");var pb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function ja(e){return pb.has(e)||e.startsWith("x-")}o(ja,"isAnnotationOnlyJsonSchemaKeyword");var mb=new Set(["$schema",...Object.keys(ks.shape.requestedSchema.shape)]),mh={string:To([Ts,ra,na,oa]),number:To([Es]),integer:To([Es]),boolean:To([ta]),array:To([sa,ia])},hb=new Set(Ts.shape.format.unwrap().options);function fb(e,t,r,n){if(!Po(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(mh,e.type)?mh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||ja(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?hb.has(e.format)?(typeof c!="string"||!ub(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(fb,"walkProperty");function gb(e,t){let r={},n=[];for(let[s,i]of Object.entries(e))s==="properties"&&Po(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,fb(c,`properties.${a}`,t,n)])):mb.has(s)?r[s]=i:ja(s)||n.push(s);if(n.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}o(gb,"walkRequestedSchema");function yb(e,t){if(!Po(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!Na(aa,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}o(yb,"describeUnsupportedProperties");function ka(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,s)=>ka(n,t[s],`${r}[${s}]`)):!Po(e)||!Po(t)?[]:Object.entries(e).flatMap(([n,s])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?ka(s,t[n],i):ja(n)?[]:[i]})}o(ka,"findDroppedConstraintPaths");function Sb(e){if(!Ta(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=gb(lb(e.requestedSchema),t),n=Na(ks.shape.requestedSchema,r);if(!n.success)throw new _e(A.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${yb(r,n.error.message)}`);let s=ka(r,n.data);if(s.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new _e(A.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}o(Sb,"normalizeElicitInputParams");function _b(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}o(_b,"buildInputRequired");var QM=Object.assign(_b,{elicit(e){try{return{method:"elicitation/create",params:Sb(e)}}catch(t){throw t instanceof _e?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var wb=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Rb={IdJagTokenExchangeResponseSchema:ca,OAuthClientInformationFullSchema:or,OAuthClientInformationSchema:go,OAuthClientMetadataSchema:Wp,OAuthClientRegistrationErrorSchema:Zp,OAuthErrorResponseSchema:Ps,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Mr,OAuthTokenRevocationRequestSchema:Yp,OAuthTokensSchema:At,OpenIdProviderDiscoveryMetadataSchema:qr,OpenIdProviderMetadataSchema:Kp},Bh={},Fh={};function Jh(e,t){let r=e.slice(0,-6);Bh[r]=t,Fh[r]=n=>t.safeParse(n).success}o(Jh,"register");for(let e of wb)Jh(e,nb[e]);for(let[e,t]of Object.entries(Rb))Jh(e,t);var bb=Object.freeze(Bh),vb=Object.freeze(Fh);function Cb(e){switch(e){case"initialize":case"notifications/initialized":return Ao(void 0);case"server/discover":return Ao(za);default:return}}o(Cb,"bootstrapOutboundCodec");var Vh=6e4,Ib=[Pr,mo,Or,ho],Tb=["inputResponses","requestState"];function hh(e,t){let r=e.params;if(!ba(r))return{message:e,lifted:{}};let n=r._meta,s=ba(n)?Ib.filter(d=>d in n):[],i=t==="request"?Tb.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&ba(n)){let d={},u={...n};for(let m of s)d[m]=n[m],delete u[m];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}o(hh,"liftWireOnlyMaterial");function fh(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let s=e.validateResult(t,n);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}o(fh,"codecResultValidator");function Gh(e){return()=>e}o(Gh,"requestStateAccessor");var Eb=Gh(void 0),kb,Ab=class{static{o(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{kb=o((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Wi,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(Se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Ia(s)||$h(s)?this._onresponse(s):Dh(s)?this._onrequest(s,i):Lh(s)?this._onnotification(s,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(Se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=hh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=uh(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(wa(r.method)&&!n.hasNotificationMethod(r.method))return;let s=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;s===void 0&&i===void 0||Promise.resolve().then(()=>s===void 0?i(r):s(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=hh(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=o((_,y,b)=>{let I={jsonrpc:"2.0",id:r.id,error:{code:_,message:y,...b!==void 0&&{data:b}}};i?.send(I).catch(U=>this._onerror(new Error(`Failed to send an error response: ${U}`)))},"sendErrorResponse");if(t?.classification!==void 0){let _=uh(t.classification);if(_!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${_} but this instance serves ${s.era}`));let y=t.classification.revision??_;a(A.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(_a(r.method)&&!s.hasRequestMethod(r.method)&&!(lh(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(A.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(A.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(n);if(d!==void 0){a(A.InvalidParams,d);return}let u=o((_,y)=>this._notificationViaCodec(this._resolveOutboundCodec(_.method),_,{...y,relatedRequestId:r.id}),"sendNotification"),m=o((_,y,b)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(_.method),_,y,{...b,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:Pb(n.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:n.requestState===void 0?Eb:Gh(n.requestState),signal:h.signal,send:o(((_,y,b)=>{let I=this._resolveOutboundCodec(_.method);if(this._assertOutboundRequestInEra(I,_.method),Ta(y))return m(_,y,b);let U=fh(I,_.method);if(U===void 0)throw new TypeError(`'${_.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(_,U,y)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},R=this.buildContext(S,t);Promise.resolve().then(()=>c(r,R)).then(async _=>{if(h.signal.aborted)return;let y;try{y=s.encodeResult(r.method,_,this._outboundServerInfo())}catch(I){this._onerror(new Error(`Failed to encode result for ${r.method}: ${I}`)),a(A.InternalError,"Internal error");return}let b={result:y,jsonrpc:"2.0",id:r.id};await i?.send(b)},async _=>{if(h.signal.aborted)return;let y=Number.isSafeInteger(_.code)?_.code:A.InternalError,b={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(y),message:_.message??"Internal error",..._.data!==void 0&&{data:_.data}}};await i?.send(b)}).catch(_=>this._onerror(new Error(`Failed to send response: ${_}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Ia(e)?r(e):r(_e.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(Ta(t))return lh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=fh(n,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,s,t)}_negotiatedWireCodec(){return Ao(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Cb(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(_a(t)&&!e.hasRequestMethod(t))throw new le(Se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},d=Date.now(),u,m;return new Promise((h,f)=>{let S=o(x=>{f(x)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(x){S(x);return}if(n?.signal?.aborted){let x=n.signal.reason;throw x instanceof le?x:new le(Se.RequestTimeout,String(x))}let R=e.era===za&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;m=_;let y={...t,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:_}});let b=this._envelopeOutbound(y),I=!1,U=o(x=>{I||(this._progressHandlers.delete(_),R===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(x)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`))):R.abort(),f(x instanceof le?x:new le(Se.RequestTimeout,String(x))))},"cancel");this._responseHandlers.set(_,x=>{if(n?.signal?.aborted)return;if(I=!0,x instanceof Error)return f(x);let Z;try{Z=e.decodeResult(t.method,x.result)}catch(P){return f(P instanceof Error?P:new Error(String(P)))}if(Z.kind==="invalid")return f(Z.error);if(Z.kind==="input_required"){if(n?.allowInputRequired===!0)return h(xb(Z));let P={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:d,retry:o((B,j)=>this._requestWithSchemaViaCodec(e,B===void 0?{method:t.method}:{method:t.method,params:B},r,j),"retry")};return h(this._resolveNonCompleteResult(Z,P))}let re=Z.result;Ra(r,re).then(P=>{P.success?h(P.data):f(new le(Se.InvalidResult,`Invalid result for ${t.method}: ${P.error}`))},f)}),u=o(()=>U(n?.signal?.reason),"onAbort"),n?.signal?.addEventListener("abort",u,{once:!0});let v=n?.timeout??Vh,Y=o(()=>U(new le(Se.RequestTimeout,"Request timed out",{timeout:v})),"timeoutHandler");this._setupTimeout(_,v,n?.maxTotalTimeout,Y,n?.resetTimeoutOnProgress??!1),this._transport.send(b,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:R?.signal}).catch(x=>{this._progressHandlers.delete(_),f(x)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(Se.NotConnected,"Not connected");if(wa(t.method)&&!e.hasNotificationMethod(t.method))throw new le(Se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(s=>this._onerror(s))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!_a(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=o((s,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,s);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,s)),!c.ok)throw c.reason==="not-in-era"?new _e(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)n=o(async(s,i)=>{let a=await Ra(t.params,{...s.params});if(!a.success)throw new _e(A.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!wa(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,s)=>{let i=s.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new _e(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let s=await Ra(t.params,{...n.params});if(!s.success)throw new _e(A.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ba(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(ba,"isPlainObject$1");function gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(gh,"isPlainObject");function Pb(e){let t={},r=[];if(!gh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!gh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(Pb,"partitionInputResponses");function xb(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(xb,"manualInputRequiredValue");var Ob=nh((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(c){if(!c)throw new TypeError("argument string is required");var d=typeof c=="object"?i(c):c;if(typeof d!="string")throw new TypeError("argument string is required to be a string");var u=d.indexOf(";"),m=u!==-1?d.slice(0,u).trim():d.trim();if(!n.test(m))throw new TypeError("invalid media type");var h=new a(m.toLowerCase());if(u!==-1){var f,S,R;for(t.lastIndex=u;S=t.exec(d);){if(S.index!==u)throw new TypeError("invalid parameter format");u+=S[0].length,f=S[1].toLowerCase(),R=S[2],R.charCodeAt(0)===34&&(R=R.slice(1,-1),R.indexOf("\\")!==-1&&(R=R.replace(r,"$1"))),h.parameters[f]=R}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}o(s,"parse");function i(c){var d;if(typeof c.getHeader=="function"?d=c.getHeader("content-type"):typeof c.headers=="object"&&(d=c.headers&&c.headers["content-type"]),typeof d!="string")throw new TypeError("content-type header is missing from object");return d}o(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}o(a,"ContentType")})),e0=sh(Ob(),1);var Mb=10*1024*1024;var Ub=new Set([301,302,303,307,308]),qb=5;function zb(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}o(zb,"isWithinOrigin");function Nb(e,t){let r=Ub.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Nb,"redirectTarget");var jb=new WeakSet;function ni(e){return jb.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let n=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Nb(s,a);if(!c||i===qb)return a;let d=new URL(s),u=n==="GET"||a.status===307||a.status===308,m=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!m||!zb(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(ni,"fetchWithinOrigin");function Da(){Pa(),ft(),TR(),GR(),rb()}o(Da,"preloadSchemas");var p0=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var Db=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Lb=[0,31,28,31,30,31,30,31,31,30,31,30,31],$b=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Hb=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Bb=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Fb=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Jb=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Vb=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Gb=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Kb=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Wb=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Zb=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),Yb=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xb=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Qb=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function st(e){return e.test.bind(e)}o(st,"bind");var m0={date:Kh,time:Wh.bind(void 0,!1),"date-time":rv,duration:Qb,uri:sv,"uri-reference":st(Bb),"uri-template":st(Fb),url:st(Jb),email:Zb,hostname:st(Hb),ipv4:st(Yb),ipv6:st(Xb),regex:av,uuid:st(Vb),"json-pointer":st(Gb),"json-pointer-uri-fragment":st(Kb),"relative-json-pointer":st(Wb)};function ev(e){return e%4===0&&(e%100!==0||e%400===0)}o(ev,"isLeapYear");function Kh(e){let t=e.match(Db);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&ev(r)?29:Lb[n])}o(Kh,"date");function Wh(e,t){let r=t.match($b);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!e||a)}o(Wh,"time");var tv=/t|\s/i;function rv(e){let t=e.split(tv);return t.length==2&&Kh(t[0])&&Wh(!0,t[1])}o(rv,"date_time");var nv=/\/|:/,ov=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function sv(e){return nv.test(e)&&ov.test(e)}o(sv,"uri");var iv=/[^\\]\\Z/;function av(e){if(iv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(av,"regex");Da();var Zh=!1;var La;La=globalThis.crypto;async function dv(e){return(await La).getRandomValues(new Uint8Array(e))}o(dv,"getRandomValues");async function uv(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await dv(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(uv,"random");async function lv(e){return await uv(e)}o(lv,"generateVerifier");async function pv(e){let t=await(await La).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(pv,"generateChallenge");async function $a(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await lv(e),r=await pv(t);return{code_verifier:t,code_challenge:r}}o($a,"pkceChallenge");var Oo=class extends Error{static{o(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e),this.name=new.target.name,cr(this,new.target)}},xo=class extends Oo{static{o(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},Va=class extends Oo{static{o(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},ii=class extends Oo{static{o(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},si=class extends Oo{static{o(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},rU=class extends Oo{static{o(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Ja(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):ef(e.issuer,t)?e:void 0}o(Ja,"discardIfIssuerMismatch");function ef(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(ef,"issuersMatch");var nU=class extends Error{static{o(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",cr(this,new.target)}};function tf(e){return e?.authorization_response_iss_parameter_supported===!0}o(tf,"isIssParameterSupported");function rf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new xo("authorization_response",t,void 0);return}if(e!==t)throw new xo("authorization_response",t,e)}}o(rf,"validateAuthorizationResponseIssuer");function mv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(mv,"isClientAuthMethod");var Ha="code",Ba="S256";function hv(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&mv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(hv,"selectClientAuthMethod");function fv(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":gv(s,i,r);return;case"client_secret_post":yv(s,i,n);return;case"none":Sv(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(fv,"applyClientAuthentication");function gv(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(gv,"applyBasicAuth");function yv(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(yv,"applyPostAuth");function Sv(e,t){t.set("client_id",e)}o(Sv,"applyPublicAuth");function nf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(nf,"isLoopbackHost");function _v(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!nf(t.hostname))throw new ii(t.href);return t}o(_v,"assertSecureTokenEndpoint");function wv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||nf(r.hostname))return"native"}return"web"}o(wv,"deriveApplicationType");function Rv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??wv(t.redirect_uris)}}o(Rv,"resolveClientMetadata");async function Yh(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Ps.parse(JSON.parse(r));return Mt.fromResponse(n)}catch(n){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Mt(me.ServerError,s)}}o(Yh,"parseErrorResponse");function Xh(e,t,r){let n=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${n}. Cause: ${JSON.stringify(t.message)}`)}o(Xh,"warnCredentialInvalidation");async function Ga(e,t){try{return await Fa(e,t)}catch(r){if(r instanceof Mt){if(r.code===me.InvalidClient||r.code===me.UnauthorizedClient)return Xh(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Fa(e,t);if(r.code===me.InvalidGrant||r.code===me.InvalidDpopProof)return Xh(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Fa(e,t)}throw r}}o(Ga,"auth");function bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}o(bv,"determineScope");async function Fa(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=Rv(e),m=await e.discoveryState?.(),h,f,S,R,_=i;if(!_&&m?.resourceMetadataUrl&&(_=new URL(m.resourceMetadataUrl)),m?.authorizationServerUrl){if(f=m.authorizationServerUrl,h=m.resourceMetadata,S=m.authorizationServerMetadata??await cf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await sf(t,{resourceMetadataUrl:_},a)}catch(X){if(X instanceof TypeError)throw X}(S!==m.authorizationServerMetadata||h!==m.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S})}else{let X=await Av(t,{resourceMetadataUrl:_,fetchFn:a,skipIssuerMetadataValidation:c});f=X.authorizationServerUrl,S=X.authorizationServerMetadata,h=X.resourceMetadata,R={authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:S}}let y=S?.issuer??String(f),b={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),r!==void 0){let X=m?.authorizationServerMetadata?.issuer??m?.authorizationServerUrl;if(X===void 0){if(e.saveDiscoveryState!==void 0)throw new si("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!ef(X,y))throw new si(X,y)}R&&await e.saveDiscoveryState?.(R);let I=await vv(t,e,h),U=I&&h&&!e.validateResourceURL?h.resource:I;U&&await e.saveResourceUrl?.(Wa(U));let v=bv({requestedScope:s,resourceMetadata:h,authServerMetadata:S,clientMetadata:e.clientMetadata}),Y=await Promise.resolve(e.clientInformation(b)),x=Ja(Y,y,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&Y?.issuer&&e.saveClientInformation===void 0)throw new si(Y.issuer,y);if(x&&x.issuer===void 0&&(x={...x,issuer:y},await e.saveClientInformation?.(x,b)),!x){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let X=S?.client_id_metadata_document_supported===!0,Q=e.clientMetadataUrl;if(Q&&!Ka(Q))throw new Mt(me.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Q}`);if(X&&Q)x={client_id:Q,issuer:y},await e.saveClientInformation?.(x,b);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");x={...await Uv(f,{metadata:S,clientMetadata:u,scope:v,fetchFn:a}),issuer:y},await e.saveClientInformation(x,b)}}let Z=!e.redirectUrl;if(r!==void 0||Z){r!==void 0&&rf({iss:n,expectedIssuer:S?.issuer,issParameterSupported:tf(S)});let X=await Mv(e,f,{metadata:S,resource:U,authorizationCode:r,iss:n,scope:v,fetchFn:a});return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let re=Ja(await e.tokens(b),y);if(re&&re.issuer===void 0&&(re={...re,issuer:y},await e.saveTokens(re,b)),re?.refresh_token&&!d){let X;try{X=await Ov(f,{metadata:S,clientInformation:x,refreshToken:re.refresh_token,resource:U,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(Q){if(Q instanceof ii)throw Q;if(!(Q instanceof Mt)||Q.code===me.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(Q instanceof Error?Q.message:String(Q))}`);else throw Q}if(X)return await e.saveTokens({...X,issuer:y},b),"AUTHORIZED"}let P=e.state?await e.state():void 0,{authorizationUrl:B,codeVerifier:j}=await Pv(f,{metadata:S,clientInformation:x,state:P,redirectUrl:e.redirectUrl,scope:v,resource:U});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(B),"REDIRECT"}o(Fa,"authInternal");function Ka(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Ka,"isHttpsUrl");async function vv(e,t,r){let n=Sh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ei({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(vv,"selectResourceURL");var Cv=new Set(["bearer","dpop"]);function of(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!Cv.has(r.toLowerCase())||!n)return{};let s=oi(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=oi(e,"scope")||void 0,c=oi(e,"error")||void 0,d=oi(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}o(of,"extractWWWAuthenticateParams");function oi(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(n);if(s){let i=s[1]||s[2];if(i)return i}return null}o(oi,"extractFieldFromWwwAuth");async function sf(e,t,r=fetch){let n=await Ev(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Mr.parse(await n.json())}o(sf,"discoverOAuthProtectedResourceMetadata");async function af(e,t,r=fetch){let n=ni(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Zh)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(af,"fetchWithCorsRetry");function Iv(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(Iv,"buildWellKnownPath");async function Qh(e,t,r=fetch){return await af(e,{"MCP-Protocol-Version":t},r)}o(Qh,"tryMetadataDiscovery");function Tv(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(Tv,"shouldAttemptFallback");async function Ev(e,t,r,n){let s=new URL(e),i=n?.protocolVersion??Is,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let d=Iv(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await Qh(a,i,r);return!n?.metadataUrl&&Tv(c,s.pathname)&&(c=await Qh(new URL(`/.well-known/${t}`,s),i,r)),c}o(Ev,"discoverMetadataWithFallback");function kv(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"},{url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(kv,"buildDiscoveryUrls");async function cf(e,{fetchFn:t=fetch,protocolVersion:r=Is,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=kv(e);for(let{url:a,type:c}of i){let d=await af(a,s,t);if(!d)continue;if(!d.ok){if(await d.text?.().catch(()=>{}),d.status<500||d.status===502)continue;throw new Error(`HTTP ${d.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=c==="oauth"?Ur.parse(await d.json()):qr.parse(await d.json());if(!n){let m=typeof e=="string"?e:e.href;if(!(u.issuer===m||m.endsWith("/")&&u.issuer===m.slice(0,-1)))throw new xo("metadata",m,u.issuer)}return u}}o(cf,"discoverAuthorizationServerMetadata");async function Av(e,t){let r,n;try{r=await sf(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let s=await cf(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(Av,"discoverOAuthServerInfo");function Wa(e){return typeof e=="string"?e:e.href}o(Wa,"resourceIndicatorToString");async function Pv(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ha))throw new Error(`Incompatible auth server: does not support response type ${Ha}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ba))throw new Error(`Incompatible auth server: does not support code challenge method ${Ba}`)}else c=new URL("/authorize",e);let d=await $a(),u=d.code_verifier,m=d.code_challenge;return c.searchParams.set("response_type",Ha),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Ba),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),s&&c.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",Wa(a)),{authorizationUrl:c,codeVerifier:u}}o(Pv,"startAuthorization");function xv(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(xv,"prepareAuthorizationCodeRequest");async function df(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=_v(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",Wa(i)),!s&&n&&fv(hv(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let m=o(async()=>{let S=new Headers(u);return s&&await s(S,r,d,t),a&&S.set("DPoP",await a.buildProof({htm:"POST",htu:d})),ni(c??fetch)(d,{method:"POST",headers:S,body:r})},"requestOnce"),h=await m();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===me.UseDpopNonce&&(a.observeNonce(h,d),h=await m()),a?.observeNonce(h,d),!h.ok)throw await Yh(h);let f=await h.json();try{return At.parse(Aa(f))}catch(S){throw typeof f=="object"&&f!==null&&"error"in f?await Yh(JSON.stringify(f)):S}}o(df,"executeTokenRequest");async function Ov(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await df(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(Ov,"refreshAuthorization");async function Mv(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&rf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:tf(r)});let d=r?.issuer??String(t),u=o(async()=>{let S=await e.clientInformation({issuer:d}),R=Ja(S,d,{canPersistStamp:!1});if(S&&R===void 0)throw new si(String(S.issuer),d);return R},"readClientInformation"),m=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=xv(s,await e.codeVerifier(),e.redirectUrl)}return m??=await u(),df(t,{metadata:r,tokenRequestParams:f,clientInformation:m,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(Mv,"fetchToken");async function Uv(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:s}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},c=await ni(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new Va({status:c.status,body:await c.text(),submittedMetadata:a});return or.parse(Aa(await c.json()))}o(Uv,"registerClient");var oU=class extends Error{static{o(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return De(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return De(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,cr(this,new.target)}};function Me(e){let t=nr.safeParse(e);return t.success?t.data.id:void 0}o(Me,"parseJsonRpcRequestId");function Za(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Me(t)}catch{return}}o(Za,"readJsonRpcRequestIdFromBody");function gt(e){return fo.parse({jsonrpc:rr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}o(gt,"jsonRpcErrorResponse");function uf(e){return new ri([As.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o(uf,"urlElicitationRequiredError");function it(e){return(e??"").split(";")[0].trim().toLowerCase()}o(it,"mediaTypeEssence");var qv=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function yt(e){for(let t of qv)e.delete(t);return e}o(yt,"deleteEncodedBodyHeaders");function lf(){let e=ws.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(lf,"currentRuntime");var zv=new Set(["gzip","x-gzip","deflate","br","zstd"]);function at(e,t=lf()){let r=e.get("content-encoding")?.trim();if(!r||r.toLowerCase()==="identity")return!1;switch(t){case"deno":return!0;case"workerd":return r!=="gzip"&&r!=="br";default:return!r.toLowerCase().split(",").every(n=>zv.has(n.trim()))}}o(at,"isBodyStillEncoded");function pf(e){return at(e)?e:yt(e)}o(pf,"deleteEncodedBodyHeadersIfDecoded");function mf(e,t=lf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?at(e,t):e.has("content-length"))?e:yt(e)}o(mf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var ff=10*1024*1024,Nv=1024,jv=32,Dv=64,dr=class extends Error{constructor(r,n=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=n;this.name="SseEventTooLargeError"}maxEventChars;comment;static{o(this,"SseEventTooLargeError")}},Lv=10;function $v(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o($v,"handleRejection");function gf(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(gf,"fieldName");var Mo=class{static{o(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#l=!1;#p=/\r\n|\r|\n/g;#m="";#d=[];#o=[];#i=0;#a=!1;#u=!1;#h=!1;#s=!1;#f=!1;#S=0;#C=0;#c=[];#g=0;#y=[];#_;#w;#R;#b=[];constructor(t={}){let r=t.maxEventChars??ff;if(!Number.isInteger(r)||r<=0)throw new RangeError(`maxEventChars must be a positive integer, got ${r}`);this.#e=r,this.#r=t.onOversize==="discard",this.#t=t.emitLoneComments===!0}get discardedEvents(){return this.#S}get discardedComments(){return this.#C}get discarding(){return this.#s||this.#f}get idle(){return this.#i===0&&!this.#a&&!this.#s&&this.#c.length===0}push(t){let r=[];return this.#T(this.#I(this.#n.decode(t,{stream:!0})),r),r}end(){let t=[];return this.#T(this.#I(this.#n.decode()),t),(this.#i>0||this.#a)&&this.#A(t,!1),this.#s||this.#P(t,!1),this.#s=!1,t}#I(t){return this.#l||t===""?t:(this.#l=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let n=0;this.#h&&(this.#h=!1,t.charCodeAt(0)===Lv&&(n=1));let s=this.#p;s.lastIndex=n;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(n,i.index)),this.#A(r),n=i.index+i[0].length,i[0]==="\r"&&n===t.length&&(this.#h=!0),i=s.exec(t);this.#E(t.slice(n))}#E(t){if(t!==""){if(this.#s||this.#f){this.#a=!0;return}if(this.#i===0?this.#m=t:(this.#o.push(t),this.#o.length>=Dv&&(this.#d.push(this.#o.join("")),this.#o=[])),this.#i+=t.length,this.#g+this.#i>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#f=!0,this.#S++,this.#C++):this.#k(r),this.#a=!0}}}#O(){return this.#t&&this.#c.length===0&&this.#m.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new dr(this.#e,t);this.#x(),this.#u=!1,this.#v(),this.#s=!0,this.#S++}#v(){this.#m="",this.#d.length>0&&(this.#d=[]),this.#o.length>0&&(this.#o=[]),this.#i=0}#A(t,r=!0){let n=this.#d.length===0&&this.#o.length===0?this.#m:this.#m+this.#d.join("")+this.#o.join(""),s=n===""&&!this.#a;if(this.#v(),this.#a=!1,this.#f){this.#f=!1,this.#u=!0;return}if(s){this.#s?this.#s=!1:this.#u&&this.#c.length===0?(this.#u=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#u=!1,this.#P(t,!0));return}if(this.#s)return;if(this.#t&&r&&this.#c.length===0&&n.charCodeAt(0)===58){t.push({lines:[n],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[n.slice(1)],terminated:!0,lone:!0}),this.#u=!0;return}if(this.#g+=n.length,this.#c.push(n),this.#c.length>Nv&&(this.#g+=Math.max(0,jv-n.length),this.#g>this.#e)){this.#k();return}if(n.charCodeAt(0)===58){this.#b.push(n.slice(1));return}let i=n.indexOf(":"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#y.push(c);break;case"event":this.#_=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#R=Number(c));break;default:break}}#P(t,r){this.#c.length>0&&t.push({lines:this.#c,data:this.#y.length>0?this.#y.join(`
26
+ `):void 0,event:this.#_,id:this.#w,retry:this.#R,comments:this.#b,terminated:r}),this.#x()}#x(){this.#c=[],this.#g=0,this.#y=[],this.#_=void 0,this.#w=void 0,this.#R=void 0,this.#b=[]}};function Ya(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}o(Ya,"assertSingleLine");function Xa(e){if("lines"in e){for(let n of e.lines){if(/[\r\n]/.test(n))throw new TypeError("SSE event line must not contain a line break");if(n==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(n=>`${n}
27
27
  `).join("");return e.lines[0]?.charCodeAt(0)===65279&&(r=`
28
28
  ${r}`),e.terminated?`${r}
29
- `:r}let t="";for(let r of e.comments??[])Sa("comment",r),t+=`:${r}
30
- `;if(e.event!==void 0&&(Sa("event",e.event),t+=`event: ${e.event}
31
- `),e.id!==void 0){if(Sa("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
29
+ `:r}let t="";for(let r of e.comments??[])Ya("comment",r),t+=`:${r}
30
+ `;if(e.event!==void 0&&(Ya("event",e.event),t+=`event: ${e.event}
31
+ `),e.id!==void 0){if(Ya("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
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
- `}n(_a,"serializeSseEvent");var KR=new Set(["data","event","id","retry"]);function nh(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!KR.has(rh(t)))}n(nh,"hasUnknownSseFields");function Ra(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(o=>rh(o)!=="data"),...r.map(o=>`data: ${o}`)],data:r.join(`
36
- `)}}n(Ra,"replaceSseData");var oh=Symbol("sse.terminate");function ba(...e){return{[oh]:!0,events:e}}n(ba,"terminateSse");function WR(e){return typeof e=="object"&&e!==null&&oh in e}n(WR,"isTerminate");var ZR=64,eh=new Uint8Array(0),wa=class{static{n(this,"SseRawEventBytes")}#e=eh;#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>=ZR&&this.#d())}take(){let t;return this.#r===0?t=eb(this.#t):(this.#d(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=eh,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#d(){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}},So=10,zs=13,YR=[239,187,191];function XR(e){let t=[],r=0;for(let o=0;o<e.length;o++){let s=e[o];(s===So||s===zs&&e[o+1]!==So)&&(t.push(e.subarray(r,o+1)),r=o+1)}return r<e.length&&t.push(e.subarray(r)),t}n(XR,"splitLines");function QR(e){let t=e[e.length-1];return t===So||t===zs}n(QR,"endsLine");function va(e,t,r={}){let o=r.failureMode??"closed",s=o==="open"&&r.onOversize!=="discard",i=r.maxEventChars??th,a=new yo(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,l={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},m=e.getReader(),h=!1,y=!1,f=0,R=new wa,S=0,w=!1,x,I,O=n(A=>{h=!0,d.abort(A),m.cancel(A).catch(()=>{})},"stop"),N=n((A,K)=>{try{VR(r.onFailure?.(A,K),()=>{})}catch{}},"report"),we=n(A=>{N(A,{mode:o,kind:"oversize",...A.comment?{comment:!0}:{}})},"reportOversize"),q=n(A=>{if(!("lines"in A))return _a(A);if(A.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return A.lone===!0&&A.lines.length>0&&A.lines.every(K=>K.charCodeAt(0)===58)?_a({...A,terminated:!1}):_a(A)},"write"),ie=n((A,K)=>WR(A)?{text:A.events.map(q).join(""),terminate:!0}:A===void 0?{text:K===void 0?"":q(K),terminate:!1}:A===null?{text:"",terminate:!1}:{text:(Array.isArray(A)?A:[A]).map(q).join(""),terminate:!1},"render"),pe=n(A=>{if(!s)try{return a.push(A).map(j=>({event:j}))}catch(j){throw j instanceof Qt&&we(j),j}let K=[];for(let j of XR(A)){if(w&&(w=!1,j[0]===So)){a.push(j),f+=j.length,K.push({raw:j,atStart:!1});continue}let W=a.discardedEvents,Z=a.discardedComments,De=a.discarding;!De&&R.length===0&&(S=f),f+=j.length;for(let Oe of a.push(j))K.push({event:Oe});De?(K.push({raw:j,atStart:!1}),w=!a.discarding&&j[j.length-1]===zs):a.discardedEvents>W?(we(new Qt(i,a.discardedComments>Z)),R.push(j),K.push({raw:R.take(),atStart:S===0}),w=!a.discarding&&j[j.length-1]===zs):QR(j)&&a.idle?R.clear():R.push(j)}return K},"parse");return new ReadableStream({async pull(A){if(I!==void 0){A.error(I.error);return}try{for(;;){let K=await m.read();if(h)return;let j,W=!1,Z=!1;if(K.done){j=[],Z=s&&a.discarding;let G=a.discardedEvents,ae=a.discardedComments,ke;try{ke=a.end()}catch(ee){throw ee instanceof Qt&&we(ee),ee}for(let ee of ke)ee.terminated?j.push({event:ee}):W=!0;a.discardedEvents>G&&R.length>0&&(we(new Qt(i,a.discardedComments>ae)),j.push({raw:R.take(),atStart:S===0}),Z=!0),R.clear(),W||=Z}else j=pe(K.value);let De=!1,Oe=n(G=>{G.length>0&&(A.enqueue(G),De=!0,y=!0)},"enqueue"),$e=n(G=>{G!==""&&Oe(c.encode(G))},"emit");for(let G of j){if("raw"in G){!y&&!G.atStart&&YR.every((ee,Ge)=>G.raw[Ge]===ee)&&$e(`
37
- `),Oe(G.raw.slice()),x=G.raw[G.raw.length-1];continue}let{event:ae}=G,ke;try{let ee=await t(ae,l);if(h)return;ke=ie(ee,ae)}catch(ee){if(h)return;if(N(ee,{mode:o,kind:"transform",event:ae}),o==="closed")throw ee;ke={text:q(ae),terminate:!1}}if($e(ke.text),ke.terminate){O("SSE stream terminated by its rewriter"),A.close();return}}if(K.done){if(r.end!==void 0){let G;try{let ae=await r.end({...l,unterminated:W});if(h)return;G=ie(ae,void 0)}catch(ae){if(h)return;if(N(ae,{mode:o,kind:"end"}),o==="closed")throw ae;G={text:"",terminate:!1}}if(Z&&G.text!==""&&$e(x===So?`
35
+ `}o(Xa,"serializeSseEvent");var Hv=new Set(["data","event","id","retry"]);function yf(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!Hv.has(gf(t)))}o(yf,"hasUnknownSseFields");function qo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>gf(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
36
+ `)}}o(qo,"replaceSseData");var Sf=Symbol("sse.terminate");function ec(...e){return{[Sf]:!0,events:e}}o(ec,"terminateSse");function Bv(e){return typeof e=="object"&&e!==null&&Sf in e}o(Bv,"isTerminate");var Fv=64,hf=new Uint8Array(0),Qa=class{static{o(this,"SseRawEventBytes")}#e=hf;#r=0;#t=[];#n=0;get length(){return this.#r+this.#n}get views(){return this.#t.length}push(t){t.length!==0&&(this.#t.push(t),this.#n+=t.length,this.#t.length>=Fv&&this.#l())}take(){let t;return this.#r===0?t=Kv(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=hf,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#l(){let t=this.#r+this.#n;if(t>this.#e.length){let r=new Uint8Array(Math.max(t,this.#e.length*2));r.set(this.#e.subarray(0,this.#r)),this.#e=r}for(let r of this.#t)this.#e.set(r,this.#r),this.#r+=r.length;this.#t=[],this.#n=0}},Uo=10,ai=13,Jv=[239,187,191];function Vv(e){let t=[],r=0;for(let n=0;n<e.length;n++){let s=e[n];(s===Uo||s===ai&&e[n+1]!==Uo)&&(t.push(e.subarray(r,n+1)),r=n+1)}return r<e.length&&t.push(e.subarray(r)),t}o(Vv,"splitLines");function Gv(e){let t=e[e.length-1];return t===Uo||t===ai}o(Gv,"endsLine");function tc(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??ff,a=new Mo(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,u={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},m=e.getReader(),h=!1,f=!1,S=0,R=new Qa,_=0,y=!1,b,I,U=o(P=>{h=!0,d.abort(P),m.cancel(P).catch(()=>{})},"stop"),v=o((P,B)=>{try{$v(r.onFailure?.(P,B),()=>{})}catch{}},"report"),Y=o(P=>{v(P,{mode:n,kind:"oversize",...P.comment?{comment:!0}:{}})},"reportOversize"),x=o(P=>{if(!("lines"in P))return Xa(P);if(P.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return P.lone===!0&&P.lines.length>0&&P.lines.every(B=>B.charCodeAt(0)===58)?Xa({...P,terminated:!1}):Xa(P)},"write"),Z=o((P,B)=>Bv(P)?{text:P.events.map(x).join(""),terminate:!0}:P===void 0?{text:B===void 0?"":x(B),terminate:!1}:P===null?{text:"",terminate:!1}:{text:(Array.isArray(P)?P:[P]).map(x).join(""),terminate:!1},"render"),re=o(P=>{if(!s)try{return a.push(P).map(j=>({event:j}))}catch(j){throw j instanceof dr&&Y(j),j}let B=[];for(let j of Vv(P)){if(y&&(y=!1,j[0]===Uo)){a.push(j),S+=j.length,B.push({raw:j,atStart:!1});continue}let X=a.discardedEvents,Q=a.discardedComments,He=a.discarding;!He&&R.length===0&&(_=S),S+=j.length;for(let Ue of a.push(j))B.push({event:Ue});He?(B.push({raw:j,atStart:!1}),y=!a.discarding&&j[j.length-1]===ai):a.discardedEvents>X?(Y(new dr(i,a.discardedComments>Q)),R.push(j),B.push({raw:R.take(),atStart:_===0}),y=!a.discarding&&j[j.length-1]===ai):Gv(j)&&a.idle?R.clear():R.push(j)}return B},"parse");return new ReadableStream({async pull(P){if(I!==void 0){P.error(I.error);return}try{for(;;){let B=await m.read();if(h)return;let j,X=!1,Q=!1;if(B.done){j=[],Q=s&&a.discarding;let K=a.discardedEvents,de=a.discardedComments,xe;try{xe=a.end()}catch(ne){throw ne instanceof dr&&Y(ne),ne}for(let ne of xe)ne.terminated?j.push({event:ne}):X=!0;a.discardedEvents>K&&R.length>0&&(Y(new dr(i,a.discardedComments>de)),j.push({raw:R.take(),atStart:_===0}),Q=!0),R.clear(),X||=Q}else j=re(B.value);let He=!1,Ue=o(K=>{K.length>0&&(P.enqueue(K),He=!0,f=!0)},"enqueue"),Be=o(K=>{K!==""&&Ue(c.encode(K))},"emit");for(let K of j){if("raw"in K){!f&&!K.atStart&&Jv.every((ne,Ye)=>K.raw[Ye]===ne)&&Be(`
37
+ `),Ue(K.raw.slice()),b=K.raw[K.raw.length-1];continue}let{event:de}=K,xe;try{let ne=await t(de,u);if(h)return;xe=Z(ne,de)}catch(ne){if(h)return;if(v(ne,{mode:n,kind:"transform",event:de}),n==="closed")throw ne;xe={text:x(de),terminate:!1}}if(Be(xe.text),xe.terminate){U("SSE stream terminated by its rewriter"),P.close();return}}if(B.done){if(r.end!==void 0){let K;try{let de=await r.end({...u,unterminated:X});if(h)return;K=Z(de,void 0)}catch(de){if(h)return;if(v(de,{mode:n,kind:"end"}),n==="closed")throw de;K={text:"",terminate:!1}}if(Q&&K.text!==""&&Be(b===Uo?`
38
38
  `:`
39
39
 
40
- `),$e(G.text),G.terminate){O("SSE stream terminated by its rewriter"),A.close();return}}h=!0,A.close();return}if(De)return}}catch(K){h||(O(K),(A.desiredSize??0)<0?I={error:K}:A.error(K))}},cancel(A){if(!h)return h=!0,d.abort(A),m.cancel(A)}},{highWaterMark:0})}n(va,"rewriteSseStream");function eb(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((o,s)=>o+s.length,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}n(eb,"concatBytes");function sh(e,t,r){if(e.body===null)return e;let o=dt(new Headers(e.headers));return o.set("content-type","text/event-stream"),new Response(va(e.body,t,r),{status:e.status,statusText:e.statusText,headers:o})}n(sh,"rewriteSseResponse");var ch=new Set(["jsonrpc","method","id","params"]),dh=new Set(["name","uri","ref"]),uh=new Set(["type","name","uri"]),tb=/[^\u0000-\u007f]/,rb=34,nb=92,ih=123,ob=125,sb=91,ib=93,ab=58,ah=44;function Ca(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Ca,"isRecord");function _o(e){return e.toUpperCase().toLowerCase()}n(_o,"foldCase");function Ia(e,t){return Object.keys(e).some(r=>{let o=_o(r);return o!==r&&t.has(o)})}n(Ia,"hasCaseVariant");function cb(e){let t={batch:void 0,member:ch,params:dh,ref:uh},r=[],o=0,s=n(i=>{let a=r.at(-1);if(a===void 0)return i?"member":"batch";if(i){if(a.role==="batch")return"member";if(a.role==="member"&&a.key==="params")return"params";if(a.role==="params"&&a.key==="ref")return"ref"}},"childRole");for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a===rb){let c=i;for(;;){if(c=e.indexOf('"',c+1),c===-1)return!0;let l=0;for(;e.charCodeAt(c-1-l)===nb;)l++;if(l%2===0)break}let d=o>0?void 0:r.at(-1);if(d?.isObject&&d.expectKey){let l=e.slice(i,c+1),m=l.includes("\\")?JSON.parse(l):l.slice(1,-1);if(tb.test(m))return!0;d.key=m;let h=_o(m);if(t[d.role]?.has(h)){if(d.seen.has(h))return!0;d.seen.add(h)}}i=c}else if(a===ih||a===sb){let c=a===ih,d=o>0?void 0:s(c);d===void 0?o++:r.push({role:d,isObject:c,seen:new Set,expectKey:c})}else if(a===ob||a===ib)o>0?o--:r.pop();else if(o===0&&(a===ab||a===ah)){let c=r.at(-1);c?.isObject&&(c.expectKey=a===ah)}}return!1}n(cb,"hasUnsafeKeyInText");function lh(e){for(let t of e.envelope.messages){let r=t.raw;if(Ca(r)){if(Ia(r,ch))return!0;if(!(typeof r.method!="string"||!e.isCapabilityMethod(r.method)||!Ca(r.params))&&(Ia(r.params,dh)||Ca(r.params.ref)&&Ia(r.params.ref,uh)))return!0}}return cb(e.text)}n(lh,"hasAmbiguousIdentifyingKeys");var db=n(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),ub=47,ph=44,lb=38,Ta=n(e=>e!==ub&&e!==ph,"VALUE"),pb=n(e=>!db(e),"ANY"),mb=n(e=>e!==lb,"QUERY_VALUE"),hb=["+","#",".","/","?","&"],Ea=class{static{n(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 o=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:n(i=>i===o,"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(Ta),!t)return;let r=this.current,o=this.#e();this.edges[r].push({test:n(s=>s===ph,"test"),to:o}),this.edges[o].push({test:Ta,to:r})}};function mh(e){let t=new Ea,r="",o=0;for(;o<e.length;){if(e[o]!=="{"){r+=e[o],o++;continue}let s=e.indexOf("}",o);if(s===-1)return;t.literal(r),r="";let i=e.slice(o+1,s),a=hb.find(l=>i.startsWith(l))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(l=>l.replace("*","").trim()).filter(l=>l.length>0);switch(a){case"?":case"&":d.forEach((l,m)=>{t.literal(`${m===0?a:"&"}${l}=`),t.plus(mb)});break;case"+":case"#":t.plus(pb);break;case".":t.literal("."),t.plus(Ta);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}o=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}n(mh,"compileUriTemplate");function hh(e,t){if(t.length>1e6)return!1;let{edges:r,accept:o}=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 l of i)for(let m of r[l])s[m.to]!==a&&m.test(c)&&(s[m.to]=a,d.push(m.to));if(d.length===0)return!1;i=d}return i.includes(o)}n(hh,"matchesUriTemplate");var $s=p.record(p.string(),p.unknown()),fb=p.record(p.string(),p.unknown()),Et=p.array(p.string().min(1)).min(1).optional(),gb=p.object({name:p.string().min(1),description:p.string().min(1).optional(),annotations:fb.optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),yb=p.object({name:p.string().min(1),description:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),Sb=p.object({uri:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),_b=p.object({uriTemplate:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:$s.optional(),roles:Et,groups:Et,public:p.boolean().optional()}).strict(),wb=p.array(p.union([p.string(),gb])),Rb=p.array(p.union([p.string(),yb])),bb=p.array(p.union([p.string(),Sb])),vb=p.array(p.union([p.string(),_b])),Cb=p.object({module:p.unknown(),export:p.string().min(1)}).strict(),Ib=p.object({mode:p.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:p.string().min(1).optional(),groupClaim:p.string().min(1).optional(),identifier:Cb.optional()}).strict(),Tb=p.object({tools:wb.optional(),prompts:Rb.optional(),resources:bb.optional(),resourceTemplates:vb.optional(),accessControl:Ib.optional()}).strict(),lt=[{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 Eb(e,t){return tp(Tb,e,`MCP capability filter policy "${t}"`)}n(Eb,"parseMcpCapabilityFilterOptions");function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Q,"isRecord");function ut(e){return typeof e.method=="string"?e.method:void 0}n(ut,"messageMethod");function bo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(bo,"correlationKey");function Rh(e){let t=new Set,r=new Map;for(let o of e){let s=bo(o);if(s===void 0)continue;t.add(s);let i=String(o),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return o=>{let s=bo(o);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(o));return i?.size===1?[...i][0]:void 0}}n(Rh,"createReplyIdMatcher");function fh(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(fh,"asStringArray");function gh(e,t){if(!Q(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,s)=>Q(o)?o[s]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n(gh,"readClaimValues");function Oa(e,t){if(typeof e=="string")return{key:e,public:!1};if(!Q(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:fh(e.roles),groups:fh(e.groups),public:e.public===!0}}n(Oa,"normalizeEntry");function kb(e,t,r){if(e.public)return!0;let o=e.roles??[],s=e.groups??[];return o.length===0&&s.length===0?!1:o.some(i=>t.has(i))||s.some(i=>r.has(i))}n(kb,"isCallerAllowed");function Ns(e,t,r,o){if(e===void 0)return;let s=[];for(let i of e){let a=Oa(i,t);a!==void 0&&kb(a,r,o)&&s.push(a.key)}return s}n(Ns,"allowedKeys");var bh=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(gh(e.user?.data,o)),a=new Set(gh(e.user?.data,s));return{tools:Ns(r.tools,"name",i,a),prompts:Ns(r.prompts,"name",i,a),resources:Ns(r.resources,"uri",i,a),resourceTemplates:Ns(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function Ab(e,t){let r=[];for(let o of lt){let s=e[o.option];if(s!==void 0)for(let i of s){let a=Oa(i,o.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new Y(`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(", ")}`)}n(Ab,"assertNoConflictingMarkup");function Pb(e,t){let r=[];for(let o of lt){let s=e[o.option];if(s!==void 0)for(let i of s){let a=Oa(i,o.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${o.option} "${a.key}"`)}}if(r.length>0)throw new Y(`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(", ")}`)}n(Pb,"assertNoMarkup");function xb(e,t){let r=e.identifier;if(r===void 0)throw new Y(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new Y(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=o;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new T(`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 T(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}n(xb,"buildCustomResolver");function Ob(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new Y(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return xb(r,t)}if(o==="rolesAndGroups")return Ab(e,t),bh;Pb(e,t)}n(Ob,"buildCapabilityResolver");function Ub(e){let t={};for(let r of lt){let o=e[r.option];if(o===void 0)continue;let s=new Map;for(let i of o){let a=Vb(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}n(Ub,"buildProjectionMaps");function vh(e){return e===void 0?void 0:lt.find(t=>t.listMethod===e)}n(vh,"findListRule");function Ua(e){return e===void 0?void 0:lt.find(t=>t.directMethods.includes(e))}n(Ua,"findDirectRule");var Ls="completion/complete",Ch=["prompts","resources","resourceTemplates"];function Ih(e){return e===Ls||Ua(e)!==void 0}n(Ih,"isCapabilityMethod");var Mb=[...lt.flatMap(e=>[e.listMethod,...e.directMethods]),Ls];function qb(e){let t=_o(e.trim()),r=Mb.find(o=>_o(o)===t);return r!==void 0&&r!==e?r:void 0}n(qb,"methodVariantOf");function zb(e,[t,r]){return{code:k.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}n(zb,"invalidParams");function js(e){return t=>({code:k.InvalidParams,message:`${e} "${us(t)}" not found`})}n(js,"namedNotFound");function Nb(e,t){return{code:Zl(t),message:"Resource not found",data:{uri:Xl(e,Yl)}}}n(Nb,"resourceNotFound");function jb(e){let t=ut(e);if(t===void 0||!Ih(t))return[];let r=Q(e.raw)?e.raw.params:void 0,o=n((d,l)=>Q(d)&&typeof d[l]=="string"?d[l]:void 0,"stringAt"),s=n(d=>Q(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==Ls){let d=Ua(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:o(r,"uri"),issue:s("params.uri"),notFound:Nb}]:[{options:[d.option],target:o(r,"name"),issue:s("params.name"),notFound:js(d.option==="tools"?"Tool":"Prompt")}]}let i=Q(r)?r.ref:void 0,a=Q(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:o(i,"name"),issue:["params.ref.name","a string"],notFound:js("Prompt")}];if(a==="ref/resource"){let d=o(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&Db(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:js("Resource template")}]}let c=Q(r)?Q(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Ch,target:void 0,issue:c,notFound:js("Prompt")}]}n(jb,"capabilityAccesses");function Db(e){let t=!1,r=0;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else $b(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}n(Db,"hasTemplateExpression");function $b(e){return e>32&&e<127?!1:Lb.test(String.fromCharCode(e))}n($b,"isWhitespaceCode");var Lb=/\s/;function Hb(e){return e.type==="invalid"&&(!Q(e.raw)||e.raw.jsonrpc!=="2.0")}n(Hb,"isNonJsonRpcMember");function Bb(e){return Q(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}n(Bb,"hasNonStringMethod");function Th(e){return e.type==="request"||e.type==="invalid"&&ut(e)!==void 0}n(Th,"awaitsReply");var Jb={code:k.MethodNotFound,message:"Method not found"},yh={code:k.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},Fb={code:k.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},Gb="2025-06-18";function Eh(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}n(Eh,"isValidRequestId");function kh(e){return Q(e.raw)&&!Object.hasOwn(e.raw,"id")}n(kh,"isSentAsNotification");function wo(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}n(wo,"jsonRpcError");function Ro(e,t,r){return Response.json(wo(t,r),{status:e})}n(Ro,"jsonRpcErrorResponse");function Ds(e){return Ro(400,{code:k.InvalidRequest,message:`Invalid Request: ${e}`})}n(Ds,"invalidRequestResponse");function ka(e,t){if(kh(e))return{status:400,body:wo({code:k.InvalidRequest,message:`Invalid Request: a notification cannot use ${us(ut(e)??"this method")}; send it as a request with an id`})};let r=Q(e.raw)?e.raw.id:void 0;return Eh(r)?{status:200,body:wo(t,r)}:{status:400,body:wo({code:k.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}n(ka,"refusalOf");function Sh(e,t){let[r]=[...t];if(e.shape!=="batch"){let{status:i,body:a}=ka(r[0],r[1]);return Response.json(a,{status:i})}let o=e.protocolVersion;if(o!==void 0&&o>=Gb)return Ds(`protocol version ${us(o)} does not support JSON-RPC batches`);let s=e.messages.flatMap(i=>i.type==="result"||i.type==="error"||kh(i)?[]:[ka(i,t.get(i)??Fb).body]);if(s.length===0){let{status:i,body:a}=ka(r[0],r[1]);return Response.json(a,{status:i})}return Response.json(s)}n(Sh,"refusalResponse");function Vb(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!Q(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(Vb,"buildProjection");function _h(e){let t=e.base[e.property],r=e.overlay[e.property];return Q(r)?Q(t)?{...t,...r}:r:t}n(_h,"mergeRecordProperty");function Kb(e,t){let r={...e,...t.overlay},o=_h({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let s=_h({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}n(Kb,"applyProjection");var Ie=Symbol("unreadable");function Wb(e,t,r,o){let s=e.result;if(!Q(s))return Ie;let i=s[t.resultProperty];return!Array.isArray(i)||Object.hasOwn(s,"nextCursor")&&s.nextCursor!==null&&typeof s.nextCursor!="string"?Ie:{...e,result:{...s,[t.resultProperty]:i.flatMap(a=>{if(!Q(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let d=r.get(c);return d===void 0?[]:[Kb(a,d)]})}}}n(Wb,"filterAndProjectItems");function Ah(e,t){let r=vh(ut(e)),o=r===void 0?void 0:t[r.option];return r===void 0||o===void 0?null:{rule:r,projections:o}}n(Ah,"listTargetOf");function Zb(e,t,r){return Q(e)&&lt.some(o=>o!==t?.rule&&r[o.option]!==void 0&&Object.hasOwn(e,o.resultProperty))}n(Zb,"carriesUnfilteredList");function Yb(e){let{envelope:t,projectionMaps:r,allowedSets:o}=e,s=n(h=>Ah(h,r),"listTarget"),i=t.messages.filter(Th),a=new Map;for(let h of i){let y=bo(h.id);y!==void 0&&!a.get(y)&&a.set(y,s(h))}let c=Rh(i.map(h=>h.id)),d=t.messages[0],l=n(h=>{if(t.shape!=="batch")return d===void 0?void 0:s(d);let y=c(h);return y===void 0?void 0:a.get(y)},"targetForReply"),m=n(h=>{if(!Q(h))return Ie;if(!("result"in h))return"error"in h||"method"in h?h:Ie;let y=l(h.id);return y===void 0||Zb(h.result,y,r)?Ie:y===null?h:Wb(h,y.rule,y.projections,o?.[y.rule.option])},"filterMessage");return h=>{if(!Array.isArray(h))return m(h);if(t.shape!=="batch")return Ie;let y=h.map(m);return y.includes(Ie)?Ie:y}}n(Yb,"createReplyFilter");function Xb(e){return It(e.headers.get("content-type")).includes("json")}n(Xb,"isJsonResponse");function Qb(e){return It(e.headers.get("content-type"))==="text/event-stream"}n(Qb,"isEventStreamResponse");var ev=10*1024*1024,tv=/^[\w.~:/+=-]{0,256}$/;function rv(e){if(nh(e))return null;let t=!1;for(let o of e.lines){let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&tv.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=n(o=>o.trim()===""?o:"","blank");return{...e,lines:e.lines.map(o=>o.startsWith(":")?`:${r(o.slice(1))}`:o),comments:e.comments.map(r)}}n(rv,"inspectSseLines");var Ph="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",nv="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function Pa(e,t){let r=e.messages.filter(Th),o=new Map,s=new Set;for(let l of r){let m=l.id,h=bo(m);m==null||h===void 0||(o.set(h,m),Ah(l,t)!==null&&s.add(h))}let i=Rh(r.map(l=>l.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:bo(a.id),d=new Set;return{keyOf(l){if(!(!Q(l)||!("result"in l||"error"in l)))return e.shape==="batch"?i(l.id):c},isPending:n(l=>l!==void 0&&o.has(l),"isPending"),hasFailed:n(l=>d.has(l),"hasFailed"),answer(l){l!==void 0&&o.delete(l)},fail(l){return[...l].flatMap(m=>{let h=o.get(m);return h===void 0?[]:(o.delete(m),d.add(m),[{jsonrpc:"2.0",id:h,error:{code:k.InternalError,message:s.has(m)?Ph:nv}}])})},pendingKeys:n(()=>[...o.keys()],"pendingKeys")}}n(Pa,"createReplyTracker");function xh(e,t,r){let o=[],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)?Ie:t(i);c!==Ie?(o.push(c),r.answer(a)):r.isPending(a)?o.push(...r.fail([a])):s++}return{replies:o,dropped:s}}n(xh,"filterBatchMembers");function ov(e){let{response:t,envelope:r,projectionMaps:o,filterReply:s,warn:i}=e,a=Pa(r,o),c=!1,d=n(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),l=n(h=>h.map(y=>({data:JSON.stringify(y)})),"toEvents"),m=n(()=>a.pendingKeys().length===0,"isDone");return sh(t,h=>{let y=rv(h);if(y===null)return d("it has a line the filter does not forward");if(y.data===void 0||y.data==="")return y;let f;try{f=JSON.parse(y.data)}catch{return d("its data is not JSON")}let R=a.keyOf(f);if(R!==void 0&&a.hasFailed(R))return null;let S=s(f);if(S===Ie&&r.shape==="batch"&&Array.isArray(f)){let{replies:w,dropped:x}=xh(f,s,a);if(x>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),w.length===0)return null;let I=Ra(y,JSON.stringify(w));return m()?ba(I):I}if(S===Ie){if(!a.isPending(R))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let w=l(a.fail([R]));return m()?ba(...w):w}for(let w of Array.isArray(S)?S:[S])a.answer(a.keyOf(w));return S===f?y:Ra(y,JSON.stringify(S))},{maxEventChars:ev,onOversize:"discard",end:n(({unterminated:h,discardedEvents:y})=>((h||y>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||y>0?l(a.fail(a.pendingKeys())):null),"end"),onFailure:n((h,y)=>{i(`could not rewrite the upstream SSE stream (${y.kind})`)},"onFailure")})}n(ov,"filterEventStream");var Aa=Symbol("access unresolved"),wh=10*1024*1024,Oh="the request body could not be read";async function sv(e,t,r){let o=e.clone().body;if(o===null)return{blank:!0,overLimit:!1};let s=o.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:l}=await s.read(),m=d?i.decode():i.decode(l,{stream:!0});if(a+=m.length,c&&=!/\S/.test(m),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}n(sv,"scanBody");function Ma(e){return Array.isArray(e)?`batch member 0: ${Ma(e[0])}`:Q(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}n(Ma,"invalidMessageReason");async function iv(e,t){if(e.body===null)return;let r=n(()=>He.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)>wh)return r();let s=It(e.headers.get("content-type")).includes("json"),i=n(()=>He.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=n(()=>Ro(400,{code:k.ParseError,message:`Parse error: ${Oh}`}),"unreadable"),c;try{c=await sv(e,wh,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(m){return m instanceof SyntaxError?Ro(400,{code:k.ParseError,message:"Parse error: Invalid JSON"}):a()}let l=Q(d)?d.id:void 0;return Ro(400,{code:k.InvalidRequest,message:`Invalid Request: ${Ma(d)}`},Eh(l)?l:void 0)}n(iv,"refuseUninspectable");var xa=class extends ns{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let o=Eb(t,r);super(o,r),this.#r=r,this.#e=Ub(o),this.#t=Ob(o,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,mh(i)]))}async handler(t,r){let o=await Bp(t);if(o===null)return await iv(t,r)??t;let s=o.messages.findIndex(Hb);if(s!==-1)return Ds(`batch member ${s}: ${Ma(o.messages[s].raw)}`);let i=o.messages.findIndex(Bb);if(i!==-1)return Ds(o.shape==="batch"?`batch member ${i}: method must be a string`:"method must be a string");let a=Hp(o);if(a===void 0)try{a=await t.clone().text()}catch{return Ro(400,{code:k.ParseError,message:`Parse error: ${Oh}`})}if(lh({envelope:o,text:a,isCapabilityMethod:Ih}))return Ds("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let c=new Map;for(let f of o.messages){let R=ut(f),S=R===void 0?void 0:qb(R);S!==void 0&&this.#s(S)&&c.set(f,Jb)}let d=c.size===0&&this.#t!==void 0&&this.#u(o)?await this.#c(t,r):void 0;if(c.size===0)for(let f of o.messages){let R=d===Aa?this.#s(ut(f)??"")?yh:void 0:this.#d(f,d,o.protocolVersion);R!==void 0&&c.set(f,R)}if(c.size>0)return Sh(o,c);if(d===Aa)return Sh(o,new Map(o.messages.map(f=>[f,yh])));if(!this.#o(o))return t;let l=Yb({envelope:o,projectionMaps:this.#e,allowedSets:d}),m=n(f=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${f}`),"warn"),h=n((f,R)=>{m(`did not forward an upstream reply (${f}); answered -32603`);let S=Pa(o,this.#e),w=S.fail(S.pendingKeys()),x=dt(new Headers(R.headers));return x.set("content-type","application/json"),w.length===0?new Response(JSON.stringify(wo({code:k.InternalError,message:Ph})),{status:502,headers:x}):new Response(JSON.stringify(o.shape==="batch"?w:w[0]),{status:200,headers:x})},"unreadable");r.addResponseSendingHook(async f=>{let R=!f.ok;if(f.body!==null&&Tt(f.headers))return R?f:h("its body is still content-encoded",f);if(Qb(f))return ov({response:f,envelope:o,projectionMaps:this.#e,filterReply:l,warn:m});if(!Xb(f))return f.ok&&f.status!==202&&f.status!==204&&f.body!==null?h("no or an unknown media type",f):f;let S;try{S=await f.clone().json()}catch{return R?f:h("its body is not JSON",f)}if(R&&!Array.isArray(S)&&!(Q(S)&&"result"in S))return f;let w=l(S);if(w===Ie&&o.shape==="batch"&&Array.isArray(S)){let I=Pa(o,this.#e),{replies:O,dropped:N}=xh(S,l,I);N>0&&O.push(...I.fail(I.pendingKeys())),O.length>0&&(m("did not forward a batch reply member it could not read; sent the rest"),w=O)}if(w===Ie)return h("the filter could not read the reply",f);if(w===S)return f;let x=dt(new Headers(f.headers));return new Response(JSON.stringify(w),{status:f.status,statusText:f.statusText,headers:x})});let y=new _r(t);return y.headers.set("accept-encoding","gzip, br"),y}#d(t,r,o){let s=n(a=>this.#e[a]!==void 0,"isConfigured"),i=n((a,c)=>{let d=r?.[a];return this.#e[a]?.has(c)===!0&&(d===void 0||d.has(c))},"isAllowed");for(let a of jb(t)){if(!(a.refusedBy??a.options).some(s))continue;let{target:c}=a;if(c===void 0)return zb(ut(t)??"",a.issue);if(!(a.resource?this.#g(c,i):a.options.filter(s).some(l=>i(l,c))))return a.notFound(c,o??null)}}#g(t,r){let o=this.#e.resources!==void 0;if(o&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!hh(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!o&&!s}#s(t){let r=n(o=>this.#e[o]!==void 0,"isConfigured");return t===Ls?Ch.some(r):Ua(t)?.option==="resources"&&r("resourceTemplates")?!0:lt.some(o=>r(o.option)&&(o.listMethod===t||o.directMethods.includes(t)))}#u(t){return t.messages.some(r=>{let o=ut(r);return o!==void 0&&this.#s(o)})}#o(t){return t.messages.some(r=>{let o=vh(ut(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#c(t,r){let o=this.#t;if(o===void 0)return{};let s;try{s=await o(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),Aa}let i={};for(let a of lt){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let l=new Set;if(Array.isArray(d))for(let m of d)typeof m=="string"&&c.has(m)&&l.add(m);i[a.option]=l}return i}};var qa="zuplo.com",av=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),cv=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Uh(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Uh,"s2FaviconHref");function dv(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`}n(dv,"strictFaviconHref");var Mh=Uh(qa);function za(e){let t=e.toLowerCase();return t===qa||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Uh(qa):dv(e)}n(za,"resolveIconHref");function uv(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(uv,"hostnameFromHost");function lv(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(lv,"isLocalOrAddressHost");function pv(e){let t=uv(e).toLowerCase().replace(/\.$/,"");if(lv(t)||cv.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),s=av.has(o)?3:2;return r.slice(-s).join(".")}n(pv,"inferFaviconDomain");function Na(e){return{src:za(pv(e)),mimeType:"image/png",sizes:["128x128"]}}n(Na,"resolveMcpFaviconIcon");function Hs(e){try{return Na(new URL(e).host)}catch{return}}n(Hs,"resolveMcpFaviconIconFromUrl");function kt(e){let t=_e().connectionsById.get(e);if(!t)throw new Y(`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}}}n(kt,"getUpstreamServerConfig");function Bs(e){let t=_e().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new Y(`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}n(Bs,"getUpstreamAuthConfig");function Nr(e,t){let r=Bs({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new Y(`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}n(Nr,"requireUpstreamOAuthConfig");function qh(e,t){let r=Bs({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new Y(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(qh,"requireUpstreamIdJagConfig");import{base64url as Js}from"jose";var mv="__Host-",hv=16,fv=32,Nh=".",gv=!1;function At(){return gv}n(At,"isBrowserBindingEnforced");var vo=p.object({id:p.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:p.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function Fs(e,t){return new URL(ne(e,t)).protocol==="https:"}n(Fs,"isSecureGatewayOrigin");function ja(e,t){return t?`${mv}${e}`:e}n(ja,"gatewayCookieName");function Co(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}n(Co,"serializeGatewayCookie");function Da(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}n(Da,"parseCookieHeader");function zh(e){return Js.encode(crypto.getRandomValues(new Uint8Array(e)))}n(zh,"randomBase64url");async function jh(e){let t=await crypto.subtle.digest("SHA-256",he(new TextEncoder().encode(e)));return Js.encode(new Uint8Array(t))}n(jh,"hashNonce");function yv(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o+=1)r|=e.charCodeAt(o)^t.charCodeAt(o);return r===0}n(yv,"constantTimeEqual");function Dh(e,t,r){return ja(`zuplo_mcp_${e}_${t}`,r)}n(Dh,"bindingCookieName");async function Io(e){let t=zh(hv),r=zh(fv),o=Fs(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${Nh}${Js.encode(e.payload)}`;return{claim:{id:t,hash:await jh(r)},setCookie:Co({name:Dh(e.purpose,t,o),value:s,maxAgeSeconds:e.ttlSeconds,secure:o})}}n(Io,"startBrowserBinding");async function Gs(e){let t=Fs(e.request.url,e.request.headers),r=Dh(e.purpose,e.claim.id,t),o=Co({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Da(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:o};let i=s.indexOf(Nh),a=i<0?s:s.slice(0,i);if(!yv(await jh(a),e.claim.hash))return{matched:!1,clearCookie:o};if(i<0)return{matched:!0,clearCookie:o};try{return{matched:!0,payload:new TextDecoder().decode(Js.decode(s.slice(i+1))),clearCookie:o}}catch{return{matched:!1,clearCookie:o}}}n(Gs,"verifyBrowserBinding");function $h(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n($h,"mergeAbortSignals");async function Sv(e){try{await e.cancel()}catch{}}n(Sv,"cancelReader");async function Vs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await Sv(r),t.createLimitError();o.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of o)a.set(d,c),c+=d.byteLength;return a}n(Vs,"readBoundedByteStream");var _v=2,wv=1024*1024,Rv=1e4,bv=new Set([301,302,303,307,308]),vv=["authorization","proxy-authorization","cookie","cookie2"];function $a(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n($a,"readRequestUrl");function jr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(jr,"readRequestMethod");function Cv(e,t,r){let o=e.headers.get("content-length");if(!o)return;let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>t)throw new T({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[E]:r}})}n(Cv,"assertContentLengthWithinLimit");async function Iv(e,t,r){return Cv(e,t,r),Vs(e.body,{maxBytes:t,createLimitError:n(()=>new T({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[E]:r}}),"createLimitError")})}n(Iv,"readBoundedResponseBody");function Tv(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})}n(Tv,"responseFromBufferedBody");function Ev(e,t){if(!bv.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ev,"resolveRedirectUrl");function Lh(e,t){try{return t.validateUrl(e)}catch(r){throw new T({message:"Outbound URL was not allowed.",extensionMembers:{[E]:t.problemCode}},{cause:r})}}n(Lh,"validateOutboundUrl");function kv(e,t){throw e instanceof T&&ps(e.extensionMembers?.[E])?e:new T({message:"Outbound fetch failed.",extensionMembers:{[E]:t}},{cause:e})}n(kv,"normalizeFetchError");function To(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[o,s]of Object.entries(t.extra))s!==void 0&&(r[o]=s);t.error!==void 0&&Ce(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(To,"logOutboundFailure");async function Av(e,t,r,o,s,i,a){let c=jr(r,o);try{return await t(r,o)}catch(d){let l=d instanceof DOMException&&d.name==="AbortError";To(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ce(i),error:d,extra:{abortReason:a()}}),kv(d,s)}}n(Av,"fetchWithNormalizedError");function Pv(e){if(e.redirects>=e.maxRedirects)throw new T({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[E]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new T({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[E]:e.problemCode}})}n(Pv,"assertRedirectAllowed");function xv(e,t){let r=new Headers(e);for(let o of vv)r.delete(o);for(let o of t)r.delete(o);return r}n(xv,"stripCrossOriginHeaders");function Ov(e,t,r,o,s){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=xv(e.headers,s)),i}n(Ov,"buildRedirectInit");function Uv(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Uv,"buildInitialRequestInit");function Mv(e){let t=jr(e.currentInput,e.currentInit);Pv({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Lh(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),s=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Ov(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Mv,"followRedirect");async function La(e,t,r){let o=r.problemCode??"invalid_request",s=r.maxRedirects??_v,i=r.maxResponseBytes??wv,a=r.timeoutMs??Rv,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],l=r.context,m=new AbortController,h=$h(m,t.signal),y=!1,f=setTimeout(()=>{y=!0,m.abort()},a),R=e,S=Uv(e,t,m.signal),w;try{w=Lh($a(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(I){throw To(l,{event:"outbound_url_blocked",problemCode:o,method:jr(e,t),host:ce($a(e)),error:I}),clearTimeout(f),h?.(),I}let x=0;try{for(;;){let I=await Av(l,c,R,S,o,w,()=>y?`timeout_after_${a}ms`:void 0),O=Ev(I,w);if(O!==void 0)try{let N=Mv({currentInput:R,currentInit:S,currentUrl:w,redirectUrl:O,redirects:x,maxRedirects:s,problemCode:o,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:d});R=N.currentInput,S=N.currentInit,w=N.currentUrl,x=N.redirects;continue}catch(N){throw To(l,{event:"outbound_redirect_blocked",problemCode:o,method:jr(R,S),host:ce(w),error:N,extra:{redirects:x,maxRedirects:s,redirectTargetHost:ce(O)}}),N}try{return Tv(I,await Iv(I,i,o))}catch(N){throw To(l,{event:"outbound_response_size_exceeded",problemCode:o,method:jr(R,S),host:ce(w),error:N,extra:{maxResponseBytes:i,status:I.status}}),N}}}finally{clearTimeout(f),h?.()}}n(La,"runSafeOutboundExchange");async function Eo(e,t,r){let o=await La(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(s){throw To(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:jr(e,t),host:ce($a(e)),error:s,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new T({message:"Outbound JSON response could not be parsed.",extensionMembers:{[E]:r.problemCode??"invalid_request"}},{cause:s})}}n(Eo,"runSafeOutboundJsonExchange");function Hh(e,t={},r={}){return La(e,t,{...r,validateUrl:so})}n(Hh,"fetchConfiguredOutbound");function Bh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:so})}n(Bh,"fetchConfiguredOutboundJson");function Ks(e,t={},r={}){return Eo(e,t,{...r,validateUrl:Ap})}n(Ks,"fetchIdentityProviderJson");function Jh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:Rs})}n(Jh,"fetchCimdClientMetadataJson");function Fh(e,t={},r={}){return Eo(e,t,{...r,validateUrl:io})}n(Fh,"fetchCimdClientJwksJson");import{errors as Yh,jwtVerify as Xh,SignJWT as Qh}from"jose";var Te="zuplo-mcp-gateway",Pe=Te,xe="HS256";import{base64url as qv}from"jose";var zv=new TextEncoder,Nv="MCP gateway could not initialize secure key material.",jv=32,Gh=new Map,Vh=new Map,Dv;function $v(){return Dv??es.instance.authPrivateKey}n($v,"readAuthPrivateKey");function Kh(e){return new be(Nv,e===void 0?void 0:{cause:e})}n(Kh,"createGeneratedKeyMaterialError");function Wh(e,t){let r=qv.decode(t);if(r.byteLength!==jv)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Wh,"decodeJwkKeyField");function Lv(e){let t=$v();if(!t)throw Kh();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 o=Wh("d",r.d);Wh("x",r.x);let s=zv.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+o.byteLength);return i.set(s),i.set(o,s.byteLength),i}catch(r){throw Kh(r)}}n(Lv,"decodeGeneratedKeyMaterial");function Hv(e){let t=Gh.get(e);return t||(t=Lv(e),Gh.set(e,t)),t}n(Hv,"getMasterKeyMaterial");async function tt(e){let t=Vh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Hv(e.keyMaterialPurpose));return Vh.set(e.purpose,r),r}n(tt,"readCachedDerivedKey");var Bv="SHA-256",Jv=32,Fv="zuplo-mcp-gateway:",Gv=new TextEncoder,Zh=new WeakMap;async function Pt(e,t){let r=Zh.get(e);r||(r=new Map,Zh.set(e,r));let o=r.get(t);if(o)return o;let s=await Vv(e,t);return r.set(t,s),s}n(Pt,"deriveGatewaySigningKey");async function Vv(e,t){let r=he(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=Gv.encode(`${Fv}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:Bv,salt:new Uint8Array,info:he(s)},o,Jv*8);return new Uint8Array(i)}n(Vv,"hkdfExpand");var ef=900,Kv=900,Wv=lp.extend({id:Mp,browserBinding:vo.optional()}),Zv=Wv.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),tf=xi.extend({id:qp,purpose:p.literal("browser_connect")}),Yv=xi.extend({purpose:p.literal("browser_connect")}),Xv=tf.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),Ws=ef*1e3;async function rf(){return tt({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"oauth-state"),"derive")})}n(rf,"getOAuthStateKey");async function nf(){return tt({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-connect"),"derive")})}n(nf,"getBrowserConnectKey");async function of(e){let t=Math.floor(Date.now()/1e3)+ef;return new Qh(e).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(t).sign(await rf())}n(of,"signOAuthState");async function Zs(e){try{let{payload:t}=await Xh(e,await rf(),{algorithms:[xe],issuer:Te,audience:Pe});return Zv.parse(t)}catch(t){throw t instanceof Yh.JWTExpired?new T({message:"OAuth state has expired",extensionMembers:{[E]:"oauth_state_expired"}},{cause:t}):new T({message:"OAuth state could not be verified",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:t})}}n(Zs,"verifyOAuthState");async function sf(e){let t=Math.floor(Date.now()/1e3)+Kv,r=Yv.parse(e),o=tf.parse({...r,id:Dp()});return new Qh(o).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(t).sign(await nf())}n(sf,"signBrowserConnectTicket");async function af(e){try{let{payload:t}=await Xh(e,await nf(),{algorithms:[xe],issuer:Te,audience:Pe});return Xv.parse(t)}catch(t){throw t instanceof Yh.JWTExpired?new T({message:"Browser connect ticket has expired",extensionMembers:{[E]:"oauth_state_expired"}},{cause:t}):new T({message:"Browser connect ticket could not be verified",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:t})}}n(af,"verifyBrowserConnectTicket");async function cf(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new T({message:"Browser connect ticket has already been used",extensionMembers:{[E]:"oauth_state_reused"}})}n(cf,"consumeBrowserConnectTicket");function Qv(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.`}n(Qv,"buildConnectRequiredMessage");async function eC(e){let t=ne(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 sf({...no(e),purpose:"browser_connect"})),r.toString()}n(eC,"buildGatewayBrowserTicketUrl");function tC(e){return me().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(tC,"buildGatewayConnectPath");async function Ha(e){return eC({...e,path:tC(e.upstreamServerId),redirect:!0})}n(Ha,"buildGatewayConnectUrl");async function Ys(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 Ha(t),message:Qv(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ys,"buildRedirectConnectRequiredResponse");function df(e){return uf({...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.`})}n(df,"buildAdminConnectRequiredResponse");function uf(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"}}n(uf,"buildAdminSetupRequiredResponse");function lf(e){return _e().byOperationId.get(e)?.downstreamOAuth!==void 0}n(lf,"routeSupportsBrowserConnect");function pf(e){return uf({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}n(pf,"buildBrowserConnectUnavailableResponse");var mf=12;async function hf(e){let t=await crypto.subtle.digest("SHA-256",he(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(hf,"sha256Hex");async function er(e){if(e)return(await hf(e)).slice(0,mf)}n(er,"fingerprintSecret");async function Dr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await hf(t)).slice(0,mf)}n(Dr,"fingerprintConnectionIdentity");var rC=6e4;function $r(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,o)=>t.scopes[o]!==r)}n($r,"credentialGenerationChanged");function Ee(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()+rC)return"near_expiry"}return"usable"}n(Ee,"describeAccessTokenState");var ff=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function nC(e,t){return e&&e.length>0?e.join(t):void 0}n(nC,"joinOAuthScopes");function oC(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ff)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(oC,"sanitizeAuthorizationServerMetadata");function gf(e){let t=oC(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(gf,"sanitizeOAuthDiscoveryState");function yf(e){let t=new URL(e);for(let r of ff){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(yf,"dedupeSingletonAuthorizationRequestParams");function Xs(e){let t=new URL(e);return qe(t)&&ep(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Xs,"normalizeLoopbackOAuthRedirectUri");function Sf(e){return nC(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Sf,"readProtectedResourceMetadataScope");function sC(e){return`Zuplo MCP Gateway - ${e}`}n(sC,"buildGatewayOAuthClientName");function iC(e,t){return e&&e.length>0?e.join(t):void 0}n(iC,"joinOAuthScopeList");function aC(e){if(e.clientRegistration.mode!=="auto")return iC(e.scopes,e.scopeDelimiter)}n(aC,"readPublicClientMetadataScope");function Ba(e){return new URL(me().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Ba,"buildOAuthClientMetadataDocumentUrl");function Ja(e){let t=kt(e.upstreamServerId);return{client_name:sC(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"}}n(Ja,"buildGatewayOAuthClientMetadata");function _f(e,t,r){let o=Nr(t,r),s=aC(o);return{client_id:Ba({origin:e,upstreamServerId:t}),...Ja({origin:e,upstreamServerId:t,redirectUri:Xs(new URL(o.redirectPath,e)).toString(),scope:s})}}n(_f,"buildOAuthClientMetadataDocument");import{base64url as xt}from"jose";var cC="SHA-256",Lr="AES-GCM",dC=12,Ga="zuplo-secret",Va=1,wf="generated:auth_private_key:token-encryption",uC=p.object({version:p.literal(Va),keyId:p.literal(wf),algorithm:p.literal(Lr),iv:p.string().min(1),ciphertext:p.string().min(1)}).strict();async function Fa(){return tt({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(cC,he(e));return crypto.subtle.importKey("raw",t,{name:Lr},!1,["encrypt","decrypt"])},"derive")})}n(Fa,"getEncryptionKey");function Rf(e){return he(new TextEncoder().encode(`${Ga}:v${e.version}:${e.keyId}`))}n(Rf,"getAssociatedData");function lC(e){return`${Ga}:v${e.version}:${xt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(lC,"encodeEnvelope");function pC(e){let t=`${Ga}:v${Va}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(xt.decode(r));return uC.parse(JSON.parse(o))}n(pC,"decodeEnvelope");async function pt(e){let t=await Fa(),r=crypto.getRandomValues(new Uint8Array(dC)),o={version:Va,keyId:wf},s=await crypto.subtle.encrypt({name:Lr,iv:r,additionalData:Rf(o)},t,new TextEncoder().encode(e));return lC({...o,algorithm:Lr,iv:xt.encode(r),ciphertext:xt.encode(new Uint8Array(s))})}n(pt,"encryptSecret");async function mt(e){let t=pC(e);if(t){let a=await Fa(),c=await crypto.subtle.decrypt({name:Lr,iv:he(xt.decode(t.iv)),additionalData:Rf(t)},a,he(xt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new be("Encrypted payload is malformed");let s=await Fa(),i=await crypto.subtle.decrypt({name:Lr,iv:he(xt.decode(r))},s,he(xt.decode(o)));return new TextDecoder().decode(i)}n(mt,"decryptSecret");var bf={issuer:p.string().min(1).optional()},mC=p.union([Zt.extend(bf),Qn.extend(bf)]),vf=p.object({authorizationServerUrl:p.url(),resourceMetadataUrl:p.url().optional(),resourceMetadata:Cr.optional(),authorizationServerMetadata:p.union([Ir,Tr]).optional()}).passthrough(),hC="Bearer",fC="__zuplo_refresh_only_upstream_access_token__";function Ka(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ka,"splitScopes");function Wa(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Wa,"scopesCover");function gC(e){return kr.parse(e)}n(gC,"parsePkceCodeVerifier");function yC(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}n(yC,"readTokenExpiry");async function Cf(e){if(e!==void 0)return pt(JSON.stringify(e))}n(Cf,"encryptJson");async function If(e,t){if(!e)return;let r=await mt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new T({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[E]:"oauth_state_invalid"}},{cause:o})}}n(If,"decryptJson");function SC(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(SC,"clientInformationAllowsRedirectUri");function _C(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(_C,"clientInformationMatchesCurrentClientMetadataUrl");function wC(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(wC,"isUrlBasedClientInformation");function RC(e,t){return t===void 0?e:{...e,scope:t}}n(RC,"applyOAuthClientMetadataScope");function bC(e,t){return Sf({state:e,delimiter:t})}n(bC,"readResourceMetadataScope");function vC(e,t){return e&&e.length>0?e.join(t):void 0}n(vC,"joinOAuthScopeList");function CC(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new Y(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Zt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(CC,"buildManualOAuthClientInformation");function IC(e,t){let r=Ba({origin:new URL(t).origin,upstreamServerId:e});return ha(r)?r:void 0}n(IC,"buildClientMetadataUrl");function TC(e){for(let t of e)if(t!==void 0)return t}n(TC,"firstDefined");function EC(e){let t=Nr(e.target.upstreamServerId,e.target.authProfileId),r=vC(t.scopes,t.scopeDelimiter),o=Ja({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:CC({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=IC(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}n(EC,"buildInitialOAuthClientSetup");function kC(e,t){if(t===void 0)return TC([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(kC,"readEncryptedClientInformation");function AC(e){return e.pendingState?.encryptedDiscoveryState}n(AC,"readEncryptedDiscoveryState");function Za(e,t){return t===void 0?e:{...e,issuer:t}}n(Za,"applyIssuerStamp");var Ot=class{static{n(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=EC({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=kC(t,this.configuredClientInformation),this.encryptedDiscoveryState=AC(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 o=Ka(this.configuredScope??r??this.readEffectiveScope());return Wa(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Ee(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 o=te();o&&o.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 Dr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await er(await mt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(o){let s=te();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:o}),{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 o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return RC(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return of({id:t.id,...no({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?Za(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,te()?.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"),!wC({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cf(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!As({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=gf(vf.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Cf(r),await this.syncPendingState(!1),te()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ce(r.authorizationServerUrl),resourceMetadataHost:ce(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=bC(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let s=Ka(this.configuredScope).filter(i=>!o.includes(i));s.length>0&&te()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:o},"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 Za(r,t?.issuer)}async saveTokens(t){let r=Rt.parse(t),o=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 pt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:Rt.parse({...r,refresh_token:await mt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??bs(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await pt(r.access_token),encryptedRefreshToken:a,scopes:Ka(r.scope??this.readEffectiveScope()),expiresAt:yC(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},l=await this.conditionalUpsertCredential(c,d),m=!1;if(l.kind==="precondition_failed"&&l.connection!==void 0&&(Ee(l.connection)!=="usable"||!Wa(l.connection.scopes,c.scopes)||!$r(s,l.connection))){m=!0;let y=l.connection,f={id:y.id,ownerMode:y.ownerMode,subjectId:y.subjectId,upstreamServerId:y.upstreamServerId,authProfileId:y.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?y.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:y.metadata};te()?.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:y.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:y.scopes.length,resultingScopeCount:f.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),l=await this.conditionalUpsertCredential(f,{expectedUpdatedAt:y.updatedAt})}if(l.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=l.kind,l.kind==="persisted"?(this.credentialState.currentConnection=l.connection,this.credentialState.peerAdoption=void 0):l.kind==="precondition_failed"&&l.connection!==void 0?(this.credentialState.currentConnection=l.connection,$r(s,l.connection)&&Ee(l.connection)==="usable"&&Wa(l.connection.scopes,c.scopes)?this.adoptPeerConnection(l.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),m){let y=l.kind==="persisted"?"succeeded":l.kind==="precondition_failed"?"lost":"exhausted";te()?.info({event:`upstream_oauth_bounded_rebase_${y}`,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 ${y}`)}let h=l.kind==="persisted"?l.connection:void 0;te()?.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 er(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:l.kind,rebaseAttempted:m,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=yf(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:gC(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new T({message:"OAuth code verifier is missing",extensionMembers:{[E]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(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:jp(),...no({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:J(new Date(Date.now()+Ws)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await If(this.encryptedClientInformation,mC)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!SC(r,this.redirectUriValue)||!_C({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Za(Qn.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 If(this.encryptedDiscoveryState,vf)}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"){te()?.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 mt(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await mt(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let s=te();this.usedRefreshTokenFingerprintValue=s?await er(o):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:!!o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Rt.parse({access_token:r??fC,token_type:hC,refresh_token:o,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 o=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,$r(r,a.connection)&&Ee(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=te();if(c){let d=a.kind==="missing"?void 0:a.connection,l={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:o,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...l,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(l,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(l,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var PC=3e4,xC=256*1024,OC=2,UC="does not support dynamic client registration",MC=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],qC=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],zC=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],NC="Protected resource ",jC=" does not match expected ",DC=["HTTP 403 Forbidden","Access Denied","permission to access"],$C=new Set([le.AccessDenied,le.InvalidClient,le.InvalidGrant,le.InvalidRequest,le.InvalidScope,le.InvalidTarget,le.UnauthorizedClient,le.UnsupportedGrantType]);function LC(e){return e instanceof Error&&e.message.includes(UC)}n(LC,"isDynamicClientRegistrationUnsupported");function HC(e){return e instanceof Error&&MC.some(t=>e.message.includes(t))}n(HC,"isProtectedResourceMetadataUnavailable");function BC(e){return e instanceof Error&&qC.some(t=>e.message.includes(t))}n(BC,"isAuthorizationServerMetadataUnavailable");function JC(e){return e instanceof Error&&zC.some(t=>e.message.includes(t))}n(JC,"isAuthorizationServerIncompatible");function FC(e){return e instanceof Error&&e.message.includes(NC)&&e.message.includes(jC)}n(FC,"isProtectedResourceMismatch");function GC(e){return e instanceof Error&&DC.some(t=>e.message.includes(t))}n(GC,"isUpstreamProviderAccessDenied");function VC(e){return e instanceof Ct&&$C.has(e.code)}n(VC,"isStoredConnectionReconsentError");function ht(e){let t=e.diagnostics??{};return new T({message:e.message,extensionMembers:{[E]:e.code,[ls]:e.upstreamServerId,[xr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[nt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[rt]:t.httpStatus},...t.providerError===void 0?{}:{[Or]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Ur]:t.providerErrorDescription}}},{cause:e.cause})}n(ht,"buildUpstreamSetupProblem");function KC(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.`}n(KC,"describeIssuerMetadataMismatch");var WC=128,ZC=256;function Tf(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Tf,"truncateProviderDetail");function YC(e){let{error:t,errorDescription:r}=kf(e.body),o=Tf(t,WC),s=Tf(r,ZC);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...s===void 0?{}:{providerErrorDescription:s}}}n(YC,"readRegistrationRejectionDiagnostics");function XC(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}`}n(XC,"describeRegistrationRejection");function QC(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(QC,"readDiscoveryEndpointUrl");function eI(e){if(e.error instanceof T&&e.error.extensionMembers?.[E]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(LC(e.error))return ht({...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 pa){let r=YC(e.error);return ht({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${XC(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 ho&&e.error.kind==="metadata")return ht({...t,code:"upstream_oauth_issuer_mismatch",message:KC(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof qs)return ht({...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(JC(e.error))return ht({...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(BC(e.error)){let r=QC(e.error.message);return ht({...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(FC(e.error))return ht({...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(HC(e.error))return ht({...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(GC(e.error))return ht({...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.`})}n(eI,"mapUpstreamOAuthSetupError");function tI(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(tI,"readOAuthFetchRequest");function rI(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(rI,"readOAuthFetchMethod");function nI(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(nI,"responseLooksJson");function oI(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(oI,"responseLooksHtml");var sI=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function iI(e){return sI.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(iI,"isMetadataDiscoveryRequest");function aI(e,t,r){return e!=="GET"||!iI(t)?!1:r>=400&&r<500||r===502}n(aI,"sdkRetriesDiscoveryCandidate");function cI(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new T({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[E]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[rt]:e.response.status,[Ar]:r,[nt]:e.request.url.toString(),[Pr]:e.body}})}n(cI,"throwUpstreamHtmlError");function kf(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(kf,"readUpstreamOAuthErrorBody");function dI(e){let{error:t,errorDescription:r}=kf(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ce(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(dI,"logUpstreamOAuthHttpError");function Af(e){return async(t,r)=>{let o=tI(t),s=rI(t,r),i=te(),a=Date.now(),c=await Hh(t,r,{maxRedirects:OC,maxResponseBytes:xC,problemCode:"upstream_token_exchange_failed",timeoutMs:PC}),d=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:ce(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:d.length},"Upstream OAuth HTTP request completed"),c.ok||dI({log:i,upstreamServerId:e,method:s,request:o,response:c,body:d}),aI(s,o.url,c.status)||(!c.ok&&oI(c,d)&&cI({upstreamServerId:e,request:o,response:c,body:d}),!nI(c,d)))return c;try{JSON.parse(d)}catch(l){throw new T({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[E]:"upstream_token_exchange_failed"}},{cause:l})}return c}}n(Af,"createUpstreamOAuthFetch");function Pf(e){te()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ce(e.serverUrl),resourceMetadataHost:ce(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Pf,"logUpstreamOAuthFlowStarted");function xf(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ce(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof T?e.error.extensionMembers?.[E]:void 0;typeof o=="string"&&(t.code=o),Ce(t,"error",e.error),te()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(xf,"logUpstreamOAuthFlowFailed");function Of(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Of,"readAuthorizationRequestScope");async function Uf(e,t){e.applyChallengeScope(t.requestedScope),Pf({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Af(t.upstreamServerId)},o=Of(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await ma(e,r)}catch(r){xf({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=eI({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Uf,"runUpstreamOAuth");async function uI(e,t){e.applyChallengeScope(t.requestedScope),Pf({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Af(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Of(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await ma(e,r)}catch(s){throw xf({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}n(uI,"exchangeUpstreamAuthorizationCode");async function Ef(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await H().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Ee(r)!=="usable"||!$r(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(Ef,"adoptPeerCredentialAtResolutionBoundary");async function Mf(e,t){let r=await Uf(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new T({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}}):new T({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}})}n(Mf,"requireUpstreamAuthorizationRedirect");async function qf(e){let t=Ee(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=te(),i=s?await Dr({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:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a;try{a=await Uf(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!VC(c))throw c;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await Ef({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 Ya({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Ya({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new T({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new T({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});return await Ef({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 Ya({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}})}}n(qf,"authorizeUpstreamOAuthSession");async function lI(e){let t=await Zs(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),o=pI(r);return mI({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),hI(o),o}n(lI,"consumeStoredCallbackState");function pI(e){switch(e.kind){case"consumed":throw new T({message:"OAuth state has already been used",extensionMembers:{[E]:"oauth_state_reused"}});case"missing":throw new T({message:"OAuth state is missing or expired",extensionMembers:{[E]:"oauth_state_expired"}});case"available":return e.record}}n(pI,"readConsumedCallbackState");function mI(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 T({message:"OAuth callback did not match the initiating request",extensionMembers:{[E]:"oauth_callback_mismatch"}})}n(mI,"assertStoredCallbackStateMatches");function hI(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new T({message:"OAuth state has expired",extensionMembers:{[E]:"oauth_state_expired"}})}n(hI,"assertStoredCallbackStateFresh");async function Ya(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),df(r)}if(At()&&!lf(e.operationId))return te()?.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"),pf({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),Ys(t)}n(Ya,"buildOAuthConnectRequiredResponse");async function zf(e){let t=await lI({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=fs(t),[o]=await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(s.connection=o);let i=new Ot(s),a=await uI(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 T({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[E]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new T({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}}):new T({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[E]:"upstream_token_exchange_failed"}})}n(zf,"finishUpstreamOAuthCallback");import{importPKCS8 as fI,SignJWT as gI}from"jose";var jf=1e4,Df=64*1024,$f=2,yI=300,Ze=p.string().min(1),SI=p.object({access_token:Ze,issued_token_type:p.literal(Ui),token_type:p.string().optional(),expires_in:p.number().int().positive().optional(),scope:Ze.optional()}).passthrough(),_I=p.object({id_token:Ze,token_type:Ze.optional(),expires_in:p.number().int().positive().optional(),refresh_token:Ze.optional(),scope:Ze.optional()}).passthrough(),wI=p.object({access_token:Ze,token_type:Ze,expires_in:p.number().int().positive().optional(),scope:Ze.optional(),resource:Ze.optional(),refresh_token:Ze.optional()}).passthrough();function Nf(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Nf,"formEncodeClientCredential");function RI(e){return e.replaceAll("\\n",`
41
- `)}n(RI,"normalizePem");async function bI(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??yI,o=await fI(RI(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new gI({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(bI,"createPrivateKeyJwtClientAssertion");async function vI(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=Nf(e.clientAuth.clientId),r=Nf(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",ys),e.form.set("client_assertion",await bI({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(vI,"appendClientAuthentication");async function Xa(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await vI({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(Xa,"buildFormRequest");function Lf(e){return(t,r)=>Ks(t,r,{context:e,maxRedirects:$f,maxResponseBytes:Df,problemCode:"upstream_token_exchange_failed",timeoutMs:jf})}n(Lf,"defaultIdpFetchJson");function CI(e){return(t,r)=>Bh(t,r,{context:e,maxRedirects:$f,maxResponseBytes:Df,problemCode:"upstream_token_exchange_failed",timeoutMs:jf})}n(CI,"defaultResourceAsFetchJson");function Qs(e){let t={[E]:e.code,[nt]:e.tokenUrl};return e.response!==void 0&&(t[rt]=e.response.status),new T({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(Qs,"runtimeError");function Qa(e){if(!e.response.ok)throw Qs({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})}n(Qa,"assertTokenEndpointSucceeded");function II(e){let t=_I.safeParse(e.json);if(!t.success)throw Qs({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}n(II,"parseIdpRefreshTokenResponse");function TI(e){let t=SI.safeParse(e.json);if(!t.success)throw Qs({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}n(TI,"parseIdJagTokenExchangeResponse");function EI(e){let t=wI.safeParse(e.json);if(!t.success)throw Qs({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}n(EI,"parseAccessTokenResponse");async function Hf(e){let t=new URLSearchParams({grant_type:gs,requested_token_type:Ui,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??Lf(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qa({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),TI({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Hf,"requestIdJag");async function Bf(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Lf(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qa({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),II({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Bf,"refreshIdpSubjectToken");async function Jf(e){let t=new URLSearchParams({grant_type:vt,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??CI(e.context),{response:o,json:s}=await r(e.resourceAs.tokenUrl,await Xa({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Qa({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),EI({json:s,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Jf,"exchangeIdJagForAccessToken");function kI(e){return Ee(e)==="usable"}n(kI,"hasUsableAccessToken");function AI(e){if(e.tokenType.toLowerCase()!=="bearer")throw new T({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[E]:"upstream_token_response_invalid"}})}n(AI,"assertBearerToken");function Ff(e,t){if(t===zr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Ff,"hasExpiredSubjectToken");async function PI(e){let t=await mt(e.encryptedSubjectToken);if(e.subjectTokenType!==zr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Bf({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:oo};let o=await H().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await pt(r.refreshToken),idpSubjectTokenType:zr,idpSubjectTokenExpiresAt:void 0}});return te()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:o.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await er(t),newSubjectRefreshTokenFingerprint:await er(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:oo}}n(PI,"resolveIdJagSubjectToken");async function Gf(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Ee(t),o=!!e.forceRefresh,s=!o&&r==="usable",i=te(),a=i?await Dr({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:o,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&kI(t))return{kind:"authorized",credential:{type:"bearer_token",token:await mt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||Ff(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&&Ff(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 l=kt(e.upstreamServerId),m=qh(e.upstreamServerId,e.authProfileId),h=m.resourceAs.resource??l.transport.baseUrl,y=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),f=await PI({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),R=await Hf({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:f.subjectToken,subjectTokenType:f.subjectTokenType,audience:m.resourceAs.audience,resource:h,scope:y,clientAuth:m.idp.clientAuth,context:e.context}),S=R.scope??y,w=await Jf({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:R.assertion,resource:h,scope:S,clientAuth:m.resourceAs.clientAuth,context:e.context});if(AI(w),t!==void 0){let I=(w.scope??S)?.split(/[,\s]+/).filter(Boolean)??[],O=w.expiresIn===void 0?void 0:J(new Date(Date.now()+w.expiresIn*1e3)),N=await H().upsertUpstreamConnection({id:f.connection.id,ownerMode:f.connection.ownerMode,subjectId:f.connection.subjectId,upstreamServerId:f.connection.upstreamServerId,authProfileId:f.connection.authProfileId,status:"active",encryptedAccessToken:await pt(w.accessToken),encryptedRefreshToken:f.connection.encryptedRefreshToken,scopes:I,expiresAt:O,metadata:f.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:f.connection.status,priorUpdatedAt:f.connection.updatedAt,scopeCount:I.length,expiresAt:O},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:w.accessToken}}}n(Gf,"authorizeUpstreamIdJagRequest");var ei=new Map;function xI(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(xI,"normalizeRefreshFlightScope");function OI(e){return Xs(new URL(e.callbackPath,ne(e.requestUrl,e.requestHeaders))).toString()}n(OI,"buildGatewayOAuthRedirectUri");async function ec(e){let t=kt(e.upstreamServerId),r=Nr(e.upstreamServerId,e.authProfileId),o=OI({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:ne(e.request.url,e.request.headers)}}}n(ec,"prepareUpstreamOAuthRequest");async function Vf(e){let t=await ec(e),r=new Ot({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Mf(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Vf,"startUpstreamConnect");async function Kf(e){let t=await ec(e),r=new Ot({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>qf({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&&Ee(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o();let s=zp({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,xI(r.configuredAuthorizationScope??e.requestedScope)]),a=ei.get(i);if(a!==void 0){te()?.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 l=await a;if(l.kind==="usable"&&r.connectionSatisfiesRequestedScope(l.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(l.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:m,...h}=e;if(t=await ec(h),r=new Ot({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Ee(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o()}let c=o(),d;return d=c.then(()=>{let l=r.currentConnection;return l!==void 0&&Ee(l)==="usable"?{kind:"usable",connection:l}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{ei.get(i)===d&&ei.delete(i)}),ei.set(i,d),c}n(Kf,"authorizeUpstreamRequest");async function Hr(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Kf({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 Gf({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 be(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Hr,"resolveUpstreamCredentialForRoute");async function Wf(e){if(e.connectRequest.authMode==="id-jag")throw new be(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Vf({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}}n(Wf,"startUpstreamConnectForRequest");async function UI(e,t){if(t===void 0)throw new T({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[E]:"oauth_callback_mismatch"}});let r=await Gs({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new T({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[E]:"oauth_callback_mismatch"}})}n(UI,"requireCallbackBrowser");async function Zf(e){let t=await Zs(e.callbackRequest.state);At()&&await UI(e,t.browserBinding);let r=t.authProfileId;if(Bs({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new be(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return zf({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:kt(e.callbackRequest.upstreamServerId)})}n(Zf,"finishUpstreamCallbackForRequest");function MI(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}}n(MI,"buildRouteAuthBaseFromConnection");function Yf(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:pp(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Yf,"buildRouteAuthBaseFromPolicyOptions");function ti(e,t){let o=_e().byOperationId.get(t);if(!o)throw new Y(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new Y(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new Y(`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 MI({connection:o.connection,operationId:t})}n(ti,"resolveRouteAuthBase");function tc(e,t){switch(e){case"user":return Mr(t);case"shared":return up()}}n(tc,"buildOwnerForSubject");function Br(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:tc("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:tc("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:tc("user",t),initiatedBySubjectId:t}}}n(Br,"resolveRouteAuthForSubject");var rc=new WeakMap;function Xf(e,t){rc.set(e,t)}n(Xf,"setUpstreamAuthRetry");function Qf(e){let t=rc.get(e);return rc.delete(e),t}n(Qf,"takeUpstreamAuthRetry");var qI=k.InvalidRequest,zI="The upstream connection returned no OAuth tokens.";function eg(e){let t=ga(e);return Response.json(ya({id:t,error:{code:k.InternalError,message:zI}}),{status:t===void 0?500:200})}n(eg,"noUpstreamTokensJsonRpcResponse");function NI(e,t){return{credentialType:e.type,forceRefresh:t}}n(NI,"buildCredentialResolvedAttributes");function jI(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(jI,"connectRequiredReasonCode");function tg(e){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:NI(e.credential,e.forceRefresh===!0)})}n(tg,"emitCredentialResolvedAnalyticsEvent");function rg(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(X(e.context,{eventType:F.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"){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:jI(e.payload.state),reasonClass:"auth",attributes:t})}n(rg,"emitCredentialMissingAnalyticsEvents");function DI(e){let t=e.route.raw();return hs.parse(t?.operationId)}n(DI,"readOperationId");async function $I(e,t,r,o,s){let i=await Hr({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return rg({context:o,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),o.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(tg({context:o,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}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}n($I,"buildCredentialHeaders");var LI=new Set(["authorization","cookie","cookie2"]);function HI(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}n(HI,"parseJsonRequestBody");function BI(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}n(BI,"readJsonRequestMethod");function JI(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(JI,"isJsonResponse");function nc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(nc,"isRecord");function FI(e){return Array.isArray(e)&&e.length>0}n(FI,"hasIconList");function GI(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Hs(cp(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(GI,"readFallbackServerIcons");function VI(e){if(!nc(e.body))return e.body;let t=e.body.result;if(!nc(t))return e.body;let r=t.serverInfo;return!nc(r)||FI(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(VI,"addMissingServerIcons");function KI(e,t){let r=ng(e.headers);for(let o of LI)r.delete(o);for(let[o,s]of t)r.set(o,s);return new _r(e,{headers:r})}n(KI,"applyUpstreamHeaders");function ng(e){let t=new Headers(e);return sd(t),t}n(ng,"buildProxyHeaders");async function WI(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(WI,"readRetryBody");function og(e,t){let r=t.authUrl===void 0?void 0:Zm({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(ya({id:ga(e),error:{code:r?.code??qI,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(og,"connectRequiredJsonRpcResponse");async function ZI(e){let{scope:t}=Fm(e.upstreamResponse),r=await Hr({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return rg({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),s=r.credential;if(tg({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return o.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:o};let i=await s.provider.tokens();return i?(o.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:o}):(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"})}n(ZI,"applyRefreshedCredentialHeaders");function YI(e){Xf(e.context,{refresh:n(async(t,r)=>{let o=await ZI({request:e.request,context:e.context,headers:ng(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return o.kind==="connect_required"?{kind:"response",response:og(e.requestBody,o.payload)}:o.kind==="no_tokens"?{kind:"response",response:eg(e.requestBody)}:o},"refresh")})}n(YI,"registerUpstreamAuthRetry");function XI(e){if(BI(e.requestJson)!=="initialize")return;let t=GI({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!JI(r))return r;let o;try{o=await r.clone().json()}catch{return r}let s=VI({body:o,icons:t});if(s===o)return r;let i=Xm(new Headers(r.headers));return i.delete("content-length"),new Response(JSON.stringify(s),{status:r.status,statusText:r.statusText,headers:i})})}n(XI,"installInitializeIconHook");async function oc(e,t,r){let o=DI(t),s=await WI(e),i=HI(s),a=eo(e.headers,i),c=Yf({connection:r,operationId:o}),d=Yt(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),Sp(t,d);let l=Br(c,d.subjectId),m=await $I(e,l,r,t,a);if(m.kind==="connect_required")return og(s,m.payload);if(m.kind==="no_tokens")return eg(s);let h=KI(e,m.headers);return YI({request:h,context:t,requestBody:s,routeAuth:l,mcpProtocolVersion:a}),XI({context:t,requestJson:i,connection:r}),h}n(oc,"mcpTokenExchangePolicy");var sc=class extends ns{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=mp(t,r);super(o,r),this.#e=o}async handler(t,r){return oc(t,r,this.#e)}};var sg=Symbol("Html");function QI(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(QI,"escapeHtml");function eT(e){return e===null||typeof e!="object"?!1:e[sg]===!0}n(eT,"isHtml");function ri(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ri).join(""):eT(e)?e.value:QI(String(e))}n(ri,"renderValue");function Be(e){return{[sg]:!0,value:e}}n(Be,"trustedHtml");var Je=Be("");function V(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ri(t[o]),r+=e[o+1]??"";return Be(r)}n(V,"html");function Jr(e,t=Je){let r=ri(t),o="",s=!0;for(let i of e)s||(o+=r),o+=ri(i),s=!1;return Be(o)}n(Jr,"joinHtml");function Fr(e){return e.value}n(Fr,"renderHtml");function ig(e){return V`<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>`}n(ig,"renderBrowserErrorPage");var ag=Be('<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>'),cg=Be('<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>'),Gr=Be('*,: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 Vr(e){return V`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
40
+ `),Be(K.text),K.terminate){U("SSE stream terminated by its rewriter"),P.close();return}}h=!0,P.close();return}if(He)return}}catch(B){h||(U(B),(P.desiredSize??0)<0?I={error:B}:P.error(B))}},cancel(P){if(!h)return h=!0,d.abort(P),m.cancel(P)}},{highWaterMark:0})}o(tc,"rewriteSseStream");function Kv(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(Kv,"concatBytes");function ci(e,t,r){if(e.body===null)return e;let n=yt(new Headers(e.headers));return n.set("content-type","text/event-stream"),new Response(tc(e.body,t,r),{status:e.status,statusText:e.statusText,headers:n})}o(ci,"rewriteSseResponse");var Rf=new Set(["jsonrpc","method","id","params"]),oc=new Set(["name","uri","ref"]),bf=new Set(["type","name","uri"]),Wv="subscriptions/listen",sc="notifications",vf="resourceSubscriptions",Zv=new Set([...oc,St(sc)]),Yv=new Set([St(vf)]),Xv=/[^\u0000-\u007f]/,Qv=34,eC=92,_f=123,tC=125,rC=91,nC=93,oC=58,rc=44;function zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(zo,"isRecord");function St(e){return e.toUpperCase().toLowerCase()}o(St,"foldCase");function nc(e,t){return Object.keys(e).some(r=>{let n=St(r);return n!==r&&t.has(n)})}o(nc,"hasCaseVariant");function wf(e,t){let r=St(t);return Object.keys(e).some(n=>n!==t&&St(n)===r)}o(wf,"hasCaseVariantOf");function sC(e,t){let r=o(a=>{switch(a.role){case"member":return Rf;case"params":return t.has(a.member)?Zv:oc;case"ref":return bf;case"notifications":return Yv;default:return}},"watchedFor"),n=[],s=0,i=o(a=>{let c=n.at(-1);if(c===void 0)return a?"member":"batch";if(a){if(c.role==="batch")return"member";if(c.role==="member"&&c.key==="params")return"params";if(c.role==="params"&&c.key==="ref")return"ref";if(c.role==="params"&&c.key===sc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===Qv){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let m=0;for(;e.charCodeAt(d-1-m)===eC;)m++;if(m%2===0)break}let u=s>0?void 0:n.at(-1);if(u?.isObject&&u.expectKey){let m=e.slice(a,d+1),h=m.includes("\\")?JSON.parse(m):m.slice(1,-1);if(Xv.test(h))return!0;u.key=h;let f=St(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===_f||c===rC){let d=c===_f,u=s>0?void 0:i(d);if(u===void 0)s++;else{let m=n.at(-1)?.member??0;n.push({role:u,isObject:d,seen:new Set,member:m,expectKey:d})}}else if(c===tC||c===nC)s>0?s--:n.pop();else if(s===0&&(c===oC||c===rc)){let d=n.at(-1);d?.isObject?d.expectKey=c===rc:d?.role==="batch"&&c===rc&&d.member++}}return!1}o(sC,"hasUnsafeKeyInText");function Cf(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(zo(s)){if(nc(s,Rf)||e.checksListen===!0&&s.method===Wv&&(t.add(r),zo(s.params)&&(wf(s.params,sc)||zo(s.params.notifications)&&wf(s.params.notifications,vf))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!zo(s.params))&&(nc(s.params,oc)||zo(s.params.ref)&&nc(s.params.ref,bf)))return!0}}return sC(e.text,t)}o(Cf,"hasAmbiguousIdentifyingKeys");var iC=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),aC=47,If=44,cC=38,ic=o(e=>e!==aC&&e!==If,"VALUE"),dC=o(e=>!iC(e),"ANY"),uC=o(e=>e!==cC,"QUERY_VALUE"),lC=["+","#",".","/","?","&"],ac=class{static{o(this,"Builder")}edges=[[]];current=0;#e(){return this.edges.push([]),this.edges.length-1}literal(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:o(i=>i===n,"test"),to:s}),this.current=s}}plus(t){let r=this.#e();this.edges[this.current].push({test:t,to:r}),this.edges[r].push({test:t,to:r}),this.current=r}value(t){if(this.plus(ic),!t)return;let r=this.current,n=this.#e();this.edges[r].push({test:o(s=>s===If,"test"),to:n}),this.edges[n].push({test:ic,to:r})}};function Tf(e){let t=new ac,r="",n=0;for(;n<e.length;){if(e[n]!=="{"){r+=e[n],n++;continue}let s=e.indexOf("}",n);if(s===-1)return;t.literal(r),r="";let i=e.slice(n+1,s),a=lC.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,m)=>{t.literal(`${m===0?a:"&"}${u}=`),t.plus(uC)});break;case"+":case"#":t.plus(dC);break;case".":t.literal("."),t.plus(ic);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}n=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}o(Tf,"compileUriTemplate");function Ef(e,t){if(t.length>1e6)return!1;let{edges:r,accept:n}=e,s=new Array(r.length).fill(-1),i=[0];for(let a=0;a<t.length;a++){let c=t.charCodeAt(a),d=[];for(let u of i)for(let m of r[u])s[m.to]!==a&&m.test(c)&&(s[m.to]=a,d.push(m.to));if(d.length===0)return!1;i=d}return i.includes(n)}o(Ef,"matchesUriTemplate");var mi=p.record(p.string(),p.unknown()),pC=p.record(p.string(),p.unknown()),Ut=p.array(p.string().min(1)).min(1).optional(),mC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),annotations:pC.optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),hC=p.object({name:p.string().min(1),description:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),fC=p.object({uri:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),gC=p.object({uriTemplate:p.string().min(1),name:p.string().min(1).optional(),description:p.string().min(1).optional(),mimeType:p.string().min(1).optional(),_meta:mi.optional(),roles:Ut,groups:Ut,public:p.boolean().optional()}).strict(),yC=p.array(p.union([p.string(),mC])),SC=p.array(p.union([p.string(),hC])),_C=p.array(p.union([p.string(),fC])),wC=p.array(p.union([p.string(),gC])),RC=p.object({module:p.unknown(),export:p.string().min(1)}).strict(),bC=p.object({mode:p.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:p.string().min(1).optional(),groupClaim:p.string().min(1).optional(),identifier:RC.optional()}).strict(),vC=p.object({tools:yC.optional(),prompts:SC.optional(),resources:_C.optional(),resourceTemplates:wC.optional(),accessControl:bC.optional()}).strict(),_t=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read","resources/subscribe","resources/unsubscribe"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function CC(e,t){return ym(vC,e,`MCP capability filter policy "${t}"`)}o(CC,"parseMcpCapabilityFilterOptions");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(G,"isRecord");function Je(e){return typeof e.method=="string"?e.method:void 0}o(Je,"messageMethod");function jo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}o(jo,"correlationKey");function qf(e){let t=new Set,r=new Map;for(let n of e){let s=jo(n);if(s===void 0)continue;t.add(s);let i=String(n),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return n=>{let s=jo(n);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(n));return i?.size===1?[...i][0]:void 0}}o(qf,"createReplyIdMatcher");function kf(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(kf,"asStringArray");function Af(e,t){if(!G(e))return[];let r=t in e?e[t]:t.split(".").reduce((n,s)=>G(n)?n[s]:void 0,e);return Array.isArray(r)?r.filter(n=>typeof n=="string"):typeof r=="string"?r.split(/\s+/).filter(n=>n.length>0):[]}o(Af,"readClaimValues");function fc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!G(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:kf(e.roles),groups:kf(e.groups),public:e.public===!0}}o(fc,"normalizeEntry");function IC(e,t,r){if(e.public)return!0;let n=e.roles??[],s=e.groups??[];return n.length===0&&s.length===0?!1:n.some(i=>t.has(i))||s.some(i=>r.has(i))}o(IC,"isCallerAllowed");function di(e,t,r,n){if(e===void 0)return;let s=[];for(let i of e){let a=fc(i,t);a!==void 0&&IC(a,r,n)&&s.push(a.key)}return s}o(di,"allowedKeys");var zf=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(Af(e.user?.data,n)),a=new Set(Af(e.user?.data,s));return{tools:di(r.tools,"name",i,a),prompts:di(r.prompts,"name",i,a),resources:di(r.resources,"uri",i,a),resourceTemplates:di(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function TC(e,t){let r=[];for(let n of _t){let s=e[n.option];if(s!==void 0)for(let i of s){let a=fc(i,n.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new ee(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}o(TC,"assertNoConflictingMarkup");function EC(e,t){let r=[];for(let n of _t){let s=e[n.option];if(s!==void 0)for(let i of s){let a=fc(i,n.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}o(EC,"assertNoMarkup");function kC(e,t){let r=e.identifier;if(r===void 0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let n=r.module[r.export];if(typeof n!="function")throw new ee(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=n;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new k(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof d!="object"||Array.isArray(d))throw new k(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}o(kC,"buildCustomResolver");function AC(e,t){let r=e.accessControl,n=r?.mode??"allPublic";if(n==="function"){if(r===void 0)throw new ee(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return kC(r,t)}if(n==="rolesAndGroups")return TC(e,t),zf;EC(e,t)}o(AC,"buildCapabilityResolver");function PC(e){let t={};for(let r of _t){let n=e[r.option];if(n===void 0)continue;let s=new Map;for(let i of n){let a=QC(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o(PC,"buildProjectionMaps");function Nf(e){return e===void 0?void 0:_t.find(t=>t.listMethod===e)}o(Nf,"findListRule");function gc(e){return e===void 0?void 0:_t.find(t=>t.directMethods.includes(e))}o(gc,"findDirectRule");var hi="completion/complete",jf=["prompts","resources","resourceTemplates"];function Df(e){return e===hi||gc(e)!==void 0}o(Df,"isCapabilityMethod");var pi="subscriptions/listen",xC=[..._t.flatMap(e=>[e.listMethod,...e.directMethods]),hi,pi];function OC(e){let t=St(e.trim()),r=xC.find(n=>St(n)===t);return r!==void 0&&r!==e?r:void 0}o(OC,"methodVariantOf");function MC(e,[t,r]){return{code:A.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(MC,"invalidParams");function yc(e){return t=>({code:A.InvalidParams,message:`${e} "${Os(t)}" not found`})}o(yc,"namedNotFound");function UC(e,t){return{code:em(t),message:"Resource not found",data:{uri:xs(e,tm)}}}o(UC,"resourceNotFound");var qC={legacy:yc("Tool"),modern:yo.tool},cc={legacy:yc("Prompt"),modern:yo.prompt},zC={legacy:UC,modern:yo.resource},NC={legacy:yc("Resource template"),modern:yo.resourceTemplate};function jC(e){let t=Je(e);if(t===void 0||!Df(t))return[];let r=G(e.raw)?e.raw.params:void 0,n=o((d,u)=>G(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=o(d=>G(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==hi){let d=gc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:n(r,"uri"),issue:s("params.uri"),notFound:zC}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?qC:cc}]}let i=G(r)?r.ref:void 0,a=G(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:n(i,"name"),issue:["params.ref.name","a string"],notFound:cc}];if(a==="ref/resource"){let d=n(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&DC(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:NC}]}let c=G(r)?G(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:jf,target:void 0,issue:c,notFound:cc}]}o(jC,"capabilityAccesses");function DC(e){let t=!1,r=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else LC(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(DC,"hasTemplateExpression");function LC(e){return e>32&&e<127?!1:$C.test(String.fromCharCode(e))}o(LC,"isWhitespaceCode");var $C=/\s/;function HC(e){return e.type==="invalid"&&(!G(e.raw)||e.raw.jsonrpc!=="2.0")}o(HC,"isNonJsonRpcMember");function BC(e){return G(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(BC,"hasNonStringMethod");function Lf(e){return e.type==="request"||e.type==="invalid"&&Je(e)!==void 0}o(Lf,"awaitsReply");function FC(e){return G(e.raw)&&G(e.raw.params)?e.raw.params:void 0}o(FC,"rawParams");function JC(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:fe()&&zr(e.headers,r.raw)}o(JC,"isModernRequest");var Pf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},dc="=?base64?",uc="?=",VC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function GC(e){if(!e.startsWith(dc)||!e.endsWith(uc)||e.length<dc.length+uc.length)return e;let t=e.slice(dc.length,e.length-uc.length);if(VC.test(t))try{let r=atob(t),n=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}o(GC,"decodeMcpHeaderValue");var KC=-32020;function WC(e,t){let r=Je(t);if(r===void 0)return;let n=G(t.raw)?t.raw.id:void 0,s=Sc(n)?n:void 0,i=e.headers.get("mcp-protocol-version"),a=im(t.raw);if(i!==null&&a!==void 0&&i!==a)return ui(s,i,`the body envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let c=e.headers.get("mcp-method");if(c!==null&&c!==r)return ui(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(Pf,r)?Pf[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let m=GC(d);if(m===void 0)return ui(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=FC(t)?.[u];if(typeof h=="string"&&m!==h)return ui(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${m}"`)}o(WC,"headerMismatchResponse");function ui(e,t,r){return Gr(400,{code:KC,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(ui,"mismatchResponse");var ZC={code:A.MethodNotFound,message:"Method not found"},xf={code:A.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},YC={code:A.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},XC="2025-06-18";function Sc(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(Sc,"isValidRequestId");function $f(e){return G(e.raw)&&!Object.hasOwn(e.raw,"id")}o($f,"isSentAsNotification");function No(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}o(No,"jsonRpcError");function Gr(e,t,r){return Response.json(No(t,r),{status:e})}o(Gr,"jsonRpcErrorResponse");function li(e){return Gr(400,{code:A.InvalidRequest,message:`Invalid Request: ${e}`})}o(li,"invalidRequestResponse");function lc(e,t,r=!1){if($f(e))return{status:400,body:No({code:A.InvalidRequest,message:`Invalid Request: a notification cannot use ${Os(Je(e)??"this method")}; send it as a request with an id`})};let n=G(e.raw)?e.raw.id:void 0;return Sc(n)?{status:r&&t.code===A.MethodNotFound?404:200,body:No(t,n)}:{status:400,body:No({code:A.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}o(lc,"refusalOf");function Of(e,t,r=!1){let[n]=[...t];if(e.shape!=="batch"){let{status:a,body:c}=lc(n[0],n[1],r);return Response.json(c,{status:a})}let s=e.protocolVersion;if(s!==void 0&&s>=XC)return li(`protocol version ${Os(s)} does not support JSON-RPC batches`);let i=e.messages.flatMap(a=>a.type==="result"||a.type==="error"||$f(a)?[]:[lc(a,t.get(a)??YC).body]);if(i.length===0){let{status:a,body:c}=lc(n[0],n[1]);return Response.json(c,{status:a})}return Response.json(i)}o(Of,"refusalResponse");function QC(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!G(e))return;let r=e[t];if(typeof r!="string")return;let n={...e};return delete n.roles,delete n.groups,delete n.public,{key:r,overlay:n}}o(QC,"buildProjection");function Mf(e){let t=e.base[e.property],r=e.overlay[e.property];return G(r)?G(t)?{...t,...r}:r:t}o(Mf,"mergeRecordProperty");function eI(e,t){let r={...e,...t.overlay},n=Mf({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=Mf({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(eI,"applyProjection");var Ae=Symbol("unreadable"),Kr=Symbol("dropped");function tI(e,t,r,n,s){let i=e.result;if(!G(i))return Ae;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?Ae:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!G(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(n!==void 0&&!n.has(u))return[];let m=r.get(u);return m===void 0?[]:[eI(d,m)]})}}}o(tI,"filterAndProjectItems");var Hf="resources/read";function rI(e){let t=e.result;return!G(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}o(rI,"withPrivateReadScope");function Bf(e,t){let r=Nf(Je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(Bf,"listTargetOf");function nI(e,t,r){return G(e)&&_t.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(nI,"carriesUnfilteredList");function oI(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(y=>Bf(y,r),"listTarget"),d=t.messages.filter(Lf),u=new Map;for(let y of d){let b=jo(y.id);b!==void 0&&!u.get(b)&&u.set(b,c(y))}let m=qf(d.map(y=>y.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&Je(h)===Hf,S=o(y=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let b=m(y);return b===void 0?void 0:u.get(b)},"targetForReply"),R=o(y=>{if(!G(y))return Ae;if(!("result"in y))return"method"in y&&!("error"in y)?_(y):"error"in y||"method"in y?y:Ae;let b=S(y.id);return b===void 0||nI(y.result,b,r)?Ae:b===null?f?rI(y):y:tI(y,b.rule,b.projections,n?.[b.rule.option],s)},"filterMessage"),_=o(y=>{if(a===void 0)return y;if(y.method==="notifications/resources/updated"){let b=G(y.params)?y.params.uri:void 0;return typeof b=="string"&&!a(b)?Kr:y}if(y.method==="notifications/subscriptions/acknowledged"){let b=Vf(y.params,a);return b===void 0?y:{...y,params:b}}return y},"filterServerMessage");return y=>{if(!Array.isArray(y))return R(y);if(t.shape!=="batch")return Ae;let b=y.map(R);if(b.includes(Ae))return Ae;let I=b.filter(U=>U!==Kr);return I.length===b.length?b:I.length===0?Kr:I}}o(oI,"createReplyFilter");function sI(e){return it(e.headers.get("content-type")).includes("json")}o(sI,"isJsonResponse");function iI(e){return it(e.headers.get("content-type"))==="text/event-stream"}o(iI,"isEventStreamResponse");var aI=10*1024*1024,cI=/^[\w.~:/+=-]{0,256}$/;function dI(e){if(yf(e))return null;let t=!1;for(let n of e.lines){let s=n.indexOf(":"),i=s===-1?n:n.slice(0,s),a=s===-1?"":n.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&cI.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=o(n=>n.trim()===""?n:"","blank");return{...e,lines:e.lines.map(n=>n.startsWith(":")?`:${r(n.slice(1))}`:n),comments:e.comments.map(r)}}o(dI,"inspectSseLines");var Ff="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",uI="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function mc(e,t){let r=e.messages.filter(Lf),n=new Map,s=new Set;for(let u of r){let m=u.id,h=jo(m);m==null||h===void 0||(n.set(h,m),Bf(u,t)!==null&&s.add(h))}let i=qf(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:jo(a.id),d=new Set;return{keyOf(u){if(!(!G(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:o(u=>u!==void 0&&n.has(u),"isPending"),hasFailed:o(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&n.delete(u)},fail(u){return[...u].flatMap(m=>{let h=n.get(m);return h===void 0?[]:(n.delete(m),d.add(m),[{jsonrpc:"2.0",id:h,error:{code:A.InternalError,message:s.has(m)?Ff:uI}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(mc,"createReplyTracker");function Jf(e,t,r){let n=[],s=0;for(let i of e){let a=r.keyOf(i);if(a!==void 0&&r.hasFailed(a))continue;let c=Array.isArray(i)?Ae:t(i);c!==Kr&&(c!==Ae?(n.push(c),r.answer(a)):r.isPending(a)?n.push(...r.fail([a])):s++)}return{replies:n,dropped:s}}o(Jf,"filterBatchMembers");function lI(e){let{response:t,envelope:r,projectionMaps:n,filterReply:s,warn:i}=e,a=mc(r,n),c=!1,d=o(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=o(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),m=o(()=>a.pendingKeys().length===0,"isDone");return ci(t,h=>{let f=dI(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let S;try{S=JSON.parse(f.data)}catch{return d("its data is not JSON")}let R=a.keyOf(S);if(R!==void 0&&a.hasFailed(R))return null;let _=s(S);if(_===Kr)return null;if(_===Ae&&r.shape==="batch"&&Array.isArray(S)){let{replies:y,dropped:b}=Jf(S,s,a);if(b>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),y.length===0)return null;let I=qo(f,JSON.stringify(y));return m()?ec(I):I}if(_===Ae){if(!a.isPending(R))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let y=u(a.fail([R]));return m()?ec(...y):y}for(let y of Array.isArray(_)?_:[_])a.answer(a.keyOf(y));return _===S?f:qo(f,JSON.stringify(_))},{maxEventChars:aI,onOversize:"discard",end:o(({unterminated:h,discardedEvents:f})=>((h||f>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||f>0?u(a.fail(a.pendingKeys())):null),"end"),onFailure:o((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}o(lI,"filterEventStream");function _c(e){return Je(e)===pi}o(_c,"isListenRequest");function pI(e){return fe()&&e.messages.some(_c)}o(pI,"filtersListen");function Vf(e,t){if(!G(e)||!G(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let n=r.filter(s=>typeof s=="string"&&t(s));if(n.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:n}}}o(Vf,"narrowSubscriptionParams");function mI(e,t,r){let n=!1,s=t.messages.map(a=>{if(!_c(a)||!G(a.raw))return a.raw;let c=Vf(a.raw.params,r);return c===void 0?a.raw:(n=!0,{...a.raw,params:c})});if(!n)return e;let i=new Headers(e.headers);return i.delete("content-length"),new kt(e,{headers:i,body:JSON.stringify(t.shape==="batch"?s:s[0])})}o(mI,"narrowListenSubscriptions");var pc=Symbol("access unresolved"),Uf=10*1024*1024,Gf="the request body could not be read";async function hI(e,t,r){let n=e.clone().body;if(n===null)return{blank:!0,overLimit:!1};let s=n.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:u}=await s.read(),m=d?i.decode():i.decode(u,{stream:!0});if(a+=m.length,c&&=!/\S/.test(m),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}o(hI,"scanBody");function wc(e){return Array.isArray(e)?`batch member 0: ${wc(e[0])}`:G(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}o(wc,"invalidMessageReason");async function fI(e,t){if(e.body===null)return;let r=o(()=>Ne.contentTooLarge(e,t,{detail:"The request body is larger than the MCP capability filter can inspect."}),"tooLarge");if(Number(e.headers.get("content-length")??Number.NaN)>Uf)return r();let s=it(e.headers.get("content-type")).includes("json"),i=o(()=>Ne.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=o(()=>Gr(400,{code:A.ParseError,message:`Parse error: ${Gf}`}),"unreadable"),c;try{c=await hI(e,Uf,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(m){return m instanceof SyntaxError?Gr(400,{code:A.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=G(d)?d.id:void 0;return Gr(400,{code:A.InvalidRequest,message:`Invalid Request: ${wc(d)}`},Sc(u)?u:void 0)}o(fI,"refuseUninspectable");var hc=class extends Cs{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=CC(t,r);super(n,r),this.#r=r,this.#e=PC(n),this.#t=AC(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,Tf(i)]))}async handler(t,r){let n=await dm(t);if(n===null)return await fI(t,r)??t;let s=JC(t,n);if(s){let v=n.messages[0],Y=v===void 0?void 0:WC(t,v);if(Y!==void 0)return Y}let i=n.messages.findIndex(HC);if(i!==-1)return li(`batch member ${i}: ${wc(n.messages[i].raw)}`);let a=n.messages.findIndex(BC);if(a!==-1)return li(n.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=cm(n);if(c===void 0)try{c=await t.clone().text()}catch{return Gr(400,{code:A.ParseError,message:`Parse error: ${Gf}`})}if(Cf({envelope:n,text:c,isCapabilityMethod:Df,checksListen:this.#a()}))return li("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let d=new Map;for(let v of n.messages){let Y=Je(v),x=Y===void 0?void 0:OC(Y);x!==void 0&&this.#u(x)&&d.set(v,ZC)}let u=pI(n),m=d.size===0&&this.#t!==void 0&&n.messages.some(v=>this.#i(v,u))?await this.#s(t,r):void 0,h=s&&Us(t.headers.get("mcp-protocol-version"));if(d.size===0)for(let v of n.messages){let Y=m===pc?this.#i(v,u)?xf:void 0:this.#m(v,m,h,n.protocolVersion);Y!==void 0&&d.set(v,Y)}if(d.size>0)return Of(n,d,s);if(m===pc)return Of(n,new Map(n.messages.map(v=>[v,xf])),s);let f=u||s?this.#l(m):void 0,S=f===void 0?t:mI(t,n,f),R=s&&this.#t!==void 0,_=R&&this.#p();if(!this.#h(n,u,_))return S;let y=oI({envelope:n,projectionMaps:this.#e,allowedSets:m,privateScope:R,privateReadScope:_,isResourceVisible:f}),b=o(v=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${v}`),"warn"),I=o((v,Y)=>{b(`did not forward an upstream reply (${v}); answered -32603`);let x=mc(n,this.#e),Z=x.fail(x.pendingKeys()),re=yt(new Headers(Y.headers));return re.set("content-type","application/json"),Z.length===0?new Response(JSON.stringify(No({code:A.InternalError,message:Ff})),{status:502,headers:re}):new Response(JSON.stringify(n.shape==="batch"?Z:Z[0]),{status:200,headers:re})},"unreadable");r.addResponseSendingHook(async v=>{let Y=!v.ok;if(v.body!==null&&at(v.headers))return Y?v:I("its body is still content-encoded",v);if(iI(v))return lI({response:v,envelope:n,projectionMaps:this.#e,filterReply:y,warn:b});if(!sI(v))return v.ok&&v.status!==202&&v.status!==204&&v.body!==null?I("no or an unknown media type",v):v;let x;try{x=await v.clone().json()}catch{return Y?v:I("its body is not JSON",v)}if(Y&&!Array.isArray(x)&&!(G(x)&&"result"in x))return v;let Z=y(x);if(Z===Ae&&n.shape==="batch"&&Array.isArray(x)){let P=mc(n,this.#e),{replies:B,dropped:j}=Jf(x,y,P);j>0&&B.push(...P.fail(P.pendingKeys())),B.length>0&&(b("did not forward a batch reply member it could not read; sent the rest"),Z=B)}if(Z===Ae||Z===Kr)return I("the filter could not read the reply",v);if(Z===x)return v;let re=yt(new Headers(v.headers));return new Response(JSON.stringify(Z),{status:v.status,statusText:v.statusText,headers:re})});let U=new kt(S);return U.headers.set("accept-encoding","gzip, br"),U}#l(t){if(!this.#p())return;let r=o((n,s)=>{let i=t?.[n];return this.#e[n]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return n=>this.#d(n,r)}#p(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#m(t,r,n,s){let i=o(c=>this.#e[c]!==void 0,"isConfigured"),a=o((c,d)=>{let u=r?.[c];return this.#e[c]?.has(d)===!0&&(u===void 0||u.has(d))},"isAllowed");for(let c of jC(t)){if(!(c.refusedBy??c.options).some(i))continue;let{target:d}=c;if(d===void 0)return MC(Je(t)??"",c.issue);if(!(c.resource?this.#d(d,a):c.options.filter(i).some(m=>a(m,d))))return n?c.notFound.modern(d):c.notFound.legacy(d,s??null)}}#d(t,r){let n=this.#e.resources!==void 0;if(n&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!Ef(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!n&&!s}#o(t){let r=o(n=>this.#e[n]!==void 0,"isConfigured");return t===hi?jf.some(r):gc(t)?.option==="resources"&&r("resourceTemplates")?!0:_t.some(n=>r(n.option)&&(n.listMethod===t||n.directMethods.includes(t)))}#i(t,r){let n=Je(t);return r&&n===pi&&this.#p()?!0:n!==void 0&&this.#o(n)}#a(){return fe()&&this.#p()}#u(t){return t===pi?this.#a():this.#o(t)}#h(t,r,n){return t.messages.some(s=>{if(r&&_c(s))return this.#p();if(n&&t.shape==="single"&&Je(s)===Hf)return!0;let i=Nf(Je(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#s(t,r){let n=this.#t;if(n===void 0)return{};let s;try{s=await n(t,r,this.options)}catch(a){return r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; refused the requests that needed it`,a),pc}let i={};for(let a of _t){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let m of d)typeof m=="string"&&c.has(m)&&u.add(m);i[a.option]=u}return i}};var Rc="zuplo.com",gI=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),yI=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Kf(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(Kf,"s2FaviconHref");function SI(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}o(SI,"strictFaviconHref");var Wf=Kf(Rc);function bc(e){let t=e.toLowerCase();return t===Rc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Kf(Rc):SI(e)}o(bc,"resolveIconHref");function _I(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(_I,"hostnameFromHost");function wI(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(wI,"isLocalOrAddressHost");function RI(e){let t=_I(e).toLowerCase().replace(/\.$/,"");if(wI(t)||yI.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let n=r.slice(-2).join("."),s=gI.has(n)?3:2;return r.slice(-s).join(".")}o(RI,"inferFaviconDomain");function vc(e){return{src:bc(RI(e)),mimeType:"image/png",sizes:["128x128"]}}o(vc,"resolveMcpFaviconIcon");function fi(e){try{return vc(new URL(e).host)}catch{return}}o(fi,"resolveMcpFaviconIconFromUrl");var bI=-32020,vI=new Set(["envelope-invalid","modern-header-without-claim","header-body-version-mismatch","method-header-mismatch","notification-envelope-invalid","notification-header-body-version-mismatch","notification-method-header-mismatch"]),Zf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Yf="=?base64?",Xf="?=",CI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function II(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(II,"isRecord");function Qf(e){return e===" "||e===" "}o(Qf,"isHttpOws");function TI(e){let t=0,r=e.length;for(;t<r&&Qf(e[t]);)t++;for(;r>t&&Qf(e[r-1]);)r--;return e.slice(t,r)}o(TI,"stripHttpOws");function gi(e,t){return e.get(t)??void 0}o(gi,"readHeader");function EI(e){if(!e.startsWith(Yf)||!e.endsWith(Xf))return e;let t=e.slice(Yf.length,e.length-Xf.length);if(CI.test(t))try{let r=Uint8Array.from(atob(t),n=>n.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}o(EI,"decodeMcpHeaderValue");function Ic(e,t,r){let n=Me(e);return Response.json(gt({...n===void 0?{}:{id:n},error:r}),{status:t})}o(Ic,"errorResponse");function eg(e,t,r){return Ic(e,400,{code:bI,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(eg,"headerMismatchResponse");function kI(e,t){let r=t.method,n=gi(e,"mcp-name");if(n===void 0||typeof r!="string"||!Object.hasOwn(Zf,r))return;let s=Zf[r],i=TI(n),a=EI(i);if(a===void 0)return eg(t,i,"the Mcp-Name header carries an invalid Base64 sentinel value");let c=II(t.params)?t.params[s]:void 0,d=typeof c=="string"?c:void 0;if(d!==void 0&&a!==d)return eg(t,i,`the body carries params.${s}="${d}" but the Mcp-Name header names "${a}"`)}o(kI,"mcpNameMismatchResponse");function tg(e){let{headers:t,message:r}=e,n=Qp({httpMethod:"POST",...Cc("protocolVersionHeader",gi(t,"mcp-protocol-version")),...Cc("mcpMethodHeader",gi(t,"mcp-method")),...Cc("mcpNameHeader",gi(t,"mcp-name")),body:r});if(n.kind==="reject")return vI.has(n.cell)?Ic(r,n.httpStatus,{code:n.code,message:n.message,...n.data===void 0?{}:{data:n.data}}):void 0;if(n.kind!=="modern")return;let s=n.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new Xp({supported:[...e.supportedVersions],requested:s??"unknown"});return Ic(r,400,{code:i.code,message:i.message,data:i.data})}return n.messageKind==="request"?kI(t,r):void 0}o(tg,"validateModernGatewayRequest");function Cc(e,t){return t===void 0?{}:{[e]:t}}o(Cc,"optionalHeader");function qt(e){let t=Ce().connectionsById.get(e);if(!t)throw new ee(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}o(qt,"getUpstreamServerConfig");function yi(e){let t=Ce().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new ee(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}o(yi,"getUpstreamAuthConfig");function Wr(e,t){let r=yi({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new ee(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}o(Wr,"requireUpstreamOAuthConfig");function rg(e,t){let r=yi({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new ee(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}o(rg,"requireUpstreamIdJagConfig");import{base64url as Si}from"jose";var AI="__Host-",PI=16,xI=32,og=".",OI=!1;function zt(){return OI}o(zt,"isBrowserBindingEnforced");var Do=p.object({id:p.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:p.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function _i(e,t){return new URL(ie(e,t)).protocol==="https:"}o(_i,"isSecureGatewayOrigin");function Tc(e,t){return t?`${AI}${e}`:e}o(Tc,"gatewayCookieName");function Lo(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}o(Lo,"serializeGatewayCookie");function Ec(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let s=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}o(Ec,"parseCookieHeader");function ng(e){return Si.encode(crypto.getRandomValues(new Uint8Array(e)))}o(ng,"randomBase64url");async function sg(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Si.encode(new Uint8Array(t))}o(sg,"hashNonce");function MI(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}o(MI,"constantTimeEqual");function ig(e,t,r){return Tc(`zuplo_mcp_${e}_${t}`,r)}o(ig,"bindingCookieName");async function $o(e){let t=ng(PI),r=ng(xI),n=_i(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${og}${Si.encode(e.payload)}`;return{claim:{id:t,hash:await sg(r)},setCookie:Lo({name:ig(e.purpose,t,n),value:s,maxAgeSeconds:e.ttlSeconds,secure:n})}}o($o,"startBrowserBinding");async function wi(e){let t=_i(e.request.url,e.request.headers),r=ig(e.purpose,e.claim.id,t),n=Lo({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Ec(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:n};let i=s.indexOf(og),a=i<0?s:s.slice(0,i);if(!MI(await sg(a),e.claim.hash))return{matched:!1,clearCookie:n};if(i<0)return{matched:!0,clearCookie:n};try{return{matched:!0,payload:new TextDecoder().decode(Si.decode(s.slice(i+1))),clearCookie:n}}catch{return{matched:!1,clearCookie:n}}}o(wi,"verifyBrowserBinding");function ag(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(ag,"mergeAbortSignals");async function UI(e){try{await e.cancel()}catch{}}o(UI,"cancelReader");async function Ri(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await UI(r),t.createLimitError();n.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of n)a.set(d,c),c+=d.byteLength;return a}o(Ri,"readBoundedByteStream");var qI=2,zI=1024*1024,NI=1e4,jI=new Set([301,302,303,307,308]),DI=["authorization","proxy-authorization","cookie","cookie2"];function kc(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(kc,"readRequestUrl");function Zr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Zr,"readRequestMethod");function LI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[O]:r}})}o(LI,"assertContentLengthWithinLimit");async function $I(e,t,r){return LI(e,t,r),Ri(e.body,{maxBytes:t,createLimitError:o(()=>new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[O]:r}}),"createLimitError")})}o($I,"readBoundedResponseBody");function HI(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(HI,"responseFromBufferedBody");function BI(e,t){if(!jI.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(BI,"resolveRedirectUrl");function cg(e,t){try{return t.validateUrl(e)}catch(r){throw new k({message:"Outbound URL was not allowed.",extensionMembers:{[O]:t.problemCode}},{cause:r})}}o(cg,"validateOutboundUrl");function FI(e,t){throw e instanceof k&&zs(e.extensionMembers?.[O])?e:new k({message:"Outbound fetch failed.",extensionMembers:{[O]:t}},{cause:e})}o(FI,"normalizeFetchError");function Ho(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,s]of Object.entries(t.extra))s!==void 0&&(r[n]=s);t.error!==void 0&&ke(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Ho,"logOutboundFailure");async function JI(e,t,r,n,s,i,a){let c=Zr(r,n);try{return await t(r,n)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Ho(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ue(i),error:d,extra:{abortReason:a()}}),FI(d,s)}}o(JI,"fetchWithNormalizedError");function VI(e){if(e.redirects>=e.maxRedirects)throw new k({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[O]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new k({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[O]:e.problemCode}})}o(VI,"assertRedirectAllowed");function GI(e,t){let r=new Headers(e);for(let n of DI)r.delete(n);for(let n of t)r.delete(n);return r}o(GI,"stripCrossOriginHeaders");function KI(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=GI(e.headers,s)),i}o(KI,"buildRedirectInit");function WI(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(WI,"buildInitialRequestInit");function ZI(e){let t=Zr(e.currentInput,e.currentInit);VI({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=cg(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),s=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:KI(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(ZI,"followRedirect");async function Ac(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??qI,i=r.maxResponseBytes??zI,a=r.timeoutMs??NI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,m=new AbortController,h=ag(m,t.signal),f=!1,S=setTimeout(()=>{f=!0,m.abort()},a),R=e,_=WI(e,t,m.signal),y;try{y=cg(kc(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(I){throw Ho(u,{event:"outbound_url_blocked",problemCode:n,method:Zr(e,t),host:ue(kc(e)),error:I}),clearTimeout(S),h?.(),I}let b=0;try{for(;;){let I=await JI(u,c,R,_,n,y,()=>f?`timeout_after_${a}ms`:void 0),U=BI(I,y);if(U!==void 0)try{let v=ZI({currentInput:R,currentInit:_,currentUrl:y,redirectUrl:U,redirects:b,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:d});R=v.currentInput,_=v.currentInit,y=v.currentUrl,b=v.redirects;continue}catch(v){throw Ho(u,{event:"outbound_redirect_blocked",problemCode:n,method:Zr(R,_),host:ue(y),error:v,extra:{redirects:b,maxRedirects:s,redirectTargetHost:ue(U)}}),v}try{return HI(I,await $I(I,i,n))}catch(v){throw Ho(u,{event:"outbound_response_size_exceeded",problemCode:n,method:Zr(R,_),host:ue(y),error:v,extra:{maxResponseBytes:i,status:I.status}}),v}}}finally{clearTimeout(S),h?.()}}o(Ac,"runSafeOutboundExchange");async function Bo(e,t,r){let n=await Ac(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(s){throw Ho(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Zr(e,t),host:ue(kc(e)),error:s,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new k({message:"Outbound JSON response could not be parsed.",extensionMembers:{[O]:r.problemCode??"invalid_request"}},{cause:s})}}o(Bo,"runSafeOutboundJsonExchange");function dg(e,t={},r={}){return Ac(e,t,{...r,validateUrl:vo})}o(dg,"fetchConfiguredOutbound");function ug(e,t={},r={}){return Bo(e,t,{...r,validateUrl:vo})}o(ug,"fetchConfiguredOutboundJson");function bi(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Jm})}o(bi,"fetchIdentityProviderJson");function lg(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Vs})}o(lg,"fetchCimdClientMetadataJson");function pg(e,t={},r={}){return Bo(e,t,{...r,validateUrl:Co})}o(pg,"fetchCimdClientJwksJson");import{errors as Sg,jwtVerify as _g,SignJWT as wg}from"jose";var he="zuplo-mcp-gateway",we=he,Re="HS256";import{base64url as YI}from"jose";var XI=new TextEncoder,QI="MCP gateway could not initialize secure key material.",eT=32,mg=new Map,hg=new Map,tT;function rT(){return tT??ws.instance.authPrivateKey}o(rT,"readAuthPrivateKey");function fg(e){return new Te(QI,e===void 0?void 0:{cause:e})}o(fg,"createGeneratedKeyMaterialError");function gg(e,t){let r=YI.decode(t);if(r.byteLength!==eT)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(gg,"decodeJwkKeyField");function nT(e){let t=rT();if(!t)throw fg();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=gg("d",r.d);gg("x",r.x);let s=XI.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+n.byteLength);return i.set(s),i.set(n,s.byteLength),i}catch(r){throw fg(r)}}o(nT,"decodeGeneratedKeyMaterial");function oT(e){let t=mg.get(e);return t||(t=nT(e),mg.set(e,t)),t}o(oT,"getMasterKeyMaterial");async function Ve(e){let t=hg.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(oT(e.keyMaterialPurpose));return hg.set(e.purpose,r),r}o(Ve,"readCachedDerivedKey");var sT="SHA-256",iT=32,aT="zuplo-mcp-gateway:",cT=new TextEncoder,yg=new WeakMap;async function ct(e,t){let r=yg.get(e);r||(r=new Map,yg.set(e,r));let n=r.get(t);if(n)return n;let s=await dT(e,t);return r.set(t,s),s}o(ct,"deriveGatewaySigningKey");async function dT(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=cT.encode(`${aT}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:sT,salt:new Uint8Array,info:ye(s)},n,iT*8);return new Uint8Array(i)}o(dT,"hkdfExpand");var Rg=900,uT=900,lT=Em.extend({id:Zm,browserBinding:Do.optional()}),pT=lT.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),bg=ua.extend({id:Ym,purpose:p.literal("browser_connect")}),mT=ua.extend({purpose:p.literal("browser_connect")}),hT=bg.extend({exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),vi=Rg*1e3;async function vg(){return Ve({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"oauth-state"),"derive")})}o(vg,"getOAuthStateKey");async function Cg(){return Ve({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-connect"),"derive")})}o(Cg,"getBrowserConnectKey");async function Ig(e){let t=Math.floor(Date.now()/1e3)+Rg;return new wg(e).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await vg())}o(Ig,"signOAuthState");async function Ci(e){try{let{payload:t}=await _g(e,await vg(),{algorithms:[Re],issuer:he,audience:we});return pT.parse(t)}catch(t){throw t instanceof Sg.JWTExpired?new k({message:"OAuth state has expired",extensionMembers:{[O]:"oauth_state_expired"}},{cause:t}):new k({message:"OAuth state could not be verified",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:t})}}o(Ci,"verifyOAuthState");async function Tg(e){let t=Math.floor(Date.now()/1e3)+uT,r=mT.parse(e),n=bg.parse({...r,id:th()});return new wg(n).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(t).sign(await Cg())}o(Tg,"signBrowserConnectTicket");async function Eg(e){try{let{payload:t}=await _g(e,await Cg(),{algorithms:[Re],issuer:he,audience:we});return hT.parse(t)}catch(t){throw t instanceof Sg.JWTExpired?new k({message:"Browser connect ticket has expired",extensionMembers:{[O]:"oauth_state_expired"}},{cause:t}):new k({message:"Browser connect ticket could not be verified",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:t})}}o(Eg,"verifyBrowserConnectTicket");async function kg(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new k({message:"Browser connect ticket has already been used",extensionMembers:{[O]:"oauth_state_reused"}})}o(kg,"consumeBrowserConnectTicket");function fT(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(fT,"buildConnectRequiredMessage");async function gT(e){let t=ie(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Tg({...Ro(e),purpose:"browser_connect"})),r.toString()}o(gT,"buildGatewayBrowserTicketUrl");function yT(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(yT,"buildGatewayConnectPath");async function Pc(e){return gT({...e,path:yT(e.upstreamServerId),redirect:!0})}o(Pc,"buildGatewayConnectUrl");async function Ii(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Pc(t),message:fT(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ii,"buildRedirectConnectRequiredResponse");function Ag(e){return Pg({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(Ag,"buildAdminConnectRequiredResponse");function Pg(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(Pg,"buildAdminSetupRequiredResponse");function xg(e){return Ce().byOperationId.get(e)?.downstreamOAuth!==void 0}o(xg,"routeSupportsBrowserConnect");function Og(e){return Pg({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o(Og,"buildBrowserConnectUnavailableResponse");var Mg=12;async function Ug(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}o(Ug,"sha256Hex");async function ur(e){if(e)return(await Ug(e)).slice(0,Mg)}o(ur,"fingerprintSecret");async function Yr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Ug(t)).slice(0,Mg)}o(Yr,"fingerprintConnectionIdentity");var ST=6e4;function Xr(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,n)=>t.scopes[n]!==r)}o(Xr,"credentialGenerationChanged");function Pe(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+ST)return"near_expiry"}return"usable"}o(Pe,"describeAccessTokenState");var qg=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _T(e,t){return e&&e.length>0?e.join(t):void 0}o(_T,"joinOAuthScopes");function wT(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of qg)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o(wT,"sanitizeAuthorizationServerMetadata");function zg(e){let t=wT(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(zg,"sanitizeOAuthDiscoveryState");function Ng(e){let t=new URL(e);for(let r of qg){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(Ng,"dedupeSingletonAuthorizationRequestParams");function Ti(e){let t=new URL(e);return je(t)&&gm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(Ti,"normalizeLoopbackOAuthRedirectUri");function jg(e){return _T(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(jg,"readProtectedResourceMetadataScope");function RT(e){return`Zuplo MCP Gateway - ${e}`}o(RT,"buildGatewayOAuthClientName");function bT(e,t){return e&&e.length>0?e.join(t):void 0}o(bT,"joinOAuthScopeList");function vT(e){if(e.clientRegistration.mode!=="auto")return bT(e.scopes,e.scopeDelimiter)}o(vT,"readPublicClientMetadataScope");function xc(e){return new URL(ge().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}o(xc,"buildOAuthClientMetadataDocumentUrl");function Oc(e){let t=qt(e.upstreamServerId);return{client_name:RT(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}o(Oc,"buildGatewayOAuthClientMetadata");function Dg(e,t,r){let n=Wr(t,r),s=vT(n);return{client_id:xc({origin:e,upstreamServerId:t}),...Oc({origin:e,upstreamServerId:t,redirectUri:Ti(new URL(n.redirectPath,e)).toString(),scope:s})}}o(Dg,"buildOAuthClientMetadataDocument");import{base64url as Nt}from"jose";var CT="SHA-256",Qr="AES-GCM",IT=12,Uc="zuplo-secret",qc=1,Lg="generated:auth_private_key:token-encryption",TT=p.object({version:p.literal(qc),keyId:p.literal(Lg),algorithm:p.literal(Qr),iv:p.string().min(1),ciphertext:p.string().min(1)}).strict();async function Mc(){return Ve({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(CT,ye(e));return crypto.subtle.importKey("raw",t,{name:Qr},!1,["encrypt","decrypt"])},"derive")})}o(Mc,"getEncryptionKey");function $g(e){return ye(new TextEncoder().encode(`${Uc}:v${e.version}:${e.keyId}`))}o($g,"getAssociatedData");function ET(e){return`${Uc}:v${e.version}:${Nt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(ET,"encodeEnvelope");function kT(e){let t=`${Uc}:v${qc}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Nt.decode(r));return TT.parse(JSON.parse(n))}o(kT,"decodeEnvelope");async function wt(e){let t=await Mc(),r=crypto.getRandomValues(new Uint8Array(IT)),n={version:qc,keyId:Lg},s=await crypto.subtle.encrypt({name:Qr,iv:r,additionalData:$g(n)},t,new TextEncoder().encode(e));return ET({...n,algorithm:Qr,iv:Nt.encode(r),ciphertext:Nt.encode(new Uint8Array(s))})}o(wt,"encryptSecret");async function Rt(e){let t=kT(e);if(t){let a=await Mc(),c=await crypto.subtle.decrypt({name:Qr,iv:ye(Nt.decode(t.iv)),additionalData:$g(t)},a,ye(Nt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new Te("Encrypted payload is malformed");let s=await Mc(),i=await crypto.subtle.decrypt({name:Qr,iv:ye(Nt.decode(r))},s,ye(Nt.decode(n)));return new TextDecoder().decode(i)}o(Rt,"decryptSecret");var Hg={issuer:p.string().min(1).optional()},AT=p.union([or.extend(Hg),go.extend(Hg)]),Bg=p.object({authorizationServerUrl:p.url(),resourceMetadataUrl:p.url().optional(),resourceMetadata:Mr.optional(),authorizationServerMetadata:p.union([Ur,qr]).optional()}).passthrough(),PT="Bearer",xT="__zuplo_refresh_only_upstream_access_token__";function zc(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(zc,"splitScopes");function Nc(e,t){let r=new Set(e);return t.every(n=>r.has(n))}o(Nc,"scopesCover");function OT(e){return Dr.parse(e)}o(OT,"parsePkceCodeVerifier");function MT(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}o(MT,"readTokenExpiry");async function Fg(e){if(e!==void 0)return wt(JSON.stringify(e))}o(Fg,"encryptJson");async function Jg(e,t){if(!e)return;let r=await Rt(e);try{return t.parse(JSON.parse(r))}catch(n){throw new k({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[O]:"oauth_state_invalid"}},{cause:n})}}o(Jg,"decryptJson");function UT(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(UT,"clientInformationAllowsRedirectUri");function qT(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(qT,"clientInformationMatchesCurrentClientMetadataUrl");function zT(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(zT,"isUrlBasedClientInformation");function NT(e,t){return t===void 0?e:{...e,scope:t}}o(NT,"applyOAuthClientMetadataScope");function jT(e,t){return jg({state:e,delimiter:t})}o(jT,"readResourceMetadataScope");function DT(e,t){return e&&e.length>0?e.join(t):void 0}o(DT,"joinOAuthScopeList");function LT(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new ee(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return or.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(LT,"buildManualOAuthClientInformation");function $T(e,t){let r=xc({origin:new URL(t).origin,upstreamServerId:e});return Ka(r)?r:void 0}o($T,"buildClientMetadataUrl");function HT(e){for(let t of e)if(t!==void 0)return t}o(HT,"firstDefined");function BT(e){let t=Wr(e.target.upstreamServerId,e.target.authProfileId),r=DT(t.scopes,t.scopeDelimiter),n=Oc({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:LT({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=$T(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}o(BT,"buildInitialOAuthClientSetup");function FT(e,t){if(t===void 0)return HT([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(FT,"readEncryptedClientInformation");function JT(e){return e.pendingState?.encryptedDiscoveryState}o(JT,"readEncryptedDiscoveryState");function jc(e,t){return t===void 0?e:{...e,issuer:t}}o(jc,"applyIssuerStamp");var jt=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;skipIssuerMetadataValidationValue;skipResourceIndicatorValidationValue;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=BT({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.browserBinding=t.browserBinding,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.skipIssuerMetadataValidationValue=r.skipIssuerMetadataValidation,this.skipResourceIndicatorValidationValue=r.skipResourceIndicatorValidation,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=FT(t,this.configuredClientInformation),this.encryptedDiscoveryState=JT(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get skipIssuerMetadataValidation(){return this.skipIssuerMetadataValidationValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let n=zc(this.configuredScope??r??this.readEffectiveScope());return Nc(t.scopes,n)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Pe(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let n=oe();n&&n.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Yr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await ur(await Rt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(n){let s=oe();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:n}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});s.error(i,"Upstream OAuth conditional storage write failed")}throw n}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return NT(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ig({id:t.id,...Ro({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId}),...this.browserBinding===void 0?{}:{browserBinding:this.browserBinding}})}async clientInformation(t){return this.configuredClientInformation?jc(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,oe()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!zT({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Fg(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ei({requestedResource:t,configuredResource:r}))throw new Error(`Protected resource ${r} does not match expected ${t} (or origin)`);return new URL(r)}}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=zg(Bg.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Fg(r),await this.syncPendingState(!1),oe()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ue(r.authorizationServerUrl),resourceMetadataHost:ue(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=jT(r,this.scopeDelimiter);let n=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&n!==void 0){let s=zc(this.configuredScope).filter(i=>!n.includes(i));s.length>0&&oe()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:n},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return jc(r,t?.issuer)}async saveTokens(t){let r=At.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,a=r.refresh_token?await wt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:At.parse({...r,refresh_token:await Rt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Gs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await wt(r.access_token),encryptedRefreshToken:a,scopes:zc(r.scope??this.readEffectiveScope()),expiresAt:MT(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),m=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Pe(u.connection)!=="usable"||!Nc(u.connection.scopes,c.scopes)||!Xr(s,u.connection))){m=!0;let f=u.connection,S={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};oe()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,Xr(s,u.connection)&&Pe(u.connection)==="usable"&&Nc(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),m){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";oe()?.info({event:`upstream_oauth_bounded_rebase_${f}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${f}`)}let h=u.kind==="persisted"?u.connection:void 0;oe()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await ur(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:m,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Ng(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:OT(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new k({message:"OAuth code verifier is missing",extensionMembers:{[O]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),s&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:eh(),...Ro({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:J(new Date(Date.now()+vi)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await Jg(this.encryptedClientInformation,AT)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!UT(r,this.redirectUriValue)||!qT({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=jc(go.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await Jg(this.encryptedDiscoveryState,Bg)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){oe()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await Rt(t.encryptedAccessToken):void 0,n=t.encryptedRefreshToken?await Rt(t.encryptedRefreshToken):void 0;if(!r&&!n)return;let s=oe();this.usedRefreshTokenFingerprintValue=s?await ur(n):void 0,s?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!n,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=At.parse({access_token:r??xT,token_type:PT,refresh_token:n,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=i,i}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let n=r.status,s=r.updatedAt,i={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let a=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,Xr(r,a.connection)&&Pe(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=oe();if(c){let d=a.kind==="missing"?void 0:a.connection,u={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:n,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...u,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(u,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(u,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var VT=3e4,GT=256*1024,KT=2,WT="does not support dynamic client registration",ZT=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],YT=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],XT=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],QT="Protected resource ",eE=" does not match expected ",tE=["HTTP 403 Forbidden","Access Denied","permission to access"],rE=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function nE(e){return e instanceof Error&&e.message.includes(WT)}o(nE,"isDynamicClientRegistrationUnsupported");function oE(e){return e instanceof Error&&ZT.some(t=>e.message.includes(t))}o(oE,"isProtectedResourceMetadataUnavailable");function sE(e){return e instanceof Error&&YT.some(t=>e.message.includes(t))}o(sE,"isAuthorizationServerMetadataUnavailable");function iE(e){return e instanceof Error&&XT.some(t=>e.message.includes(t))}o(iE,"isAuthorizationServerIncompatible");function aE(e){return e instanceof Error&&e.message.includes(QT)&&e.message.includes(eE)}o(aE,"isProtectedResourceMismatch");function cE(e){return e instanceof Error&&tE.some(t=>e.message.includes(t))}o(cE,"isUpstreamProviderAccessDenied");function dE(e){return e instanceof Mt&&rE.has(e.code)}o(dE,"isStoredConnectionReconsentError");function bt(e){let t=e.diagnostics??{};return new k({message:e.message,extensionMembers:{[O]:e.code,[qs]:e.upstreamServerId,[Hr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[ut]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[dt]:t.httpStatus},...t.providerError===void 0?{}:{[Br]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Fr]:t.providerErrorDescription}}},{cause:e.cause})}o(bt,"buildUpstreamSetupProblem");function uE(e,t){return`The authorization server for ${e} failed RFC 8414 \xA73.3 issuer validation: the gateway discovered it at "${t.expected}", but its metadata document declares issuer "${t.received}". Providers that publish a path-scoped authorization server whose metadata reports the root origin hit this; if that is the case here, set skipIssuerMetadataValidation on this upstream's OAuth config to accept it \u2014 that weakens the authorization-server mix-up defense, so scope it to this upstream. Otherwise correct the authorization server URL this upstream points at, or ask the provider to fix the published issuer.`}o(uE,"describeIssuerMetadataMismatch");var lE=128,pE=256;function Vg(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}o(Vg,"truncateProviderDetail");function mE(e){let{error:t,errorDescription:r}=Kg(e.body),n=Vg(t,lE),s=Vg(r,pE);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(mE,"readRegistrationRejectionDiagnostics");function hE(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}o(hE,"describeRegistrationRejection");function fE(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(fE,"readDiscoveryEndpointUrl");function gE(e){if(e.error instanceof k&&e.error.extensionMembers?.[O]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(nE(e.error))return bt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`});if(e.error instanceof Va){let r=mE(e.error);return bt({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${hE(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof xo&&e.error.kind==="metadata")return bt({...t,code:"upstream_oauth_issuer_mismatch",message:uE(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof ii)return bt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} publishes the non-HTTPS token endpoint "${e.error.tokenEndpoint}". The gateway will not send credentials to it. Ask the provider to serve the token endpoint over TLS before retrying.`,diagnostics:{upstreamUrl:e.error.tokenEndpoint}});if(iE(e.error))return bt({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} cannot run the OAuth flow the gateway requires: ${e.error.message}. Ask the provider to support the authorization code flow with PKCE (S256), or configure this upstream to use an authorization server that does.`});if(sE(e.error)){let r=fE(e.error.message);return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The gateway could not load OAuth authorization server metadata for the upstream MCP server "${e.upstreamServerId}": ${e.error.message}. Confirm the authorization server advertised by "${e.resourceMetadataUrl}" publishes RFC 8414 or OpenID Connect discovery metadata and is reachable from the gateway, then retry.`,diagnostics:r===void 0?{}:{upstreamUrl:r}})}if(aE(e.error))return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The protected resource metadata at "${e.resourceMetadataUrl}" names a resource that does not match the configured MCP URL for ${e.upstreamServerId}: ${e.error.message}. Point this upstream's MCP URL at the resource the provider publishes, or ask the provider to correct the advertised resource.`});if(oE(e.error))return bt({...t,code:"upstream_oauth_discovery_unavailable",message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`});if(cE(e.error))return bt({...t,code:"upstream_provider_access_denied",message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`})}o(gE,"mapUpstreamOAuthSetupError");function yE(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(yE,"readOAuthFetchRequest");function SE(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(SE,"readOAuthFetchMethod");function _E(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(_E,"responseLooksJson");function wE(e,t){let r=e.headers.get("content-type")??"",n=t.trimStart().toLowerCase();return r.includes("html")||n.startsWith("<!doctype html")||n.startsWith("<html")}o(wE,"responseLooksHtml");var RE=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function bE(e){return RE.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o(bE,"isMetadataDiscoveryRequest");function vE(e,t,r){return e!=="GET"||!bE(t)?!1:r>=400&&r<500||r===502}o(vE,"sdkRetriesDiscoveryCandidate");function CE(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new k({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[O]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[dt]:e.response.status,[Lr]:r,[ut]:e.request.url.toString(),[$r]:e.body}})}o(CE,"throwUpstreamHtmlError");function Kg(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}o(Kg,"readUpstreamOAuthErrorBody");function IE(e){let{error:t,errorDescription:r}=Kg(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ue(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}o(IE,"logUpstreamOAuthHttpError");function Wg(e){return async(t,r)=>{let n=yE(t),s=SE(t,r),i=oe(),a=Date.now(),c=await dg(t,r,{maxRedirects:KT,maxResponseBytes:GT,problemCode:"upstream_token_exchange_failed",timeoutMs:VT}),d=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:s,host:ue(n.url),path:n.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:d.length},"Upstream OAuth HTTP request completed"),c.ok||IE({log:i,upstreamServerId:e,method:s,request:n,response:c,body:d}),vE(s,n.url,c.status)||(!c.ok&&wE(c,d)&&CE({upstreamServerId:e,request:n,response:c,body:d}),!_E(c,d)))return c;try{JSON.parse(d)}catch(u){throw new k({message:`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[O]:"upstream_token_exchange_failed"}},{cause:u})}return c}}o(Wg,"createUpstreamOAuthFetch");function Zg(e){oe()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ue(e.serverUrl),resourceMetadataHost:ue(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}o(Zg,"logUpstreamOAuthFlowStarted");function Yg(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ue(e.serverUrl);r!==void 0&&(t.serverHost=r);let n=e.error instanceof k?e.error.extensionMembers?.[O]:void 0;typeof n=="string"&&(t.code=n),ke(t,"error",e.error),oe()?.warn(t,"Upstream OAuth flow failed before a connection was established")}o(Yg,"logUpstreamOAuthFlowFailed");function Xg(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(Xg,"readAuthorizationRequestScope");async function Qg(e,t){e.applyChallengeScope(t.requestedScope),Zg({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Wg(t.upstreamServerId)},n=Xg(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await Ga(e,r)}catch(r){Yg({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=gE({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(Qg,"runUpstreamOAuth");async function TE(e,t){e.applyChallengeScope(t.requestedScope),Zg({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Wg(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=Xg(e,t);n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await Ga(e,r)}catch(s){throw Yg({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(TE,"exchangeUpstreamAuthorizationCode");async function Gg(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await H().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Pe(r)!=="usable"||!Xr(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}o(Gg,"adoptPeerCredentialAtResolutionBoundary");async function ey(e,t){let r=await Qg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new k({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}}):new k({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}})}o(ey,"requireUpstreamAuthorizationRedirect");async function ty(e){let t=Pe(e.connection),r=!!e.forceRefresh,n=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=oe(),i=s?await Yr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(s?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:i,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!n,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},n?"Reusing stored upstream access token":"Refreshing upstream credential"),n)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a;try{a=await Qg(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!dE(c))throw c;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await Gg({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(a==="AUTHORIZED"){let c=e.provider.readUsablePeerAdoption(e.requestedScope);return c!==void 0&&await e.provider.adoptConnectionForDirectResolution(c,"cas_loss"),!e.provider.tokenWriteWasPersisted&&c===void 0?{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(a!=="REDIRECT")throw new k({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${a}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new k({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});return await Gg({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Dc({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(ty,"authorizeUpstreamOAuthSession");async function EE(e){let t=await Ci(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),n=kE(r);return AE({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),PE(n),n}o(EE,"consumeStoredCallbackState");function kE(e){switch(e.kind){case"consumed":throw new k({message:"OAuth state has already been used",extensionMembers:{[O]:"oauth_state_reused"}});case"missing":throw new k({message:"OAuth state is missing or expired",extensionMembers:{[O]:"oauth_state_expired"}});case"available":return e.record}}o(kE,"readConsumedCallbackState");function AE(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new k({message:"OAuth callback did not match the initiating request",extensionMembers:{[O]:"oauth_callback_mismatch"}})}o(AE,"assertStoredCallbackStateMatches");function PE(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[O]:"oauth_state_expired"}})}o(PE,"assertStoredCallbackStateFresh");async function Dc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Ag(r)}if(zt()&&!xg(e.operationId))return oe()?.warn({event:"upstream_connect_link_unavailable",upstreamServerId:e.upstreamServerId,operationId:e.operationId},"User-owned upstream needs a connection, but this MCP route has no gateway MCP OAuth sign-in to bind a connect link to; returning an administrator answer instead of a link"),Og({upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,...e.connection===void 0?{}:{connectionId:e.connection.id},requiresReconsent:!!e.connection});let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Ii(t)}o(Dc,"buildOAuthConnectRequiredResponse");async function ry(e){let t=await EE({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ds(t),[n]=await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(s.connection=n);let i=new jt(s),a=await TE(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(a==="AUTHORIZED"){let c=i.readUsablePeerAdoption();if(c!==void 0&&await i.adoptConnectionForDirectResolution(c,"cas_loss"),!i.tokenWriteWasPersisted&&c===void 0)throw new k({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[O]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new k({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}}):new k({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[O]:"upstream_token_exchange_failed"}})}o(ry,"finishUpstreamOAuthCallback");import{importPKCS8 as xE,SignJWT as OE}from"jose";var oy=1e4,sy=64*1024,iy=2,ME=300,tt=p.string().min(1),UE=p.object({access_token:tt,issued_token_type:p.literal(pa),token_type:p.string().optional(),expires_in:p.number().int().positive().optional(),scope:tt.optional()}).passthrough(),qE=p.object({id_token:tt,token_type:tt.optional(),expires_in:p.number().int().positive().optional(),refresh_token:tt.optional(),scope:tt.optional()}).passthrough(),zE=p.object({access_token:tt,token_type:tt,expires_in:p.number().int().positive().optional(),scope:tt.optional(),resource:tt.optional(),refresh_token:tt.optional()}).passthrough();function ny(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(ny,"formEncodeClientCredential");function NE(e){return e.replaceAll("\\n",`
41
+ `)}o(NE,"normalizePem");async function jE(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??ME,n=await xE(NE(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new OE({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(n)}o(jE,"createPrivateKeyJwtClientAssertion");async function DE(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=ny(e.clientAuth.clientId),r=ny(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Hs),e.form.set("client_assertion",await jE({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(DE,"appendClientAuthentication");async function Lc(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await DE({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(Lc,"buildFormRequest");function ay(e){return(t,r)=>bi(t,r,{context:e,maxRedirects:iy,maxResponseBytes:sy,problemCode:"upstream_token_exchange_failed",timeoutMs:oy})}o(ay,"defaultIdpFetchJson");function LE(e){return(t,r)=>ug(t,r,{context:e,maxRedirects:iy,maxResponseBytes:sy,problemCode:"upstream_token_exchange_failed",timeoutMs:oy})}o(LE,"defaultResourceAsFetchJson");function Ei(e){let t={[O]:e.code,[ut]:e.tokenUrl};return e.response!==void 0&&(t[dt]=e.response.status),new k({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}o(Ei,"runtimeError");function $c(e){if(!e.response.ok)throw Ei({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}o($c,"assertTokenEndpointSucceeded");function $E(e){let t=qE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o($E,"parseIdpRefreshTokenResponse");function HE(e){let t=UE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(HE,"parseIdJagTokenExchangeResponse");function BE(e){let t=zE.safeParse(e.json);if(!t.success)throw Ei({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}o(BE,"parseAccessTokenResponse");async function cy(e){let t=new URLSearchParams({grant_type:$s,requested_token_type:pa,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??ay(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return $c({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),HE({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(cy,"requestIdJag");async function dy(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??ay(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return $c({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),$E({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(dy,"refreshIdpSubjectToken");async function uy(e){let t=new URLSearchParams({grant_type:Ot,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??LE(e.context),{response:n,json:s}=await r(e.resourceAs.tokenUrl,await Lc({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return $c({response:n,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),BE({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(uy,"exchangeIdJagForAccessToken");function FE(e){return Pe(e)==="usable"}o(FE,"hasUsableAccessToken");function JE(e){if(e.tokenType.toLowerCase()!=="bearer")throw new k({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[O]:"upstream_token_response_invalid"}})}o(JE,"assertBearerToken");function ly(e,t){if(t===Vr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(ly,"hasExpiredSubjectToken");async function VE(e){let t=await Rt(e.encryptedSubjectToken);if(e.subjectTokenType!==Vr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await dy({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:bo};let n=await H().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await wt(r.refreshToken),idpSubjectTokenType:Vr,idpSubjectTokenExpiresAt:void 0}});return oe()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:n.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await ur(t),newSubjectRefreshTokenFingerprint:await ur(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:n,subjectToken:r.idToken,subjectTokenType:bo}}o(VE,"resolveIdJagSubjectToken");async function py(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Pe(t),n=!!e.forceRefresh,s=!n&&r==="usable",i=oe(),a=i?await Yr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(i?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:a,connectionId:t?.id,accessTokenState:r,forceRefresh:n,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&FE(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Rt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||ly(t,d))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:d,subjectTokenExpired:d!==void 0&&ly(t,d)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let u=qt(e.upstreamServerId),m=rg(e.upstreamServerId,e.authProfileId),h=m.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),S=await VE({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),R=await cy({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:m.resourceAs.audience,resource:h,scope:f,clientAuth:m.idp.clientAuth,context:e.context}),_=R.scope??f,y=await uy({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:R.assertion,resource:h,scope:_,clientAuth:m.resourceAs.clientAuth,context:e.context});if(JE(y),t!==void 0){let I=(y.scope??_)?.split(/[,\s]+/).filter(Boolean)??[],U=y.expiresIn===void 0?void 0:J(new Date(Date.now()+y.expiresIn*1e3)),v=await H().upsertUpstreamConnection({id:S.connection.id,ownerMode:S.connection.ownerMode,subjectId:S.connection.subjectId,upstreamServerId:S.connection.upstreamServerId,authProfileId:S.connection.authProfileId,status:"active",encryptedAccessToken:await wt(y.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:I,expiresAt:U,metadata:S.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:v.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:I.length,expiresAt:U},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}o(py,"authorizeUpstreamIdJagRequest");var ki=new Map;function GE(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(GE,"normalizeRefreshFlightScope");function KE(e){return Ti(new URL(e.callbackPath,ie(e.requestUrl,e.requestHeaders))).toString()}o(KE,"buildGatewayOAuthRedirectUri");async function Hc(e){let t=qt(e.upstreamServerId),r=Wr(e.upstreamServerId,e.authProfileId),n=KE({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:n,returnOrigin:ie(e.request.url,e.request.headers)}}}o(Hc,"prepareUpstreamOAuthRequest");async function my(e){let t=await Hc(e),r=new jt({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return ey(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(my,"startUpstreamConnect");async function hy(e){let t=await Hc(e),r=new jt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>ty({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n();let s=Xm({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,GE(r.configuredAuthorizationScope??e.requestedScope)]),a=ki.get(i);if(a!==void 0){oe()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let u=await a;if(u.kind==="usable"&&r.connectionSatisfiesRequestedScope(u.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(u.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:m,...h}=e;if(t=await Hc(h),r=new jt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Pe(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n()}let c=n(),d;return d=c.then(()=>{let u=r.currentConnection;return u!==void 0&&Pe(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{ki.get(i)===d&&ki.delete(i)}),ki.set(i,d),c}o(hy,"authorizeUpstreamRequest");async function en(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return hy({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return py({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Te(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(en,"resolveUpstreamCredentialForRoute");async function fy(e){if(e.connectRequest.authMode==="id-jag")throw new Te(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await my({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding}});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}o(fy,"startUpstreamConnectForRequest");async function WE(e,t){if(t===void 0)throw new k({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[O]:"oauth_callback_mismatch"}});let r=await wi({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new k({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[O]:"oauth_callback_mismatch"}})}o(WE,"requireCallbackBrowser");async function gy(e){let t=await Ci(e.callbackRequest.state);zt()&&await WE(e,t.browserBinding);let r=t.authProfileId;if(yi({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Te(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return ry({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:qt(e.callbackRequest.upstreamServerId)})}o(gy,"finishUpstreamCallbackForRequest");function ZE(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(ZE,"buildRouteAuthBaseFromConnection");function yy(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:km(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(yy,"buildRouteAuthBaseFromPolicyOptions");function Ai(e,t){let n=Ce().byOperationId.get(t);if(!n)throw new ee(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(n.connection===void 0)throw new ee(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(n.connection.upstreamServerId!==e)throw new ee(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return ZE({connection:n.connection,operationId:t})}o(Ai,"resolveRouteAuthBase");function Bc(e,t){switch(e){case"user":return Jr(t);case"shared":return Tm()}}o(Bc,"buildOwnerForSubject");function tn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:Bc("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:Bc("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:Bc("user",t),initiatedBySubjectId:t}}}o(tn,"resolveRouteAuthForSubject");import{base64url as YE,errors as XE,jwtVerify as QE,SignJWT as ek}from"jose";var Fc="zuplo-connect.",tk=600,Sy="mcp_connect_request_state",rk=p.object({purpose:p.literal(Sy),binding:p.string().min(1),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),nk=new TextEncoder;async function _y(){return Ve({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"connect-request-state"),"derive")})}o(_y,"getConnectRequestStateKey");async function wy(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",nk.encode(t));return YE.encode(new Uint8Array(r))}o(wy,"digestBinding");function Jc(e){return typeof e=="string"&&e.startsWith(Fc)}o(Jc,"isConnectRequestState");async function Ry(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new ek({purpose:Sy,binding:await wy(e)}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt(r).setExpirationTime(r+tk).sign(await _y());return`${Fc}${n}`}o(Ry,"signConnectRequestState");async function by(e,t,r=new Date){if(!Jc(e))return"invalid";let n;try{let{payload:s}=await QE(e.slice(Fc.length),await _y(),{algorithms:[Re],issuer:he,audience:we,currentDate:r,clockTolerance:0});n=rk.parse(s)}catch(s){return s instanceof XE.JWTExpired?"expired":"invalid"}return n.binding===await wy(t)?void 0:"mismatch"}o(by,"verifyConnectRequestState");var ok=new Set(["tools/call","prompts/get","resources/read"]);var sk=-32021,ik="Invalid or expired requestState";function rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(rn,"isRecord");function vy(e,t){if(!(!fe()||!rn(t)||typeof t.method!="string"||!zr(e,t)))return{message:t,method:t.method}}o(vy,"readModernMcpRequest");function Vc(e){return!Object.hasOwn(e.message,"id")}o(Vc,"isModernNotification");function Gc(){return new Response(null,{status:202})}o(Gc,"acceptedNotificationResponse");function Kc(e){let t=e.message.params;return rn(t)?t:void 0}o(Kc,"readParams");function Cy(e){if(!ok.has(e.method))return;let t=Kc(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}o(Cy,"readInputRequiredTarget");function Iy(e,t,r){return{...e,method:t.method,target:r}}o(Iy,"buildBinding");function ak(e){let t=Me(e.message);return Response.json(gt({...t===void 0?{}:{id:t},error:{code:A.InvalidParams,message:ik,data:{reason:"invalid_request_state"}}}))}o(ak,"invalidRequestStateResponse");function ck(e){if(!rn(e))return;let t=e[Nr],r=rn(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}o(ck,"readElicitationAction");function dk(e){let t={...Kc(e)};if(delete t.requestState,rn(t.inputResponses)){let r={...t.inputResponses};delete r[Nr],Object.keys(r).length===0?delete t.inputResponses:t.inputResponses=r}return{...e.message,params:t}}o(dk,"stripConnectState");async function Ty(e){let t=Kc(e.request),r=t?.requestState;if(!Jc(r))return{kind:"none"};let n=Cy(e.request),s=n===void 0?"mismatch":await by(r,Iy(e.binding,e.request,n),e.now);if(s!==void 0)return{kind:"rejected",reason:s,response:ak(e.request)};let i=dk(e.request),a=new TextEncoder().encode(JSON.stringify(i));return{kind:"accepted",body:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),request:{message:i,method:e.request.method},action:ck(t?.inputResponses)}}o(Ty,"readModernConnectRetry");function uk(e){let t=am(e.message)?.elicitation;return rn(t)&&t.url!==void 0}o(uk,"declaresUrlElicitation");function lk(e,t){return Response.json(gt({...e===void 0?{}:{id:e},error:{code:A.InvalidRequest,message:t.message,data:{connectRequired:t}}}))}o(lk,"connectRequiredErrorResponse");async function Ey(e){if(Vc(e.request))return Gc();let t=Me(e.request.message),r=Cy(e.request),n=e.payload.authUrl;if(r===void 0||n===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return lk(t,e.payload);if(!uk(e.request))return Response.json(gt({...t===void 0?{}:{id:t},error:{code:sk,message:`${e.payload.message} The client must declare URL elicitation (clientCapabilities.elicitation.url) to be sent the connect link.`,data:{requiredCapabilities:{elicitation:{url:{}}},connectRequired:e.payload}}}),{status:400});let s=await Ry(Iy(e.binding,e.request,r),e.now);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"input_required",inputRequests:{[Nr]:{method:"elicitation/create",params:{mode:"url",message:e.payload.message,url:n}}},requestState:s,_meta:{[ir]:e.serverInfo}}})}o(Ey,"modernConnectRequiredResponse");var Wc=[So],pk=0,mk="private",hk="0.0.0";function fk(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(fk,"buildGatewayDiscoverCapabilities");function Zc(e){let{connection:t}=e,r=t.serverInfo,n=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...n===void 0?{}:{title:n},version:r?.version??hk,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}o(Zc,"buildGatewayDiscoverServerInfo");function ky(e){let t=Me(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...Wc],capabilities:fk(e.capabilityFilter),_meta:{[ir]:Zc({connection:e.connection,icons:e.icons})},ttlMs:pk,cacheScope:mk}})}o(ky,"gatewayDiscoverResponse");var Yc=new WeakMap;function Ay(e,t){Yc.set(e,t)}o(Ay,"setUpstreamAuthRetry");function Py(e){let t=Yc.get(e);return Yc.delete(e),t}o(Py,"takeUpstreamAuthRetry");var gk=A.InvalidRequest,yk="The upstream connection returned no OAuth tokens.";function xy(e){let t=Za(e);return Response.json(gt({id:t,error:{code:A.InternalError,message:yk}}),{status:t===void 0?500:200})}o(xy,"noUpstreamTokensJsonRpcResponse");function Sk(e,t){return{credentialType:e.type,forceRefresh:t}}o(Sk,"buildCredentialResolvedAttributes");function _k(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(_k,"connectRequiredReasonCode");function Oy(e){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:Sk(e.credential,e.forceRefresh===!0)})}o(Oy,"emitCredentialResolvedAnalyticsEvent");function My(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:_k(e.payload.state),reasonClass:"auth",attributes:t})}o(My,"emitCredentialMissingAnalyticsEvents");function wk(e){let t=e.route.raw();return js.parse(t?.operationId)}o(wk,"readOperationId");async function Rk(e,t,r,n,s){let i=await en({request:e,context:n,routeAuth:t});if(i.kind==="connect_required")return My({context:n,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),n.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(Oy({context:n,credential:a,routeBinding:t,mcpProtocolVersion:s}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(n.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}o(Rk,"buildCredentialHeaders");var bk=new Set(["authorization","cookie","cookie2"]);function vk(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(vk,"parseJsonRequestBody");function Ck(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(Ck,"readJsonRequestMethod");function Ik(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Ik,"isJsonResponse");function Dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Dt,"isRecord");function Uy(e){return Array.isArray(e)&&e.length>0}o(Uy,"hasIconList");function qy(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=fi(Cm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(qy,"readFallbackServerIcons");function Tk(e){if(!Dt(e.body))return e.body;let t=e.body.result;if(!Dt(t))return e.body;let r=t.serverInfo;return!Dt(r)||Uy(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(Tk,"addMissingServerIcons");function Ek(e){if(!Dt(e.body))return e.body;let t=e.body.result;if(!Dt(t))return e.body;let r=t._meta;if(!Dt(r))return e.body;let n=r[ir];return!Dt(n)||Uy(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[ir]:{...n,icons:e.icons}}}}}o(Ek,"addMissingDiscoverServerIcons");function kk(e,t){let r=zy(e.headers);for(let n of bk)r.delete(n);for(let[n,s]of t)r.set(n,s);return new kt(e,{headers:r})}o(kk,"applyUpstreamHeaders");function zy(e){let t=new Headers(e);return au(t),t}o(zy,"buildProxyHeaders");async function Ak(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(Ak,"readRetryBody");function Pk(e,t){let r=t.authUrl===void 0?void 0:uf({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(gt({id:Za(e),error:{code:r?.code??gk,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}o(Pk,"connectRequiredJsonRpcResponse");function xk(e){let t=e.modern;if(t===void 0)return{respond:o(async s=>Pk(e.requestBody,s),"respond")};let r=o(()=>qy({connection:e.connection,context:e.context}),"readIcons"),n=t.request.method==="server/discover"?async()=>ky({request:t.request,connection:e.connection,capabilityFilter:Ok(e.context),icons:r()}):s=>Ey({request:t.request,payload:s,binding:t.binding,previousAction:t.previousAction,serverInfo:Zc({connection:e.connection,icons:r()})});return{respond:o(async s=>{let i=tg({headers:e.headers,message:t.request.message,supportedVersions:Wc});return i!==void 0?i:Vc(t.request)?Gc():n(s)},"respond")}}o(xk,"createConnectRequiredResponder");function Ok(e){return Ls()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(Ok,"readRouteCapabilityFilter");async function Mk(e){let{scope:t}=of(e.upstreamResponse),r=await en({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return My({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let n=new Headers(e.headers),s=r.credential;if(Oy({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return n.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:n};let i=await s.provider.tokens();return i?(n.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:n}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"no_tokens"})}o(Mk,"applyRefreshedCredentialHeaders");function Uk(e){Ay(e.context,{refresh:o(async(t,r)=>{let n=await Mk({request:e.request,context:e.context,headers:zy(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return n.kind==="connect_required"?{kind:"response",response:await e.connectRequired.respond(n.payload)}:n.kind==="no_tokens"?{kind:"response",response:xy(e.requestBody)}:n},"refresh")})}o(Uk,"registerUpstreamAuthRetry");function qk(e){return e.body!==null&&e.status>=200&&e.status<=299&&it(e.headers.get("content-type"))==="text/event-stream"&&!at(e.headers)}o(qk,"isRewritableEventStream");function zk(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(zk,"answersRequestId");function Nk(e,t){if(e.data===void 0||e.data===""||e.event!==void 0&&e.event!=="message")return;let r;try{r=JSON.parse(e.data)}catch{return}if(!(!Dt(r)||"method"in r||!("result"in r||"error"in r)||!zk(r.id,t)))return r}o(Nk,"readResponseInEvent");function jk(e){let t=!1;return ci(e.response,r=>{if(t)return;let n=Nk(r,e.requestId);if(n===void 0)return;t=!0;let s=e.addMissingIcons({body:n,icons:e.icons});return s===n?void 0:qo(r,JSON.stringify(s))},{failureMode:"open"})}o(jk,"addMissingIconsToEventStream");function Dk(e){let t=Ck(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?Tk:Ek,n=qy({connection:e.connection,context:e.context});if(n===void 0||n.length===0)return;let s=fe()?Me(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!Ik(i))return s!==void 0&&qk(i)?jk({response:i,requestId:s,addMissingIcons:r,icons:n}):i;let a;try{a=await i.clone().json()}catch{return i}let c=r({body:a,icons:n});if(c===a)return i;let d=pf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(Dk,"installInitializeIconHook");function Lk(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new kt(e,{headers:r,body:t})}o(Lk,"withRequestBody");async function Xc(e,t,r){let n=wk(t),s=e,i=await Ak(s),a=vk(i),c=sr(s.headers,a),d=yy({connection:r,operationId:n}),u=ar(s.user,s.url,s.headers);t.log.setLogProperties?.({requestId:t.requestId}),Mm(t,u);let m=tn(d,u.subjectId),h=vy(s.headers,a),f={subjectId:u.subjectId,operationId:n,upstreamServerId:m.upstreamServerId,authProfileId:m.authProfileId},S;if(h!==void 0){let b=await Ty({request:h,binding:f});if(b.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:b.reason,upstreamServerId:m.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),b.response;b.kind==="accepted"&&(s=Lk(s,b.body),i=b.body,a=b.request.message,h=b.request,S=b.action)}let R=xk({requestBody:i,headers:s.headers,modern:h===void 0?void 0:{request:h,binding:f,previousAction:S},context:t,connection:r}),_=await Rk(s,m,r,t,c);if(_.kind==="connect_required")return R.respond(_.payload);if(_.kind==="no_tokens")return xy(i);let y=kk(s,_.headers);return Uk({request:y,context:t,requestBody:i,connectRequired:R,routeAuth:m,mcpProtocolVersion:c}),Dk({context:t,requestJson:a,connection:r,modern:h!==void 0}),y}o(Xc,"mcpTokenExchangePolicy");var Qc=class extends Cs{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=Am(t,r);super(n,r),this.#e=n}async handler(t,r){return Xc(t,r,this.#e)}};var Ny=Symbol("Html");function $k(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o($k,"escapeHtml");function Hk(e){return e===null||typeof e!="object"?!1:e[Ny]===!0}o(Hk,"isHtml");function Pi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Pi).join(""):Hk(e)?e.value:$k(String(e))}o(Pi,"renderValue");function Ge(e){return{[Ny]:!0,value:e}}o(Ge,"trustedHtml");var Ke=Ge("");function W(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Pi(t[n]),r+=e[n+1]??"";return Ge(r)}o(W,"html");function nn(e,t=Ke){let r=Pi(t),n="",s=!0;for(let i of e)s||(n+=r),n+=Pi(i),s=!1;return Ge(n)}o(nn,"joinHtml");function on(e){return e.value}o(on,"renderHtml");function jy(e){return W`<section class="page-section" aria-labelledby="error-next-steps"><h2 class="section-label" id="error-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol>${e.action}</section><section class="page-section" aria-labelledby="error-reference"><h2 class="section-label" id="error-reference">Reference</h2><dl class="kv kv--boxed">${e.reference}</dl></section><section class="page-section tech" aria-labelledby="error-technical"><h2 class="section-label" id="error-technical">Technical details <span class="section-label__count">for administrators</span></h2><dl class="kv">${e.diagnostics}</dl>${e.upstreamResponse}</section>`}o(jy,"renderBrowserErrorPage");var Dy=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><path d="m8.25 12.25 2.5 2.5 5-5.25"/></svg>'),Ly=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><line x1="12" y1="7.5" x2="12" y2="12.75"/><circle cx="12" cy="16.25" r=".9" fill="currentColor" stroke="none"/></svg>'),sn=Ge('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}.card__status{border:1px solid;border-radius:50%;justify-content:center;align-items:center;width:48px;height:48px;margin:0 auto 16px;display:flex}.card__status svg{width:24px;height:24px}.card__status--error{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger)}.card__status--success{background:var(--success-bg);border-color:var(--success-border);color:var(--success)}.card__status--neutral{background:var(--surface-2);border-color:var(--border);color:var(--text-3)}.page-section{flex-direction:column;gap:10px;display:flex}.steps{counter-reset:step;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.steps li{counter-increment:step;color:var(--text-2);align-items:flex-start;gap:10px;font-size:13.5px;line-height:1.5;display:flex}.steps li:before{content:counter(step);border:1px solid var(--border-strong);background:var(--surface);width:20px;height:20px;color:var(--text-2);border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;margin-top:1px;font-size:11.5px;font-weight:600;line-height:1;display:inline-flex}.kv{flex-direction:column;margin:0;display:flex}.kv__row{border-top:1px solid var(--border);grid-template-columns:124px minmax(0,1fr);gap:2px 12px;padding:7px 0;display:grid}.kv__row:first-child{border-top:0;padding-top:0}.kv__row:last-child{padding-bottom:0}.kv__row--block{grid-template-columns:minmax(0,1fr)}.kv__label{color:var(--text-3);margin:0;padding-top:1px;font-size:12px;font-weight:500}.kv__value{min-width:0;color:var(--text);overflow-wrap:anywhere;margin:0;font-size:13px;line-height:1.5}.kv__value code{font-family:var(--font-mono);color:var(--text);font-size:12px}.kv__row--fix .kv__value{color:var(--text);font-weight:500}.kv--boxed{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px}.kv--boxed .kv__row{grid-template-columns:92px minmax(0,1fr);padding:6px 0}.kv--boxed .kv__row:first-child{padding-top:0}.kv--boxed .kv__row:last-child{padding-bottom:0}.tech{border-top:1px solid var(--border);padding-top:18px}.provider-response{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2)}.provider-response__summary{cursor:pointer;user-select:none;color:var(--text-2);align-items:center;gap:8px;padding:9px 12px;font-size:12.5px;font-weight:500;list-style:none;display:flex}.provider-response__summary::-webkit-details-marker{display:none}.provider-response__summary:before{content:"";border-bottom:1.5px solid;border-right:1.5px solid;flex-shrink:0;width:6px;height:6px;margin-left:2px;transition:transform .15s;transform:rotate(-45deg)}.provider-response[open]>.provider-response__summary:before{transform:rotate(45deg)}.provider-response__summary:hover{color:var(--text)}.provider-response__summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--radius)}.provider-response__frame{border:0;border-top:1px solid var(--border);border-radius:0 0 var(--radius)var(--radius);background:#fff;width:100%;min-height:240px;display:block}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.kv__row{grid-template-columns:minmax(0,1fr)}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function an(e){return W`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
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>`}n(Vr,"renderShell");function ni(e){return V`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?ag:cg}</div>`}n(ni,"renderStatusIcon");var tT="text/html; charset=utf-8";function Ut(e){try{return new URL(e).host}catch{return""}}n(Ut,"safeHostFromUrl");function Fe(e){let t=e.kind??"authorization_failed",r=nT(t),o=rT(e),s=e.title??r.title;return new Response(Fr(Vr({title:s,iconHref:"",styles:Gr,headerIcon:ni(t==="access_denied"?"neutral":"error"),heading:s,subhead:V`<p class="card__subtitle">${e.detail}</p>`,body:ig({steps:Jr(r.steps.map(i=>V`<li>${i}</li>`)),action:iT(e.action),reference:aT(o),diagnostics:cT({diagnostic:o,detail:e.detail}),upstreamResponse:dT(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":tT,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Fe,"browserErrorPageResponse");function rT(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??oT(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??sT(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(rT,"buildBrowserErrorDiagnostic");function nT(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."]}}}n(nT,"readBrowserErrorPagePresentation");function oT(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(oT,"readBrowserErrorStage");function sT(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."}}n(sT,"readBrowserErrorSuggestedFix");function iT(e){return e===void 0?Je:V`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(iT,"renderAction");function oi(e){if(e.value===void 0||e.value==="")return Je;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return V`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}n(oi,"renderRow");function Ne(e){return oi({label:e.label,value:e.value===void 0?void 0:V`<code>${e.value}</code>`})}n(Ne,"renderCodeRow");function aT(e){return Jr([oi({label:"Error code",value:V`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Ne({label:"Request ID",value:e.requestId}),Ne({label:"Time",value:e.timestamp})])}n(aT,"renderReference");function cT(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return Jr([oi({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),oi({label:"Reason",value:r,block:!0}),Ne({label:"Stage",value:t.stage}),Ne({label:"Gateway route",value:t.routePath}),Ne({label:"Operation ID",value:t.operationId}),Ne({label:"Upstream",value:t.upstreamServerId}),Ne({label:"Auth profile",value:t.authProfileId}),Ne({label:"Upstream URL",value:t.upstreamUrl}),Ne({label:"Metadata URL",value:t.metadataUrl}),Ne({label:"HTTP status",value:t.httpStatus}),Ne({label:"Content type",value:t.contentType}),Ne({label:"Provider error",value:t.providerError}),Ne({label:"Provider error description",value:t.providerErrorDescription})])}n(cT,"renderDiagnostics");function dT(e){return e===void 0?Je:V`<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>`}n(dT,"renderUpstreamHtml");var dg="application/json",uT="application/x-www-form-urlencoded";function si(e,t){return new T({message:e,extensionMembers:{[E]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(si,"invalidRequestError");function lT(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(lT,"normalizeContentType");function pT(e,t){return e===t?!0:t===dg&&e.endsWith("+json")}n(pT,"contentTypeMatches");function mT(e,t){if(!t||t.length===0)return;let r=lT(e.headers.get("content-type"));if(!t.some(o=>pT(r,o)))throw si(`Request body must be ${t.join(" or ")}.`)}n(mT,"assertExpectedContentType");function hT(e,t,r){let o=e.headers.get("content-length");if(!o)return;let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>t)throw si(`${r} exceeded the maximum allowed size.`)}n(hT,"assertContentLengthWithinLimit");async function ug(e,t){let r=t.label??"Request body";mT(e,t.expectedContentTypes),hT(e,t.maxBytes,r);let o=await Vs(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>si(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ug,"readBoundedTextBody");async function lg(e,t){let r=await ug(e,{...t,expectedContentTypes:[dg]});try{return JSON.parse(r)}catch(o){throw si("Request body must be valid JSON.",o)}}n(lg,"readBoundedJsonBody");async function pg(e,t){let r=await ug(e,{...t,expectedContentTypes:[uT]});return new URLSearchParams(r)}n(pg,"readBoundedFormUrlEncodedBody");import{errors as hg,jwtVerify as fg,SignJWT as ac}from"jose";import{base64url as fT}from"jose";var gT="mcp-browser-login-pkce:",yT=new TextEncoder;async function ST(e){return crypto.subtle.importKey("raw",he(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}n(ST,"importHmacKey");async function ic(e){let t=await ST(e.signingKey),r=yT.encode(`${gT}${e.stateId}`),o=await crypto.subtle.sign("HMAC",t,he(r));return kr.parse(fT.encode(new Uint8Array(o)))}n(ic,"deriveBrowserLoginPkceVerifier");async function mg(e){let t=await ic(e),r=await vs(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Er}}n(mg,"deriveBrowserLoginPkceParams");var _T={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},v=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=_T[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var wT=300,RT=p.object({purpose:p.literal("gateway_browser_login"),transactionId:Mi,stateId:Ss,binding:vo,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),bT=p.object({purpose:p.literal("gateway_browser_login_return"),stateId:Ss,binding:vo,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),vT=p.discriminatedUnion("purpose",[RT,bT]),CT=p.object({purpose:p.literal("gateway_authorization_setup"),transactionId:Mi,stateId:Ss,exp:p.number().int().positive(),iat:p.number().int().positive().optional()});async function Kr(){return tt({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-login"),"derive")})}n(Kr,"getBrowserLoginKey");async function gg(){return tt({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"authorization-csrf"),"derive")})}n(gg,"getCsrfKey");function yg(e){return{now:e.now??new Date,ttlSeconds:cc()}}n(yg,"readPendingTransactionDependencies");function cc(){return ve().browserLogin.stateTtlSeconds}n(cc,"readBrowserLoginStateTtlSeconds");function IT(e){let t=me();return qe(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(IT,"isLoopbackDevLoginUrl");async function Sg(e){let t=ve().browserLogin,r=me(),o=new URL(bt("url")),s=new URL(r.actionPath("/oauth/callback"),qr(e.requestUrl,e.requestHeaders));if(IT(o))return o.searchParams.set("redirect_uri",s.toString()),o.searchParams.set("state",e.state),o;if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",bt("clientId")),o.searchParams.set("redirect_uri",s.toString()),o.searchParams.set("scope",t.scope),o.searchParams.set("state",e.state),o.searchParams.set("nonce",e.nonce),t.audience&&o.searchParams.set("audience",t.audience),t.pkce===Er){let i=await mg({stateId:e.stateId,signingKey:await Kr()});o.searchParams.set("code_challenge",i.codeChallenge),o.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return o}n(Sg,"buildBrowserLoginUrl");function TT(e,t){return e.subjectId===t.subjectId}n(TT,"principalsMatch");function _g(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(_g,"toPendingPrincipal");function wg(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:J(e.now),expiresAt:J(st(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 M("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:_g(e.principal)}}n(wg,"createTransactionRecord");async function Rg(e){let{id:t,...r}=e.record,o=await H().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw M("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new v("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new v("invalid_request","redirect_uri is not registered for the client.")}}n(Rg,"startPendingTransaction");async function ET(e){return new ac({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Kr())}n(ET,"signBrowserLoginState");async function bg(e){return new ac({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:ws()}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await gg())}n(bg,"signCsrfToken");async function dc(e){try{let{payload:t}=await fg(e,await Kr(),{algorithms:[xe],issuer:Te,audience:Pe}),r=vT.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof hg.JWTExpired?M("oauth_state_expired","Browser login state has expired.",t):M("oauth_state_invalid","Browser login state could not be verified.",t)}}n(dc,"verifyAnyBrowserLoginStateToken");async function kT(e){let t=await dc(e);if(t.kind!=="authorization")throw M("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding}}n(kT,"verifyBrowserLoginStateToken");async function ii(e){try{let{payload:t}=await fg(e,await gg(),{algorithms:[xe],issuer:Te,audience:Pe});return{transactionId:CT.parse(t).transactionId}}catch(t){throw t instanceof hg.JWTExpired?M("oauth_state_expired","Authorization setup state has expired.",t):M("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(ii,"verifyCsrfToken");function uc(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(uc,"pendingStateErrorCode");function AT(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(AT,"toPendingAuthorizationGetResult");function PT(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(PT,"toPendingAuthorizationAdvanceResult");function lc(e){return e==="principal_mismatch"?"oauth_callback_mismatch":uc(e==="consumed_already"?"consumed_already":e)}n(lc,"setupDecisionErrorCode");async function vg(e){let t=e.now??new Date,r=await ii(e.csrfToken),o=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(o.kind!=="marked")throw M(lc(o.kind),"Authorization setup state is invalid, expired, or already used.");return Cg({kind:"available",record:o.transaction})}n(vg,"markSetupApproved");function Cg(e){if(e.kind!=="available")throw M(uc(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Cg,"requireAwaitingSetup");function xT(e){if(!TT(e.currentBrowserPrincipal,e.transaction.principal))throw M("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(xT,"requireCurrentPrincipalMatches");async function Ig(e){let t=e.now??new Date,r=cc(),o=qi(),s=ws(),i=await Io({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await ET({transactionId:o,stateId:s,binding:i.claim,ttlSeconds:r}),c=wg({id:o,transaction:e.transaction,currentStateHash:await oe(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw M("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await Rg({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw M("oauth_state_invalid","Authorization transaction did not start in login phase.");let l=await Sg({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:l,browserBindingCookie:i.setCookie}}n(Ig,"startAwaitingLogin");async function Tg(e){let t=cc(),r=ws(),o=await Io({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new ac({purpose:"gateway_browser_login_return",stateId:r,binding:o.claim}).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Kr());return{browserLoginUrl:await Sg({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:o.setCookie}}n(Tg,"startReturnToBrowserLogin");async function Eg(e){let{now:t,ttlSeconds:r}=yg(e),o=qi(),s=await bg({transactionId:o,ttlSeconds:r}),i=wg({id:o,transaction:e.transaction,currentStateHash:await oe(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await Rg({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw M("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}n(Eg,"startAwaitingSetup");async function kg(e){let{now:t,ttlSeconds:r}=yg(e),o=await kT(e.browserLoginStateToken),s=await bg({transactionId:o.transactionId,ttlSeconds:r}),i=PT(await H().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await oe(e.browserLoginStateToken),nextStateHash:await oe(s),nextPhase:"awaiting_setup",principal:_g(e.principal),now:J(t)}));if(i.kind!=="advanced")throw M(uc(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw M("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}n(kg,"completeLogin");async function Ag(e){let t=await pc(e);return xT({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Ag,"getSetup");async function pc(e){let t=e.now??new Date,r=await ii(e.csrfToken);return Cg(AT(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await oe(e.csrfToken),now:J(t)})))}n(pc,"getSetupTransaction");async function OT(e){let t=await ii(e.csrfToken),r=at(),o=J(st(e.now,wT)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await oe(r),authorizationCodeExpiresAt:o,grantId:bp(),now:J(e.now)});if(s.kind!=="approved")throw M(s.kind==="cancelled"?"oauth_state_invalid":lc(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),i}n(OT,"createAuthorizationCodeRedirectWithDecision");async function UT(e){let t=await ii(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await oe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw M(r.kind==="approved"?"oauth_state_invalid":lc(r.kind),"Authorization setup state is invalid, expired, or already used.");return MT({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(UT,"createCancelRedirectWithDecision");function MT(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),t}n(MT,"buildClientCancelRedirect");async function Pg(e){let t=e.now??new Date;return OT({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Pg,"approve");async function xg(e){let t=e.now??new Date;return UT({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(xg,"cancel");import{createRemoteJWKSet as qT,errors as Wr,jwtVerify as Og,SignJWT as zT}from"jose";var NT="zuplo_mcp_session",jT=p.object({purpose:p.literal("gateway_browser_session"),sub:to,browserLoginOrigin:p.string().min(1),roles:p.array(p.string().min(1)).optional(),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),DT=p.object({id_token:p.string().min(1),token_type:p.string().min(1).optional(),expires_in:p.number().optional(),access_token:p.string().min(1).optional(),refresh_token:p.string().min(1).optional(),scope:p.string().min(1).optional()}),$T=p.object({error:p.string().min(1).optional(),error_description:p.string().min(1).optional(),error_uri:p.string().min(1).optional()}),LT=p.object({sub:to,nonce:p.string().min(1)}).catchall(p.unknown()),mc;async function Ug(){return tt({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Pt(e,"browser-session"),"derive")})}n(Ug,"getBrowserSessionKey");function fc(e,t){let r=Fs(e,t);return{name:ja(NT,r),secure:r}}n(fc,"browserSessionCookieName");function hc(e,t){let{name:r,secure:o}=fc(e,t);return Co({name:r,value:"",maxAgeSeconds:0,secure:o})}n(hc,"buildBrowserSessionEvictionCookie");function HT(e){let{name:t,secure:r}=fc(e.requestUrl,e.requestHeaders);return Co({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}n(HT,"serializeSessionCookie");function Mg(){return new URL(bt("url")).origin}n(Mg,"readBrowserLoginOrigin");function BT(e){let t=$T.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}n(BT,"readIdpErrorFields");function JT(e){return e instanceof Wr.JWTExpired?"expired":e instanceof Wr.JWTClaimValidationFailed?"claim":e instanceof Wr.JWSSignatureVerificationFailed?"signature":e instanceof Wr.JWKSNoMatchingKey?"jwks_no_match":e instanceof Wr.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(JT,"readJwtFailureKind");function FT(e){return e instanceof Error&&"cause"in e?e.cause:e}n(FT,"readErrorCause");function GT(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(GT,"readRuntimeGatewayCode");function VT(){if(!mc){let e=ve();mc=qT(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return mc}n(VT,"readFederatedJwks");function qg(e){if(!e.user)throw M("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Yt(e.user,e.url)}n(qg,"resolveCurrentRequestPrincipal");async function Zr(e,t={}){let r=Da(e.headers.get("cookie")).get(fc(e.url,e.headers).name);if(!r)return{};try{let{payload:o}=await Og(r,await Ug(),{algorithms:[xe],issuer:Te,audience:Pe}),s=jT.parse(o);if(s.browserLoginOrigin!==Mg())return{evictCookie:hc(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(o){return o instanceof Wr.JWTExpired?{evictCookie:hc(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:hc(e.url,e.headers)})}}n(Zr,"readBrowserSession");async function ko(e){let t=ve().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:Mg()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new zT(r).setProtectedHeader({alg:xe,typ:"JWT"}).setIssuer(Te).setAudience(Pe).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Ug());return HT({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(ko,"createBrowserSessionCookie");async function KT(e){let t=ve(),r=bt("tokenUrl"),o=bt("clientId"),s=bt("clientSecret"),i=new URL(me().actionPath("/oauth/callback"),qr(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:o,client_secret:s});if(t.browserLogin.pkce===Er){let c=await ic({stateId:e.stateId,signingKey:await Kr()});a.set("code_verifier",c)}try{let{response:c,json:d}=await Ks(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 f=BT(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ce(r),idpStatus:c.status,...f},"Federated browser login token exchange returned non-2xx from the identity provider"),M({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${f.idpError?` idp_error=${f.idpError}`:""}${f.idpErrorDescription?` idp_error_description=${f.idpErrorDescription}`:""})`)})}let l=DT.parse(d),m;try{({payload:m}=await Og(l.id_token,VT(),{issuer:t.oidc.issuer,audience:o}))}catch(f){let R={};throw Ce(R,"error",f),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:JT(f),idpHost:ce(r),expectedIssuer:t.oidc.issuer,...R},"Federated id_token failed jose verification"),f}if(m.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ce(r),nonceMissingFromIdToken:m.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),M("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=LT.parse(m);return{principal:Yt({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:l.id_token,tokenType:oo,expiresAt:typeof m.exp=="number"?J(new Date(m.exp*1e3)):void 0}}}catch(c){let d=ot(c)??GT(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:M("browser_login_verification_failed","Federated browser login callback could not be verified.",FT(c))}}n(KT,"exchangeFederatedAuthorizationCode");async function gc(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return KT({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await Zr(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw M("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(gc,"resolveBrowserLoginCallbackIdentity");var WT=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function ZT(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(ZT,"readScheme");function YT(e){return e.protocol==="https:"}n(YT,"isSpecCompliantRedirectUri");function XT(e){let t=ZT(e);return t.length>0&&t!=="http"&&t!=="https"&&!WT.has(t)}n(XT,"isNativeAppCustomSchemeRedirectUri");var Ng=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>YT(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>qe(e),"accepts"),matches:n((e,t)=>qe(e)&&qe(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>XT(e),"accepts")}];function jg(e){let t=Ng.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(jg,"evaluateBuiltInRedirectUriCompatibility");function zg(e){try{return new URL(e)}catch{return}}n(zg,"parseUrl");function Dg(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=zg(e.registeredRedirectUri),r=zg(e.requestedRedirectUri);return t===void 0||r===void 0?!1:Ng.some(o=>o.matches?.(t,r))}n(Dg,"redirectUriMatchesBuiltInCompatibility");var QT=1e4,eE=5*1024,tE=0,rE=2160*60*60,$g=["authorization_code","refresh_token",gs,vt],nE=["authorization_code","refresh_token"],Lg=[_p],oE=["code"],sE=p.object({client_name:p.string().min(1).optional(),redirect_uris:p.array(p.string().min(1)).min(1),grant_types:p.array(p.enum($g)).min(1).max($g.length).optional(),authorization_grant_profiles_supported:p.array(p.enum(Lg)).min(1).max(Lg.length).optional(),response_types:p.array(p.enum(oE)).min(1).max(1).optional(),scope:p.literal(ue).optional(),token_endpoint_auth_method:Rp.optional(),jwks_uri:p.string().min(1).optional()});function iE(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&qe(t))&&t.pathname!=="/"}catch{return!1}}n(iE,"isCimdClientIdCandidate");function Hg(e,t){throw new v("invalid_client",Pp({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Hg,"invalidCimdClientError");function Yr(e,t="invalid_request"){if(aE(e))throw new v(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new v(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new v(t,"redirect_uris must not include credentials or fragments.");if(jg({url:r}).kind==="rejected")throw new v(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Yr,"assertValidRedirectUri");function aE(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}n(aE,"hasForbiddenRawRedirectUriCharacter");async function cE(e){let{response:t,json:r}=await Jh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:tE,maxResponseBytes:eE,timeoutMs:QT});if(!t.ok)throw M("invalid_request","CIMD metadata could not be fetched.");let o=_s(r);for(let s of o.redirect_uris)Yr(s,"invalid_request");if(o.jwks_uri!==void 0&&io(o.jwks_uri),o.client_id!==e.clientId)throw M("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(cE,"fetchCimdMetadata");async function dE(e){let t=Rs(e),r=await cE({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(dE,"resolveCimdClient");async function ai(e,t){let r=it.parse(e);if(iE(r)){ve().gateway.downstreamCimdEnabled||Hg(r);try{return await dE(r)}catch(s){Hg(r,s)}}let o=await H().readClient({clientId:r});if(o.kind==="found"){let s=o.client,i=Op(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 v("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=_s({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),l={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(l.hashedClientSecret=s.hashedClientSecret),l}throw new v("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(ai,"resolveClient");function Bg(e,t){if(!e.metadata.redirect_uris.some(r=>Dg({registeredRedirectUri:r,requestedRedirectUri:t})))throw M("invalid_request","redirect_uri is not registered for the client.")}n(Bg,"assertRedirectRegistered");function uE(e){return e===void 0?[...nE]:Array.from(new Set(e))}n(uE,"normalizeGrantTypes");function lE(e){try{io(e)}catch(t){throw new v("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})}}n(lE,"assertValidDcrJwksUri");function pE(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?it.parse(xp({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):it.parse(`dcr:${crypto.randomUUID()}`)}n(pE,"createDcrClientId");function Xr(e){if(e===void 0||e===ue)return ue;throw new v("invalid_request",`Only the ${ue} scope is supported.`)}n(Xr,"assertSupportedOAuthScope");function tr(e,t,r){let o;try{o=new URL(t)}catch{throw new v("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new v("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!qe(o))throw new v("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ne(e,r),i=yp(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new v("invalid_target","resource must match a published MCP route.");return a}n(tr,"resolveResource");async function Jg(e){let t;try{t=sE.parse(e)}catch(f){if(f instanceof p.ZodError){let R=f.issues.some(S=>S.path[0]==="redirect_uris");throw new v(R?"invalid_redirect_uri":"invalid_client_metadata",f.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:f})}throw f}for(let f of t.redirect_uris)Yr(f,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new v("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&lE(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",s=o==="private_key_jwt"?"none":o,i=pE({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),a=_s({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:o,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=st(r,rE),d=Math.floor(r.getTime()/1e3),l=Math.floor(c.getTime()/1e3),m={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:uE(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:ue,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:J(r),clientExpiresAt:J(c)};if(o==="client_secret_basic"||o==="client_secret_post"){let f=at();h.hashedClientSecret=await oe(f),h.clientSecretExpiresAt=J(c),m.client_secret=f,m.client_secret_expires_at=l,m.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw M("invalid_request","OAuth client is already registered.");return m}n(Jg,"registerDownstreamClient");function mE(e){return e?.metadata?.idpSubjectTokenType!==zr&&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}n(mE,"hasStoredIdJagSubjectTokenBinding");async function Fg(e){let t=Mr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Fg,"readIdJagSubjectConnection");async function yc(e){let t=_e().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Fg({connection:t.connection,principal:e.principal});return!mE(r)}n(yc,"requiresIdJagSubjectTokenBinding");async function Gg(e){if(e.subjectToken===void 0)return;let t=_e().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 Fg({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??bs(),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 pt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Gg,"bindIdJagSubjectTokenForAuthorizationTransaction");function Vg(e){return V`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(Vg,"renderShellIcon");function Kg(e){return V`<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>`}n(Kg,"renderActions");var Wg=Be('<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 Zg(e){return V`<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>`}n(Zg,"renderBannerWarning");var Wz=Be('<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>'),Zz=Be('<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 Yz=Be('<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 hE="data:,",Yg=V`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);"`,Xg=V`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 fE(e,t,r){if(e)try{let o=new URL(t).origin,s=new URL(e,o);return s.origin!==o||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}n(fE,"safeGatewayConnectHref");function gE(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(gE,"deriveMode");function yE(e){return Kg({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Yg,authorizeAttrs:Je})}n(yE,"renderActions");function Sc(e,t,r,o){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=fE(s.connectUrl,t,o);if(i)return i}}n(Sc,"firstUserConnectHref");function SE(e){let t=e.connectHref===void 0?Je:V`<a class="button button--primary" href="${e.connectHref}" ${Xg}>Connect</a>`;return V`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Yg}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(SE,"renderSetupActions");function _E(e){return e?V`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Xg}>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>`:Je}n(_E,"renderReconnectAction");function wE(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}}n(wE,"isRenderableIconHref");function Qg(e){return e?.find(t=>wE(t.src))?.src}n(Qg,"readIconHref");function RE(e){return Qg(e.serverIcons)??(e.transportHost===void 0?void 0:Na(e.transportHost).src)}n(RE,"readUpstreamIconHref");function bE(e){let t=Qg(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=RE(r);if(o!==void 0)return o}}n(bE,"readHeaderIconHref");function vE(e){let t=e.setupMessage===void 0?Je:Zg({icon:Wg,message:e.setupMessage});return V`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(vE,"renderBody");function _c(e){let t=gE(e.upstreams),r=Sc(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=Sc(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=Sc(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o:void 0,a=t==="setup"?e.upstreams.find(l=>l.ownerMode==="user"&&l.status!=="active"&&l.connectUrl===void 0&&l.setupMessage!==void 0)?.setupMessage:void 0,c=bE({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?V`<footer class="card__footer">${SE({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:V`<footer class="card__footer">${_E(s)}${yE({state:e.state,gateway:e.gateway})}</footer>`;return Fr(Vr({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??hE,styles:Gr,headerIcon:c===void 0?Je:Vg({iconHref:c,fallbackIconHref:Mh}),heading:"Authorize access",subhead:Je,body:vE({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}n(_c,"renderConsentPage");var CE=1e4,ey="mcp-session-id",IE;function sy(){return{tools:[],prompts:[],resources:[]}}n(sy,"emptyCapabilities");function ty(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":zi})}n(ty,"buildReadinessHeaders");async function ry(e){if(e.type==="bearer_token"){let o=ty();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=ty();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(ry,"buildAsyncCredentialHeaders");function ny(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Wt.parse({jsonrpc:vr,id:1,method:"initialize",params:{protocolVersion:zi,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(ny,"buildInitializePreflight");async function wc(e){so(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),CE);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await Yc.fetch(o)}finally{clearTimeout(r)}}n(wc,"runPreflight");function Rc(e){e.body?.cancel().catch(()=>{})}n(Rc,"releasePreflightBody");async function TE(e){let t=e.response.headers.get(ey);if(!t)return;let r=new Headers(e.headers);r.set(ey,t),r.delete("content-type");try{let o=await wc(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Rc(o)}catch{}}n(TE,"terminatePreflightSession");async function iy(e){let{response:t}=e;return Rc(t),t.status>=200&&t.status<300?(await TE(e),{kind:"ready",upstreamStatus:t.status,capabilities:sy()}):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."}}n(iy,"classifyResponse");function oy(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}}n(oy,"connectRequiredResult");async function EE(e){try{return iy({response:await wc(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(EE,"classifyPreflight");async function kE(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:sy()};let r=ti(t.upstreamServerId,e.route.operationId),o=Br(r,e.subjectId),s=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await Hr({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return oy(a.payload);let c=await ry(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d=ny({upstreamUrl:t.mcpUrl,headers:c}),l;try{l=await wc(d)}catch(y){return{kind:"upstream_unavailable",message:y instanceof Error?y.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return iy({response:l,upstreamUrl:t.mcpUrl,headers:c});Rc(l);let m=await Hr({request:i,routeAuth:s,forceRefresh:!0});if(m.kind==="connect_required")return oy(m.payload);let h=await ry(m.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:EE({request:ny({upstreamUrl:t.mcpUrl,headers:h}),upstreamUrl:t.mcpUrl,headers:h})}n(kE,"checkUpstreamRouteReadinessImpl");function ay(e){return(IE??kE)(e)}n(ay,"checkUpstreamRouteReadiness");function AE(e){try{return new URL(e).host}catch{return}}n(AE,"safeUrlHost");function cy(e){return e!==void 0&&e.length>0}n(cy,"hasItems");function PE(e){let t=e.serverInfo?.icons;if(cy(t))return t;let r=Hs(e.mcpUrl);return r===void 0?void 0:[r]}n(PE,"readServerIcons");async function xE(e){let{authConfig:t,authMode:r,description:o,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,l=a==="user",m=l&&r!=="id-jag",h=e.readiness??(l?Np(e.connection):{connected:!0,status:"active"}),y=m?e.readiness?.connectUrl??(e.returnTo!==void 0?await Ha({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,f=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:o,transportHost:AE(i),scopesRequested:cy(f)?f:void 0,serverIcons:PE(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:y,setupMessage:e.setupMessage,updatedAt:l&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}n(xE,"buildSetupRequirement");function dy(e){let t=_e().byOperationId.get(e);if(!t)throw M("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(dy,"requireRoute");async function bc(e){let t=dy(e.transaction.operationId),r=Mr(e.transaction.principal.subjectId),o=t.connection;if(o===void 0)return[];let i=o.ownerMode==="user"?(await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:o.upstreamServerId,authProfileId:o.authProfileId}]))[0]:void 0,a=await ay({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,l=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await xE({connection:i,registeredConnection:o,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:l,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}n(bc,"requirementsForSetup");async function vc(e){let t=dy(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ne(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:o?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}n(vc,"consentContext");function Cc(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Cc,"hasUnresolvedUserUpstream");var OE=["mcp_user"],UE="dev-browser-user",ME=["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(" "),qE=p.object({response_type:p.literal("code"),client_id:p.string().min(1),redirect_uri:p.string().min(1),resource:p.url(),code_challenge:p.string().min(43),code_challenge_method:sp,state:p.string().min(1).optional(),scope:p.literal(ue).default(ue)}),zE=p.enum(["continue","approve","cancel"]).default("continue"),NE=p.object({state:p.string().min(1),decision:zE}),Mt=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;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}};function uy(e){return typeof e=="string"&&e.length>0?e:void 0}n(uy,"readQueryString");function jE(e,t){let r=uy(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new v("invalid_target",ME)}let o=Tp(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new v("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(jE,"requireAuthorizeResource");async function DE(e,t){let r={};t!==void 0&&(r.context=t);let o=await Zr(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let s=qg(e);return{principal:s,setCookie:await ko({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(DE,"resolveBrowserPrincipal");async function $E(e,t){let r={};t!==void 0&&(r.context=t);let o=await Zr(e,r);if(!o.principal)throw M("authentication_required","Authorization setup requires a current browser session.");return o.principal}n($E,"requireSetupPrincipal");function ly(e){return`${me().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(ly,"buildSetupReturnTo");async function py(e){let t=await bc({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:ly(e.csrfToken)}),r=await vc({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:_c({state:e.csrfToken,operationId:e.transaction.operationId,gateway:me(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(o.setCookies=e.setCookies),o}n(py,"renderSetup");function LE(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}}n(LE,"toAuthorizationTransactionClient");async function Ic(e,t={}){let r=qE.parse({...e.query,resource:jE(e,t.operationId),state:uy(e.query.state)}),o=Xr(r.scope);Yr(r.redirect_uri,"invalid_request");let s=new Date,i=it.parse(r.client_id),a=await ai(r.client_id,s);Bg(a,r.redirect_uri);try{let c=tr(e.url,r.resource,e.headers),d=LE(a);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&X(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type}});let l={clientId:a?.clientId??i,...d===void 0?{}:{client:d},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:h}=await DE(e,t.context),y=m===void 0?!1:await yc({operationId:c.operationId,principal:m});if(!m||y){let R=await Ig({transaction:l,requestUrl:e.url,requestHeaders:e.headers,now:s});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,operationId:c.operationId,reason:m?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:R.browserLoginUrl,setCookies:[...h===void 0?[]:[h],R.browserBindingCookie]}}let f=await Eg({transaction:l,principal:m,now:s});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&X(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),py({transaction:f.transaction,csrfToken:f.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:h===void 0?void 0:[h]})}catch(c){throw HE({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Ic,"authorizeDownstreamClient");function HE(e){if(e.cause instanceof Mt)return e.cause;let t=BE(e.cause);return t?new Mt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(HE,"toDownstreamAuthorizeRedirectError");function BE(e){if(e instanceof v)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof p.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(BE,"mapToOAuthRedirectError");async function my(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let l=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...l===void 0?{}:{idpErrorDescription:l},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),M("provider_access_denied",l??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),M("oauth_state_invalid","Browser login callback is missing state.");let s=await dc(o),i=await Gs({purpose:"login",claim:s.binding,request:e});if(!i.matched&&At())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"),M("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 l=JE(i.payload),m=await gc(a);return{kind:"redirect",location:new URL(l,ne(e.url,e.headers)),setCookies:[await ko({principal:m.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await gc(a),d=await kg({browserLoginStateToken:o,principal:c.principal});if(await Gg({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await yc({operationId:d.transaction.operationId,principal:c.principal}))throw M("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return py({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await ko({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}n(my,"completeBrowserLoginCallback");function JE(e){let t=ro(e),r=me().actionPath("/auth/connections/"),o=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||o===void 0||!o.startsWith(r)||!/^[^/]+\/connect$/u.test(o.slice(r.length)))throw M("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}n(JE,"readConnectReturnTo");async function hy(e){let t=await Tg(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}n(hy,"startConnectBrowserLogin");async function fy(e){let t=ve(),r=new URL(e.url);if(!qe(r))throw M("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw M("oauth_state_invalid","Local browser login is missing state.");let s=me().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ne(e.url)),a=new URL(ne(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw M("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",o);let c={subjectId:to.parse(UE),roles:OE};return{kind:"redirect",location:i,setCookies:[await ko({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}n(fy,"completeLocalDevBrowserLogin");function FE(e){let t=e.method==="POST"?e.body:e.query;return NE.parse(t)}n(FE,"readSetupContinueRequest");async function gy(e){let{state:t,decision:r}=FE({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,s=await pc({csrfToken:t,now:o}),i=await $E(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await xg({csrfToken:t,currentBrowserPrincipal:i,now:o})};let a=await Ag({csrfToken:t,currentBrowserPrincipal:i,now:o}),c=await bc({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:ly(t)});if(r==="approve"&&Cc(c)&&await vg({csrfToken:t,currentBrowserPrincipal:i,now:o}),Cc(c)){let d=await vc({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:_c({state:t,operationId:a.operationId,gateway:me(),upstreams:c,...d})}}return{kind:"redirect",location:await Pg({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(gy,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as ok,decodeJwt as sk,errors as Po,jwtVerify as ik}from"jose";import{createRemoteJWKSet as GE,decodeJwt as VE,decodeProtectedHeader as KE,errors as Ao,jwtVerify as WE}from"jose";var Ry=30,se=p.string().min(1),ZE=p.union([se,p.array(se).min(1)]),YE=p.union([se,p.array(se).min(1)]),XE=p.object({type:se,locations:p.array(se).optional(),actions:p.array(se).optional(),datatypes:p.array(se).optional(),identifier:se.optional(),privileges:p.array(se).optional()}).passthrough(),QE=p.object({iss:p.url(),sub:se,aud:ZE,client_id:se,resource:YE.optional(),scope:se.optional(),authorization_details:p.array(XE).optional(),jti:se,iat:p.number().int(),nbf:p.number().int().optional(),exp:p.number().int(),tenant:se.optional(),aud_tenant:se.optional(),aud_sub:se.optional(),sub_id:se.optional(),act:p.unknown().optional(),email:se.optional(),auth_time:p.number().int().optional(),acr:se.optional(),amr:p.array(se).optional(),cnf:p.unknown().optional()}).passthrough();function je(e){throw new v("invalid_grant",e)}n(je,"throwInvalidGrant");function ek(e){return e instanceof Ao.JWTExpired?"expired":e instanceof Ao.JWTClaimValidationFailed?"claim":e instanceof Ao.JWSSignatureVerificationFailed?"signature":e instanceof Ao.JWKSNoMatchingKey?"jwks_no_match":e instanceof Ao.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(ek,"readJwtFailureKind");function tk(e){return Array.isArray(e.aud)?(e.aud.length!==1&&je("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(tk,"readSingleAudience");function yy(e){try{let t=QE.parse(e);return tk(t),t}catch(t){if(t instanceof v)throw t;je("ID-JAG claims are invalid.")}}n(yy,"parseIdJagClaims");function rk(e,t){e.idJag.enabled||je("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&je("ID-JAG issuer is not trusted."),r}n(rk,"readTrustedIssuer");function nk(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(o=>r.has(o.type))}n(nk,"readGrantedAuthorizationDetails");function Sy(e){if(e.clientAuth.method==="none")throw new v("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&je("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&je("ID-JAG client_id is not allowed for this issuer.")}n(Sy,"assertClientBinding");function _y(e){e.cnf!==void 0&&je("ID-JAG cnf-bound assertions require DPoP support.")}n(_y,"assertProofOfPossessionNotDeferred");function wy(e){let t=Math.floor(e.now.getTime()/1e3)+Ry;e.claims.iat>t&&je("ID-JAG iat must not be in the future.")}n(wy,"assertIssuedAtNotInFuture");async function by(e){let t;try{t=KE(e.assertion)}catch{je("ID-JAG assertion is malformed.")}t.typ!==Oi&&je('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=yy(VE(e.assertion))}catch(c){if(c instanceof v)throw c;je("ID-JAG assertion is malformed.")}let o=qr(e.requestUrl,e.requestHeaders),s=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&s.push(e.requestedResource);let i=rk(e.config,r.iss);s.includes(r.iss)&&je("ID-JAG issuer must be different from the gateway."),Sy({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),_y(r),wy({claims:r,now:e.now});let a;try{let c=GE(new URL(i.jwksUrl)),{payload:d}=await WE(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:Ry,typ:Oi});a=yy(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:ek(c)},"OAuth ID-JAG assertion verification failed"),je("ID-JAG assertion verification failed.")}return Sy({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),_y(a),wy({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:Ep({issuer:a.iss,subject:a.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:nk({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(by,"verifyIdJagAssertion");var ak=new Set(["authorization_code","refresh_token",vt]),ck=1e4,dk=32*1024,uk=2,lk=3600,Tc=p.object({client_id:p.string().min(1).optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),pk=p.discriminatedUnion("grant_type",[Tc.extend({grant_type:p.literal("authorization_code"),code:p.string().min(1),redirect_uri:p.string().min(1),code_verifier:kr,resource:p.url().optional(),scope:p.literal(ue).optional()}),Tc.extend({grant_type:p.literal("refresh_token"),refresh_token:p.string().min(1),resource:p.url().optional(),scope:p.literal(ue).optional()}),Tc.extend({grant_type:p.literal(vt),assertion:p.string().min(1),resource:p.url().optional(),scope:p.literal(ue).optional(),authorization_details:p.string().min(1).optional()})]);function mk(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!ak.has(t)))throw new v("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(mk,"assertSupportedGrantType");var hk=p.object({token:p.string().min(1),client_id:p.string().min(1).optional(),token_type_hint:p.string().optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),fk=p.object({keys:p.array(p.record(p.string(),p.unknown())).min(1)}).passthrough();function Cy(){return ve().gateway.accessTokenTtlSeconds}n(Cy,"readAccessTokenTtlSeconds");function gk(){return ve().gateway.refreshTokenTtlSeconds}n(gk,"readRefreshTokenTtlSeconds");function vy(e,t){let r=Cy(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,o);return{expiresAt:J(st(e,s)),expiresIn:s}}n(vy,"calculateAccessTokenExpiresAt");function yk(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 v("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new v("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new v("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}n(yk,"readIdJagResource");function Sk(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 v("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}n(Sk,"readIdJagGrantedAuthorizationDetails");function _k(e){if(e.claimScope?.split(/\s+/).includes(ue)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return ue;if(e.claimScope===void 0)throw new v("invalid_grant",`ID-JAG must include ${ue} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(ue))throw new v("invalid_grant",`ID-JAG scope must include ${ue}.`);return ue}n(_k,"readIdJagGrantedScope");function wk(e){if(e!==void 0&&e.get("dpop")!==null)throw new v("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}n(wk,"assertNoDpopProofForIdJag");function Iy(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new v("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new v("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new v("invalid_client","Malformed HTTP Basic client authentication.")}}n(Iy,"readBasicClientSecret");function Ty(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new v("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=sk(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new v("invalid_client","Malformed private_key_jwt client assertion.")}throw new v("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new v("invalid_client","Client authentication or client_id is required.")}n(Ty,"resolveAuthenticatedClientId");function Rk(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new v("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"}:{}}n(Rk,"resolveClientSecretInput");function bk(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(bk,"hasClientAssertion");function vk(e){if(e.requestUrl===void 0)throw new v("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(me().actionPath(e.pathname),ne(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(vk,"buildEndpointAudience");function Ck(e){return e instanceof Po.JWTExpired?"expired":e instanceof Po.JWTClaimValidationFailed?"claim":e instanceof Po.JWSSignatureVerificationFailed?"signature":e instanceof Po.JWKSNoMatchingKey?"jwks_no_match":e instanceof Po.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}n(Ck,"readJwtFailureKind");async function Ik(e){let{response:t,json:r}=await Fh(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:uk,maxResponseBytes:dk,timeoutMs:ck});if(!t.ok)throw new v("invalid_client","Client JWKS could not be fetched.");return fk.parse(r)}n(Ik,"fetchClientJwks");async function Tk(e){if(e.clientAssertionType!==ys||e.clientAssertion===void 0)throw new v("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=it.parse(e.clientId),r=await ai(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new v("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new v("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=vk({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await Ik({jwksUri:o,context:e.context}),{payload:a}=await ik(e.clientAssertion,ok(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+lk;if(typeof a.exp!="number"||a.exp>c)throw new v("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Ck(i)},"OAuth private_key_jwt client authentication failed"),new v("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(Tk,"verifyPrivateKeyJwtClientAssertion");async function Ek(e){let t=it.parse(e.clientId);if(Up(t))throw new v("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 oe(e.clientSecret)}}n(Ek,"buildRuntimeHttpClientAuth");async function Ey(e){if(bk({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new v("invalid_request","Use only one client authentication method per request.");return Tk(e)}let t=Rk({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Ek({clientId:e.clientId,...t})}n(Ey,"resolveRuntimeHttpClientAuth");async function ky(e){mk(e.body);let t=pk.parse(e.body),r=Iy(e.authorizationHeader),o=Ty({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await Ey({clientId:o,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 kk({parsed:t,clientId:o,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(ky,"exchangeDownstreamToken");async function kk(e){if(e.parsed.grant_type==="authorization_code"){Yr(e.parsed.redirect_uri,"invalid_request"),Xr(e.parsed.scope),e.parsed.resource!==void 0&&tr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=at(),d=at(),l=J(st(e.now,gk())),m=vy(e.now,l),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await oe(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await vs(e.parsed.code_verifier),currentRefreshTokenHash:await oe(c),accessTokenHash:await oe(d),grantExpiresAt:l,accessTokenExpiresAt:m.expiresAt,now:J(e.now)});if(h.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new v("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:m.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===vt){Xr(e.parsed.scope),wk(e.requestHeaders);let c=await by({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:ve()}),d=yk({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),l=tr(e.requestUrl??d,d,e.requestHeaders),m=Sk({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=_k({claimScope:c.claims.scope,grantedAuthorizationDetails:m}),y=at(),f=J(new Date(c.claims.exp*1e3)),R=vy(e.now,f),S=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await oe(y),subjectId:c.subjectId,resource:d,operationId:l.operationId,scope:h,authorizationDetails:m,accessTokenExpiresAt:R.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:f}});if(S.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(S.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:y,token_type:"Bearer",expires_in:R.expiresIn,scope:S.grant.scope,resource:S.grant.resource,...m===void 0?{}:{authorization_details:m}}}Xr(e.parsed.scope),e.parsed.resource!==void 0&&tr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await oe(e.parsed.refresh_token),r=e.parsed.refresh_token,o=at(),s=J(st(e.now,Cy())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await oe(o),resource:e.parsed.resource,accessTokenExpiresAt:s,now:J(e.now)});if(i.kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new v("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new v("invalid_grant","Refresh token is invalid, expired, or revoked.");tr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:o,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}}n(kk,"exchangeDownstreamTokenWithRuntimeHttp");async function Ay(e){let t=hk.parse(e.body),r=Iy(e.authorizationHeader),o=Ty({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await Ey({clientId:o,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 oe(t.token),now:J(s)})).kind==="invalid_client")throw new v("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&X(e.context,{eventType:F.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Ay,"revokeDownstreamToken");var Ak=64*1024,Pk=16*1024,xk="text/html; charset=utf-8";function Ok(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Ok,"formDataToObject");async function Uk(e){return lg(e,{maxBytes:Ak,label:"Request body"})}n(Uk,"readJsonBody");async function kc(e){return Ok(await pg(e,{maxBytes:Pk,label:"Request body"}))}n(kc,"readFormBody");async function Py(e,t,r){let o=ot(r),s=r instanceof p.ZodError?qt(r):void 0,i={code:o??(r instanceof p.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),ms(e,t,i)}n(Py,"handleProblem");function xy(e){return e?.requestId}n(xy,"readBrowserRequestId");function Oy(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[Pr];return typeof t=="string"?t:void 0}n(Oy,"readUpstreamHtmlError");function Qr(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Qr,"readRuntimeErrorExtensionString");function Mk(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(Mk,"readRuntimeErrorExtensionNumber");function qk(e){try{return new URL(e.url).pathname}catch{return}}n(qk,"readBrowserRequestPath");function rr(e){let t={code:e.code,requestId:e.requestId,routePath:qk(e.request),underlyingError:e.underlyingError};return e.error instanceof T&&(t.httpStatus=Mk(e.error,rt),t.contentType=Qr(e.error,Ar),t.upstreamUrl=Qr(e.error,nt),t.upstreamServerId=Qr(e.error,ls),t.metadataUrl=Qr(e.error,xr),t.providerError=Qr(e.error,Or),t.providerErrorDescription=Qr(e.error,Ur)),t}n(rr,"buildBrowserErrorDiagnostic");function xo(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})}n(xo,"oauthErrorResponse");function zk(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(zk,"readOAuthProtocolHeaders");function Nk(e,t){let r=We("internal_server_error");return xo({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:zk(e,t)})}n(Nk,"oauthProtocolErrorResponse");function Ec(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Ec,"readZodOAuthErrorCode");function jk(e){let t={error:Ec(e)},r=qt(e);return r!==void 0&&(t.errorDescription=r),xo(t)}n(jk,"oauthZodErrorResponse");function Dk(e){let t=ot(e);if(t===void 0)return;let r=We(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:Lk(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,xo(o)}n(Dk,"oauthGatewayProblemResponse");function $k(){let t={error:"server_error",status:500,errorDescription:We("internal_server_error").publicDetail};return xo(t)}n($k,"oauthFallbackErrorResponse");function Lk(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(Lk,"readOAuthStatus");function Ac(e,t={}){return e instanceof Mt?qy(e):e instanceof v?Nk(e,t):e instanceof p.ZodError?jk(e):Dk(e)??$k()}n(Ac,"oauthProblemResponse");function Pc(e,t,r){let o=Ut(e.url),s=xy(t);if(r instanceof Mt)return qy(r);if(r instanceof v){let c=We("internal_server_error");return Fe({host:o,kind:Hk(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 p.ZodError)return Fe({host:o,kind:"invalid_request",detail:qt(r)??"The authorization request was invalid.",developerDetail:qt(r)??"The authorization request was invalid.",code:Ec(r),diagnostic:rr({request:e,requestId:s,code:Ec(r),underlyingError:qt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=ot(r);if(i!==void 0){let c=We(i);return Fe({host:o,kind:My(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:Oy(r),status:c.status})}let a=We("internal_server_error");return Fe({host:o,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})}n(Pc,"browserOAuthProblemResponse");function Uy(e,t,r){let o=Ut(e.url),s=xy(t),i=ot(r);if(i!==void 0){let c=We(i);return Fe({host:o,kind:My(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:Oy(r),status:c.status})}if(r instanceof p.ZodError)return Fe({host:o,kind:"invalid_request",detail:qt(r)??"The authorization request was invalid.",developerDetail:qt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:rr({request:e,requestId:s,code:"invalid_request",underlyingError:qt(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=We("internal_server_error");return Fe({host:o,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})}n(Uy,"browserGatewayProblemResponse");function Hk(e){return e==="server_error"?"internal_error":"invalid_request"}n(Hk,"readOAuthBrowserErrorKind");function My(e){if(We(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(My,"readGatewayBrowserErrorKind");function ft(e,t,r){let o={event:t},s=!1;if(r instanceof v)o.oauthError=r.errorCode,o.status=r.status,Ce(o,"error",r);else if(r instanceof Mt)o.oauthError=r.errorCode,Ce(o,"error",r);else if(r instanceof p.ZodError){o.code="invalid_request",Ce(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=ot(r);if(i!==void 0){let a=We(i);o.code=i,o.status=a.status,a.oauthError!==void 0&&(o.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",Ce(o,"error",r)}else s=!0,Ce(o,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,i.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(ft,"logUnexpectedOAuthHandlerError");function qy(e){let t;try{t=new URL(e.redirectUri)}catch{return xo({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);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(qy,"downstreamAuthorizeRedirectErrorResponse");function qt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(qt,"formatZodErrorDetail");function Bk(e,t){let r={event:"browser_login_callback_failed",code:ot(t)??"invalid_request"};Ce(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Bk,"logBrowserLoginCallbackFailure");function zy(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})}n(zy,"redirectResultResponse");function ci(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":xk,"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 zy(e)}n(ci,"authorizeResultResponse");async function Ny(e,t){try{return Response.json(vp(e.url,e.headers))}catch(r){return ft(t,"oauth_authorization_server_metadata_failed",r),Py(e,t,r)}}n(Ny,"authorizationServerMetadataHandler");async function jy(e,t){try{let r=Ni(e.params.routePath);return Response.json(Cp({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return ft(t,"oauth_authorization_server_metadata_failed",r),Py(e,t,r)}}n(jy,"scopedAuthorizationServerMetadataHandler");async function Dy(e,t){try{let r=await Jg(await Uk(e)),o=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:o,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),X(t,{eventType:F.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:o,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return ft(t,"oauth_register_failed",r),Ac(r)}}n(Dy,"registerHandler");async function $y(e,t){try{return ci(await Ic(e,{context:t}))}catch(r){return ft(t,"oauth_authorize_failed",r),Pc(e,t,r)}}n($y,"authorizeHandler");async function Ly(e,t){try{let r=Ni(e.params.routePath);return ci(await Ic(e,{operationId:r.operationId,context:t}))}catch(r){return ft(t,"oauth_authorize_scoped_failed",r),Pc(e,t,r)}}n(Ly,"scopedAuthorizeHandler");async function Hy(e,t){try{let r=await my(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),ci(r)}catch(r){return Bk(t,r),Uy(e,t,r)}}n(Hy,"callbackHandler");async function By(e,t){try{return zy(await fy(e))}catch(r){return ft(t,"oauth_dev_login_failed",r),Pc(e,t,r)}}n(By,"devLoginHandler");async function Jy(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await gy({request:e,body:e.method==="POST"?await kc(e):void 0,context:t});return ci(r)}catch(r){return ft(t,"oauth_setup_failed",r),Uy(e,t,r)}}n(Jy,"setupHandler");async function Fy(e,t){try{return Response.json(await ky({body:await kc(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 ft(t,"oauth_token_failed",r),Ac(r)}}n(Fy,"tokenHandler");async function Gy(e,t){try{return await Ay({body:await kc(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 ft(t,"oauth_revoke_failed",r),Ac(r)}}n(Gy,"revokeHandler");var Vy="0.0.0",Jk=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function Oo(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}n(Oo,"firstNonBlank");function Uo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}n(Uo,"clampToCodePoints");function Fk(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")}n(Fk,"shortHash");function Ky(e,t){let r=[...e];if(r.length<=t)return e;let o=`-${Fk(e)}`;return t<=o.length?r.slice(0,t).join(""):`${r.slice(0,t-o.length).join("")}${o}`}n(Ky,"clampNameSegment");function Gk(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}n(Gk,"sanitizeRegistryNameSegment");var Vk=/^\d{1,3}(\.\d{1,3}){3}$/u;function Kk(e){let t=new URL(e).hostname.toLowerCase();if(Vk.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(o=>o.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(o=>o.length>0);return r.length>0?r.join("."):"local"}n(Kk,"buildRegistryNamespaceFromOrigin");function Wk(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}n(Wk,"sanitizeWebsiteUrl");function Zk(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let o;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;o=i.toString()}catch{continue}if(o.length>255||r.mimeType!==void 0&&!Jk.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:o,...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}n(Zk,"sanitizeIcons");function Yk(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}n(Yk,"localNameFromRoutePath");function Wy(e){return e.includes("{")||e.includes(":")}n(Wy,"isParameterizedRoutePath");var Xk=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Zy(e){let t=Oo(e)??Vy;return Xk.test(t)?Vy:Uo(t,255)}n(Zy,"sanitizeRegistryVersion");function Yy(e){let t=Ky(Kk(e.origin),150),r=200-t.length-1,o=new Set,s=[];function i(c){let d=Ky(Gk(c),r),l=d;for(let m=2;o.has(l);m++){let h=`-${m}`;l=`${[...d].slice(0,r-h.length).join("")}${h}`}return o.add(l),l}n(i,"claimLocalName");function a(c,d){let l=`${t}/${i(c)}`;s.push({name:l,response:{server:{...d,name:l},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}n(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(Wy(c.routePath))continue;let d=c.connection,l=d?.serverInfo,m=Uo(Oo(d?.description,l?.description,d?.displayName,c.operationId)??c.operationId,100),h=Oo(l?.title,d?.displayName),y=Wk(l?.websiteUrl),f=Zk(l?.icons);a(c.operationId,{description:m,...h===void 0?{}:{title:Uo(h,100)},version:Zy(l?.version),...y===void 0?{}:{websiteUrl:y},...f===void 0?{}:{icons:f},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(Wy(c.routePath))continue;let d=c.operationId??Yk(c.routePath),l=Uo(Oo(c.summary,c.description,c.serverName,c.operationId,d)??d,100),m=Oo(c.serverName);a(d,{description:l,...m===void 0?{}:{title:Uo(m,100)},version:Zy(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}n(Yy,"buildMcpRegistryDirectory");var Qk=30,Xy=100;function Ye(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}n(Ye,"registryErrorResponse");function Oc(e){return Yy({registry:_e(),origin:ne(e.url,e.headers)})}n(Oc,"readEntries");function xc(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}n(xc,"decodePathParam");function Qy(e,t){return e.find(r=>r.name===t)}n(Qy,"findEntryByName");function eA(e){let t=e.get("limit");return t===null?{ok:!0,value:Qk}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Xy)}}n(eA,"parseLimit");function tA(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}}n(tA,"parseCursor");var rA=/^(\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 nA(e){let t=rA.exec(e);if(!t)return!1;let[,r,o,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(o)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(o)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}n(nA,"isValidRfc3339Timestamp");async function eS(e,t){let r=new URL(e.url).searchParams,o=eA(r);if(!o.ok)return Ye(400,`Invalid 'limit' parameter: expected a positive integer (max ${Xy}).`);let s=tA(r);if(!s.ok)return Ye(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&&!nA(i))return Ye(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=Oc(e).sort((h,y)=>h.name<y.name?-1:h.name>y.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 l=d.slice(s.value,s.value+o.value),m=s.value+o.value;return Response.json({servers:l.map(h=>h.response),metadata:{count:l.length,...m<d.length?{nextCursor:String(m)}:{}}})}n(eS,"listMcpRegistryServersHandler");async function tS(e,t){let r=xc(e.params.serverName);if(!r.ok)return Ye(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=Qy(Oc(e),r.value);return o===void 0?Ye(404,"Server not found"):Response.json({servers:[o.response],metadata:{count:1}})}n(tS,"listMcpRegistryServerVersionsHandler");async function rS(e,t){let r=xc(e.params.serverName);if(!r.ok)return Ye(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=xc(e.params.version);if(!o.ok)return Ye(400,"Invalid version: malformed encoding.");let s=Qy(Oc(e),r.value);return s===void 0?Ye(404,"Server not found"):o.value!=="latest"&&o.value!==s.response.server.version?Ye(404,"Server or version not found"):Response.json(s.response)}n(rS,"getMcpRegistryServerVersionHandler");function di(e,t){return(r,o)=>Ye(e,t)}n(di,"createWriteNotSupportedHandler");async function nS(e,t){return Ye(404,"Not found")}n(nS,"mcpRegistryNotFoundHandler");var oS=di(501,"Publishing is not supported by this registry"),sS=di(501,"Updates are not supported by this registry"),iS=di(501,"Deletion is not supported by this registry"),Uc=di(403,"You do not have publish or edit permissions for this server");function aS(e){return V`<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>`}n(aS,"renderBrowserResult");var oA="text/html; charset=utf-8";function sA(e){return Vr({title:e.title,iconHref:za(e.host),styles:Gr,headerIcon:ni("success"),heading:e.title,subhead:V`<p class="card__subtitle">${e.detail}</p>`,body:aS({steps:Jr(e.steps.map(t=>V`<li>${t}</li>`))}),footer:""})}n(sA,"browserResultHtml");function iA(e,t=200){return new Response(Fr(e),{status:t,headers:{"content-type":oA,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(iA,"browserResultResponse");function cS(e){return iA(sA(e))}n(cS,"browserConnectionSuccessResponse");function ui(e,t,r={}){let o=ap(t);return Fe({host:e,kind:aA(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(ui,"browserConnectionFailureResponse");function aA(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"}}n(aA,"readCallbackFailureBrowserErrorKind");var cA={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},dS=Symbol("upstream-request");function Mo(e,t){Object.defineProperty(e,dS,{configurable:!0,value:t})}n(Mo,"setUpstreamRequestContext");function dA(e){let t=e[dS];if(!t)throw new be("Upstream request context has not been set");return t}n(dA,"readUpstreamRequestContext");function uA(e,t){return t.some(r=>r===e)}n(uA,"requestContextMatchesKind");function lA(e){return typeof e=="string"?[e]:e}n(lA,"toExpectedKinds");function qo(e,t){let r=dA(e),o=lA(t);if(!uA(r.kind,o)){let s=cA[o[0]];throw new be(`${s} request context has not been set`)}return r}n(qo,"requireUpstreamRequestContext");function zt(e){if(typeof e=="string"&&e.length!==0)return e}n(zt,"readOptionalQueryString");function pA(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new be(`Validated path parameter ${t} is missing`);return mA(r,t)}n(pA,"requirePathString");function mA(e,t){try{return decodeURIComponent(e)}catch(r){throw new T({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[E]:"invalid_request"}},{cause:r})}}n(mA,"decodePathString");function hA(e){let t=zt(e);return t?hs.parse(t):void 0}n(hA,"readOptionalOperationId");function fA(e){let t=_e().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new T({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[E]:"unknown_upstream_server"}})}n(fA,"readRegisteredAuthProfileId");function gA(e){let t=hA(e);if(!t)throw new T({message:"operationId query parameter is required.",extensionMembers:{[E]:"invalid_request"}});return t}n(gA,"readRequiredOperationId");async function Mc(e){return e.redirect?Fe({host:Ut(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?He.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):He.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}n(Mc,"browserConnectRefusal");function yA(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let o of t)r.append("set-cookie",o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}n(yA,"withSetCookies");async function SA(e){let{request:t,context:r,ticket:o,redirect:s}=e;if(np(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await Mc({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 Zr(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return yA(await Mc({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),l=ro(`${d.pathname}${d.search}`);if(l===void 0)throw new be("Connect request path is empty");let m=await hy({returnTo:l,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:m.location.toString(),"cache-control":"no-store"});for(let y of[...a,m.setCookie])h.append("set-cookie",y);return new Response(null,{status:302,headers:h})}let c=o.ownerMode==="user"?o.ownerSubjectId:o.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:o.upstreamServerId,operationId:o.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await Mc({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."})}n(SA,"requireTicketOwnerBrowser");async function _A(e,t,r){let o=ti(r,gA(e.query.operationId));if(o.authMode==="id-jag")throw new T({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[E]:"invalid_request"}});let s=e.query.redirect==="true",i=zt(e.query.browserTicket);if(e.user){if(i)throw new T({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[E]:"invalid_request"}});let d=Yt(e.user,e.url),l={kind:"connect",...Br(o,d.subjectId),redirect:s},m=ro(zt(e.query.returnTo));return m!==void 0&&(l.returnTo=m),l}if(!i)throw new T({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[E]:"authentication_required"}});let a=await af(i);if(a.ownerMode!==o.ownerMode||a.upstreamServerId!==o.upstreamServerId||a.authProfileId!==o.authProfileId||a.operationId!==o.operationId)throw new T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});if(At()){let d=await SA({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await cf(a);let c=fs(a);switch(o.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});let d={kind:"connect",...o,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 T({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[E]:"oauth_callback_mismatch"}});let d={kind:"connect",...o,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}n(_A,"resolveConnectContext");async function wA(e,t,r){let o=dp.parse(pA(e,"connection"));switch(r){case"connect":{let s=await _A(e,t,o);if(s instanceof Response)return s;Mo(e,s);return}case"callback":{let s=zt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:o,error:s},d=zt(e.query.error_description);d!==void 0&&(c.errorDescription=d),Mo(e,c);return}let i=zt(e.query.code),a=zt(e.query.state);if(i&&a){let c=zt(e.query.iss);Mo(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:a,...c===void 0?{}:{iss:c}});return}Mo(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Mo(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:fA(o)});return}}n(wA,"resolveUpstreamRequestInbound");async function RA(e,t,r){try{return await wA(e,t,r)}catch(o){let s=o instanceof T?o.extensionMembers?.[E]:void 0,i=o instanceof Error?o.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return He.badRequest(e,t,{code:s,detail:i});case"authentication_required":return He.unauthorized(e,t,{code:s,detail:i});default:throw o}}}n(RA,"applyUpstreamRequestContext");function li(e,t){return n(async(o,s)=>{let i=await RA(o,s,e);return i||t(o,s)},"wrapped")}n(li,"withUpstreamRequestContext");var bA=["callback_authorization_code","callback_provider_error","callback_invalid"];function qc(e){try{return new URL(e.url).pathname}catch{return}}n(qc,"readBrowserRequestPath");function vA(e){return"cause"in e?e.cause:void 0}n(vA,"readErrorCause");function CA(e){return e.stack?.split(`
44
- `).slice(1,4).map(t=>t.trim()).join(" | ")}n(CA,"readFirstStackFrame");function uS(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=CA(r))}n(uS,"addErrorAttributes");function zc(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[E];return ps(t)?t:void 0}n(zc,"readRuntimeGatewayCode");function zo(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(zo,"readRuntimeErrorExtensionString");function IA(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(IA,"readRuntimeErrorExtensionNumber");function TA(e,t,r,o){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"),X(t,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),ui(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:qc(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"),ui(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:qc(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n(TA,"requireAuthorizationCallbackRequest");function EA(e,t){X(e,{eventType:F.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(EA,"emitCallbackReceivedAnalyticsEvent");function kA(e,t){X(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(kA,"emitTokenExchangeSucceededAnalyticsEvent");function AA(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return cS({host:Ut(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."]})}n(AA,"buildSuccessfulCallbackResponse");function PA(e){let t={detail:e instanceof Error?e.message:void 0};return uS(t,"error",e),e instanceof Error&&uS(t,"cause",vA(e)),t}n(PA,"buildTokenExchangeFailureAttributes");function xA(e){X(e.context,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:zc(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:PA(e.error)})}n(xA,"emitTokenExchangeFailedAnalyticsEvent");function OA(e){let t=e.error,r=zc(t),o=ip(r)?r:"upstream_token_exchange_failed",s={code:o,requestId:e.context.requestId,routePath:qc(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof T?{httpStatus:IA(t,rt),contentType:zo(t,Ar),upstreamUrl:zo(t,nt),metadataUrl:zo(t,xr),providerError:zo(t,Or),providerErrorDescription:zo(t,Ur)}:{}};return ui(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:UA(t)})}n(OA,"tokenExchangeFailureResponse");function lS(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})}n(lS,"withSetCookie");function UA(e){if(!(e instanceof T))return;let t=e.extensionMembers?.[Pr];return typeof t=="string"?t:void 0}n(UA,"readUpstreamHtmlError");async function Nc(e,t){let r=qo(e,bA),o=Ut(e.url),s=TA(e,t,r,o);if(s instanceof Response)return s;EA(t,s);let i;try{let a=await Zf({request:e,callbackRequest:s,onBrowserBinding:n(c=>{i=c},"onBrowserBinding")});return kA(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"),lS(AA(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:zc(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return Ce(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),xA({context:t,callbackRequest:s,error:a}),lS(OA({request:e,context:t,host:o,callbackRequest:s,error:a}),i)}}n(Nc,"callbackHandler");function MA(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(MA,"clientMetadataProblemDetail");async function pS(e,t){let r=qo(e,"connect"),o=r.redirect?await Io({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:Ws/1e3}):void 0,s=await Wf({request:e,connectRequest:r,...o===void 0?{}:{browserBinding:o.claim}});if(X(t,{eventType:F.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"),o!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":o.setCookie,"cache-control":"no-store"}});let i=await Ys({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})}n(pS,"connectHandler");async function mS(e,t){let r=qo(e,"client_metadata");try{let o=ne(e.url,e.headers),s=_f(o,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(o){if(!(o instanceof Y))throw o;let s=o instanceof Error?o.message:String(o);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"),He.notFound(e,t,{code:"not_found",detail:MA(o)})}}n(mS,"oauthClientMetadataHandler");function qA(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(qA,"resolveInternalRoutePath");var zA={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function NA(){return new Response(null,{status:204,headers:zA})}n(NA,"buildWellKnownPreflightResponse");function jA(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})}n(jA,"withWellKnownCorsHeaders");function nr(e){return async(t,r)=>t.method==="OPTIONS"?NA():jA(await e(t,r))}n(nr,"wrapWellKnownHandler");var hS=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:nr(Ny),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:nr(jy),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:nr(Ip),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Dy},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:$y},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Ly},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Hy},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:By},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Jy},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Fy},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Gy},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:li("client_metadata",mS)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:li("connect",pS)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:li("callback",Nc)}],DA=hS.filter(e=>!e.routeName.startsWith("upstream_")),$A=hS.filter(e=>e.routeName.startsWith("upstream_"));function LA(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:nr(eS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:nr(tS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:nr(rS),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:oS},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:sS},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:iS},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Uc},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Uc},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:nr(nS),corsPolicy:"anything-goes"}]}n(LA,"buildMcpRegistryInternalRoutes");function HA(e){let t=hp({routes:e.routes,policies:e.policies,gateway:e.gateway});return fp(t),t}n(HA,"initializeMcpGatewayConnectionRegistry");function BA(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(BA,"hasDownstreamOAuthRoutes");function JA(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(JA,"hasIdJagDownstreamOAuth");function FA(e){let t=new Map;for(let o of e.byOperationId.values())o.downstreamOAuth&&t.set(o.downstreamOAuth.policyName,o.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new be("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(o=>`"${o}"`).join(", ");throw new Y(`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.`)}n(FA,"readSingletonDownstreamOAuthConfig");function GA(e,t,r){let o=String(t.params.routePath??""),s=e.byRoutePath.get(wp(o));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?ms(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(GA,"readScopedDownstreamOAuthConfig");function VA(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(VA,"routeUsesScopedOAuthConfig");function jc(e,t,r){return async(o,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let d=await r(o,s);if(d instanceof Response)return d;d&&rp(s,d)}let i=o.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}n(jc,"wrapInternalHandler");function Dc(e,t,r,o){e.addPluginRoute({path:qA(t,r),methods:t.methods,handler:o,processors:[nd],corsPolicy:t.corsPolicy??"none"})}n(Dc,"addInternalRoute");function fS(e,t){let r=HA(t);if(r.gateway.registry.enabled){Qe("plugin.mcp-gateway.registry");for(let c of LA(r.gateway.registry))Dc(e,c,r.gateway,jc(c.routeName,c.handler))}let o=BA(r),s=r.connectionsById.size>0,i,a=n(()=>(i===void 0&&(i=FA(r)),i),"readSingletonOAuthConfig");if(o){Qe("plugin.mcp-gateway.downstream-oauth"),JA(r)&&Qe("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of DA){let d=VA(c)?(l,m)=>GA(r,l,m):a;Dc(e,c,r.gateway,jc(c.routeName,c.handler,d))}}if(s){Qe("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())Qe(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of $A)Dc(e,c,r.gateway,jc(c.routeName,c.handler,o?a:void 0))}}n(fS,"registerMcpGatewayInternalRoutes");var $c=class extends rd{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),Qe("plugin.mcp-gateway"),this.#e=op(t)}registerRoutes(t){let r=t.parsedRouteData;r&&fS(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var _S=new Set(["jsonrpc","method","id"]),wS=new Set(["name","uri"]),KA=9,WA=[..._S,...wS,"params"],ZA=44,YA=1024,XA=1e3,gS=new TextDecoder("utf-8",{fatal:!0}),Lc=class{constructor(t){this.bytes=t}bytes;static{n(this,"EnvelopeScanner")}pos=0;scan(){let t=this.bytes;t[0]===239&&t[1]===187&&t[2]===191&&(this.pos=3),this.skipWhitespace();let r;return t[this.pos]===123?r=this.readObject():t[this.pos]===91?r=this.readBatch():this.fail(),this.skipWhitespace(),this.expect(this.pos===t.length),r}readBatch(){let t=[];if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===93)return this.pos++,t;for(;;){if(this.skipWhitespace(),this.bytes[this.pos]===123){let o=this.readObject();(o.id!==void 0||o.method!==void 0)&&(this.expect(t.length<XA),t.push(o))}else this.skipValue();this.skipWhitespace();let r=this.bytes[this.pos++];if(r===93)return t;this.expect(r===44)}}fail(){throw new SyntaxError("Unscannable request body")}expect(t){t||this.fail()}skipWhitespace(){for(;;){let t=this.bytes[this.pos];if(t!==32&&t!==10&&t!==13&&t!==9)return;this.pos++}}skipString(){this.expect(this.bytes[this.pos]===34),this.pos++;let t=!1;for(;;){let r=this.bytes[this.pos++];if(r===34)return t;r===92?(t=!0,this.pos++):this.expect(r!==void 0)}}skipValue(){this.skipWhitespace();let t=this.bytes[this.pos];if(t===34){this.skipString();return}if(t!==void 0&&t!==123&&t!==91&&t!==125&&t!==93&&t!==44&&t!==58){for(;!yS(this.bytes[this.pos]);)this.pos++;return}let r=[];for(;;){this.skipWhitespace();let o=this.bytes[this.pos];if(this.expect(o!==void 0),o===34)this.skipString();else if(o===123||o===91){r.push(o),this.pos++;continue}else if(o===125||o===93)this.expect(r.pop()===(o===125?123:91)),this.pos++;else if(o===44||o===58){this.expect(r.length>0),this.pos++;continue}else for(;!yS(this.bytes[this.pos]);)this.pos++;if(r.length===0)return}}readKey(){let t=this.pos,r=this.skipString(),o=this.pos-t;if(r)return o>ZA?void 0:JSON.parse(gS.decode(this.bytes.subarray(t,this.pos)));if(o>KA)return;let s=o-2;for(let i of WA){if(i.length!==s)continue;let a=0;for(;a<s&&this.bytes[t+1+a]===i.charCodeAt(a);)a++;if(a===s)return i}}readObject(t=_S,r=!0){let o={};if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===125)return this.pos++,o;for(;;){this.skipWhitespace();let s=this.readKey();this.skipWhitespace(),this.expect(this.bytes[this.pos++]===58),this.skipWhitespace();let i=this.pos;if(r&&s==="params")if(delete o.params,this.bytes[i]===123){let c=this.readObject(wS,!1);Object.keys(c).length>0&&(o.params=c)}else this.skipValue();else if(this.skipValue(),s!==void 0&&t.has(s)){delete o[s];let c=this.readPrimitive(i);(typeof c=="string"||typeof c=="number"&&s==="id")&&(o[s]=c)}this.skipWhitespace();let a=this.bytes[this.pos++];if(a===125)return o;this.expect(a===44)}}readPrimitive(t){let r=this.bytes[t];if(!(r===34||r===45||r>=48&&r<=57)||this.pos-t>YA)return;let s=gS.decode(this.bytes.subarray(t,this.pos)),i=JSON.parse(s);return typeof i=="number"&&!tP(s,i)?void 0:i}};function yS(e){return e===void 0||e===44||e===125||e===93||e===32||e===10||e===13||e===9}n(yS,"isDelimiter");function QA(e){try{return new Lc(new Uint8Array(e)).scan()}catch{return{}}}n(QA,"sniffEnvelope");var eP=/^(-)?(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function SS(e){let t=eP.exec(e);if(!t)return;let[,r,o,s="",i]=t,a=`${o}${s}`.replace(/^0+/,""),c=Number(i??0)-s.length;if(a==="")return"0";let d=/0*$/.exec(a)?.[0].length??0;return a=a.slice(0,a.length-d),c+=d,`${r??""}${a}e${c}`}n(SS,"canonicalDecimal");function tP(e,t){if(!Number.isFinite(t))return!1;let r=SS(e),o=SS(JSON.stringify(t));return r!==void 0&&r===o}n(tP,"isLosslessNumberLiteral");function RS(e){if(!(e===void 0||e.byteLength===0)){if(e.byteLength>262144)return{value:QA(e)};try{return{value:JSON.parse(new TextDecoder().decode(e))}}catch{return}}}n(RS,"parseRequestJson");var rP="zuplo_mcp_",nP=["__host-","__secure-"];function oP(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let o of nP)r.startsWith(o)&&(r=r.slice(o.length));return r.startsWith(rP)}n(oP,"setsGatewayCookie");function bS(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!oP(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let o=new Headers(e.headers);o.delete("clear-site-data"),o.delete("set-cookie");for(let s of r)o.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:o})}n(bS,"stripUpstreamOriginStateHeaders");function gt(e){return e&&typeof e=="object"?e:void 0}n(gt,"readRecord");function No(e,t){let r=gt(e)?.[t];return typeof r=="string"?r:void 0}n(No,"readStringProperty");function CS(e,t){let r=gt(e)?.[t];return typeof r=="number"?r:void 0}n(CS,"readNumberProperty");function vS(e,t){return CS(e,"code")??(t>=400?t:void 0)}n(vS,"readErrorCode");function IS(e){return Array.isArray(e)?e.map(IS).find(t=>t?.method):gt(e)}n(IS,"readJsonRpcMessage");function Hc(e){let t=IS(e),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:No(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:No(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=No(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}n(Hc,"buildBaseCapabilityInput");function pi(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(pi,"isCapabilityListMethod");function sP(e,t,r){let i=gt(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(sP,"readItemCount");function TS(e){let t=Hc(e);return!t||pi(t.mcpMethod)?null:{eventType:F.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(TS,"buildCapabilityInvokedAnalyticsInput");function iP(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}}n(iP,"readMissingResponseFailure");function ES(e,t){let r=Hc(e);if(!r)return null;let o=gt(t.message),s=gt(o?.error),i=gt(s?.data),a=o?.result,c=r.mcpMethod==="tools/call"&&gt(a)?.isError===!0;if(gt(i?.connectRequired))return{eventType:F.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:CS(s,"code"),mcpErrorType:No(s,"message")};let d=t.status<400?iP(t):void 0;if(d&&!s)return{eventType:pi(r.mcpMethod)?F.MCP_CAPABILITY_LISTED:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,...d};if(pi(r.mcpMethod)){let l=t.status>=400?void 0:sP(r.mcpMethod,r.capabilityType,a),m=t.status<400&&!s&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:F.MCP_CAPABILITY_LISTED,outcome:t.status>=400||s?"failure":"success",...r,httpStatusCode:t.status,...m?{mcpStatus:"not_parsed"}:{},...t.status>=400||s?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:vS(s,t.status)}:{},...l===void 0?{}:{attributes:{itemCount:l}}}}return t.status>=400||s?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:vS(s,t.status),mcpErrorType:No(s,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:"success",...r,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:c?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:c,applicationError:c}}n(ES,"buildCapabilityFinalAnalyticsInput");function kS(e,t){let r=Hc(e);return r?{eventType:pi(r.mcpMethod)?F.MCP_CAPABILITY_LISTED:F.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}n(kS,"buildCapabilityThrownAnalyticsInput");var AS={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},PS={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var Fc=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),xS=64*1024,Gc=1024*1024,aP=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function OS(e){return e!==void 0&&aP.has(e)?Gc:xS}n(OS,"tapMaxBytesForMethod");function cP(e){let t=It(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}n(cP,"readTapMode");function dP(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(dP,"isPlainObject");function uP(e){return dP(e)&&!("method"in e)&&("result"in e||"error"in e)}n(uP,"isResponseShaped");function lP(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}n(lP,"isSameJsonRpcIdValue");function US(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(uP);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>lP(a.id,t));if(i||r)return i}return s[0]}n(US,"selectResponse");function MS(e){try{return JSON.parse(e)}catch{return}}n(MS,"tryParseJson");var Bc=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{n(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 o of this.#e)t.set(o,r),r+=o.byteLength;this.#e=[],this.#n=US(MS(new TextDecoder().decode(t)),this.requestId,!1)}},Jc=class{constructor(t,r){this.requestId=t;this.#e=new yo({maxEventChars:r,onOversize:"discard"})}requestId;static{n(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 o=t(r);this.#r||=r.discardedEvents>0;for(let s of o){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=US(MS(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},pP={push(){},end(){},message:void 0,truncated:!1};function mP(e,t,r){switch(e){case"json":return new Bc(t,r);case"sse":return new Jc(t,r);case"passthrough":return pP}}n(mP,"createObserver");function qS(e,t={}){let r=e.body;if(r===null){let I=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:I,outcome:I}}let o=Tt(e.headers)?"passthrough":cP(e),s=mP(o,t.requestId,t.maxBytes??xS),i,a=new Promise(I=>{i=I}),c,d=new Promise(I=>{c=I}),l=!1,m=n(()=>{l||s.message===void 0||(l=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,y=!1,f=n((I,O)=>{if(y)return;if(y=!0,I==="complete")try{s.end()}catch{}let N={ended:I,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...o==="passthrough"&&h>0?{uninspected:!0}:{},...O===void 0?{}:{error:O}};i(N),l||(l=!0,c(N))},"settle"),R=r.getReader(),S=new ReadableStream({async pull(I){let O;try{O=await R.read()}catch(N){f("errored",N),I.error(N);return}if(O.done){f("complete"),I.close();return}if(h+=O.value.byteLength,!y)try{s.push(O.value)}catch{}I.enqueue(O.value),m()},async cancel(I){f(I===Fc?"released":"cancelled"),await R.cancel(I)}},{highWaterMark:0}),w=Qm(new Headers(e.headers)),x;try{x=new Response(S,{status:e.status,statusText:e.statusText,headers:w})}catch(I){throw R.cancel(I).catch(()=>{}),I}return{response:x,done:a,outcome:d}}n(qS,"tapJsonRpcResponse");var hP=-32603,fP="The upstream MCP server ended the response stream without a response to this request.",gP="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function zS(e){return`${typeof e}:${String(e)}`}n(zS,"idKey");function yP(e,t){if(e.delete(zS(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}n(yP,"clearAnsweredRequest");function NS(e){let t=Array.isArray(e)?e:[e],r=[];for(let o of t){if(!jS(o)||typeof o.method!="string"||typeof o.id!="string"&&typeof o.id!="number")continue;let s=go(o);s!==void 0&&r.push(s)}return r}n(NS,"readJsonRpcRequestIds");function jS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(jS,"isRecord");function SP(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],o=[];for(let s of r)jS(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&o.push(s.id);return o}n(SP,"readResponseIds");function _P(e){let t=e.getReader();return new ReadableStream({async pull(r){let o;try{o=await t.read()}catch{r.close();return}if(o.done){r.close();return}r.enqueue(o.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}n(_P,"endOnError");function DS(e,t,r=Gc,o){let s=new Map;for(let a of t)s.set(zS(a),a);let i=!1;return va(_P(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of SP(a.data))yP(s,c)},{failureMode:"open",maxEventChars:r,onFailure:n((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:n(()=>{if(s.size===0||i)return[];let a=o?.aborted?gP:fP;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:hP,message:a}})}))},"end")})}n(DS,"answerUnansweredRequests");var wP={Allow:"POST"},$S="mcp-session-id";async function RP(e){try{return await e.clone().arrayBuffer()}catch{return}}n(RP,"readRequestBody");function Vc(e){try{let t=gp(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{}}}n(Vc,"readRouteAnalyticsFields");function Kc(e){return kp(e.user,e.url,e.headers)?.subjectId}n(Kc,"readRequestSubjectId");function bP(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}n(bP,"readRequestMethod");function LS(e,t){let r=e.get(t);return r===null||r===""?void 0:r}n(LS,"readHeader");function Wc(e){let t=LS(e.request.headers,$S)??(e.response?LS(e.response.headers,$S):void 0),r=e.tapResult?.message?.result,o=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=eo(e.request.headers,e.requestJson?.value)??o;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}n(Wc,"readMcpProtocolFields");function vP(e){let t=TS(e.requestJson?.value);t&&X(e.context,{...t,...Vc(e.context),...Wc({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http"})}n(vP,"emitCapabilityInvokedAnalytics");function CP(e){let t=ES(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended});t&&$p(e.context,{...t,...Vc(e.context),...Wc(e),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(CP,"emitCapabilityFinalAnalytics");function HS(e){let t=kS(e.requestJson?.value,e.details);t&&X(e.context,{...t,...Vc(e.context),...Wc({request:e.request}),httpMethod:e.request.method,subjectId:Kc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(HS,"emitCapabilityThrownAnalytics");async function BS(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 o=new _r(e.request,{headers:t,...r===void 0?{}:{body:r}});return Ql(o,e.context,s=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=s)})}n(BS,"callUpstream");async function FS(e){try{await e.body?.cancel()}catch{}}n(FS,"discardBody");async function IP(e){let t=await BS(e);if(t.status!==401)return t;let r=Qf(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return t;await FS(t);let o=await r.refresh(t,new Headers(e.request.headers));return o.kind==="response"?o.response:BS({...e,headers:o.headers})}n(IP,"forwardToUpstream");function TP(e,t,r){if(e.body===null||e.status<200||e.status>299||It(e.headers.get("content-type"))!=="text/event-stream"||Tt(e.headers))return e;let o=NS(t?.value);if(o.length===0)return e;let s=dt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(DS(e.body,o,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}n(TP,"withUnansweredRequestErrors");function EP(e,t){od.findContextExtensions(e)?.addPipelineExitHook(r=>{let o=t.body;r===t||o===null||r?.body===o||o.locked||o.cancel(Fc).catch(()=>{})})}n(EP,"releaseBodyIfNotSent");function JS(e){return e instanceof Y?PS:AS}n(JS,"thrownDetails");async function kP(e,t){if(Qe("handler.mcp-gateway-proxy"),e.method==="GET")return He.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},wP);let r=Date.now(),o=await RP(e),s=RS(o);Lp(t,eo(e.headers,s?.value)),vP({context:t,request:e,requestJson:s});let i={},a;try{a=bS(await IP({request:e,context:t,bodyBytes:o,upstreamTimeout:i}))}catch(l){throw HS({context:t,request:e,requestJson:s,startedAt:r,details:JS(l)}),l}let c,d;try{c=qS(a,{requestId:go(s?.value),maxBytes:OS(bP(s))}),d=TP(c.response,s,i.signal),EP(t,d)}catch(l){throw await FS(c?.response??a),HS({context:t,request:e,requestJson:s,startedAt:r,details:JS(l)}),l}return t.waitUntil(c.outcome.then(l=>{CP({context:t,request:e,requestJson:s,response:a,tapResult:l,startedAt:r})}).catch(l=>{try{td.getLogger(t).error(l,"Error emitting MCP gateway capability analytics")}catch{}})),d}n(kP,"McpProxyHandler");export{n_ as McpAuth0OAuthInboundPolicy,xa as McpCapabilityFilterInboundPolicy,VS as McpClerkOAuthInboundPolicy,KS as McpCognitoOAuthInboundPolicy,WS as McpEntraOAuthInboundPolicy,$c as McpGatewayPlugin,ZS as McpGoogleOAuthInboundPolicy,YS as McpKeycloakOAuthInboundPolicy,XS as McpLogtoOAuthInboundPolicy,o_ as McpOAuthInboundPolicy,QS as McpOktaOAuthInboundPolicy,e_ as McpOneLoginOAuthInboundPolicy,t_ as McpPingOAuthInboundPolicy,kP as McpProxyHandler,sc as McpTokenExchangeInboundPolicy,r_ as McpWorkosOAuthInboundPolicy,bh 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(an,"renderShell");function xi(e){return W`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?Dy:Ly}</div>`}o(xi,"renderStatusIcon");var Bk="text/html; charset=utf-8";function Lt(e){try{return new URL(e).host}catch{return""}}o(Lt,"safeHostFromUrl");function We(e){let t=e.kind??"authorization_failed",r=Jk(t),n=Fk(e),s=e.title??r.title;return new Response(on(an({title:s,iconHref:"",styles:sn,headerIcon:xi(t==="access_denied"?"neutral":"error"),heading:s,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:jy({steps:nn(r.steps.map(i=>W`<li>${i}</li>`)),action:Kk(e.action),reference:Wk(n),diagnostics:Zk({diagnostic:n,detail:e.detail}),upstreamResponse:Yk(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":Bk,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(We,"browserErrorPageResponse");function Fk(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Vk(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??Gk(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(Fk,"buildBrowserErrorDiagnostic");function Jk(e){switch(e){case"session_expired":return{title:"Authorization expired",steps:["Return to your MCP client and reconnect.","Expired authorization requests cannot be resumed, so start a new connection instead of reloading this page."]};case"access_denied":return{title:"Authorization canceled",steps:["Return to your MCP client.","If you want to grant access, start the connection again and approve the request."]};case"configuration_error":return{title:"Configuration needs attention",steps:["Contact your workspace admin and share the reference below.","The gateway or upstream configuration must be fixed before retrying."]};case"connection_failed":return{title:"Connection failed",steps:["Return to your MCP client and reconnect this upstream.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"invalid_request":return{title:"Authorization request invalid",steps:["Return to your MCP client and try connecting again.","If this keeps happening, the client request may need to be fixed."]};case"admin_required":return{title:"Admin setup required",steps:["Contact your workspace admin and share the reference below.","This connection cannot be completed until setup is finished."]};case"internal_error":return{title:"Gateway error",steps:["Try again later from your MCP client.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"authorization_failed":return{title:"Authorization failed",steps:["Return to your MCP client and start authorization again.","If this keeps happening, contact your gateway administrator and share the reference below."]}}}o(Jk,"readBrowserErrorPagePresentation");function Vk(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}o(Vk,"readBrowserErrorStage");function Gk(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}o(Gk,"readBrowserErrorSuggestedFix");function Kk(e){return e===void 0?Ke:W`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(Kk,"renderAction");function Oi(e){if(e.value===void 0||e.value==="")return Ke;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return W`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}o(Oi,"renderRow");function Le(e){return Oi({label:e.label,value:e.value===void 0?void 0:W`<code>${e.value}</code>`})}o(Le,"renderCodeRow");function Wk(e){return nn([Oi({label:"Error code",value:W`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Le({label:"Request ID",value:e.requestId}),Le({label:"Time",value:e.timestamp})])}o(Wk,"renderReference");function Zk(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return nn([Oi({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Oi({label:"Reason",value:r,block:!0}),Le({label:"Stage",value:t.stage}),Le({label:"Gateway route",value:t.routePath}),Le({label:"Operation ID",value:t.operationId}),Le({label:"Upstream",value:t.upstreamServerId}),Le({label:"Auth profile",value:t.authProfileId}),Le({label:"Upstream URL",value:t.upstreamUrl}),Le({label:"Metadata URL",value:t.metadataUrl}),Le({label:"HTTP status",value:t.httpStatus}),Le({label:"Content type",value:t.contentType}),Le({label:"Provider error",value:t.providerError}),Le({label:"Provider error description",value:t.providerErrorDescription})])}o(Zk,"renderDiagnostics");function Yk(e){return e===void 0?Ke:W`<details class="provider-response"><summary class="provider-response__summary">Show the provider's response</summary><iframe title="Upstream HTML error response" sandbox class="provider-response__frame" srcdoc="${e}"></iframe></details>`}o(Yk,"renderUpstreamHtml");var $y="application/json",Xk="application/x-www-form-urlencoded";function Mi(e,t){return new k({message:e,extensionMembers:{[O]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Mi,"invalidRequestError");function Qk(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(Qk,"normalizeContentType");function eA(e,t){return e===t?!0:t===$y&&e.endsWith("+json")}o(eA,"contentTypeMatches");function tA(e,t){if(!t||t.length===0)return;let r=Qk(e.headers.get("content-type"));if(!t.some(n=>eA(r,n)))throw Mi(`Request body must be ${t.join(" or ")}.`)}o(tA,"assertExpectedContentType");function rA(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw Mi(`${r} exceeded the maximum allowed size.`)}o(rA,"assertContentLengthWithinLimit");async function Hy(e,t){let r=t.label??"Request body";tA(e,t.expectedContentTypes),rA(e,t.maxBytes,r);let n=await Ri(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Mi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(Hy,"readBoundedTextBody");async function By(e,t){let r=await Hy(e,{...t,expectedContentTypes:[$y]});try{return JSON.parse(r)}catch(n){throw Mi("Request body must be valid JSON.",n)}}o(By,"readBoundedJsonBody");async function Fy(e,t){let r=await Hy(e,{...t,expectedContentTypes:[Xk]});return new URLSearchParams(r)}o(Fy,"readBoundedFormUrlEncodedBody");import{errors as Vy,jwtVerify as Gy,SignJWT as td}from"jose";import{base64url as nA}from"jose";var oA="mcp-browser-login-pkce:",sA=new TextEncoder;async function iA(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(iA,"importHmacKey");async function ed(e){let t=await iA(e.signingKey),r=sA.encode(`${oA}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return Dr.parse(nA.encode(new Uint8Array(n)))}o(ed,"deriveBrowserLoginPkceVerifier");async function Jy(e){let t=await ed(e),r=await Ks(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:jr}}o(Jy,"deriveBrowserLoginPkceParams");var aA={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},T=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=aA[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var cA=300,Ky=p.string().min(1).optional(),dA=p.object({purpose:p.literal("gateway_browser_login"),transactionId:ma,stateId:Bs,binding:Do,authorizationServerIssuer:Ky,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),uA=p.object({purpose:p.literal("gateway_browser_login_return"),stateId:Bs,binding:Do,exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),lA=p.discriminatedUnion("purpose",[dA,uA]),pA=p.object({purpose:p.literal("gateway_authorization_setup"),transactionId:ma,stateId:Bs,authorizationServerIssuer:Ky,exp:p.number().int().positive(),iat:p.number().int().positive().optional()});async function cn(){return Ve({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-login"),"derive")})}o(cn,"getBrowserLoginKey");async function Wy(){return Ve({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"authorization-csrf"),"derive")})}o(Wy,"getCsrfKey");function Zy(e){return{now:e.now??new Date,ttlSeconds:rd()}}o(Zy,"readPendingTransactionDependencies");function rd(){return Ee().browserLogin.stateTtlSeconds}o(rd,"readBrowserLoginStateTtlSeconds");function mA(e){let t=ge();return je(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o(mA,"isLoopbackDevLoginUrl");async function Yy(e){let t=Ee().browserLogin,r=ge(),n=new URL(Pt("url")),s=new URL(r.actionPath("/oauth/callback"),xt(e.requestUrl,e.requestHeaders));if(mA(n))return n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("state",e.state),n;if(n.searchParams.set("response_type","code"),n.searchParams.set("client_id",Pt("clientId")),n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("scope",t.scope),n.searchParams.set("state",e.state),n.searchParams.set("nonce",e.nonce),t.audience&&n.searchParams.set("audience",t.audience),t.pkce===jr){let i=await Jy({stateId:e.stateId,signingKey:await cn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(Yy,"buildBrowserLoginUrl");function hA(e,t){return e.subjectId===t.subjectId}o(hA,"principalsMatch");function Xy(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(Xy,"toPendingPrincipal");function Qy(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:J(e.now),expiresAt:J(pt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw z("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:Xy(e.principal)}}o(Qy,"createTransactionRecord");async function eS(e){let{id:t,...r}=e.record,n=await H().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw z("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new T("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new T("invalid_request","redirect_uri is not registered for the client.")}}o(eS,"startPendingTransaction");async function fA(e){return new td({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await cn())}o(fA,"signBrowserLoginState");async function tS(e){return new td({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Js(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Wy())}o(tS,"signCsrfToken");async function nd(e){try{let{payload:t}=await Gy(e,await cn(),{algorithms:[Re],issuer:he,audience:we}),r=lA.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding,authorizationServerIssuer:r.authorizationServerIssuer}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof Vy.JWTExpired?z("oauth_state_expired","Browser login state has expired.",t):z("oauth_state_invalid","Browser login state could not be verified.",t)}}o(nd,"verifyAnyBrowserLoginStateToken");async function gA(e){let t=await nd(e);if(t.kind!=="authorization")throw z("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding,authorizationServerIssuer:t.authorizationServerIssuer}}o(gA,"verifyBrowserLoginStateToken");async function Ui(e){try{let{payload:t}=await Gy(e,await Wy(),{algorithms:[Re],issuer:he,audience:we}),r=pA.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof Vy.JWTExpired?z("oauth_state_expired","Authorization setup state has expired.",t):z("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Ui,"verifyCsrfToken");function od(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(od,"pendingStateErrorCode");function yA(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(yA,"toPendingAuthorizationGetResult");function SA(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(SA,"toPendingAuthorizationAdvanceResult");function sd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":od(e==="consumed_already"?"consumed_already":e)}o(sd,"setupDecisionErrorCode");async function rS(e){let t=e.now??new Date,r=await Ui(e.csrfToken),n=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(n.kind!=="marked")throw z(sd(n.kind),"Authorization setup state is invalid, expired, or already used.");return nS({kind:"available",record:n.transaction})}o(rS,"markSetupApproved");function nS(e){if(e.kind!=="available")throw z(od(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(nS,"requireAwaitingSetup");function _A(e){if(!hA(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(_A,"requireCurrentPrincipalMatches");async function oS(e){let t=e.now??new Date,r=rd(),n=ha(),s=Js(),i=await $o({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await fA({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=Qy({id:n,transaction:e.transaction,currentStateHash:await ae(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await eS({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await Yy({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:u,browserBindingCookie:i.setCookie}}o(oS,"startAwaitingLogin");async function sS(e){let t=rd(),r=Js(),n=await $o({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new td({purpose:"gateway_browser_login_return",stateId:r,binding:n.claim}).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await cn());return{browserLoginUrl:await Yy({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(sS,"startReturnToBrowserLogin");async function iS(e){let{now:t,ttlSeconds:r}=Zy(e),n=ha(),s=await tS({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=Qy({id:n,transaction:e.transaction,currentStateHash:await ae(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await eS({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}o(iS,"startAwaitingSetup");async function aS(e){let{now:t,ttlSeconds:r}=Zy(e),n=await gA(e.browserLoginStateToken),s=await tS({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=SA(await H().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await ae(e.browserLoginStateToken),nextStateHash:await ae(s),nextPhase:"awaiting_setup",principal:Xy(e.principal),now:J(t)}));if(i.kind!=="advanced")throw z(od(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}o(aS,"completeLogin");async function cS(e){let t=await id(e);return _A({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(cS,"getSetup");async function id(e){let t=e.now??new Date,r=await Ui(e.csrfToken);return nS(yA(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await ae(e.csrfToken),now:J(t)})))}o(id,"getSetupTransaction");async function wA(e){let t=await Ui(e.csrfToken),r=ht(),n=J(pt(e.now,cA)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await ae(r),authorizationCodeExpiresAt:n,grantId:Nm(),now:J(e.now)});if(s.kind!=="approved")throw z(s.kind==="cancelled"?"oauth_state_invalid":sd(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),qi(i,t.authorizationServerIssuer),i}o(wA,"createAuthorizationCodeRedirectWithDecision");async function RA(e){let t=await Ui(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await ae(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw z(r.kind==="approved"?"oauth_state_invalid":sd(r.kind),"Authorization setup state is invalid, expired, or already used.");return bA({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(RA,"createCancelRedirectWithDecision");function qi(e,t){t!==void 0&&fe()&&e.searchParams.set("iss",t)}o(qi,"setAuthorizationResponseIssuer");function bA(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),qi(t,e.authorizationServerIssuer),t}o(bA,"buildClientCancelRedirect");async function dS(e){let t=e.now??new Date;return wA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(dS,"approve");async function uS(e){let t=e.now??new Date;return RA({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(uS,"cancel");import{createRemoteJWKSet as vA,errors as dn,jwtVerify as lS,SignJWT as CA}from"jose";var IA="zuplo_mcp_session",TA=p.object({purpose:p.literal("gateway_browser_session"),sub:_o,browserLoginOrigin:p.string().min(1),roles:p.array(p.string().min(1)).optional(),exp:p.number().int().positive(),iat:p.number().int().positive().optional()}),EA=p.object({id_token:p.string().min(1),token_type:p.string().min(1).optional(),expires_in:p.number().optional(),access_token:p.string().min(1).optional(),refresh_token:p.string().min(1).optional(),scope:p.string().min(1).optional()}),kA=p.object({error:p.string().min(1).optional(),error_description:p.string().min(1).optional(),error_uri:p.string().min(1).optional()}),AA=p.object({sub:_o,nonce:p.string().min(1)}).catchall(p.unknown()),ad;async function pS(){return Ve({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ct(e,"browser-session"),"derive")})}o(pS,"getBrowserSessionKey");function dd(e,t){let r=_i(e,t);return{name:Tc(IA,r),secure:r}}o(dd,"browserSessionCookieName");function cd(e,t){let{name:r,secure:n}=dd(e,t);return Lo({name:r,value:"",maxAgeSeconds:0,secure:n})}o(cd,"buildBrowserSessionEvictionCookie");function PA(e){let{name:t,secure:r}=dd(e.requestUrl,e.requestHeaders);return Lo({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}o(PA,"serializeSessionCookie");function mS(){return new URL(Pt("url")).origin}o(mS,"readBrowserLoginOrigin");function xA(e){let t=kA.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(xA,"readIdpErrorFields");function OA(e){return e instanceof dn.JWTExpired?"expired":e instanceof dn.JWTClaimValidationFailed?"claim":e instanceof dn.JWSSignatureVerificationFailed?"signature":e instanceof dn.JWKSNoMatchingKey?"jwks_no_match":e instanceof dn.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(OA,"readJwtFailureKind");function MA(e){return e instanceof Error&&"cause"in e?e.cause:e}o(MA,"readErrorCause");function UA(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(UA,"readRuntimeGatewayCode");function qA(){if(!ad){let e=Ee();ad=vA(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return ad}o(qA,"readFederatedJwks");function hS(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ar(e.user,e.url)}o(hS,"resolveCurrentRequestPrincipal");async function un(e,t={}){let r=Ec(e.headers.get("cookie")).get(dd(e.url,e.headers).name);if(!r)return{};try{let{payload:n}=await lS(r,await pS(),{algorithms:[Re],issuer:he,audience:we}),s=TA.parse(n);if(s.browserLoginOrigin!==mS())return{evictCookie:cd(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(n){return n instanceof dn.JWTExpired?{evictCookie:cd(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:cd(e.url,e.headers)})}}o(un,"readBrowserSession");async function Fo(e){let t=Ee().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:mS()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new CA(r).setProtectedHeader({alg:Re,typ:"JWT"}).setIssuer(he).setAudience(we).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await pS());return PA({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(Fo,"createBrowserSessionCookie");async function zA(e){let t=Ee(),r=Pt("tokenUrl"),n=Pt("clientId"),s=Pt("clientSecret"),i=new URL(ge().actionPath("/oauth/callback"),xt(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:s});if(t.browserLogin.pkce===jr){let c=await ed({stateId:e.stateId,signingKey:await cn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await bi(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let S=xA(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ue(r),idpStatus:c.status,...S},"Federated browser login token exchange returned non-2xx from the identity provider"),z({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${S.idpError?` idp_error=${S.idpError}`:""}${S.idpErrorDescription?` idp_error_description=${S.idpErrorDescription}`:""})`)})}let u=EA.parse(d),m;try{({payload:m}=await lS(u.id_token,qA(),{issuer:t.oidc.issuer,audience:n}))}catch(S){let R={};throw ke(R,"error",S),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:OA(S),idpHost:ue(r),expectedIssuer:t.oidc.issuer,...R},"Federated id_token failed jose verification"),S}if(m.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ue(r),nonceMissingFromIdToken:m.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),z("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=AA.parse(m);return{principal:ar({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:bo,expiresAt:typeof m.exp=="number"?J(new Date(m.exp*1e3)):void 0}}}catch(c){let d=lt(c)??UA(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",MA(c))}}o(zA,"exchangeFederatedAuthorizationCode");async function ud(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return zA({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await un(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw z("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}o(ud,"resolveBrowserLoginCallbackIdentity");var NA=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function jA(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(jA,"readScheme");function DA(e){return e.protocol==="https:"}o(DA,"isSpecCompliantRedirectUri");function LA(e){let t=jA(e);return t.length>0&&t!=="http"&&t!=="https"&&!NA.has(t)}o(LA,"isNativeAppCustomSchemeRedirectUri");var gS=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>DA(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>je(e),"accepts"),matches:o((e,t)=>je(e)&&je(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>LA(e),"accepts")}];function yS(e){let t=gS.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(yS,"evaluateBuiltInRedirectUriCompatibility");function fS(e){try{return new URL(e)}catch{return}}o(fS,"parseUrl");function SS(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=fS(e.registeredRedirectUri),r=fS(e.requestedRedirectUri);return t===void 0||r===void 0?!1:gS.some(n=>n.matches?.(t,r))}o(SS,"redirectUriMatchesBuiltInCompatibility");var $A=1e4,HA=5*1024,BA=0,FA=2160*60*60,_S=["authorization_code","refresh_token",$s,Ot],JA=["authorization_code","refresh_token"],wS=[Um],VA=["code"],GA=p.object({client_name:p.string().min(1).optional(),redirect_uris:p.array(p.string().min(1)).min(1),grant_types:p.array(p.enum(_S)).min(1).max(_S.length).optional(),authorization_grant_profiles_supported:p.array(p.enum(wS)).min(1).max(wS.length).optional(),response_types:p.array(p.enum(VA)).min(1).max(1).optional(),scope:p.literal(pe).optional(),token_endpoint_auth_method:zm.optional(),jwks_uri:p.string().min(1).optional()});function KA(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&je(t))&&t.pathname!=="/"}catch{return!1}}o(KA,"isCimdClientIdCandidate");function RS(e,t){throw new T("invalid_client",Vm({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(RS,"invalidCimdClientError");function ln(e,t="invalid_request"){if(WA(e))throw new T(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new T(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new T(t,"redirect_uris must not include credentials or fragments.");if(yS({url:r}).kind==="rejected")throw new T(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(ln,"assertValidRedirectUri");function WA(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(WA,"hasForbiddenRawRedirectUriCharacter");async function ZA(e){let{response:t,json:r}=await lg(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:BA,maxResponseBytes:HA,timeoutMs:$A});if(!t.ok)throw z("invalid_request","CIMD metadata could not be fetched.");let n=Fs(r);for(let s of n.redirect_uris)ln(s,"invalid_request");if(n.jwks_uri!==void 0&&Co(n.jwks_uri),n.client_id!==e.clientId)throw z("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(ZA,"fetchCimdMetadata");async function YA(e){let t=Vs(e),r=await ZA({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(YA,"resolveCimdClient");async function zi(e,t){let r=mt.parse(e);if(KA(r)){Ee().gateway.downstreamCimdEnabled||RS(r);try{return await YA(r)}catch(s){RS(r,s)}}let n=await H().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=Km(s.clientId),a=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",c=s.jwksUri??i;if(a==="private_key_jwt"&&c===void 0)throw new T("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=Fs({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),u={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(u.hashedClientSecret=s.hashedClientSecret),u}throw new T("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(zi,"resolveClient");function bS(e,t){if(!e.metadata.redirect_uris.some(r=>SS({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(bS,"assertRedirectRegistered");function XA(e){return e===void 0?[...JA]:Array.from(new Set(e))}o(XA,"normalizeGrantTypes");function QA(e){try{Co(e)}catch(t){throw new T("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}o(QA,"assertValidDcrJwksUri");function eP(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?mt.parse(Gm({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):mt.parse(`dcr:${crypto.randomUUID()}`)}o(eP,"createDcrClientId");function pn(e){if(e===void 0||e===pe)return pe;throw new T("invalid_request",`Only the ${pe} scope is supported.`)}o(pn,"assertSupportedOAuthScope");function lr(e,t,r){let n;try{n=new URL(t)}catch{throw new T("invalid_target","resource must be an absolute URI.")}if(n.hash)throw new T("invalid_target","resource must not include a fragment.");if(n.protocol!=="https:"&&!je(n))throw new T("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ie(e,r),i=Ls(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new T("invalid_target","resource must match a published MCP route.");return a}o(lr,"resolveResource");async function vS(e){let t;try{t=GA.parse(e)}catch(S){if(S instanceof p.ZodError){let R=S.issues.some(_=>_.path[0]==="redirect_uris");throw new T(R?"invalid_redirect_uri":"invalid_client_metadata",S.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:S})}throw S}for(let S of t.redirect_uris)ln(S,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new T("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&QA(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=eP({tokenEndpointAuthMethod:n,jwksUri:t.jwks_uri}),a=Fs({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:n,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=pt(r,FA),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),m={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:XA(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:pe,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:J(r),clientExpiresAt:J(c)};if(n==="client_secret_basic"||n==="client_secret_post"){let S=ht();h.hashedClientSecret=await ae(S),h.clientSecretExpiresAt=J(c),m.client_secret=S,m.client_secret_expires_at=u,m.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw z("invalid_request","OAuth client is already registered.");return m}o(vS,"registerDownstreamClient");function tP(e){return e?.metadata?.idpSubjectTokenType!==Vr&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}o(tP,"hasStoredIdJagSubjectTokenBinding");async function CS(e){let t=Jr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(CS,"readIdJagSubjectConnection");async function ld(e){let t=Ce().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await CS({connection:t.connection,principal:e.principal});return!tP(r)}o(ld,"requiresIdJagSubjectTokenBinding");async function IS(e){if(e.subjectToken===void 0)return;let t=Ce().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await CS({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??Gs(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await wt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}o(IS,"bindIdJagSubjectTokenForAuthorizationTransaction");function TS(e){return W`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(TS,"renderShellIcon");function ES(e){return W`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(ES,"renderActions");var kS=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function AS(e){return W`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(AS,"renderBannerWarning");var UL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),qL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var zL=Ge('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var rP="data:,",PS=W`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,xS=W`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function nP(e,t,r){if(e)try{let n=new URL(t).origin,s=new URL(e,n);return s.origin!==n||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}o(nP,"safeGatewayConnectHref");function oP(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(oP,"deriveMode");function sP(e){return ES({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:PS,authorizeAttrs:Ke})}o(sP,"renderActions");function pd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=nP(s.connectUrl,t,n);if(i)return i}}o(pd,"firstUserConnectHref");function iP(e){let t=e.connectHref===void 0?Ke:W`<a class="button button--primary" href="${e.connectHref}" ${xS}>Connect</a>`;return W`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${PS}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}o(iP,"renderSetupActions");function aP(e){return e?W`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${xS}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Ke}o(aP,"renderReconnectAction");function cP(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}o(cP,"isRenderableIconHref");function OS(e){return e?.find(t=>cP(t.src))?.src}o(OS,"readIconHref");function dP(e){return OS(e.serverIcons)??(e.transportHost===void 0?void 0:vc(e.transportHost).src)}o(dP,"readUpstreamIconHref");function uP(e){let t=OS(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=dP(r);if(n!==void 0)return n}}o(uP,"readHeaderIconHref");function lP(e){let t=e.setupMessage===void 0?Ke:AS({icon:kS,message:e.setupMessage});return W`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}o(lP,"renderBody");function md(e){let t=oP(e.upstreams),r=pd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),n=pd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=pd(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??n:void 0,a=t==="setup"?e.upstreams.find(u=>u.ownerMode==="user"&&u.status!=="active"&&u.connectUrl===void 0&&u.setupMessage!==void 0)?.setupMessage:void 0,c=uP({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?W`<footer class="card__footer">${iP({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:W`<footer class="card__footer">${aP(s)}${sP({state:e.state,gateway:e.gateway})}</footer>`;return on(an({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??rP,styles:sn,headerIcon:c===void 0?Ke:TS({iconHref:c,fallbackIconHref:Wf}),heading:"Authorize access",subhead:Ke,body:lP({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(md,"renderConsentPage");var pP=1e4,mP=2e3,hP=64*1024,NS={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},MS="mcp-session-id",fP;function jS(){return{tools:[],prompts:[],resources:[]}}o(jS,"emptyCapabilities");function US(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":fa})}o(US,"buildReadinessHeaders");async function qS(e){if(e.type==="bearer_token"){let n=US();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=US();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(qS,"buildAsyncCredentialHeaders");function gP(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(nr.parse({jsonrpc:rr,id:1,method:"initialize",params:{protocolVersion:fa,capabilities:{},clientInfo:NS}}))})}o(gP,"buildInitializePreflight");function yP(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",So),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:rr,id:1,method:"server/discover",params:{_meta:{[Ms]:So,[om]:{},[sm]:NS}}})})}o(yP,"buildDiscoverPreflight");async function SP(e){if(e.status!==400&&e.status!==404)return!1;let t=await _P(e);if(t===void 0)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&"error"in r&&typeof r.error=="object"&&r.error!==null&&"code"in r.error&&typeof r.error.code=="number"}catch{return!1}}o(SP,"isModernRejectionOfInitialize");async function _P(e){let t=e.body?.getReader();if(t===void 0)return;let r,n=new Promise(i=>{r=setTimeout(()=>i("timeout"),mP)}),s=(async()=>{let i=new TextDecoder,a="",c=0;for(;;){let{done:d,value:u}=await t.read();if(d)return a+i.decode();if(c+=u.byteLength,c>hP)return;a+=i.decode(u,{stream:!0})}})();try{let i=await Promise.race([s,n]);return i==="timeout"?void 0:i}catch{return}finally{clearTimeout(r),t.cancel().catch(()=>{})}}o(_P,"readBoundedBody");async function hd(e){vo(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),pP);try{let n=new Request(e,{redirect:"manual",signal:t.signal});return await Qd.fetch(n)}finally{clearTimeout(r)}}o(hd,"runPreflight");function Jo(e){e.body?.cancel().catch(()=>{})}o(Jo,"releasePreflightBody");async function wP(e){let t=e.response.headers.get(MS);if(!t)return;let r=new Headers(e.headers);r.set(MS,t),r.delete("content-type");try{let n=await hd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Jo(n)}catch{}}o(wP,"terminatePreflightSession");async function DS(e){let{response:t}=e;return Jo(t),t.status>=200&&t.status<300?(await wP(e),{kind:"ready",upstreamStatus:t.status,capabilities:jS()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}o(DS,"classifyResponse");function zS(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}o(zS,"connectRequiredResult");async function LS(e){let t=await hd(gP(e));if(!fe()||!await SP(t))return t;try{let r=await hd(yP(e));if(r.status>=200&&r.status<300)return Jo(t),r;Jo(r)}catch{}return t}o(LS,"probeUpstream");async function RP(e){try{return DS({response:await LS(e),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}o(RP,"classifyPreflight");async function bP(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:jS()};let r=Ai(t.upstreamServerId,e.route.operationId),n=tn(r,e.subjectId),s=e.returnTo===void 0?n:{...n,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await en({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return zS(a.payload);let c=await qS(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d;try{d=await LS({upstreamUrl:t.mcpUrl,headers:c})}catch(h){return{kind:"upstream_unavailable",message:h instanceof Error?h.message:"Upstream MCP server readiness preflight failed."}}if(d.status!==401)return DS({response:d,upstreamUrl:t.mcpUrl,headers:c});Jo(d);let u=await en({request:i,routeAuth:s,forceRefresh:!0});if(u.kind==="connect_required")return zS(u.payload);let m=await qS(u.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:RP({upstreamUrl:t.mcpUrl,headers:m})}o(bP,"checkUpstreamRouteReadinessImpl");function $S(e){return(fP??bP)(e)}o($S,"checkUpstreamRouteReadiness");function vP(e){try{return new URL(e).host}catch{return}}o(vP,"safeUrlHost");function HS(e){return e!==void 0&&e.length>0}o(HS,"hasItems");function CP(e){let t=e.serverInfo?.icons;if(HS(t))return t;let r=fi(e.mcpUrl);return r===void 0?void 0:[r]}o(CP,"readServerIcons");async function IP(e){let{authConfig:t,authMode:r,description:n,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",m=u&&r!=="id-jag",h=e.readiness??(u?Qm(e.connection):{connected:!0,status:"active"}),f=m?e.readiness?.connectUrl??(e.returnTo!==void 0?await Pc({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,S=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:n,transportHost:vP(i),scopesRequested:HS(S)?S:void 0,serverIcons:CP(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:f,setupMessage:e.setupMessage,updatedAt:u&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}o(IP,"buildSetupRequirement");function BS(e){let t=Ce().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(BS,"requireRoute");async function fd(e){let t=BS(e.transaction.operationId),r=Jr(e.transaction.principal.subjectId),n=t.connection;if(n===void 0)return[];let i=n.ownerMode==="user"?(await H().batchGetUpstreamConnections([{owner:r,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId}]))[0]:void 0,a=await $S({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),c="connectionStatus"in a?a.connectionStatus:void 0,d=(a.kind==="connect_required"||a.kind==="admin_setup_required")&&a.payload.authUrl!==void 0?a.payload.authUrl:void 0,u=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await IP({connection:i,registeredConnection:n,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:u,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}o(fd,"requirementsForSetup");async function gd(e){let t=BS(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),n=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ie(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:n?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}o(gd,"consentContext");function yd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(yd,"hasUnresolvedUserUpstream");var TP=["mcp_user"],EP="dev-browser-user",kP=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),AP=p.object({response_type:p.literal("code"),client_id:p.string().min(1),redirect_uri:p.string().min(1),resource:p.url(),code_challenge:p.string().min(43),code_challenge_method:Rm,state:p.string().min(1).optional(),scope:p.literal(pe).default(pe)}),PP=p.enum(["continue","approve","cancel"]).default("continue"),xP=p.object({state:p.string().min(1),decision:PP}),$t=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;authorizationServerIssuer;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription,this.authorizationServerIssuer=t.authorizationServerIssuer}};function FS(e){return typeof e=="string"&&e.length>0?e:void 0}o(FS,"readQueryString");function OP(e,t){let r=FS(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new T("invalid_target",kP)}let n=Hm(t,e.url,e.headers);if(r===void 0||r===n)return n;throw new T("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(OP,"requireAuthorizeResource");async function MP(e,t){let r={};t!==void 0&&(r.context=t);let n=await un(e,r);if(n.principal)return{principal:n.principal};if(!e.user)return n.evictCookie===void 0?{}:{setCookie:n.evictCookie};let s=hS(e);return{principal:s,setCookie:await Fo({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o(MP,"resolveBrowserPrincipal");async function UP(e,t){let r={};t!==void 0&&(r.context=t);let n=await un(e,r);if(!n.principal)throw z("authentication_required","Authorization setup requires a current browser session.");return n.principal}o(UP,"requireSetupPrincipal");function JS(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(JS,"buildSetupReturnTo");async function VS(e){let t=await fd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:JS(e.csrfToken)}),r=await gd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),n={kind:"setup_page",html:md({state:e.csrfToken,operationId:e.transaction.operationId,gateway:ge(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(n.setCookies=e.setCookies),n}o(VS,"renderSetup");function qP(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(qP,"toAuthorizationTransactionClient");async function Sd(e,t={}){let r=AP.parse({...e.query,resource:OP(e,t.operationId),state:FS(e.query.state)}),n=pn(r.scope);ln(r.redirect_uri,"invalid_request");let s=fe()?t.operationId===void 0?xt(e.url,e.headers):jm({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=mt.parse(r.client_id),c=await zi(r.client_id,i);bS(c,r.redirect_uri);try{let d=lr(e.url,r.resource,e.headers),u=qP(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:d.operationId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&te(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type}});let m={clientId:c?.clientId??a,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state},authorizationServerIssuer:s},{principal:h,setCookie:f}=await MP(e,t.context),S=h===void 0?!1:await ld({operationId:d.operationId,principal:h});if(!h||S){let _=await oS({transaction:m,requestUrl:e.url,requestHeaders:e.headers,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:d.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:_.browserLoginUrl,setCookies:[...f===void 0?[]:[f],_.browserBindingCookie]}}let R=await iS({transaction:m,principal:h,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:d.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&te(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type,subjectId:h.subjectId}}),VS({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw zP({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Sd,"authorizeDownstreamClient");function zP(e){if(e.cause instanceof $t)return e.cause;let t=NP(e.cause);return t?new $t({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(zP,"toDownstreamAuthorizeRedirectError");function NP(e){if(e instanceof T)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof p.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(NP,"mapToOAuthRedirectError");async function GS(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let u=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...u===void 0?{}:{idpErrorDescription:u},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),z("provider_access_denied",u??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),z("oauth_state_invalid","Browser login callback is missing state.");let s=await nd(n),i=await wi({purpose:"login",claim:s.binding,request:e});if(!i.matched&&zt())throw t.context?.log.warn({event:"browser_login_callback_binding_mismatch",code:"oauth_callback_mismatch",stateKind:s.kind},"Browser login callback arrived in a browser that did not start the login"),z("oauth_callback_mismatch","Browser login was not started in this browser.");let a={request:e,stateId:s.stateId};if(t.context!==void 0&&(a.context=t.context),s.kind==="return_to"){let u=jP(i.payload),m=await ud(a);return{kind:"redirect",location:new URL(u,ie(e.url,e.headers)),setCookies:[await Fo({principal:m.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await ud(a),d=await aS({browserLoginStateToken:n,principal:c.principal});if(await IS({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await ld({operationId:d.transaction.operationId,principal:c.principal}))throw z("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return VS({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await Fo({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}o(GS,"completeBrowserLoginCallback");function jP(e){let t=wo(e),r=ge().actionPath("/auth/connections/"),n=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||n===void 0||!n.startsWith(r)||!/^[^/]+\/connect$/u.test(n.slice(r.length)))throw z("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}o(jP,"readConnectReturnTo");async function KS(e){let t=await sS(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(KS,"startConnectBrowserLogin");async function WS(e){let t=Ee(),r=new URL(e.url);if(!je(r))throw z("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw z("oauth_state_invalid","Local browser login is missing state.");let s=ge().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ie(e.url)),a=new URL(ie(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw z("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",n);let c={subjectId:_o.parse(EP),roles:TP};return{kind:"redirect",location:i,setCookies:[await Fo({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(WS,"completeLocalDevBrowserLogin");function DP(e){let t=e.method==="POST"?e.body:e.query;return xP.parse(t)}o(DP,"readSetupContinueRequest");async function ZS(e){let{state:t,decision:r}=DP({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await id({csrfToken:t,now:n}),i=await UP(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await uS({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await cS({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await fd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:JS(t)});if(r==="approve"&&yd(c)&&await rS({csrfToken:t,currentBrowserPrincipal:i,now:n}),yd(c)){let d=await gd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:md({state:t,operationId:a.operationId,gateway:ge(),upstreams:c,...d})}}return{kind:"redirect",location:await dS({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(ZS,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as XP,decodeJwt as QP,errors as Go,jwtVerify as ex}from"jose";import{createRemoteJWKSet as LP,decodeJwt as $P,decodeProtectedHeader as HP,errors as Vo,jwtVerify as BP}from"jose";var t_=30,ce=p.string().min(1),FP=p.union([ce,p.array(ce).min(1)]),JP=p.union([ce,p.array(ce).min(1)]),VP=p.object({type:ce,locations:p.array(ce).optional(),actions:p.array(ce).optional(),datatypes:p.array(ce).optional(),identifier:ce.optional(),privileges:p.array(ce).optional()}).passthrough(),GP=p.object({iss:p.url(),sub:ce,aud:FP,client_id:ce,resource:JP.optional(),scope:ce.optional(),authorization_details:p.array(VP).optional(),jti:ce,iat:p.number().int(),nbf:p.number().int().optional(),exp:p.number().int(),tenant:ce.optional(),aud_tenant:ce.optional(),aud_sub:ce.optional(),sub_id:ce.optional(),act:p.unknown().optional(),email:ce.optional(),auth_time:p.number().int().optional(),acr:ce.optional(),amr:p.array(ce).optional(),cnf:p.unknown().optional()}).passthrough();function $e(e){throw new T("invalid_grant",e)}o($e,"throwInvalidGrant");function KP(e){return e instanceof Vo.JWTExpired?"expired":e instanceof Vo.JWTClaimValidationFailed?"claim":e instanceof Vo.JWSSignatureVerificationFailed?"signature":e instanceof Vo.JWKSNoMatchingKey?"jwks_no_match":e instanceof Vo.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(KP,"readJwtFailureKind");function WP(e){return Array.isArray(e.aud)?(e.aud.length!==1&&$e("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}o(WP,"readSingleAudience");function YS(e){try{let t=GP.parse(e);return WP(t),t}catch(t){if(t instanceof T)throw t;$e("ID-JAG claims are invalid.")}}o(YS,"parseIdJagClaims");function ZP(e,t){e.idJag.enabled||$e("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(n=>n.issuer===t);return r===void 0&&$e("ID-JAG issuer is not trusted."),r}o(ZP,"readTrustedIssuer");function YP(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(n=>r.has(n.type))}o(YP,"readGrantedAuthorizationDetails");function XS(e){if(e.clientAuth.method==="none")throw new T("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&$e("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&$e("ID-JAG client_id is not allowed for this issuer.")}o(XS,"assertClientBinding");function QS(e){e.cnf!==void 0&&$e("ID-JAG cnf-bound assertions require DPoP support.")}o(QS,"assertProofOfPossessionNotDeferred");function e_(e){let t=Math.floor(e.now.getTime()/1e3)+t_;e.claims.iat>t&&$e("ID-JAG iat must not be in the future.")}o(e_,"assertIssuedAtNotInFuture");async function r_(e){let t;try{t=HP(e.assertion)}catch{$e("ID-JAG assertion is malformed.")}t.typ!==la&&$e('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=YS($P(e.assertion))}catch(c){if(c instanceof T)throw c;$e("ID-JAG assertion is malformed.")}let n=xt(e.requestUrl,e.requestHeaders),s=[n];e.requestedResource!==void 0&&e.requestedResource!==n&&s.push(e.requestedResource);let i=ZP(e.config,r.iss);s.includes(r.iss)&&$e("ID-JAG issuer must be different from the gateway."),XS({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),QS(r),e_({claims:r,now:e.now});let a;try{let c=LP(new URL(i.jwksUrl)),{payload:d}=await BP(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:t_,typ:la});a=YS(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:KP(c)},"OAuth ID-JAG assertion verification failed"),$e("ID-JAG assertion verification failed.")}return XS({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),QS(a),e_({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:Bm({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:YP({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(r_,"verifyIdJagAssertion");var tx=new Set(["authorization_code","refresh_token",Ot]),rx=1e4,nx=32*1024,ox=2,sx=3600,_d=p.object({client_id:p.string().min(1).optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),ix=p.discriminatedUnion("grant_type",[_d.extend({grant_type:p.literal("authorization_code"),code:p.string().min(1),redirect_uri:p.string().min(1),code_verifier:Dr,resource:p.url().optional(),scope:p.literal(pe).optional()}),_d.extend({grant_type:p.literal("refresh_token"),refresh_token:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional()}),_d.extend({grant_type:p.literal(Ot),assertion:p.string().min(1),resource:p.url().optional(),scope:p.literal(pe).optional(),authorization_details:p.string().min(1).optional()})]);function ax(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!tx.has(t)))throw new T("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(ax,"assertSupportedGrantType");var cx=p.object({token:p.string().min(1),client_id:p.string().min(1).optional(),token_type_hint:p.string().optional(),client_secret:p.string().min(1).optional(),client_assertion_type:p.string().min(1).optional(),client_assertion:p.string().min(1).optional()}),dx=p.object({keys:p.array(p.record(p.string(),p.unknown())).min(1)}).passthrough();function o_(){return Ee().gateway.accessTokenTtlSeconds}o(o_,"readAccessTokenTtlSeconds");function ux(){return Ee().gateway.refreshTokenTtlSeconds}o(ux,"readRefreshTokenTtlSeconds");function n_(e,t){let r=o_(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,n);return{expiresAt:J(pt(e,s)),expiresIn:s}}o(n_,"calculateAccessTokenExpiresAt");function lx(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new T("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new T("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}o(lx,"readIdJagResource");function px(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new T("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}o(px,"readIdJagGrantedAuthorizationDetails");function mx(e){if(e.claimScope?.split(/\s+/).includes(pe)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return pe;if(e.claimScope===void 0)throw new T("invalid_grant",`ID-JAG must include ${pe} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(pe))throw new T("invalid_grant",`ID-JAG scope must include ${pe}.`);return pe}o(mx,"readIdJagGrantedScope");function hx(e){if(e!==void 0&&e.get("dpop")!==null)throw new T("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}o(hx,"assertNoDpopProofForIdJag");function s_(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new T("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new T("invalid_client","Malformed HTTP Basic client authentication.")}}o(s_,"readBasicClientSecret");function i_(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new T("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=QP(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new T("invalid_client","Malformed private_key_jwt client assertion.")}throw new T("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new T("invalid_client","Client authentication or client_id is required.")}o(i_,"resolveAuthenticatedClientId");function fx(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(fx,"resolveClientSecretInput");function gx(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(gx,"hasClientAssertion");function yx(e){if(e.requestUrl===void 0)throw new T("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(ge().actionPath(e.pathname),ie(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}o(yx,"buildEndpointAudience");function Sx(e){return e instanceof Go.JWTExpired?"expired":e instanceof Go.JWTClaimValidationFailed?"claim":e instanceof Go.JWSSignatureVerificationFailed?"signature":e instanceof Go.JWKSNoMatchingKey?"jwks_no_match":e instanceof Go.JWTInvalid?"invalid":e instanceof p.ZodError?"schema":"other"}o(Sx,"readJwtFailureKind");async function _x(e){let{response:t,json:r}=await pg(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:ox,maxResponseBytes:nx,timeoutMs:rx});if(!t.ok)throw new T("invalid_client","Client JWKS could not be fetched.");return dx.parse(r)}o(_x,"fetchClientJwks");async function wx(e){if(e.clientAssertionType!==Hs||e.clientAssertion===void 0)throw new T("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=mt.parse(e.clientId),r=await zi(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new T("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new T("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=yx({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await _x({jwksUri:n,context:e.context}),{payload:a}=await ex(e.clientAssertion,XP(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+sx;if(typeof a.exp!="number"||a.exp>c)throw new T("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Sx(i)},"OAuth private_key_jwt client authentication failed"),new T("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(wx,"verifyPrivateKeyJwtClientAssertion");async function Rx(e){let t=mt.parse(e.clientId);if(Wm(t))throw new T("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await ae(e.clientSecret)}}o(Rx,"buildRuntimeHttpClientAuth");async function a_(e){if(gx({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new T("invalid_request","Use only one client authentication method per request.");return wx(e)}let t=fx({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Rx({clientId:e.clientId,...t})}o(a_,"resolveRuntimeHttpClientAuth");async function c_(e){ax(e.body);let t=ix.parse(e.body),r=s_(e.authorizationHeader),n=i_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await a_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:s,context:e.context});return bx({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(c_,"exchangeDownstreamToken");async function bx(e){if(e.parsed.grant_type==="authorization_code"){ln(e.parsed.redirect_uri,"invalid_request"),pn(e.parsed.scope),e.parsed.resource!==void 0&&lr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=ht(),d=ht(),u=J(pt(e.now,ux())),m=n_(e.now,u),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await ae(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Ks(e.parsed.code_verifier),currentRefreshTokenHash:await ae(c),accessTokenHash:await ae(d),grantExpiresAt:u,accessTokenExpiresAt:m.expiresAt,now:J(e.now)});if(h.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new T("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:m.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===Ot){pn(e.parsed.scope),hx(e.requestHeaders);let c=await r_({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:Ee()}),d=lx({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=lr(e.requestUrl??d,d,e.requestHeaders),m=px({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=mx({claimScope:c.claims.scope,grantedAuthorizationDetails:m}),f=ht(),S=J(new Date(c.claims.exp*1e3)),R=n_(e.now,S),_=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await ae(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:m,accessTokenExpiresAt:R.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:S}});if(_.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(_.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:f,token_type:"Bearer",expires_in:R.expiresIn,scope:_.grant.scope,resource:_.grant.resource,...m===void 0?{}:{authorization_details:m}}}pn(e.parsed.scope),e.parsed.resource!==void 0&&lr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await ae(e.parsed.refresh_token),r=e.parsed.refresh_token,n=ht(),s=J(pt(e.now,o_())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await ae(n),resource:e.parsed.resource,accessTokenExpiresAt:s,now:J(e.now)});if(i.kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new T("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new T("invalid_grant","Refresh token is invalid, expired, or revoked.");lr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(bx,"exchangeDownstreamTokenWithRuntimeHttp");async function d_(e){let t=cx.parse(e.body),r=s_(e.authorizationHeader),n=i_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await a_({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:s,context:e.context}),tokenHash:await ae(t.token),now:J(s)})).kind==="invalid_client")throw new T("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&te(e.context,{eventType:V.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(d_,"revokeDownstreamToken");var vx=64*1024,Cx=16*1024,Ix="text/html; charset=utf-8";function Tx(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(Tx,"formDataToObject");async function Ex(e){return By(e,{maxBytes:vx,label:"Request body"})}o(Ex,"readJsonBody");async function Rd(e){return Tx(await Fy(e,{maxBytes:Cx,label:"Request body"}))}o(Rd,"readFormBody");async function u_(e,t,r){let n=lt(r),s=r instanceof p.ZodError?Ht(r):void 0,i={code:n??(r instanceof p.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),Ns(e,t,i)}o(u_,"handleProblem");function l_(e){return e?.requestId}o(l_,"readBrowserRequestId");function p_(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[$r];return typeof t=="string"?t:void 0}o(p_,"readUpstreamHtmlError");function mn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(mn,"readRuntimeErrorExtensionString");function kx(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(kx,"readRuntimeErrorExtensionNumber");function Ax(e){try{return new URL(e.url).pathname}catch{return}}o(Ax,"readBrowserRequestPath");function pr(e){let t={code:e.code,requestId:e.requestId,routePath:Ax(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=kx(e.error,dt),t.contentType=mn(e.error,Lr),t.upstreamUrl=mn(e.error,ut),t.upstreamServerId=mn(e.error,qs),t.metadataUrl=mn(e.error,Hr),t.providerError=mn(e.error,Br),t.providerErrorDescription=mn(e.error,Fr)),t}o(pr,"buildBrowserErrorDiagnostic");function Ko(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Ko,"oauthErrorResponse");function Px(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(Px,"readOAuthProtocolHeaders");function xx(e,t){let r=et("internal_server_error");return Ko({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Px(e,t)})}o(xx,"oauthProtocolErrorResponse");function wd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(wd,"readZodOAuthErrorCode");function Ox(e){let t={error:wd(e)},r=Ht(e);return r!==void 0&&(t.errorDescription=r),Ko(t)}o(Ox,"oauthZodErrorResponse");function Mx(e){let t=lt(e);if(t===void 0)return;let r=et(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:qx(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ko(n)}o(Mx,"oauthGatewayProblemResponse");function Ux(){let t={error:"server_error",status:500,errorDescription:et("internal_server_error").publicDetail};return Ko(t)}o(Ux,"oauthFallbackErrorResponse");function qx(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(qx,"readOAuthStatus");function bd(e,t={}){return e instanceof $t?f_(e):e instanceof T?xx(e,t):e instanceof p.ZodError?Ox(e):Mx(e)??Ux()}o(bd,"oauthProblemResponse");function vd(e,t,r){let n=Lt(e.url),s=l_(t);if(r instanceof $t)return f_(r);if(r instanceof T){let c=et("internal_server_error");return We({host:n,kind:zx(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?c.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?c.publicDetail:r.message,code:r.errorCode,diagnostic:pr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Ht(r)??"The authorization request was invalid.",developerDetail:Ht(r)??"The authorization request was invalid.",code:wd(r),diagnostic:pr({request:e,requestId:s,code:wd(r),underlyingError:Ht(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=lt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:h_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:pr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:p_(r),status:c.status})}let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:pr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(vd,"browserOAuthProblemResponse");function m_(e,t,r){let n=Lt(e.url),s=l_(t),i=lt(r);if(i!==void 0){let c=et(i);return We({host:n,kind:h_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:pr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:p_(r),status:c.status})}if(r instanceof p.ZodError)return We({host:n,kind:"invalid_request",detail:Ht(r)??"The authorization request was invalid.",developerDetail:Ht(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:pr({request:e,requestId:s,code:"invalid_request",underlyingError:Ht(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=et("internal_server_error");return We({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:pr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(m_,"browserGatewayProblemResponse");function zx(e){return e==="server_error"?"internal_error":"invalid_request"}o(zx,"readOAuthBrowserErrorKind");function h_(e){if(et(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(h_,"readGatewayBrowserErrorKind");function vt(e,t,r){let n={event:t},s=!1;if(r instanceof T)n.oauthError=r.errorCode,n.status=r.status,ke(n,"error",r);else if(r instanceof $t)n.oauthError=r.errorCode,ke(n,"error",r);else if(r instanceof p.ZodError){n.code="invalid_request",ke(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=lt(r);if(i!==void 0){let a=et(i);n.code=i,n.status=a.status,a.oauthError!==void 0&&(n.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",ke(n,"error",r)}else s=!0,ke(n,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(vt,"logUnexpectedOAuthHandlerError");function f_(e){let t;try{t=new URL(e.redirectUri)}catch{return Ko({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),qi(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(f_,"downstreamAuthorizeRedirectErrorResponse");function Ht(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Ht,"formatZodErrorDetail");function Nx(e,t){let r={event:"browser_login_callback_failed",code:lt(t)??"invalid_request"};ke(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(Nx,"logBrowserLoginCallbackFailure");function g_(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(null,{status:302,headers:t})}o(g_,"redirectResultResponse");function Ni(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Ix,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(e.html,{status:200,headers:t})}return g_(e)}o(Ni,"authorizeResultResponse");async function y_(e,t){try{return Response.json(Dm(e.url,e.headers))}catch(r){return vt(t,"oauth_authorization_server_metadata_failed",r),u_(e,t,r)}}o(y_,"authorizationServerMetadataHandler");async function S_(e,t){try{let r=ga(e.params.routePath);return Response.json(Lm({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return vt(t,"oauth_authorization_server_metadata_failed",r),u_(e,t,r)}}o(S_,"scopedAuthorizationServerMetadataHandler");async function __(e,t){try{let r=await vS(await Ex(e)),n=r.client_id,s=r.client_name,i=r.redirect_uris.length,a=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:n,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),te(t,{eventType:V.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:n,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return vt(t,"oauth_register_failed",r),bd(r)}}o(__,"registerHandler");async function w_(e,t){try{return Ni(await Sd(e,{context:t}))}catch(r){return vt(t,"oauth_authorize_failed",r),vd(e,t,r)}}o(w_,"authorizeHandler");async function R_(e,t){try{let r=ga(e.params.routePath);return Ni(await Sd(e,{operationId:r.operationId,context:t}))}catch(r){return vt(t,"oauth_authorize_scoped_failed",r),vd(e,t,r)}}o(R_,"scopedAuthorizeHandler");async function b_(e,t){try{let r=await GS(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ni(r)}catch(r){return Nx(t,r),m_(e,t,r)}}o(b_,"callbackHandler");async function v_(e,t){try{return g_(await WS(e))}catch(r){return vt(t,"oauth_dev_login_failed",r),vd(e,t,r)}}o(v_,"devLoginHandler");async function C_(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await ZS({request:e,body:e.method==="POST"?await Rd(e):void 0,context:t});return Ni(r)}catch(r){return vt(t,"oauth_setup_failed",r),m_(e,t,r)}}o(C_,"setupHandler");async function I_(e,t){try{return Response.json(await c_({body:await Rd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return vt(t,"oauth_token_failed",r),bd(r)}}o(I_,"tokenHandler");async function T_(e,t){try{return await d_({body:await Rd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return vt(t,"oauth_revoke_failed",r),bd(r)}}o(T_,"revokeHandler");var E_="0.0.0",jx=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function Wo(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}o(Wo,"firstNonBlank");function Zo(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}o(Zo,"clampToCodePoints");function Dx(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}o(Dx,"shortHash");function k_(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${Dx(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(k_,"clampNameSegment");function Lx(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(Lx,"sanitizeRegistryNameSegment");var $x=/^\d{1,3}(\.\d{1,3}){3}$/u;function Hx(e){let t=new URL(e).hostname.toLowerCase();if($x.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(n=>n.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(n=>n.length>0);return r.length>0?r.join("."):"local"}o(Hx,"buildRegistryNamespaceFromOrigin");function Bx(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}o(Bx,"sanitizeWebsiteUrl");function Fx(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let n;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;n=i.toString()}catch{continue}if(n.length>255||r.mimeType!==void 0&&!jx.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:n,...r.mimeType===void 0?{}:{mimeType:r.mimeType},...s===void 0||s.length===0?{}:{sizes:s},...r.theme===void 0?{}:{theme:r.theme}})}return t.length>0?t:void 0}o(Fx,"sanitizeIcons");function Jx(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(Jx,"localNameFromRoutePath");function A_(e){return e.includes("{")||e.includes(":")}o(A_,"isParameterizedRoutePath");var Vx=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function P_(e){let t=Wo(e)??E_;return Vx.test(t)?E_:Zo(t,255)}o(P_,"sanitizeRegistryVersion");function x_(e){let t=k_(Hx(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=k_(Lx(c),r),u=d;for(let m=2;n.has(u);m++){let h=`-${m}`;u=`${[...d].slice(0,r-h.length).join("")}${h}`}return n.add(u),u}o(i,"claimLocalName");function a(c,d){let u=`${t}/${i(c)}`;s.push({name:u,response:{server:{...d,name:u},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}o(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(A_(c.routePath))continue;let d=c.connection,u=d?.serverInfo,m=Zo(Wo(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=Wo(u?.title,d?.displayName),f=Bx(u?.websiteUrl),S=Fx(u?.icons);a(c.operationId,{description:m,...h===void 0?{}:{title:Zo(h,100)},version:P_(u?.version),...f===void 0?{}:{websiteUrl:f},...S===void 0?{}:{icons:S},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(A_(c.routePath))continue;let d=c.operationId??Jx(c.routePath),u=Zo(Wo(c.summary,c.description,c.serverName,c.operationId,d)??d,100),m=Wo(c.serverName);a(d,{description:u,...m===void 0?{}:{title:Zo(m,100)},version:P_(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o(x_,"buildMcpRegistryDirectory");var Gx=30,O_=100;function rt(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(rt,"registryErrorResponse");function Id(e){return x_({registry:Ce(),origin:ie(e.url,e.headers)})}o(Id,"readEntries");function Cd(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}o(Cd,"decodePathParam");function M_(e,t){return e.find(r=>r.name===t)}o(M_,"findEntryByName");function Kx(e){let t=e.get("limit");return t===null?{ok:!0,value:Gx}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),O_)}}o(Kx,"parseLimit");function Wx(e){let t=e.get("cursor");return t===null?{ok:!0,value:0}:/^\d+$/u.test(t)?{ok:!0,value:Number.parseInt(t,10)}:{ok:!1}}o(Wx,"parseCursor");var Zx=/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(\.\d+)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;function Yx(e){let t=Zx.exec(e);if(!t)return!1;let[,r,n,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(n)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(n)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}o(Yx,"isValidRfc3339Timestamp");async function U_(e,t){let r=new URL(e.url).searchParams,n=Kx(r);if(!n.ok)return rt(400,`Invalid 'limit' parameter: expected a positive integer (max ${O_}).`);let s=Wx(r);if(!s.ok)return rt(400,"Invalid 'cursor' parameter: pass the exact 'metadata.nextCursor' value returned by a previous list response.");let i=r.get("updated_since");if(i!==null&&!Yx(i))return rt(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let a=r.get("search")?.toLowerCase(),c=r.get("version"),d=Id(e).sort((h,f)=>h.name<f.name?-1:h.name>f.name?1:0);a!==void 0&&a!==""&&(d=d.filter(h=>h.name.toLowerCase().includes(a))),c!==null&&c!=="latest"&&(d=d.filter(h=>h.response.server.version===c));let u=d.slice(s.value,s.value+n.value),m=s.value+n.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...m<d.length?{nextCursor:String(m)}:{}}})}o(U_,"listMcpRegistryServersHandler");async function q_(e,t){let r=Cd(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=M_(Id(e),r.value);return n===void 0?rt(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(q_,"listMcpRegistryServerVersionsHandler");async function z_(e,t){let r=Cd(e.params.serverName);if(!r.ok)return rt(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Cd(e.params.version);if(!n.ok)return rt(400,"Invalid version: malformed encoding.");let s=M_(Id(e),r.value);return s===void 0?rt(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?rt(404,"Server or version not found"):Response.json(s.response)}o(z_,"getMcpRegistryServerVersionHandler");function ji(e,t){return(r,n)=>rt(e,t)}o(ji,"createWriteNotSupportedHandler");async function N_(e,t){return rt(404,"Not found")}o(N_,"mcpRegistryNotFoundHandler");var j_=ji(501,"Publishing is not supported by this registry"),D_=ji(501,"Updates are not supported by this registry"),L_=ji(501,"Deletion is not supported by this registry"),Td=ji(403,"You do not have publish or edit permissions for this server");function $_(e){return W`<section class="page-section" aria-labelledby="result-next-steps"><h2 class="section-label" id="result-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol></section>`}o($_,"renderBrowserResult");var Xx="text/html; charset=utf-8";function Qx(e){return an({title:e.title,iconHref:bc(e.host),styles:sn,headerIcon:xi("success"),heading:e.title,subhead:W`<p class="card__subtitle">${e.detail}</p>`,body:$_({steps:nn(e.steps.map(t=>W`<li>${t}</li>`))}),footer:""})}o(Qx,"browserResultHtml");function eO(e,t=200){return new Response(on(e),{status:t,headers:{"content-type":Xx,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(eO,"browserResultResponse");function H_(e){return eO(Qx(e))}o(H_,"browserConnectionSuccessResponse");function Di(e,t,r={}){let n=vm(t);return We({host:e,kind:tO(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(Di,"browserConnectionFailureResponse");function tO(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}o(tO,"readCallbackFailureBrowserErrorKind");var rO={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},B_=Symbol("upstream-request");function Yo(e,t){Object.defineProperty(e,B_,{configurable:!0,value:t})}o(Yo,"setUpstreamRequestContext");function nO(e){let t=e[B_];if(!t)throw new Te("Upstream request context has not been set");return t}o(nO,"readUpstreamRequestContext");function oO(e,t){return t.some(r=>r===e)}o(oO,"requestContextMatchesKind");function sO(e){return typeof e=="string"?[e]:e}o(sO,"toExpectedKinds");function Xo(e,t){let r=nO(e),n=sO(t);if(!oO(r.kind,n)){let s=rO[n[0]];throw new Te(`${s} request context has not been set`)}return r}o(Xo,"requireUpstreamRequestContext");function Bt(e){if(typeof e=="string"&&e.length!==0)return e}o(Bt,"readOptionalQueryString");function iO(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Te(`Validated path parameter ${t} is missing`);return aO(r,t)}o(iO,"requirePathString");function aO(e,t){try{return decodeURIComponent(e)}catch(r){throw new k({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[O]:"invalid_request"}},{cause:r})}}o(aO,"decodePathString");function cO(e){let t=Bt(e);return t?js.parse(t):void 0}o(cO,"readOptionalOperationId");function dO(e){let t=Ce().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new k({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[O]:"unknown_upstream_server"}})}o(dO,"readRegisteredAuthProfileId");function uO(e){let t=cO(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[O]:"invalid_request"}});return t}o(uO,"readRequiredOperationId");async function Ed(e){return e.redirect?We({host:Lt(e.request.url),kind:"authorization_failed",title:e.title,detail:e.detail,code:e.status===401?"authentication_required":"forbidden",requestId:e.context.requestId,status:e.status}):e.status===401?Ne.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):Ne.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}o(Ed,"browserConnectRefusal");function lO(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let n of t)r.append("set-cookie",n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(lO,"withSetCookies");async function pO(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(_m(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await Ed({request:t,context:r,redirect:s,status:403,title:"Ask an administrator",detail:"This gateway cannot confirm who opened this link, so it cannot connect an account from it. Ask an administrator to connect this service."});let i=await un(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return lO(await Ed({request:t,context:r,redirect:s,status:401,title:"Sign in required",detail:"Open this connect link in a browser. The gateway asks you to sign in before it connects an account."}),a);let d=new URL(t.url),u=wo(`${d.pathname}${d.search}`);if(u===void 0)throw new Te("Connect request path is empty");let m=await KS({returnTo:u,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:m.location.toString(),"cache-control":"no-store"});for(let f of[...a,m.setCookie])h.append("set-cookie",f);return new Response(null,{status:302,headers:h})}let c=n.ownerMode==="user"?n.ownerSubjectId:n.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await Ed({request:t,context:r,redirect:s,status:403,title:"This link is for another account",detail:"This connect link was created for a different gateway user, so it cannot connect an account in this browser. Ask your MCP client for its own connect link, or sign in to the gateway as the user who received this one."})}o(pO,"requireTicketOwnerBrowser");async function mO(e,t,r){let n=Ai(r,uO(e.query.operationId));if(n.authMode==="id-jag")throw new k({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[O]:"invalid_request"}});let s=e.query.redirect==="true",i=Bt(e.query.browserTicket);if(e.user){if(i)throw new k({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[O]:"invalid_request"}});let d=ar(e.user,e.url),u={kind:"connect",...tn(n,d.subjectId),redirect:s},m=wo(Bt(e.query.returnTo));return m!==void 0&&(u.returnTo=m),u}if(!i)throw new k({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[O]:"authentication_required"}});let a=await Eg(i);if(a.ownerMode!==n.ownerMode||a.upstreamServerId!==n.upstreamServerId||a.authProfileId!==n.authProfileId||a.operationId!==n.operationId)throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});if(zt()){let d=await pO({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await kg(a);let c=Ds(a);switch(n.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}case"user-oauth":{if(c.mode!=="user")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[O]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}o(mO,"resolveConnectContext");async function hO(e,t,r){let n=Im.parse(iO(e,"connection"));switch(r){case"connect":{let s=await mO(e,t,n);if(s instanceof Response)return s;Yo(e,s);return}case"callback":{let s=Bt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Bt(e.query.error_description);d!==void 0&&(c.errorDescription=d),Yo(e,c);return}let i=Bt(e.query.code),a=Bt(e.query.state);if(i&&a){let c=Bt(e.query.iss);Yo(e,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:a,...c===void 0?{}:{iss:c}});return}Yo(e,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":Yo(e,{kind:"client_metadata",upstreamServerId:n,authProfileId:dO(n)});return}}o(hO,"resolveUpstreamRequestInbound");async function fO(e,t,r){try{return await hO(e,t,r)}catch(n){let s=n instanceof k?n.extensionMembers?.[O]:void 0,i=n instanceof Error?n.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return Ne.badRequest(e,t,{code:s,detail:i});case"authentication_required":return Ne.unauthorized(e,t,{code:s,detail:i});default:throw n}}}o(fO,"applyUpstreamRequestContext");function Li(e,t){return o(async(n,s)=>{let i=await fO(n,s,e);return i||t(n,s)},"wrapped")}o(Li,"withUpstreamRequestContext");var gO=["callback_authorization_code","callback_provider_error","callback_invalid"];function kd(e){try{return new URL(e.url).pathname}catch{return}}o(kd,"readBrowserRequestPath");function yO(e){return"cause"in e?e.cause:void 0}o(yO,"readErrorCause");function SO(e){return e.stack?.split(`
44
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(SO,"readFirstStackFrame");function F_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=SO(r))}o(F_,"addErrorAttributes");function Ad(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[O];return zs(t)?t:void 0}o(Ad,"readRuntimeGatewayCode");function Qo(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(Qo,"readRuntimeErrorExtensionString");function _O(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(_O,"readRuntimeErrorExtensionNumber");function wO(e,t,r,n){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),te(t,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),Di(n,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:kd(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Di(n,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:kd(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}o(wO,"requireAuthorizationCallbackRequest");function RO(e,t){te(e,{eventType:V.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(RO,"emitCallbackReceivedAnalyticsEvent");function bO(e,t){te(e,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(bO,"emitTokenExchangeSucceededAnalyticsEvent");function vO(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return H_({host:Lt(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}o(vO,"buildSuccessfulCallbackResponse");function CO(e){let t={detail:e instanceof Error?e.message:void 0};return F_(t,"error",e),e instanceof Error&&F_(t,"cause",yO(e)),t}o(CO,"buildTokenExchangeFailureAttributes");function IO(e){te(e.context,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Ad(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:CO(e.error)})}o(IO,"emitTokenExchangeFailedAnalyticsEvent");function TO(e){let t=e.error,r=Ad(t),n=bm(r)?r:"upstream_token_exchange_failed",s={code:n,requestId:e.context.requestId,routePath:kd(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof k?{httpStatus:_O(t,dt),contentType:Qo(t,Lr),upstreamUrl:Qo(t,ut),metadataUrl:Qo(t,Hr),providerError:Qo(t,Br),providerErrorDescription:Qo(t,Fr)}:{}};return Di(e.host,n,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:EO(t)})}o(TO,"tokenExchangeFailureResponse");function J_(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(J_,"withSetCookie");function EO(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[$r];return typeof t=="string"?t:void 0}o(EO,"readUpstreamHtmlError");async function Pd(e,t){let r=Xo(e,gO),n=Lt(e.url),s=wO(e,t,r,n);if(s instanceof Response)return s;RO(t,s);let i;try{let a=await gy({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return bO(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),J_(vO(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:Ad(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return ke(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),IO({context:t,callbackRequest:s,error:a}),J_(TO({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(Pd,"callbackHandler");function kO(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(kO,"clientMetadataProblemDetail");async function V_(e,t){let r=Xo(e,"connect"),n=r.redirect?await $o({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:vi/1e3}):void 0,s=await fy({request:e,connectRequest:r,...n===void 0?{}:{browserBinding:n.claim}});if(te(t,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),n!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":n.setCookie,"cache-control":"no-store"}});let i=await Ii({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}o(V_,"connectHandler");async function G_(e,t){let r=Xo(e,"client_metadata");try{let n=ie(e.url,e.headers),s=Dg(n,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(n){if(!(n instanceof ee))throw n;let s=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),Ne.notFound(e,t,{code:"not_found",detail:kO(n)})}}o(G_,"oauthClientMetadataHandler");function AO(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(AO,"resolveInternalRoutePath");var PO={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function xO(){return new Response(null,{status:204,headers:PO})}o(xO,"buildWellKnownPreflightResponse");function OO(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(OO,"withWellKnownCorsHeaders");function mr(e){return async(t,r)=>t.method==="OPTIONS"?xO():OO(await e(t,r))}o(mr,"wrapWellKnownHandler");var K_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:mr(y_),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:mr(S_),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:mr($m),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:__},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:w_},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:R_},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:b_},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:v_},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:C_},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:I_},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:T_},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Li("client_metadata",G_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Li("connect",V_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Li("callback",Pd)}],MO=K_.filter(e=>!e.routeName.startsWith("upstream_")),UO=K_.filter(e=>e.routeName.startsWith("upstream_"));function qO(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:mr(U_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:mr(q_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:mr(z_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:j_},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:D_},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:L_},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Td},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Td},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:mr(N_),corsPolicy:"anything-goes"}]}o(qO,"buildMcpRegistryInternalRoutes");function zO(e){let t=Pm({routes:e.routes,policies:e.policies,gateway:e.gateway});return xm(t),t}o(zO,"initializeMcpGatewayConnectionRegistry");function NO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(NO,"hasDownstreamOAuthRoutes");function jO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(jO,"hasIdJagDownstreamOAuth");function DO(e){let t=new Map;for(let n of e.byOperationId.values())n.downstreamOAuth&&t.set(n.downstreamOAuth.policyName,n.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new Te("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(n=>`"${n}"`).join(", ");throw new ee(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}o(DO,"readSingletonDownstreamOAuthConfig");function LO(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(qm(n));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?Ns(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}o(LO,"readScopedDownstreamOAuthConfig");function $O(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o($O,"routeUsesScopedOAuthConfig");function xd(e,t,r){return async(n,s)=>{if(s.log.setLogProperties?.({requestId:s.requestId}),r){let d=await r(n,s);if(d instanceof Response)return d;d&&Sm(s,d)}let i=n.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:n.method},`MCP gateway: ${e} received`);let c=await t(n,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}o(xd,"wrapInternalHandler");function Od(e,t,r,n){e.addPluginRoute({path:AO(t,r),methods:t.methods,handler:n,processors:[ou],corsPolicy:t.corsPolicy??"none"})}o(Od,"addInternalRoute");function W_(e,t){let r=zO(t);if(r.gateway.registry.enabled){ot("plugin.mcp-gateway.registry");for(let c of qO(r.gateway.registry))Od(e,c,r.gateway,xd(c.routeName,c.handler))}let n=NO(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=DO(r)),i),"readSingletonOAuthConfig");if(n){ot("plugin.mcp-gateway.downstream-oauth"),jO(r)&&ot("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of MO){let d=$O(c)?(u,m)=>LO(r,u,m):a;Od(e,c,r.gateway,xd(c.routeName,c.handler,d))}}if(s){ot("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())ot(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of UO)Od(e,c,r.gateway,xd(c.routeName,c.handler,n?a:void 0))}}o(W_,"registerMcpGatewayInternalRoutes");var Md=class extends nu{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),ot("plugin.mcp-gateway"),this.#e=wm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&W_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as Dw}from"@opentelemetry/api";var zd=256*1024,es=34,HO=92,hn=123,fn=125,$i=91,ts=93,rs=44,Ud=58,Q_=new Set(["jsonrpc","method","id"]),ew=new Set(["name","uri"]),tw=new Set([Ms]),rw="_meta",nw=[...Q_,...ew,...tw,"params",rw],ow=Math.max(...nw.map(e=>e.length)),BO=ow+2,FO=ow*6+2,JO=1024,VO=1e3,Z_=new TextDecoder("utf-8",{fatal:!0}),qd=class{constructor(t,r){this.bytes=t;this.readMetaProtocolVersion=r}bytes;readMetaProtocolVersion;static{o(this,"EnvelopeScanner")}pos=0;scan(){let t=this.bytes;t[0]===239&&t[1]===187&&t[2]===191&&(this.pos=3),this.skipWhitespace();let r;return t[this.pos]===hn?r=this.readObject():t[this.pos]===$i?r=this.readBatch():this.fail(),this.skipWhitespace(),this.expect(this.pos===t.length),r}readBatch(){let t=[];if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===ts)return this.pos++,t;for(;;){if(this.skipWhitespace(),this.bytes[this.pos]===hn){let n=this.readObject();(n.id!==void 0||n.method!==void 0)&&(this.expect(t.length<VO),t.push(n))}else this.skipValue();this.skipWhitespace();let r=this.bytes[this.pos++];if(r===ts)return t;this.expect(r===rs)}}fail(){throw new SyntaxError("Unscannable request body")}expect(t){t||this.fail()}skipWhitespace(){for(;;){let t=this.bytes[this.pos];if(t!==32&&t!==10&&t!==13&&t!==9)return;this.pos++}}skipString(){this.expect(this.bytes[this.pos]===es),this.pos++;let t=!1;for(;;){let r=this.bytes[this.pos++];if(r===es)return t;r===HO?(t=!0,this.pos++):this.expect(r!==void 0)}}skipValue(){this.skipWhitespace();let t=this.bytes[this.pos];if(t===es){this.skipString();return}if(t!==void 0&&t!==hn&&t!==$i&&t!==fn&&t!==ts&&t!==rs&&t!==Ud){for(;!Y_(this.bytes[this.pos]);)this.pos++;return}let r=[];for(;;){this.skipWhitespace();let n=this.bytes[this.pos];if(this.expect(n!==void 0),n===es)this.skipString();else if(n===hn||n===$i){r.push(n),this.pos++;continue}else if(n===fn||n===ts)this.expect(r.pop()===(n===fn?hn:$i)),this.pos++;else if(n===rs||n===Ud){this.expect(r.length>0),this.pos++;continue}else for(;!Y_(this.bytes[this.pos]);)this.pos++;if(r.length===0)return}}readKey(){let t=this.pos,r=this.skipString(),n=this.pos-t;if(r)return n>FO?void 0:JSON.parse(Z_.decode(this.bytes.subarray(t,this.pos)));if(n>BO)return;let s=n-2;for(let i of nw){if(i.length!==s)continue;let a=0;for(;a<s&&this.bytes[t+1+a]===i.charCodeAt(a);)a++;if(a===s)return i}}readObject(t="message"){let r=t==="message"?Q_:t==="params"?ew:tw,n=t==="message"?"params":t==="params"&&this.readMetaProtocolVersion?rw:void 0,s={};if(this.pos++,this.skipWhitespace(),this.bytes[this.pos]===fn)return this.pos++,s;for(;;){this.skipWhitespace();let i=this.readKey();this.skipWhitespace(),this.expect(this.bytes[this.pos++]===Ud),this.skipWhitespace();let a=this.pos;if(n!==void 0&&i===n)if(delete s[n],this.bytes[a]===hn){let d=this.readObject(t==="message"?"params":"meta");Object.keys(d).length>0&&(s[n]=d)}else this.skipValue();else if(this.skipValue(),i!==void 0&&r.has(i)){delete s[i];let d=this.readPrimitive(a);(t==="meta"?Us(d):typeof d=="string"||typeof d=="number"&&i==="id")&&(s[i]=d)}this.skipWhitespace();let c=this.bytes[this.pos++];if(c===fn)return s;this.expect(c===rs)}}readPrimitive(t){let r=this.bytes[t];if(!(r===es||r===45||r>=48&&r<=57)||this.pos-t>JO)return;let s=Z_.decode(this.bytes.subarray(t,this.pos)),i=JSON.parse(s);return typeof i=="number"&&!sw(s,i)?void 0:i}};function Y_(e){return e===void 0||e===rs||e===fn||e===ts||e===32||e===10||e===13||e===9}o(Y_,"isDelimiter");function GO(e,t){try{return new qd(new Uint8Array(e),t).scan()}catch{return{}}}o(GO,"sniffEnvelope");var KO=/^(-)?(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function X_(e){let t=KO.exec(e);if(!t)return;let[,r,n,s="",i]=t,a=`${n}${s}`.replace(/^0+/,""),c=Number(i??0)-s.length;if(a==="")return"0";let d=/0*$/.exec(a)?.[0].length??0;return a=a.slice(0,a.length-d),c+=d,`${r??""}${a}e${c}`}o(X_,"canonicalDecimal");function sw(e,t){if(!Number.isFinite(t)||Object.is(t,-0))return!1;let r=X_(e),n=X_(JSON.stringify(t));return r!==void 0&&r===n}o(sw,"isLosslessNumberLiteral");function iw(e){let t=!0,r=o((n,s,i)=>(typeof s=="number"&&t&&(t=typeof i?.source=="string"&&sw(i.source,s)),s),"reviver");try{JSON.parse(new TextDecoder().decode(e),r)}catch{return!1}return t}o(iw,"jsonRoundTrips");function aw(e,t={}){if(!(e===void 0||e.byteLength===0)){if(e.byteLength>zd)return{value:GO(e,t.readMetaProtocolVersion===!0)};try{return{value:JSON.parse(new TextDecoder().decode(e))}}catch{return}}}o(aw,"parseRequestJson");var WO="zuplo_mcp_",ZO=["__host-","__secure-"];function YO(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of ZO)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(WO)}o(YO,"setsGatewayCookie");function cw(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!YO(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let n=new Headers(e.headers);n.delete("clear-site-data"),n.delete("set-cookie");for(let s of r)n.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}o(cw,"stripUpstreamOriginStateHeaders");function Ze(e){return e&&typeof e=="object"?e:void 0}o(Ze,"readRecord");function ns(e,t){let r=Ze(e)?.[t];return typeof r=="string"?r:void 0}o(ns,"readStringProperty");function uw(e,t){let r=Ze(e)?.[t];return typeof r=="number"?r:void 0}o(uw,"readNumberProperty");function dw(e,t){return uw(e,"code")??(t>=400?t:void 0)}o(dw,"readErrorCode");function lw(e){return Array.isArray(e)?e.map(lw).find(t=>t?.method):Ze(e)}o(lw,"readJsonRpcMessage");function Nd(e){let t=lw(e),r=typeof t?.method=="string"?t.method:"",n=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:ns(n,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:ns(n,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=ns(n,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}o(Nd,"buildBaseCapabilityInput");function Hi(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}o(Hi,"isCapabilityListMethod");function XO(e,t,r){let i=Ze(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}o(XO,"readItemCount");function pw(e){let t=Nd(e);return!t||Hi(t.mcpMethod)?null:{eventType:V.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(pw,"buildCapabilityInvokedAnalyticsInput");function QO(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}o(QO,"readMissingResponseFailure");function mw(e,t,r={}){let n=Nd(e);if(!n)return null;let s=Ze(t.message),i=Ze(s?.error),a=Ze(i?.data),c=s?.result,d=n.mcpMethod==="tools/call"&&Ze(c)?.isError===!0,u=Ze(c),m=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&Ze(Ze(u.inputRequests)?.[Nr])!==void 0;if(Ze(a?.connectRequired)||m)return{eventType:V.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...n,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:uw(i,"code"),mcpErrorType:ns(i,"message")};let h=t.status<400?QO(t):void 0;if(h&&!i)return{eventType:Hi(n.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,...h};if(Hi(n.mcpMethod)){let f=t.status>=400?void 0:XO(n.mcpMethod,n.capabilityType,c),S=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:V.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...n,httpStatusCode:t.status,...S?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:dw(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:V.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:dw(i,t.status),mcpErrorType:ns(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:"success",...n,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...n,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}o(mw,"buildCapabilityFinalAnalyticsInput");function hw(e,t){let r=Nd(e);return r?{eventType:Hi(r.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}o(hw,"buildCapabilityThrownAnalyticsInput");var jd={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},fw={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},gw={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};import{context as eM,TraceFlags as tM,trace as rM}from"@opentelemetry/api";var yw="mcp-session-id",nM=256*1024;function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(gn,"isPlainObject");function oM(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(oM,"isJsonContentType");function Sw(e,t,r){if(t===void 0||r===void 0||r.byteLength>zd||!oM(e))return;let n=t.value;if(!gn(n)||typeof n.method!="string"||n.params!==void 0&&!gn(n.params))return;let s=n.id;return{message:n,method:n.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...n.params===void 0?{}:{params:n.params},...typeof n.jsonrpc=="string"?{jsonrpc:n.jsonrpc}:{}}}o(Sw,"parseMcpRequestMessage");function Dd(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}o(Dd,"readStringParam");function sM(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Dd(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Dd(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Dd(e.params,"uri")};default:return{}}}o(sM,"readCapability");function _w(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(_w,"readHeader");function iM(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let n=new URL(r.__rewriteFunction(e,su(t))),s=n.port!==""?Number(n.port):n.protocol==="https:"?443:n.protocol==="http:"?80:void 0;return{serverAddress:n.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}o(iM,"readUpstreamServer");function ww(e){let{request:t,context:r,parsed:n}=e,s=sr(t.headers,n.message),i=_w(t.headers,yw),a={methodName:n.method,...sM(n),...n.id===void 0?{}:{jsonRpcRequestId:n.id},...n.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:n.jsonrpc},...i===void 0?{}:{mcpSessionId:i}},c=mm({...a,mcpProtocolVersion:s??um,params:n.params}),d;try{Ki(c.span);let u=c.span.isRecording()||pm()?iM(t,r):{};return d=eM.with(c.ctx,()=>hm({...a,...s===void 0?{}:{mcpProtocolVersion:s},...u})),Ki(d.span),nm(r,c.span.spanContext()),{server:c,client:d}}catch(u){throw Ld(d===void 0?[c]:[d,c]),u}}o(ww,"startMcpProxySpans");var aM=["content-digest","repr-digest","digest","content-md5"];function cM(e){return aM.some(t=>e.has(t))}o(cM,"hasBodyIntegrityHeader");function Rw(e,t,r,n){let s=rM.getSpanContext(t.client.ctx);if(r.byteLength>nM||n!==void 0&&cM(n)||s===void 0||(s.traceFlags&tM.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!gn(i))return r;try{let a=da(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!iw(r))return r;let c=da(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}o(Rw,"injectTraceContextIntoBody");function dM(e,t){if(e){if(gn(e.error)){let r=e.error.code,n=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof n=="string"?{message:xs(n,lm)}:{},httpStatusCode:t}}if(gn(e.result)&&e.result.isError===!0)return{isError:!0}}}o(dM,"readSpanResponse");function uM(e,t,r){let n=_w(t.headers,yw),s=r?.result,i=rm(gn(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);hr(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(uM,"recordInitializeResult");function bw(e){let{spans:t}=e,r=[t.client,t.server];try{lM(r,e)}catch{}finally{Ld(r)}}o(bw,"finishMcpProxySpans");function lM(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&uM(e,n,s.message);let i=dM(s.message,n.status);i?hr(e,a=>a.setResponse(i)):s.ended==="errored"?hr(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?hr(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?hr(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?hr(e,a=>a.setErrorType("response_replaced","A different response was sent before the JSON-RPC response arrived.")):t.expectsResponse&&s.ended==="complete"&&!s.message&&!s.truncated&&!s.uninspected&&hr(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(lM,"recordOutcome");function hr(e,t){for(let r of e)try{t(r)}catch{}}o(hr,"forEachHandle");function Ld(e){for(let t of e)try{t.end()}catch{}}o(Ld,"endEach");function $d(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}o($d,"failMcpProxySpans");function Hd(e){for(let t of[e.client,e.server])try{t.setErrorType("cancelled","The client cancelled the request before the upstream sent response headers.")}catch{}finally{Ld([t])}}o(Hd,"cancelMcpProxySpans");var Vd=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),Bd=64*1024,Gd=1024*1024,pM=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function vw(e,t={}){return e===void 0?Bd:pM.has(e)||t.modern===!0&&e==="server/discover"?Gd:Bd}o(vw,"tapMaxBytesForMethod");function mM(e){let t=it(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(mM,"readTapMode");function hM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(hM,"isPlainObject");function fM(e){return hM(e)&&!("method"in e)&&("result"in e||"error"in e)}o(fM,"isResponseShaped");function gM(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(gM,"isSameJsonRpcIdValue");function Cw(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(fM);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>gM(a.id,t));if(i||r)return i}return s[0]}o(Cw,"selectResponse");function Iw(e){try{return JSON.parse(e)}catch{return}}o(Iw,"tryParseJson");var Fd=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{o(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let n of this.#e)t.set(n,r),r+=n.byteLength;this.#e=[],this.#n=Cw(Iw(new TextDecoder().decode(t)),this.requestId,!1)}},Jd=class{constructor(t,r){this.requestId=t;this.#e=new Mo({maxEventChars:r,onOversize:"discard"})}requestId;static{o(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let n=t(r);this.#r||=r.discardedEvents>0;for(let s of n){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=Cw(Iw(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},yM={push(){},end(){},message:void 0,truncated:!1};function SM(e,t,r){switch(e){case"json":return new Fd(t,r);case"sse":return new Jd(t,r);case"passthrough":return yM}}o(SM,"createObserver");function Tw(e,t={}){let r=e.body;if(r===null){let I=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:I,outcome:I}}let n=at(e.headers)?"passthrough":mM(e),s=SM(n,t.requestId,t.maxBytes??Bd),i,a=new Promise(I=>{i=I}),c,d=new Promise(I=>{c=I}),u=!1,m=o(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,S=o((I,U)=>{if(f)return;if(f=!0,I==="complete")try{s.end()}catch{}let v={ended:I,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...n==="passthrough"&&h>0?{uninspected:!0}:{},...U===void 0?{}:{error:U}};i(v),u||(u=!0,c(v))},"settle"),R=r.getReader(),_=new ReadableStream({async pull(I){let U;try{U=await R.read()}catch(v){S("errored",v),I.error(v);return}if(U.done){S("complete"),I.close();return}if(h+=U.value.byteLength,!f)try{s.push(U.value)}catch{}I.enqueue(U.value),m()},async cancel(I){S(I===Vd?"released":"cancelled"),await R.cancel(I)}},{highWaterMark:0}),y=mf(new Headers(e.headers)),b;try{b=new Response(_,{status:e.status,statusText:e.statusText,headers:y})}catch(I){throw R.cancel(I).catch(()=>{}),I}return{response:b,done:a,outcome:d}}o(Tw,"tapJsonRpcResponse");var _M=-32603,wM="The upstream MCP server ended the response stream without a response to this request.",RM="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function Ew(e){return`${typeof e}:${String(e)}`}o(Ew,"idKey");function bM(e,t){if(e.delete(Ew(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(bM,"clearAnsweredRequest");function kw(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!Aw(n)||typeof n.method!="string"||typeof n.id!="string"&&typeof n.id!="number")continue;let s=Me(n);s!==void 0&&r.push(s)}return r}o(kw,"readJsonRpcRequestIds");function Aw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Aw,"isRecord");function vM(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)Aw(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&n.push(s.id);return n}o(vM,"readResponseIds");function CM(e){let t=e.getReader();return new ReadableStream({async pull(r){let n;try{n=await t.read()}catch{r.close();return}if(n.done){r.close();return}r.enqueue(n.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}o(CM,"endOnError");function Pw(e,t,r=Gd,n){let s=new Map;for(let a of t)s.set(Ew(a),a);let i=!1;return tc(CM(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of vM(a.data))bM(s,c)},{failureMode:"open",maxEventChars:r,onFailure:o((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:o(()=>{if(s.size===0||i)return[];let a=n?.aborted?RM:wM;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:_M,message:a}})}))},"end")})}o(Pw,"answerUnansweredRequests");var IM={Allow:"POST"},xw="mcp-session-id";async function TM(e){try{return await e.clone().arrayBuffer()}catch{return}}o(TM,"readRequestBody");function Wd(e){try{let t=Om(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}o(Wd,"readRouteAnalyticsFields");function Zd(e){return Fm(e.user,e.url,e.headers)?.subjectId}o(Zd,"readRequestSubjectId");function Ow(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}o(Ow,"readRequestMethod");function Mw(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Mw,"readHeader");function Yd(e){let t=Mw(e.request.headers,xw)??(e.response?Mw(e.response.headers,xw):void 0),r=e.tapResult?.message?.result,n=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=sr(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Yd,"readMcpProtocolFields");function EM(e){let t=pw(e.requestJson?.value);t&&te(e.context,{...t,...Wd(e.context),...Yd({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http"})}o(EM,"emitCapabilityInvokedAnalytics");function kM(e){let t=mw(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended},{modern:e.modern,gatewayAnswered:e.gatewayAnswered});t&&ya(e.context,{...t,...Wd(e.context),...Yd(e),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(kM,"emitCapabilityFinalAnalytics");function Bi(e){let t=hw(e.requestJson?.value,e.details);t&&(e.late?ya:te)(e.context,{...t,...Wd(e.context),...Yd({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:Zd(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(Bi,"emitCapabilityThrownAnalytics");async function Uw(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let n=new kt(e.request,{headers:t,...r===void 0?{}:{body:r}}),s=o(i=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=i)},"onTimeoutSignal");return fm(n,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}o(Uw,"callUpstream");function AM(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(AM,"readClientSignal");function qw(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(qw,"throwIfClientCancelled");function PM(e){let{clientSignal:t,context:r,onCancel:n}=e,s=!1,i=o(()=>(t.removeEventListener("abort",a),s?!1:(s=!0,!0)),"claim"),a=o(()=>{i()&&r.waitUntil(Promise.resolve().then(n).catch(c=>{try{vs.getLogger(r).error(c,"Error recording an MCP request whose client cancelled before headers")}catch{}}))},"onAbort");return t.addEventListener("abort",a,{once:!0}),{claim:i}}o(PM,"watchClientCancelBeforeHeaders");async function Kd(e){try{await e.body?.cancel()}catch{}}o(Kd,"discardBody");function xM(e,t){return e===t.reason?!0:e instanceof Error||e instanceof DOMException?e.name==="AbortError"||e instanceof Error&&e.cause===t.reason:!1}o(xM,"isClientAbortError");function OM(e,t){try{vs.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(OM,"logErrorAfterClientLeft");async function zw(e){qw(e.clientSignal);let t=await Uw(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=Py(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await Kd(t);let n=o(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await Dw.with(e.refreshContext,n):await n();return qw(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await Uw({...e,headers:s.headers}),gatewayAnswered:!1}}o(zw,"forwardToUpstream");function MM(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?zw({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):Dw.with(i.client.ctx,()=>zw({request:t,context:r,bodyBytes:n===void 0?void 0:Rw(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(MM,"callUpstreamOperation");function UM(e,t,r){if(e.body===null||e.status<200||e.status>299||it(e.headers.get("content-type"))!=="text/event-stream"||at(e.headers))return e;let n=kw(t?.value);if(n.length===0)return e;let s=yt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(Pw(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(UM,"withUnansweredRequestErrors");function qM(e,t){if(e.body===null||!t.rewritten&&!t.clientSignal)return e;let r=new Headers(e.headers);return t.rewritten&&r.set("x-accel-buffering","no"),new Response(zM(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(qM,"finishModernResponse");function zM(e,t){if(!t)return e;let r=e.getReader(),n=!1,s=o(()=>{},"onAbort"),i=o(()=>{n=!0,t.removeEventListener("abort",s)},"finish");return new ReadableStream({start(a){s=o(()=>{if(!n){i(),r.cancel(t.reason).catch(()=>{});try{a.close()}catch{}}},"onAbort"),t.aborted?s():t.addEventListener("abort",s,{once:!0})},async pull(a){let c;try{c=await r.read()}catch(d){n||(i(),a.error(d));return}if(!n){if(c.done){i(),a.close();return}a.enqueue(c.value)}},async cancel(a){i(),await r.cancel(a)}},{highWaterMark:0})}o(zM,"cancelOnClientAbort");function NM(e,t){iu.findContextExtensions(e)?.addPipelineExitHook(r=>{let n=t.body;r===t||n===null||r?.body===n||n.locked||n.cancel(Vd).catch(()=>{})})}o(NM,"releaseBodyIfNotSent");function Nw(e,t){return Ne.format({type:"https://httpproblems.com/http-status/499",title:"Client Closed Request",status:499,detail:"The client cancelled the request before the upstream MCP server responded."},e,t)}o(Nw,"clientClosedResponse");function jw(e){return e instanceof ee?gw:fw}o(jw,"thrownDetails");async function jM(e,t){if(ot("handler.mcp-gateway-proxy"),e.method==="GET")return Ne.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},IM);let r=Date.now(),n=await TM(e),s=aw(n,{readMetaProtocolVersion:fe()});rh(t,sr(e.headers,s?.value));let i=Sw(e,s,n),a;if(i!==void 0)try{a=ww({request:e,context:t,parsed:i})}catch{a=void 0}EM({context:t,request:e,requestJson:s});let c=fe()&&zr(e.headers,s?.value),d=c&&Ow(s)==="subscriptions/listen",u=c?AM(e):void 0,m=u?PM({clientSignal:u,context:t,onCancel:o(()=>{a&&Hd(a),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c,late:!0})},"onCancel")}):void 0,h={},f,S;try{let y=await MM({request:e,context:t,requestBody:n,parsed:i,spans:a,modern:c,listen:d,clientSignal:u,upstreamTimeout:h});S=y.gatewayAnswered,f=cw(y.response)}catch(y){let b=m?.claim()??!0;if(u?.aborted)return xM(y,u)||OM(t,y),b&&(a&&Hd(a),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jd,modern:c})),Nw(e,t);throw a&&$d(a,y),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jw(y),modern:c}),y}if(m&&!m.claim())return await Kd(f),Nw(e,t);let R,_;try{R=Tw(f,{requestId:Me(s?.value),maxBytes:vw(Ow(s),{modern:c})});let y=UM(R.response,s,h.signal);_=c?qM(y,{rewritten:y!==R.response,clientSignal:u}):y,NM(t,_)}catch(y){throw await Kd(R?.response??f),a&&$d(a,y),Bi({context:t,request:e,requestJson:s,startedAt:r,details:jw(y),modern:c}),y}return t.waitUntil(R.outcome.then(y=>{try{kM({context:t,request:e,requestJson:s,response:f,tapResult:y,startedAt:r,modern:c,gatewayAnswered:S})}finally{a&&i&&bw({spans:a,method:i.method,response:f,tapResult:y,expectsResponse:i.id!==void 0})}}).catch(y=>{try{vs.getLogger(t).error(y,"Error emitting MCP gateway capability analytics")}catch{}})),_}o(jM,"McpProxyHandler");export{Yw as McpAuth0OAuthInboundPolicy,hc as McpCapabilityFilterInboundPolicy,$w as McpClerkOAuthInboundPolicy,Hw as McpCognitoOAuthInboundPolicy,Bw as McpEntraOAuthInboundPolicy,Md as McpGatewayPlugin,Fw as McpGoogleOAuthInboundPolicy,Jw as McpKeycloakOAuthInboundPolicy,Vw as McpLogtoOAuthInboundPolicy,Xw as McpOAuthInboundPolicy,Gw as McpOktaOAuthInboundPolicy,Kw as McpOneLoginOAuthInboundPolicy,Ww as McpPingOAuthInboundPolicy,jM as McpProxyHandler,Qc as McpTokenExchangeInboundPolicy,Zw as McpWorkosOAuthInboundPolicy,zf as claimsCapabilityResolver};
45
45
  /*! For license information please see index.js.LEGAL.txt */
46
46
  //# sourceMappingURL=index.js.map