@zuplo/cli 7.15.13 → 7.15.16

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 (96) hide show
  1. package/node_modules/@posthog/core/dist/featureFlagUtils.d.ts.map +1 -1
  2. package/node_modules/@posthog/core/dist/featureFlagUtils.js +10 -3
  3. package/node_modules/@posthog/core/dist/featureFlagUtils.mjs +10 -3
  4. package/node_modules/@posthog/core/dist/posthog-core.d.ts.map +1 -1
  5. package/node_modules/@posthog/core/dist/posthog-core.js +7 -4
  6. package/node_modules/@posthog/core/dist/posthog-core.mjs +7 -4
  7. package/node_modules/@posthog/core/dist/types.d.ts +2 -0
  8. package/node_modules/@posthog/core/dist/types.d.ts.map +1 -1
  9. package/node_modules/@posthog/core/dist/types.js +1 -0
  10. package/node_modules/@posthog/core/dist/types.mjs +1 -0
  11. package/node_modules/@posthog/core/package.json +2 -2
  12. package/node_modules/@posthog/core/src/featureFlagUtils.ts +17 -12
  13. package/node_modules/@posthog/core/src/posthog-core.ts +19 -4
  14. package/node_modules/@posthog/core/src/types.ts +2 -0
  15. package/node_modules/@zuplo/core/customer.cli.minified.js +305 -305
  16. package/node_modules/@zuplo/core/index.minified.js +312 -312
  17. package/node_modules/@zuplo/core/package.json +1 -1
  18. package/node_modules/@zuplo/graphql/package.json +1 -1
  19. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  20. package/node_modules/@zuplo/otel/package.json +1 -1
  21. package/node_modules/@zuplo/runtime/out/esm/{chunk-AJ3MMWJS.js → chunk-5XXEIH5B.js} +2 -2
  22. package/node_modules/@zuplo/runtime/out/esm/{chunk-T2WKOG7J.js → chunk-APWLPHXH.js} +2 -2
  23. package/node_modules/@zuplo/runtime/out/esm/chunk-HMKEMARF.js +276 -0
  24. package/node_modules/@zuplo/runtime/out/esm/chunk-HMKEMARF.js.map +1 -0
  25. package/node_modules/@zuplo/runtime/out/esm/chunk-I65Y62VQ.js +24 -0
  26. package/node_modules/@zuplo/runtime/out/esm/{chunk-G42UYZ6V.js.map → chunk-I65Y62VQ.js.map} +1 -1
  27. package/node_modules/@zuplo/runtime/out/esm/chunk-KZBZ5KM5.js +188 -0
  28. package/node_modules/@zuplo/runtime/out/esm/chunk-KZBZ5KM5.js.map +1 -0
  29. package/node_modules/@zuplo/runtime/out/esm/{chunk-TOJD4RET.js → chunk-MWNVPFFM.js} +2 -2
  30. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  31. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  32. package/node_modules/@zuplo/runtime/out/esm/internal/index.js +1 -1
  33. package/node_modules/@zuplo/runtime/out/esm/mcp/messages/index.js +1 -1
  34. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  35. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
  36. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
  37. package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +1 -1
  38. package/node_modules/@zuplo/runtime/out/types/index.d.ts +32 -0
  39. package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +220 -0
  40. package/node_modules/@zuplo/runtime/package.json +1 -1
  41. package/node_modules/hono/dist/adapter/bun/websocket.js +19 -4
  42. package/node_modules/hono/dist/adapter/lambda-edge/handler.js +4 -0
  43. package/node_modules/hono/dist/cjs/adapter/bun/websocket.js +19 -4
  44. package/node_modules/hono/dist/cjs/adapter/lambda-edge/handler.js +4 -0
  45. package/node_modules/hono/dist/cjs/helper/accepts/accepts.js +5 -0
  46. package/node_modules/hono/dist/cjs/helper/proxy/index.js +2 -0
  47. package/node_modules/hono/dist/cjs/jsx/dom/components.js +1 -1
  48. package/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js +5 -2
  49. package/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js +8 -5
  50. package/node_modules/hono/dist/cjs/jsx/dom/render.js +9 -3
  51. package/node_modules/hono/dist/cjs/middleware/basic-auth/index.js +1 -0
  52. package/node_modules/hono/dist/cjs/middleware/combine/index.js +4 -0
  53. package/node_modules/hono/dist/cjs/middleware/language/language.js +1 -1
  54. package/node_modules/hono/dist/cjs/middleware/method-override/index.js +35 -12
  55. package/node_modules/hono/dist/cjs/middleware/request-id/request-id.js +3 -3
  56. package/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js +6 -3
  57. package/node_modules/hono/dist/cjs/utils/body.js +1 -0
  58. package/node_modules/hono/dist/cjs/utils/html.js +5 -0
  59. package/node_modules/hono/dist/cjs/utils/jwt/jwt.js +7 -5
  60. package/node_modules/hono/dist/helper/accepts/accepts.js +5 -0
  61. package/node_modules/hono/dist/helper/proxy/index.js +2 -0
  62. package/node_modules/hono/dist/jsx/dom/components.js +2 -2
  63. package/node_modules/hono/dist/jsx/dom/hooks/index.js +5 -2
  64. package/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js +8 -5
  65. package/node_modules/hono/dist/jsx/dom/render.js +9 -3
  66. package/node_modules/hono/dist/middleware/basic-auth/index.js +1 -0
  67. package/node_modules/hono/dist/middleware/combine/index.js +4 -0
  68. package/node_modules/hono/dist/middleware/language/language.js +1 -1
  69. package/node_modules/hono/dist/middleware/method-override/index.js +35 -12
  70. package/node_modules/hono/dist/middleware/request-id/request-id.js +3 -3
  71. package/node_modules/hono/dist/middleware/secure-headers/secure-headers.js +6 -3
  72. package/node_modules/hono/dist/types/helper/accepts/accepts.d.ts +5 -0
  73. package/node_modules/hono/dist/types/jsx/base.d.ts +2 -1
  74. package/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts +1 -0
  75. package/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts +3 -3
  76. package/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts +2 -0
  77. package/node_modules/hono/dist/types/utils/jwt/jwt.d.ts +4 -2
  78. package/node_modules/hono/dist/types/utils/types.d.ts +12 -2
  79. package/node_modules/hono/dist/utils/body.js +1 -0
  80. package/node_modules/hono/dist/utils/html.js +5 -0
  81. package/node_modules/hono/dist/utils/jwt/jwt.js +7 -5
  82. package/node_modules/hono/package.json +1 -1
  83. package/node_modules/strip-json-comments/index.d.ts +3 -1
  84. package/node_modules/strip-json-comments/index.js +9 -22
  85. package/node_modules/strip-json-comments/package.json +23 -19
  86. package/package.json +11 -11
  87. package/node_modules/@zuplo/runtime/out/esm/chunk-24DRL32G.js +0 -431
  88. package/node_modules/@zuplo/runtime/out/esm/chunk-24DRL32G.js.map +0 -1
  89. package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js +0 -13
  90. package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js.map +0 -1
  91. package/node_modules/@zuplo/runtime/out/esm/chunk-G42UYZ6V.js +0 -24
  92. /package/node_modules/@zuplo/runtime/out/esm/{chunk-AJ3MMWJS.js.map → chunk-5XXEIH5B.js.map} +0 -0
  93. /package/node_modules/@zuplo/runtime/out/esm/{chunk-T2WKOG7J.js.map → chunk-APWLPHXH.js.map} +0 -0
  94. /package/node_modules/@zuplo/runtime/out/esm/{chunk-24DRL32G.js.LEGAL.txt → chunk-HMKEMARF.js.LEGAL.txt} +0 -0
  95. /package/node_modules/@zuplo/runtime/out/esm/{chunk-G42UYZ6V.js.LEGAL.txt → chunk-I65Y62VQ.js.LEGAL.txt} +0 -0
  96. /package/node_modules/@zuplo/runtime/out/esm/{chunk-TOJD4RET.js.map → chunk-MWNVPFFM.js.map} +0 -0
@@ -9,7 +9,7 @@
9
9
  * See https://zuplo.com/legal/eula for more information.
10
10
  */
11
11
 
12
- import{$a as pa,$b as op,$c as Vp,$d as zm,$f as ot,$g as Qr,Aa as Nu,Ab as xl,Ac as Us,Ad as mm,Ag as Fs,Ah as Rh,Ba as ju,Bb as Ml,Bc as qs,Bd as wo,Bg as Io,Bh as _h,Ca as Du,Cb as Ol,Cc as fa,Cd as ar,Cg as To,Ch as wh,D as Me,Da as $u,Db as Ul,Dc as ga,Dd as hm,Dg as Yr,Dh as bh,E as wu,Ea as Lu,Eb as ql,Ec as ya,Ed as fm,Eg as Xm,Eh as vh,Fa as ir,Fb as zl,Fc as Ap,Fd as gm,Fg as Ta,Fh as Ch,G as V,Ga as da,Gb as Nl,Gc as Sa,Gd as ym,Gg as Qm,Gh as Xs,Ha as ua,Hb as jl,Hc as Ra,Hd as Sm,Hg as Eo,Hh as Ih,Ia as _o,Ib as Dl,Ic as Pp,Id as Rm,Ig as Js,Ih as Th,Ja as la,Jb as $l,Jc as xp,Jd as _m,Jg as eh,Jh as H,Ka as Hu,Kb as Ll,Kc as _a,Kd as Tm,Kg as th,Kh as Q,L as bu,La as Bu,Lb as Hl,Lc as zs,Ld as vo,Lg as rh,Lh as Oa,Ma as Fu,Mb as Bl,Mc as Ns,Md as Em,Mg as nh,Mh as me,N as xs,Na as Ju,Nb as Fl,Nc as Mp,Nd as Ds,Ng as we,Nh as pt,Oa as Vu,Ob as Jl,Oc as Op,Od as $s,Of as Hm,Og as pe,Oh as se,Pa as Gu,Pb as Vl,Pc as Up,Pd as dr,Pf as ze,Pg as oh,Ph as Qs,Q as Ms,Qa as Ku,Qb as Gl,Qc as qp,Qd as km,Qf as Bm,Qg as Xr,Qh as Ie,Ra as Wu,Rb as Kl,Rc as zp,Rd as ba,Rf as Fm,Rg as J,Rh as te,Sa as Zu,Sb as Wl,Sc as Np,Sd as Hr,Sf as Jm,Sg as ut,Sh as Eh,Ta as Yu,Tb as Zl,Tc as jp,Td as Ls,Tf as oe,Tg as Mt,Th as ee,Ua as Xu,Ub as Yl,Uc as Dp,Ud as Am,Uf as Vm,Ug as sh,Uh as kh,Va as Qu,Vb as Xl,Vc as $p,Vd as Pm,Vf as Br,Vg as Ot,Vh as Ah,W as vu,Wa as el,Wb as Ql,Wc as Lp,Wd as xm,Wf as Gm,Wg as Ea,Wh as Ph,Xa as tl,Xb as ep,Xc as Hp,Xd as Hs,Xf as Fr,Xg as Vs,Xh as xh,Ya as rl,Yb as tp,Yc as Bp,Yd as Um,Yf as x,Yg as ka,Yh as qw,Z as Cu,Za as nl,Zb as rp,Zc as Fp,Zd as qm,Zf as Jr,Zg as Gs,Zh as zw,_a as ol,_b as np,_c as Jp,_d as va,_f as Vr,_g as ko,aa as Iu,ab as sl,ac as sp,ad as Gp,ae as Nm,ag as st,ah as ih,b as ks,bb as il,bc as ip,bd as Kp,be as jm,bg as Co,bh as lt,cb as al,cc as ap,cd as Wp,ce as Ca,cg as Gr,ch as Aa,db as cl,dc as cp,dd as Zp,de as Dm,dg as Kr,dh as Ks,eb as dl,ec as dp,ed as Yp,ee as Ia,eg as Wr,eh as ah,fb as ul,fc as up,fd as Xp,fe as $m,fg as Bs,fh as Ws,gb as ll,gc as lp,gd as Qp,gg as Km,gh as Pa,ha as Os,hb as pl,hc as pp,hd as em,hg as Ze,hh as Zs,ia as Or,ib as ml,ic as ma,id as tm,ig as Wm,ih as ch,ja as Ur,jb as hl,jc as mp,jd as rm,jg as Ne,jh as de,ka as So,kb as fl,kc as hp,kd as nm,kg as q,kh as dh,la as qr,lb as gl,lc as fp,ld as om,lg as Zr,lh as uh,ma as zr,mb as yl,mc as gp,md as sm,me as Lm,mg as Ce,mh as lh,na as Ro,nb as Sl,nc as yp,nd as im,ng as xt,nh as xa,oa as sr,ob as Rl,oc as Sp,od as am,og as Iw,oh as ph,p as go,pa as Tu,pb as _l,pc as Rp,pd as cm,pg as Tw,ph as mh,q as Et,qa as Eu,qb as wl,qc as _p,qd as dm,qg as Ew,qh as Ma,r as yu,ra as ku,rb as bl,rc as wp,rd as um,rg as kw,rh as hh,s as Su,sa as Au,sb as vl,sc as bp,sd as lm,sg as Aw,sh as ur,t as As,ta as Pu,tb as Cl,tc as vp,td as Nr,tg as Pw,th as fh,u as Ru,ua as xu,ub as Il,uc as Cp,ud as jr,ug as xw,uh as Ao,v as yo,va as Mu,vb as Tl,vc as Ip,vd as pm,vg as Mw,vh as gh,w as ca,wa as Ou,wb as El,wc as Tp,wd as Dr,wg as Ow,wh as Ys,x as _u,xa as Uu,xb as kl,xc as Ep,xd as At,xg as Uw,xh as Po,y as Ps,ya as qu,yb as Al,yc as kp,yd as wa,yg as Zm,yh,za as zu,zb as Pl,zc as ha,zd as js,zg as Ym,zh as Sh}from"../chunk-24DRL32G.js";import{c as nt}from"../chunk-BH4DKEES.js";import"../chunk-TOJD4RET.js";import{a as kt,b as Y,c as cr,d as wm,e as bm,f as vm,g as Pt,i as bo,j as Cm,k as Im,l as $r,m as Lr,t as Mm,u as Om}from"../chunk-T2WKOG7J.js";import"../chunk-R6UNMRUU.js";import{A as m,b as sa,c as hu,d as l,e as fu,f as gu,g as k,h as z,i as Ts,k as D,l as C,m as g,n as L,o as U,p as ia,q as ho,r as O,s as F,t as w,u as $,v as aa,w as Es,y as fo}from"../chunk-AJ3MMWJS.js";import"../chunk-5JGLAPFA.js";import{X as Is,Y as mu}from"../chunk-G42UYZ6V.js";import{a as n,e as ve,g as E,h as X}from"../chunk-VXPFMOL5.js";var Nw=Object.create,ei=Object.defineProperty,jw=Object.getOwnPropertyDescriptor,Dw=Object.getOwnPropertyNames,$w=Object.getPrototypeOf,Lw=Object.prototype.hasOwnProperty,Mh=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),Oh=n((e,t)=>{let r={};for(var o in e)ei(r,o,{get:e[o],enumerable:!0});return t&&ei(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Hw=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=Dw(t),i=0,a=s.length,c;i<a;i++)c=s[i],!Lw.call(e,c)&&c!==r&&ei(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(o=jw(t,c))||o.enumerable});return e},"__copyProps"),Uh=n((e,t,r)=>(r=e!=null?Nw($w(e)):{},Hw(t||!e||!e.__esModule?ei(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Bw=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function qh(e){return typeof e=="string"&&Bw.has(e.replace(/#$/,""))}n(qh,"declares2019Dialect");var Da=Symbol.for("mcp.sdk.errorBrands");function lr(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,Da,{value:r,enumerable:!1,configurable:!0})}n(lr,"stampErrorBrands");function je(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Da)){let r=t[Da];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(je,"brandedHasInstance");var ce=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Ut=class Vh extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return je(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 je(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",lr(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 Vh(t.error,t.error_description??t.error,t.error_uri)}},he=(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})({}),ae=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",lr(this,new.target)}},tb=class extends ae{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 Gh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Gh,"resourceUrlFromServerUrl");function Ja(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}n(Ja,"withoutIssuer");function si({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(si,"checkResourceAllowed");var rb="2026-07-28";function Kh(e){return e>=rb}n(Kh,"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)}]}}n(Wh,"appendTextFallbackForNonObject");var Zh=["task","inputRequests","requestState"];function nb(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Zh.some(t=>t in e)?e:{...e,content:[]}}n(nb,"normalizeContentlessToolResult");function ob(){let e=aa(()=>U([l(),k(),z(),Ts(),O(l(),e),C(e)])),t=O(l(),e),r=U([l(),k().int()]),o=l(),s=g({ttl:k().optional()}),i=g({taskId:l()}),a=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),p=g({_meta:a.optional()}),h=g({method:l(),params:p.loose().optional()}),f=L({_meta:a.optional()}),y=U([l(),k().int()]),b=f.strict(),_=p.extend({requestId:y.optional(),reason:l().optional()}),S=h.extend({method:w("notifications/cancelled"),params:_}),R=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),v=g({icons:C(R).optional()}),P=g({name:l(),title:l().optional()}),N=P.extend({...P.shape,...v.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),A=ho(g({applyDefaults:z().optional()}),t),M=Es(_e=>_e&&typeof _e=="object"&&!Array.isArray(_e)&&Object.keys(_e).length===0?{form:{}}:_e,ho(g({form:A.optional(),url:t.optional()}),t.optional())),B=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),W=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),Z=g({experimental:O(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:M.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:B.optional(),extensions:O(l(),t).optional()}),le=c.extend({protocolVersion:l(),capabilities:Z,clientInfo:N}),Pe=u.extend({method:w("initialize"),params:le}),K=g({experimental:O(l(),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:W.optional(),extensions:O(l(),t).optional()}),re=f.extend({protocolVersion:l(),capabilities:K,serverInfo:N,instructions:l().optional()}),_t=h.extend({method:w("notifications/initialized"),params:p.optional()}),wt=u.extend({method:w("ping"),params:c.optional()}),Vt=g({progress:k(),total:$(k()),message:$(l())}),tt=g({...p.shape,...Vt.shape,progressToken:r}),bt=h.extend({method:w("notifications/progress"),params:tt}),yr=c.extend({cursor:o.optional()}),ct=u.extend({params:yr.optional()}),dt=f.extend({nextCursor:o.optional()}),Sr=g({uri:l(),mimeType:$(l()),_meta:O(l(),D()).optional()}),Rr=Sr.extend({text:l()}),Gt=l().refine(_e=>{try{return atob(_e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_r=Sr.extend({blob:Gt}),rt=F(["user","assistant"]),Ke=g({audience:C(rt).optional(),priority:k().min(0).max(1).optional(),lastModified:fo.datetime({offset:!0}).optional()}),Kt=g({...P.shape,...v.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(k()),annotations:Ke.optional(),_meta:$(L({}))}),_n=g({...P.shape,...v.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:Ke.optional(),_meta:$(L({}))}),wn=ct.extend({method:w("resources/list")}),bn=dt.extend({resources:C(Kt)}),vt=ct.extend({method:w("resources/templates/list")}),wr=dt.extend({resourceTemplates:C(_n)}),Wt=c.extend({uri:l()}),vn=Wt,Cn=u.extend({method:w("resources/read"),params:vn}),In=f.extend({contents:C(U([Rr,_r]))}),Tn=h.extend({method:w("notifications/resources/list_changed"),params:p.optional()}),En=Wt,kn=u.extend({method:w("resources/subscribe"),params:En}),An=Wt,Pn=u.extend({method:w("resources/unsubscribe"),params:An}),xn=p.extend({uri:l()}),Mn=h.extend({method:w("notifications/resources/updated"),params:xn}),On=g({name:l(),description:$(l()),required:$(z())}),Un=g({...P.shape,...v.shape,description:$(l()),arguments:$(C(On)),_meta:$(L({}))}),qn=ct.extend({method:w("prompts/list")}),zn=dt.extend({prompts:C(Un)}),Nn=c.extend({name:l(),arguments:O(l(),l()).optional()}),jn=u.extend({method:w("prompts/get"),params:Nn}),Zt=g({type:w("text"),text:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Yt=g({type:w("image"),data:Gt,mimeType:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Xt=g({type:w("audio"),data:Gt,mimeType:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Dn=g({type:w("tool_use"),name:l(),id:l(),input:O(l(),D()),_meta:O(l(),D()).optional()}),Ct=g({type:w("resource"),resource:U([Rr,_r]),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),$n=Kt.extend({type:w("resource_link")}),Le=U([Zt,Yt,Xt,$n,Ct]),br=g({role:rt,content:Le}),vr=f.extend({description:l().optional(),messages:C(br)}),Qt=h.extend({method:w("notifications/prompts/list_changed"),params:p.optional()}),Ln=g({title:l().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),Cr=g({taskSupport:F(["required","optional","forbidden"]).optional()}),er=g({...P.shape,...v.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:O(l(),e).optional(),required:C(l()).optional()}).catchall(D()),outputSchema:g({type:w("object"),properties:O(l(),e).optional(),required:C(l()).optional()}).catchall(D()).optional(),annotations:Ln.optional(),execution:Cr.optional(),_meta:O(l(),D()).optional()}),Ir=ct.extend({method:w("tools/list")}),Tr=dt.extend({tools:C(er)}),Er=f.extend({content:C(Le),structuredContent:O(l(),D()).optional(),isError:z().optional()}),Re=d.extend({name:l(),arguments:O(l(),D()).optional()}),Hn=u.extend({method:w("tools/call"),params:Re}),ds=h.extend({method:w("notifications/tools/list_changed"),params:p.optional()}),kr=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Bn=c.extend({level:kr}),Fn=u.extend({method:w("logging/setLevel"),params:Bn}),Jn=p.extend({level:kr,logger:l().optional(),data:D()}),Vn=h.extend({method:w("notifications/message"),params:Jn}),Gn=g({name:l().optional()}),Kn=g({hints:C(Gn).optional(),costPriority:k().min(0).max(1).optional(),speedPriority:k().min(0).max(1).optional(),intelligencePriority:k().min(0).max(1).optional()}),Wn=g({mode:F(["auto","required","none"]).optional()}),us=g({type:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Le),structuredContent:g({}).loose().optional(),isError:z().optional(),_meta:O(l(),D()).optional()}),Zn=ia("type",[Zt,Yt,Xt]),It=ia("type",[Zt,Yt,Xt,Dn,us]),Yn=g({role:rt,content:U([It,C(It)]),_meta:O(l(),D()).optional()}),Xn=d.extend({messages:C(Yn),modelPreferences:Kn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:k().optional(),maxTokens:k().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(er).optional(),toolChoice:Wn.optional()}),Qn=u.extend({method:w("sampling/createMessage"),params:Xn}),eo=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens"]).or(l())),role:rt,content:Zn}),to=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:rt,content:U([It,C(It)])}),ro=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:z().optional()}),no=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:k().optional(),maxLength:k().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),oo=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:k().optional(),maximum:k().optional(),default:k().optional()}),so=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),io=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),ao=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),co=U([so,io]),tr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),rr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),ls=U([tr,rr]),ps=U([ao,co,ls]),Ue=U([ps,ro,no,oo]),qe=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:O(l(),Ue),required:C(l()).optional()}).catchall(D())}),uo=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),We=U([qe,uo]),ms=u.extend({method:w("elicitation/create"),params:We}),hs=p.extend({elicitationId:l()}),fs=h.extend({method:w("notifications/elicitation/complete"),params:hs}),gs=f.extend({action:F(["accept","decline","cancel"]),content:Es(_e=>_e===null?void 0:_e,O(l(),U([l(),k(),z(),C(l())])).optional())}),ys=g({type:w("ref/resource"),uri:l()}),Ss=g({type:w("ref/prompt"),name:l()}),Rs=c.extend({ref:U([Ss,ys]),argument:g({name:l(),value:l()}),context:g({arguments:O(l(),l()).optional()}).optional()}),lo=u.extend({method:w("completion/complete"),params:Rs}),_s=f.extend({completion:L({values:C(l()).max(100),total:$(k().int()),hasMore:$(z())})}),ws=g({uri:l().startsWith("file://"),name:l().optional(),_meta:O(l(),D()).optional()}),Ar=u.extend({method:w("roots/list"),params:c.optional()}),po=f.extend({roots:C(ws)}),bs=h.extend({method:w("notifications/roots/list_changed"),params:p.optional()}),vs=L({ttl:k().optional(),pollInterval:k().optional()}),mo=F(["working","input_required","completed","failed","cancelled"]),Tt=g({taskId:l(),status:mo,ttl:U([k(),Ts()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:$(k()),statusMessage:$(l())}),xe=f.extend({task:Tt}),Cs=p.merge(Tt),nr=h.extend({method:w("notifications/tasks/status"),params:Cs}),Pr=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),xr=f.merge(Tt),Mr=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),oa=f.loose(),be=ct.extend({method:w("tasks/list")}),ne=dt.extend({tasks:C(Tt)}),or=u.extend({method:w("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:p,NotificationSchema:h,ResultSchema:f,RequestIdSchema:y,EmptyResultSchema:b,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:S,IconSchema:R,IconsSchema:v,BaseMetadataSchema:P,ImplementationSchema:N,ClientTasksCapabilitySchema:B,ServerTasksCapabilitySchema:W,ClientCapabilitiesSchema:Z,InitializeRequestParamsSchema:le,InitializeRequestSchema:Pe,ServerCapabilitiesSchema:K,InitializeResultSchema:re,InitializedNotificationSchema:_t,PingRequestSchema:wt,ProgressSchema:Vt,ProgressNotificationParamsSchema:tt,ProgressNotificationSchema:bt,PaginatedRequestParamsSchema:yr,PaginatedRequestSchema:ct,PaginatedResultSchema:dt,ResourceContentsSchema:Sr,TextResourceContentsSchema:Rr,BlobResourceContentsSchema:_r,RoleSchema:rt,AnnotationsSchema:Ke,ResourceSchema:Kt,ResourceTemplateSchema:_n,ListResourcesRequestSchema:wn,ListResourcesResultSchema:bn,ListResourceTemplatesRequestSchema:vt,ListResourceTemplatesResultSchema:wr,ResourceRequestParamsSchema:Wt,ReadResourceRequestParamsSchema:vn,ReadResourceRequestSchema:Cn,ReadResourceResultSchema:In,ResourceListChangedNotificationSchema:Tn,SubscribeRequestParamsSchema:En,SubscribeRequestSchema:kn,UnsubscribeRequestParamsSchema:An,UnsubscribeRequestSchema:Pn,ResourceUpdatedNotificationParamsSchema:xn,ResourceUpdatedNotificationSchema:Mn,PromptArgumentSchema:On,PromptSchema:Un,ListPromptsRequestSchema:qn,ListPromptsResultSchema:zn,GetPromptRequestParamsSchema:Nn,GetPromptRequestSchema:jn,TextContentSchema:Zt,ImageContentSchema:Yt,AudioContentSchema:Xt,ToolUseContentSchema:Dn,EmbeddedResourceSchema:Ct,ResourceLinkSchema:$n,ContentBlockSchema:Le,PromptMessageSchema:br,GetPromptResultSchema:vr,PromptListChangedNotificationSchema:Qt,ToolAnnotationsSchema:Ln,ToolExecutionSchema:Cr,ToolSchema:er,ListToolsRequestSchema:Ir,ListToolsResultSchema:Tr,CallToolResultSchema:Er,CallToolRequestParamsSchema:Re,CallToolRequestSchema:Hn,ToolListChangedNotificationSchema:ds,LoggingLevelSchema:kr,SetLevelRequestParamsSchema:Bn,SetLevelRequestSchema:Fn,LoggingMessageNotificationParamsSchema:Jn,LoggingMessageNotificationSchema:Vn,ModelHintSchema:Gn,ModelPreferencesSchema:Kn,ToolChoiceSchema:Wn,ToolResultContentSchema:us,SamplingContentSchema:Zn,SamplingMessageContentBlockSchema:It,SamplingMessageSchema:Yn,CreateMessageRequestParamsSchema:Xn,CreateMessageRequestSchema:Qn,CreateMessageResultSchema:eo,CreateMessageResultWithToolsSchema:to,BooleanSchemaSchema:ro,StringSchemaSchema:no,NumberSchemaSchema:oo,UntitledSingleSelectEnumSchemaSchema:so,TitledSingleSelectEnumSchemaSchema:io,LegacyTitledEnumSchemaSchema:ao,SingleSelectEnumSchemaSchema:co,UntitledMultiSelectEnumSchemaSchema:tr,TitledMultiSelectEnumSchemaSchema:rr,MultiSelectEnumSchemaSchema:ls,EnumSchemaSchema:ps,PrimitiveSchemaDefinitionSchema:Ue,ElicitRequestFormParamsSchema:qe,ElicitRequestURLParamsSchema:uo,ElicitRequestParamsSchema:We,ElicitRequestSchema:ms,ElicitationCompleteNotificationParamsSchema:hs,ElicitationCompleteNotificationSchema:fs,ElicitResultSchema:gs,ResourceTemplateReferenceSchema:ys,PromptReferenceSchema:Ss,CompleteRequestParamsSchema:Rs,CompleteRequestSchema:lo,CompleteResultSchema:_s,RootSchema:ws,ListRootsRequestSchema:Ar,ListRootsResultSchema:po,RootsListChangedNotificationSchema:bs,TaskCreationParamsSchema:vs,TaskStatusSchema:mo,TaskSchema:Tt,CreateTaskResultSchema:xe,TaskStatusNotificationParamsSchema:Cs,TaskStatusNotificationSchema:nr,GetTaskRequestSchema:Pr,GetTaskResultSchema:xr,GetTaskPayloadRequestSchema:Mr,GetTaskPayloadResultSchema:oa,ListTasksRequestSchema:be,ListTasksResultSchema:ne,CancelTaskRequestSchema:or,CancelTaskResultSchema:f.merge(Tt),ClientRequestSchema:U([wt,Pe,lo,Fn,jn,qn,wn,vt,Cn,kn,Pn,Hn,Ir,Pr,Mr,be,or]),ClientNotificationSchema:U([S,bt,_t,bs,nr]),ClientResultSchema:U([b,eo,to,gs,po,xr,ne,xe]),ServerRequestSchema:U([wt,Qn,ms,Ar,Pr,Mr,be,or]),ServerNotificationSchema:U([S,bt,Vn,Mn,Tn,ds,Qt,nr,fs]),ServerResultSchema:U([b,re,_s,vr,zn,bn,wr,In,Er,Tr,xr,ne,xe]),CallToolResultWireSchema:D().superRefine((_e,Cw)=>{if(!(typeof _e!="object"||_e===null||Array.isArray(_e)||_e.content!==void 0)){for(let pu of Zh)if(pu in _e){Cw.addIssue({code:"custom",message:`content is required when the body carries '${pu}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(nb).pipe(Er)}}n(ob,"build$1");var sb;function Va(){return sb??=ob()}n(Va,"buildSchemas2025");function Yh(e){return e.type!=="object"}n(Yh,"isNonObjectJsonSchemaRoot");var ib=new Set(["const","enum","default","examples"]),ab=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function zh(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(zh,"establishesNewBase");function cb(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(zh(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=qh(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&&zh(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=o(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:ib.has(d)?a[d]=u:ab.has(d)?a[d]=o(u,!0):a[d]=o(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:o(e,!1)},required:["result"]}}n(cb,"wrapOutputSchemaForLegacy");var Xh={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},Qh={"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},db={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},ti;function ii(){if(ti)return ti;let e=Va();return ti={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}},ti}n(ii,"registryMaps");function ub(){ii()}n(ub,"warmRegistryMaps2025");function ef(e){return Object.prototype.hasOwnProperty.call(Xh,e)}n(ef,"hasRequestMethod2025");function tf(e){return Object.prototype.hasOwnProperty.call(Qh,e)}n(tf,"hasNotificationMethod2025");function lb(e){return Object.prototype.hasOwnProperty.call(db,e)}n(lb,"hasResultMethod");function pb(e){return lb(e)?ii().resultSchemas[e]:void 0}n(pb,"getResultSchema");function mb(e){return ef(e)?ii().requestSchemas[e]:void 0}n(mb,"getRequestSchema");function hb(e){return tf(e)?ii().notificationSchemas[e]:void 0}n(hb,"getNotificationSchema");var jU=Object.keys(Xh),DU=Object.keys(Qh);function $a(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n($a,"isPlainObject$5");function ri(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(ri,"triState$1");var Nh={ok:!1,reason:"not-in-era"};function jh(e){return $a(e)&&$a(e.outputSchema)&&Yh(e.outputSchema)}n(jh,"toolNeedsLegacyWrap");var Ga={era:"2025-11-25",hasRequestMethod:ef,hasNotificationMethod:tf,validateRequest:n((e,t)=>ri(mb(e),t),"validateRequest"),validateResult:n((e,t)=>ri(pb(e),t),"validateResult"),validateNotification:n((e,t)=>ri(hb(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>Nh,"validateInputRequest"),validateInputResponse:n(()=>Nh,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=Va();return ri(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Wh(e),o=r.structuredContent;if(o===void 0)return r;let s=typeof o!="object"||o===null||Array.isArray(o),i=t!==void 0&&Yh(t);return!s&&!i?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if($a(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=>jh(o))?t:{...t,tools:r.map(o=>jh(o)?{...o,outputSchema:cb(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function fb(){let e=aa(()=>U([l(),k(),z(),Ts(),O(l(),e),C(e)])),t=O(l(),e),r=U([l(),k().int()]),o=l(),s=U([l(),k().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(ne=>{try{return atob(ne),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:k().optional()}),u=g({taskId:l()}),p=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:p.optional()}),f=h.extend({task:d.optional()}),y=g({_meta:p.optional()}),b=g({method:l(),params:y.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),S=g({icons:C(_).optional()}),R=g({name:l(),title:l().optional()}),v=R.extend({...R.shape,...S.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),P=ho(g({applyDefaults:z().optional()}),t),N=Es(ne=>ne&&typeof ne=="object"&&!Array.isArray(ne)&&Object.keys(ne).length===0?{form:{}}:ne,ho(g({form:P.optional(),url:t.optional()}),t.optional())),A=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),M=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),B=g({experimental:O(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:A.optional(),extensions:O(l(),t).optional()}),W=g({experimental:O(l(),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:M.optional(),extensions:O(l(),t).optional()}),Z=g({progress:k(),total:$(k()),message:$(l())}),le=g({...y.shape,...Z.shape,progressToken:r}),Pe=b.extend({method:w("notifications/progress"),params:le}),K=y.extend({level:a,logger:l().optional(),data:D()}),re=b.extend({method:w("notifications/message"),params:K}),_t=g({uri:l(),mimeType:$(l()),_meta:O(l(),D()).optional()}),wt=_t.extend({text:l()}),Vt=_t.extend({blob:c}),tt=g({audience:C(i).optional(),priority:k().min(0).max(1).optional(),lastModified:fo.datetime({offset:!0}).optional()}),bt=g({...R.shape,...S.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(k()),annotations:tt.optional(),_meta:$(L({}))}),yr=g({...R.shape,...S.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:tt.optional(),_meta:$(L({}))}),ct=b.extend({method:w("notifications/resources/list_changed"),params:y.optional()}),dt=y.extend({uri:l()}),Sr=b.extend({method:w("notifications/resources/updated"),params:dt}),Rr=g({name:l(),description:$(l()),required:$(z())}),Gt=g({...R.shape,...S.shape,description:$(l()),arguments:$(C(Rr)),_meta:$(L({}))}),_r=b.extend({method:w("notifications/prompts/list_changed"),params:y.optional()}),rt=g({type:w("text"),text:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),Ke=g({type:w("image"),data:c,mimeType:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),Kt=g({type:w("audio"),data:c,mimeType:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),_n=g({type:w("tool_use"),name:l(),id:l(),input:O(l(),D()),_meta:O(l(),D()).optional()}),wn=g({type:w("resource"),resource:U([wt,Vt]),annotations:tt.optional(),_meta:O(l(),D()).optional()}),bn=bt.extend({type:w("resource_link")}),vt=U([rt,Ke,Kt,bn,wn]),wr=g({role:i,content:vt}),Wt=g({title:l().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),vn=b.extend({method:w("notifications/tools/list_changed"),params:y.optional()}),Cn=g({name:l().optional()}),In=g({hints:C(Cn).optional(),costPriority:k().min(0).max(1).optional(),speedPriority:k().min(0).max(1).optional(),intelligencePriority:k().min(0).max(1).optional()}),Tn=g({mode:F(["auto","required","none"]).optional()}),En=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:z().optional()}),kn=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:k().optional(),maxLength:k().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),An=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:k().optional(),maximum:k().optional(),default:k().optional()}),Pn=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),xn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),Mn=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),On=U([Pn,xn]),Un=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),qn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),zn=U([Un,qn]),Nn=U([Mn,On,zn]),jn=U([Nn,En,kn,An]),Zt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:O(l(),jn),required:C(l()).optional()}).catchall(D())}),Yt=g({type:w("ref/resource"),uri:l()}),Xt=g({type:w("ref/prompt"),name:l()}),Dn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:O(l(),D()).optional()}),Ct=B.shape,$n=g({experimental:Ct.experimental,sampling:Ct.sampling,elicitation:Ct.elicitation,roots:Ct.roots,extensions:Ct.extensions}),Le=W.shape,br=g({experimental:Le.experimental,logging:Le.logging,completions:Le.completions,prompts:Le.prompts,resources:Le.resources,tools:Le.tools,extensions:Le.extensions}),vr=L({progressToken:r.optional(),[Ur]:l(),[So]:v.optional(),[zr]:$n,[Ro]:a.optional()}),Qt=g({...R.shape,...S.shape,description:l().optional(),inputSchema:L({$schema:l().optional(),type:w("object")}),outputSchema:L({$schema:l().optional()}).optional(),annotations:Wt.optional(),_meta:O(l(),D()).optional()}),Ln=g({type:w("tool_result"),toolUseId:l(),content:C(vt),structuredContent:D().optional(),isError:z().optional(),_meta:O(l(),D()).optional()}),Cr=U([rt,Ke,Kt,_n,Ln]),er=g({role:i,content:U([Cr,C(Cr)]),_meta:O(l(),D()).optional()}),Ir=l(),Tr=L({[qr]:v.optional().catch(void 0)}),Er=Tr.optional();function Re(ne){return L({_meta:Er,resultType:Ir.default("complete"),...ne})}n(Re,"wireResult");let Hn=Re({}),ds=Re({nextCursor:o.optional()}),kr=Re({content:C(vt),structuredContent:D().optional(),isError:z().optional()}),Bn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),tools:C(Qt),nextCursor:o.optional()}),Fn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),prompts:C(Gt),nextCursor:o.optional()}),Jn=Re({description:l().optional(),messages:C(wr)}),Vn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resources:C(bt),nextCursor:o.optional()}),Gn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(yr),nextCursor:o.optional()}),Kn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),contents:C(U([wt,Vt]))}),Wn=Re({completion:g({values:C(l()).max(100),total:k().int().optional(),hasMore:z().optional()}).loose()}),us=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"])}),Zn=Re({ttlMs:k().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:br,instructions:l().optional()}),It=g({messages:C(er),modelPreferences:In.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:k().optional(),maxTokens:k().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Qt).optional(),toolChoice:Tn.optional()}),Yn=g({method:w("sampling/createMessage"),params:It}),Xn=g({method:w("roots/list"),params:g({_meta:O(l(),D()).optional()}).optional()}),Qn=g({...er.shape,model:l(),stopReason:l().optional()}),eo=g({roots:C(Dn)}),to=g({action:F(["accept","decline","cancel"]),content:O(l(),U([l(),k(),z(),C(l())])).optional()}),ro=g({mode:w("url"),message:l(),url:l().url()}),no=U([Zt,ro]),oo=g({method:w("elicitation/create"),params:no}),so=U([Yn,Xn,oo]),io=U([Qn,eo,to]),ao=O(l(),so),co=O(l(),io),tr=Re({inputRequests:ao.optional(),requestState:l().optional()}),rr={inputResponses:co.optional(),requestState:l().optional()},ls=g({_meta:vr,...rr}),ps=L({progressToken:r.optional()});function Ue(ne,or){return g({method:w(ne),params:g({_meta:vr,...or})})}n(Ue,"wireRequest");function qe(ne,or){return g({method:w(ne),params:g({_meta:ps.optional(),...or}).optional()})}n(qe,"dispatchRequest");let uo={name:l(),arguments:O(l(),D()).optional(),...rr},We={cursor:o.optional()},ms=Ue("tools/call",uo),hs=Ue("tools/list",We),fs=Ue("prompts/list",We),gs=Ue("prompts/get",{name:l(),arguments:O(l(),l()).optional(),...rr}),ys=Ue("resources/list",We),Ss=Ue("resources/templates/list",We),Rs=Ue("resources/read",{uri:l(),...rr}),lo={ref:U([Xt,Yt]),argument:g({name:l(),value:l()}),context:g({arguments:O(l(),l()).optional()}).optional()},_s=Ue("completion/complete",lo),ws=Ue("server/discover",{}),Ar=g({toolsListChanged:z().optional(),promptsListChanged:z().optional(),resourcesListChanged:z().optional(),resourceSubscriptions:C(l()).optional()}),po={notifications:Ar},bs=Ue("subscriptions/listen",po),vs=Tr.extend({"io.modelcontextprotocol/subscriptionId":s}),mo=L({_meta:vs,resultType:Ir.default("complete")}),Tt={"tools/call":qe("tools/call",uo),"tools/list":qe("tools/list",We),"prompts/get":qe("prompts/get",{name:l(),arguments:O(l(),l()).optional()}),"prompts/list":qe("prompts/list",We),"resources/list":qe("resources/list",We),"resources/templates/list":qe("resources/templates/list",We),"resources/read":qe("resources/read",{uri:l()}),"completion/complete":qe("completion/complete",lo),"server/discover":qe("server/discover",{}),"subscriptions/listen":qe("subscriptions/listen",po)};function xe(ne){return L({_meta:Er,...ne})}n(xe,"liftedResult");let Cs={"tools/call":xe({content:C(vt),structuredContent:D().optional(),isError:z().optional()}),"tools/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),tools:C(Qt),nextCursor:o.optional()}),"prompts/get":xe({description:l().optional(),messages:C(wr)}),"prompts/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),prompts:C(Gt),nextCursor:o.optional()}),"resources/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resources:C(bt),nextCursor:o.optional()}),"resources/templates/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(yr),nextCursor:o.optional()}),"resources/read":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),contents:C(U([wt,Vt]))}),"completion/complete":xe({completion:g({values:C(l()).max(100),total:k().int().optional(),hasMore:z().optional()}).loose()}),"server/discover":xe({ttlMs:k().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:br,instructions:l().optional()}),"subscriptions/listen":xe({})},nr=L({"io.modelcontextprotocol/subscriptionId":s.optional()}),Pr=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:nr.optional(),notifications:Ar})}),xr=g({_meta:nr.optional(),requestId:s,reason:l().optional()}),Mr=g({method:w("notifications/cancelled"),params:xr}),oa={"notifications/cancelled":Mr,"notifications/progress":Pe,"notifications/message":re,"notifications/resources/updated":Sr,"notifications/resources/list_changed":ct,"notifications/tools/list_changed":vn,"notifications/prompts/list_changed":_r,"notifications/subscriptions/acknowledged":Pr},be=n(ne=>g({jsonrpc:w("2.0"),id:U([l(),k().int()]),result:ne}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:p,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:y,NotificationSchema:b,IconSchema:_,IconsSchema:S,BaseMetadataSchema:R,ImplementationSchema:v,ClientTasksCapabilitySchema:A,ServerTasksCapabilitySchema:M,ClientCapabilitiesSchema:B,ServerCapabilitiesSchema:W,ProgressSchema:Z,ProgressNotificationParamsSchema:le,ProgressNotificationSchema:Pe,LoggingMessageNotificationParamsSchema:K,LoggingMessageNotificationSchema:re,ResourceContentsSchema:_t,TextResourceContentsSchema:wt,BlobResourceContentsSchema:Vt,AnnotationsSchema:tt,ResourceSchema:bt,ResourceTemplateSchema:yr,ResourceListChangedNotificationSchema:ct,ResourceUpdatedNotificationParamsSchema:dt,ResourceUpdatedNotificationSchema:Sr,PromptArgumentSchema:Rr,PromptSchema:Gt,PromptListChangedNotificationSchema:_r,TextContentSchema:rt,ImageContentSchema:Ke,AudioContentSchema:Kt,ToolUseContentSchema:_n,EmbeddedResourceSchema:wn,ResourceLinkSchema:bn,ContentBlockSchema:vt,PromptMessageSchema:wr,ToolAnnotationsSchema:Wt,ToolListChangedNotificationSchema:vn,ModelHintSchema:Cn,ModelPreferencesSchema:In,ToolChoiceSchema:Tn,BooleanSchemaSchema:En,StringSchemaSchema:kn,NumberSchemaSchema:An,UntitledSingleSelectEnumSchemaSchema:Pn,TitledSingleSelectEnumSchemaSchema:xn,LegacyTitledEnumSchemaSchema:Mn,SingleSelectEnumSchemaSchema:On,UntitledMultiSelectEnumSchemaSchema:Un,TitledMultiSelectEnumSchemaSchema:qn,MultiSelectEnumSchemaSchema:zn,EnumSchemaSchema:Nn,PrimitiveSchemaDefinitionSchema:jn,ElicitRequestFormParamsSchema:Zt,ResourceTemplateReferenceSchema:Yt,PromptReferenceSchema:Xt,RootSchema:Dn,ClientCapabilities2026Schema:$n,ServerCapabilities2026Schema:br,RequestMetaEnvelopeSchema:vr,ToolSchema:Qt,ToolResultContentSchema:Ln,SamplingMessageContentBlockSchema:Cr,SamplingMessageSchema:er,ResultTypeSchema:Ir,ResultMetaSchema:Tr,ResultSchema:Hn,PaginatedResultSchema:ds,CallToolResultSchema:kr,ListToolsResultSchema:Bn,ListPromptsResultSchema:Fn,GetPromptResultSchema:Jn,ListResourcesResultSchema:Vn,ListResourceTemplatesResultSchema:Gn,ReadResourceResultSchema:Kn,CompleteResultSchema:Wn,CacheableResultSchema:us,DiscoverResultSchema:Zn,CreateMessageRequestParamsSchema:It,CreateMessageRequestSchema:Yn,ListRootsRequestSchema:Xn,CreateMessageResultSchema:Qn,ListRootsResultSchema:eo,ElicitResultSchema:to,ElicitRequestURLParamsSchema:ro,ElicitRequestParamsSchema:no,ElicitRequestSchema:oo,InputRequestSchema:so,InputResponseSchema:io,InputRequestsSchema:ao,InputResponsesSchema:co,InputRequiredResultSchema:tr,InputResponseRequestParamsSchema:ls,CallToolRequestSchema:ms,ListToolsRequestSchema:hs,ListPromptsRequestSchema:fs,GetPromptRequestSchema:gs,ListResourcesRequestSchema:ys,ListResourceTemplatesRequestSchema:Ss,ReadResourceRequestSchema:Rs,CompleteRequestSchema:_s,DiscoverRequestSchema:ws,SubscriptionFilterSchema:Ar,SubscriptionsListenRequestSchema:bs,SubscriptionsListenResultMetaSchema:vs,SubscriptionsListenResultSchema:mo,dispatchRequestSchemas:Tt,dispatchResultSchemas:Cs,NotificationMetaSchema:nr,SubscriptionsAcknowledgedNotificationSchema:Pr,CancelledNotificationParamsSchema:xr,CancelledNotificationSchema:Mr,notificationSchemas2026:oa,JSONRPCResultResponseSchema:be(Hn),CallToolResultResponseSchema:be(U([kr,tr])),ListToolsResultResponseSchema:be(Bn),ListPromptsResultResponseSchema:be(Fn),GetPromptResultResponseSchema:be(U([Jn,tr])),ListResourcesResultResponseSchema:be(Vn),ListResourceTemplatesResultResponseSchema:be(Gn),ReadResourceResultResponseSchema:be(U([Kn,tr])),CompleteResultResponseSchema:be(Wn),DiscoverResultResponseSchema:be(Zn),SubscriptionsListenResultResponseSchema:be(mo)}}n(fb,"build");var gb;function mt(){return gb??=fb()}n(mt,"buildSchemas2026");var yb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Sb(e){return yb.includes(e)}n(Sb,"isCacheableResultMethod");var Ka=Symbol("modelcontextprotocol.resultCacheHintFallback");function Rb(e){return e[Ka]}n(Rb,"cacheHintFallbackOf");function rf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(rf,"isValidCacheTtlMs");function nf(e){return e==="public"||e==="private"}n(nf,"isValidCacheScope");var I=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),fe=class of extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return je(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 je(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",lr(this,new.target)}static fromError(t,r,o){if(t===I.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new ai(s.elicitations,r)}if(t===I.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new af({supported:s.supported,requested:s.requested},r)}if(t===I.InvalidParams||t===I.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===I.ResourceNotFound||Object.keys(s).length===1))return new sf(s.uri,r)}if(t===I.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new cf({requiredCapabilities:s.requiredCapabilities},r)}return new of(t,r,o)}},sf=class extends fe{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(I.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ai=class extends fe{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},af=class extends fe{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(I.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},cf=class extends fe{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(I.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},_b=0,wb="private",bb=["tools/call","prompts/get","resources/read"];function vb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||bb.includes(e))return t;throw new fe(I.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(vb,"stampResultType");function Cb(e,t){let r=Rb(t);if(t.resultType!=="complete"||!Sb(e))return r===void 0?t:Ab(t);let o=t,s=rf(o.ttlMs)?o.ttlMs:Eb(r),i=nf(o.cacheScope)?o.cacheScope:kb(r),a={...o,ttlMs:s,cacheScope:i};return delete a[Ka],a}n(Cb,"fillCacheFields");function Ib(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ib,"isPlainObject$4");function Tb(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[qr]:t}}:!Ib(r)||r[qr]!==void 0?e:{...e,_meta:{...r,[qr]:t}}}n(Tb,"stampServerInfoMeta");function Eb(e){return e!==void 0&&rf(e.ttlMs)?e.ttlMs:_b}n(Eb,"resolveTtlMs");function kb(e){return e!==void 0&&nf(e.cacheScope)?e.cacheScope:wb}n(kb,"resolveCacheScope");function Ab(e){let t={...e};return delete t[Ka],t}n(Ab,"stripCacheHintFallback");var Pb=["elicitation/create","sampling/createMessage","roots/list"],ni;function Wa(){if(ni)return ni;let e=mt();return ni={request:{"elicitation/create":g({method:w("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:w("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:w("roots/list"),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ni}n(Wa,"inputSchemaMaps");function xb(){Wa()}n(xb,"warmInputSchemaMaps2026");function df(e){return Pb.includes(e)}n(df,"isInputRequestMethod2026");function Ua(e){return df(e)?Wa().request[e]:void 0}n(Ua,"getInputRequestSchema2026");function Mb(e){return df(e)?Wa().response[e]:void 0}n(Mb,"getInputResponseSchema2026");var Za={"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},uf={"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 lf(e){return Object.prototype.hasOwnProperty.call(Za,e)}n(lf,"hasRequestMethod2026");function pf(e){return Object.prototype.hasOwnProperty.call(uf,e)}n(pf,"hasNotificationMethod2026");function Ob(e){return Object.prototype.hasOwnProperty.call(Za,e)}n(Ob,"hasResultMethod2026");function Ub(e){return lf(e)?mt().dispatchRequestSchemas[e]:void 0}n(Ub,"getRequestSchema2026");function qb(e){return Ob(e)?mt().dispatchResultSchemas[e]:void 0}n(qb,"getResultSchema2026");function zb(e){return pf(e)?mt().notificationSchemas2026[e]:void 0}n(zb,"getNotificationSchema2026");var $U=Object.keys(Za),LU=Object.keys(uf);function Oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Oo,"isPlainObject$3");function xo(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(xo,"triState");var Nb={ok:!1,reason:"not-in-era"},jb=[Ur,zr];function Db(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=>Oo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!Oo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(Oo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}n(Db,"enforceDeletedFields");var Ya={era:"2026-07-28",hasRequestMethod:lf,hasNotificationMethod:pf,hasInputRequestMethod:n(e=>Ua(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>xo(Ub(e),t),"validateRequest"),validateResult:n((e,t)=>xo(qb(e),t),"validateResult"),validateNotification:n((e,t)=>xo(zb(e),t),"validateNotification"),validateInputRequest:n((e,t)=>xo(Ua(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>xo(Mb(e),t),"validateInputResponse"),samplingResultVariant:n(()=>Nb,"samplingResultVariant"),outboundEnvelope(e){return{[Ur]:e.protocolVersion,[So]:e.clientInfo,[zr]:e.clientCapabilities,...e.logLevel!==void 0&&{[Ro]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of jb)o in e||t.push({key:o,problem:"missing"});let r=mt().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=>Wh(e),"projectCallToolResult"),inputRequestSchema:Ua,decodeResult(e,t){if(!Oo(t))return{kind:"invalid",error:new ae(he.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new ae(he.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 ae(he.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Oo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:mt().ResultMetaSchema.safeParse(t._meta),p=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new ae(he.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...p!==void 0&&{_meta:p}}}if(r!=="complete")return{kind:"invalid",error:new ae(he.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=mf(),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 ae(he.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 Tb(Cb(e,vb(e,Db(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=mt().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("; ")}`}},oi;function mf(){if(oi)return oi;let e=mt();return oi={"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},oi}n(mf,"getWireResultSchemas");function $b(){mf()}n($b,"warmWireResultSchemas2026");var Xa="2026-07-28";function qo(e){return e!==void 0&&Kh(e)?Ya:Ga}n(qo,"codecForVersion");function Dh(e){return e.revision!==void 0?qo(e.revision).era:e.era==="modern"?Ya.era:Ga.era}n(Dh,"classifiedWireEra");function qa(e){return hf.some(t=>t.hasRequestMethod(e))}n(qa,"isSpecRequestMethod");function za(e){return hf.some(t=>t.hasNotificationMethod(e))}n(za,"isSpecNotificationMethod");function $h(e){return e==="tasks/get"||e==="tasks/cancel"}n($h,"isExtensionReusedRequestMethod");var hf=[Ga,Ya],Lb=Oh({AnnotationsSchema:n(()=>gl,"AnnotationsSchema"),AudioContentSchema:n(()=>Wl,"AudioContentSchema"),BaseMetadataSchema:n(()=>Ku,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>Uu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>hl,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>ha,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>up,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>lp,"CallToolRequestSchema"),CallToolResultSchema:n(()=>cp,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>om,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>sm,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Fu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Ju,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Xu,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>am,"ClientNotificationSchema"),ClientRequestSchema:n(()=>im,"ClientRequestSchema"),ClientResultSchema:n(()=>cm,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Zu,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>dp,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Dp,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>$p,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Lp,"CompleteResultSchema"),ContentBlockSchema:n(()=>Ql,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Ip,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Tp,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Ep,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>kp,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Wp,"CreateTaskResultSchema"),CursorSchema:n(()=>Pu,"CursorSchema"),DiscoverRequestSchema:n(()=>ol,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>pa,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>zs,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Mp,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>Op,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Ns,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>zp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>Up,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>qp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Yl,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Bu,"EmptyResultSchema"),EnumSchemaSchema:n(()=>xp,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Jl,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Vl,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>tp,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>em,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>tm,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Xp,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>Qp,"GetTaskResultSchema"),IconSchema:n(()=>Vu,"IconSchema"),IconsSchema:n(()=>Gu,"IconsSchema"),ImageContentSchema:n(()=>Kl,"ImageContentSchema"),ImplementationSchema:n(()=>Wu,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>Qu,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>el,"InitializeRequestSchema"),InitializeResultSchema:n(()=>rl,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>nl,"InitializedNotificationSchema"),JSONArraySchema:n(()=>ku,"JSONArraySchema"),JSONObjectSchema:n(()=>Eu,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>_o,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>la,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>da,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>ir,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Hu,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>ua,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Tu,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>ya,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>ma,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Bl,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Fl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>wl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>bl,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Rl,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>_l,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Bp,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Fp,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>rm,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>nm,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>ip,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>ap,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>mp,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>gp,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>yp,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Sp,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Rp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Pp,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>ju,"NotificationSchema"),NotificationsParamsSchema:n(()=>Nu,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>qs,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>dl,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>ul,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>ll,"PaginatedResultSchema"),PingRequestSchema:n(()=>sl,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>_a,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>al,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>cl,"ProgressNotificationSchema"),ProgressSchema:n(()=>il,"ProgressSchema"),ProgressTokenSchema:n(()=>Au,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Ll,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>rp,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>ep,"PromptMessageSchema"),PromptReferenceSchema:n(()=>jp,"PromptReferenceSchema"),PromptSchema:n(()=>Hl,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Cl,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Il,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Tl,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Mu,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Lu,"RequestIdSchema"),RequestMetaSchema:n(()=>Ou,"RequestMetaSchema"),RequestSchema:n(()=>zu,"RequestSchema"),ResourceContentsSchema:n(()=>pl,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Xl,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>El,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>vl,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>yl,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Np,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Sl,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Dl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>$l,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Du,"ResultMetaObjectSchema"),ResultSchema:n(()=>$u,"ResultSchema"),RoleSchema:n(()=>fl,"RoleSchema"),RootSchema:n(()=>Hp,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Jp,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>bp,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>vp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Cp,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>tl,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>um,"ServerNotificationSchema"),ServerRequestSchema:n(()=>dm,"ServerRequestSchema"),ServerResultSchema:n(()=>lm,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Yu,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>hp,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>fp,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Ap,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Us,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>kl,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Al,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Ml,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>ql,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>zl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>Ol,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>Ul,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Nl,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>jl,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>qu,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Vp,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>xu,"TaskMetadataSchema"),TaskSchema:n(()=>Kp,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Zp,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Yp,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>Gp,"TaskStatusSchema"),TextContentSchema:n(()=>Gl,"TextContentSchema"),TextResourceContentsSchema:n(()=>ml,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Ra,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>ga,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>np,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>_p,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>op,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>pp,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>wp,"ToolResultContentSchema"),ToolSchema:n(()=>sp,"ToolSchema"),ToolUseContentSchema:n(()=>Zl,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Pl,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>xl,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Sa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>fa,"UntitledSingleSelectEnumSchemaSchema")});var ff=n(e=>ir.safeParse(e).success,"isJSONRPCRequest"),gf=n(e=>da.safeParse(e).success,"isJSONRPCNotification"),La=n(e=>ua.safeParse(e).success,"isJSONRPCResultResponse"),yf=n(e=>_o.safeParse(e).success,"isJSONRPCErrorResponse");var Uo=-32020,HU=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[I.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Uo,I.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[I.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[I.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[I.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Uo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[I.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Uo],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."}],BU={[I.ParseError]:400,[I.InvalidRequest]:400,[I.MethodNotFound]:404,[I.UnsupportedProtocolVersion]:400,[I.MissingRequiredClientCapability]:400,[Uo]:400};function Qa(e,t){return hu(e,t)}n(Qa,"parseSchema");function Mo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Mo,"shapeKeys");function Ha(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(Ha,"isStandardSchema");var Lh=!1,Ba="draft-2020-12";function Hb(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:Ba});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Lh||(Lh=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=sa(e,{target:Ba,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:Sf(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(Hb,"standardSchemaToJsonSchema");function Sf(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"||Sf(o)))}return!1}n(Sf,"isProvablyObjectShapedRoot");function Bb(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Bb,"formatIssue");async function Na(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Bb(o)).join(", ")}:{success:!0,data:r.value}}n(Na,"validateStandardSchema");function Fb(e){let t=sa(e,{target:Ba,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(Fb,"zodEmittedPattern");var Jb=/\\\.\\d\{(\d+)\}/;function Vb(e){let t=Jb.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=>fo.datetime({local:o,offset:s,precision:i}))))}n(Vb,"datetimeReferenceSchemas");function Gb(e,t){let r;switch(e){case"email":r=[fu()];break;case"uri":r=[gu()];break;case"date":r=[fo.date()];break;case"date-time":r=Vb(t);break}return new Set(r.map(o=>Fb(o)).filter(o=>o!==void 0))}n(Gb,"referencePatternsForFormat");function Kb(e,t,r){return r!=="zod"?!0:Gb(e,t).has(t)}n(Kb,"isLibraryFormatPattern");function zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(zo,"isJsonObject");function Wb(e){try{return Hb(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new fe(I.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(Wb,"convertStandardElicitationSchema");var Zb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function ec(e){return Zb.has(e)||e.startsWith("x-")}n(ec,"isAnnotationOnlyJsonSchemaKeyword");var Yb=new Set(["$schema",...Object.keys(zs.shape.requestedSchema.shape)]),Hh={string:Mo([Us,fa,ga,ya]),number:Mo([qs]),integer:Mo([qs]),boolean:Mo([ha]),array:Mo([Sa,Ra])},Xb=new Set(Us.shape.format.unwrap().options);function Qb(e,t,r,o){if(!zo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Hh,e.type)?Hh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||ec(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?Xb.has(e.format)?(typeof c!="string"||!Kb(e.format,c,r))&&o.push(`${t}.${a}`):i[a]=c:o.push(`${t}.${a}`);return i}n(Qb,"walkProperty");function ev(e,t){let r={},o=[];for(let[s,i]of Object.entries(e))s==="properties"&&zo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Qb(c,`properties.${a}`,t,o)])):Yb.has(s)?r[s]=i:ec(s)||o.push(s);if(o.length>0)throw new fe(I.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(ev,"walkRequestedSchema");function tv(e,t){if(!zo(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Qa(_a,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(tv,"describeUnsupportedProperties");function Fa(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Fa(o,t[s],`${r}[${s}]`)):!zo(e)||!zo(t)?[]:Object.entries(e).flatMap(([o,s])=>{let i=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Fa(s,t[o],i):ec(o)?[]:[i]})}n(Fa,"findDroppedConstraintPaths");function rv(e){if(!Ha(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=ev(Wb(e.requestedSchema),t),o=Qa(zs.shape.requestedSchema,r);if(!o.success)throw new fe(I.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${tv(r,o.error.message)}`);let s=Fa(r,o.data);if(s.length>0)throw new fe(I.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 fe(I.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(rv,"normalizeElicitInputParams");function nv(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(nv,"buildInputRequired");var FU=Object.assign(nv,{elicit(e){try{return{method:"elicitation/create",params:rv(e)}}catch(t){throw t instanceof fe?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 ov=["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"],sv={IdJagTokenExchangeResponseSchema:wa,OAuthClientInformationFullSchema:ar,OAuthClientInformationSchema:wo,OAuthClientMetadataSchema:mm,OAuthClientRegistrationErrorSchema:hm,OAuthErrorResponseSchema:js,OAuthMetadataSchema:jr,OAuthProtectedResourceMetadataSchema:Nr,OAuthTokenRevocationRequestSchema:fm,OAuthTokensSchema:At,OpenIdProviderDiscoveryMetadataSchema:Dr,OpenIdProviderMetadataSchema:pm},Rf={},_f={};function wf(e,t){let r=e.slice(0,-6);Rf[r]=t,_f[r]=o=>t.safeParse(o).success}n(wf,"register");for(let e of ov)wf(e,Lb[e]);for(let[e,t]of Object.entries(sv))wf(e,t);var iv=Object.freeze(Rf),av=Object.freeze(_f);function cv(e){switch(e){case"initialize":case"notifications/initialized":return qo(void 0);case"server/discover":return qo(Xa);default:return}}n(cv,"bootstrapOutboundCodec");var bf=6e4,dv=[Ur,So,zr,Ro],uv=["inputResponses","requestState"];function Bh(e,t){let r=e.params;if(!ja(r))return{message:e,lifted:{}};let o=r._meta,s=ja(o)?dv.filter(d=>d in o):[],i=t==="request"?uv.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&ja(o)){let d={},u={...o};for(let p of s)d[p]=o[p],delete u[p];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}n(Bh,"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(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(Fh,"codecResultValidator");function vf(e){return()=>e}n(vf,"requestStateAccessor");var lv=vf(void 0),pv,mv=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{pv=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Or,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 ae(he.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 ae(he.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),La(s)||yf(s)?this._onresponse(s):ff(s)?this._onrequest(s,i):gf(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 ae(he.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}=Bh(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Dh(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(za(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}=Bh(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,R)=>{let v={jsonrpc:"2.0",id:r.id,error:{code:_,message:S,...R!==void 0&&{data:R}}};i?.send(v).catch(P=>this._onerror(new Error(`Failed to send an error response: ${P}`)))},"sendErrorResponse");if(t?.classification!==void 0){let _=Dh(t.classification);if(_!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${_} but this instance serves ${s.era}`));let S=t.classification.revision??_;a(I.UnsupportedProtocolVersion,`Unsupported protocol version: ${S}`,{supported:this._supportedProtocolVersions,requested:S});return}}if(qa(r.method)&&!s.hasRequestMethod(r.method)&&!($h(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(I.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(I.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(o);if(d!==void 0){a(I.InvalidParams,d);return}let u=n((_,S)=>this._notificationViaCodec(this._resolveOutboundCodec(_.method),_,{...S,relatedRequestId:r.id}),"sendNotification"),p=n((_,S,R)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(_.method),_,S,{...R,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=o.inputResponses===void 0?void 0:hv(o.inputResponses),y={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?lv:vf(o.requestState),signal:h.signal,send:n(((_,S,R)=>{let v=this._resolveOutboundCodec(_.method);if(this._assertOutboundRequestInEra(v,_.method),Ha(S))return p(_,S,R);let P=Fh(v,_.method);if(P===void 0)throw new TypeError(`'${_.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(_,P,S)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(y,t);Promise.resolve().then(()=>c(r,b)).then(async _=>{if(h.signal.aborted)return;let S;try{S=s.encodeResult(r.method,_,this._outboundServerInfo())}catch(v){this._onerror(new Error(`Failed to encode result for ${r.method}: ${v}`)),a(I.InternalError,"Internal error");return}let R={result:S,jsonrpc:"2.0",id:r.id};await i?.send(R)},async _=>{if(h.signal.aborted)return;let S=Number.isSafeInteger(_.code)?_.code:I.InternalError,R={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(S),message:_.message??"Internal error",..._.data!==void 0&&{data:_.data}}};await i?.send(R)}).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,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),La(e)?r(e):r(fe.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(Ha(t))return $h(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let s=Fh(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 qo(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=cv(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(qa(t)&&!e.hasRequestMethod(t))throw new ae(he.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(),u,p;return new Promise((h,f)=>{let y=n(M=>{f(M)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(M){y(M);return}if(o?.signal?.aborted){let M=o.signal.reason;throw M instanceof ae?M:new ae(he.RequestTimeout,String(M))}let b=e.era===Xa&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;p=_;let S={...t,jsonrpc:"2.0",id:_};o?.onprogress&&(this._progressHandlers.set(_,o.onprogress),S.params={...t.params,_meta:{...t.params?._meta,progressToken:_}});let R=this._envelopeOutbound(S),v=!1,P=n(M=>{v||(this._progressHandlers.delete(_),b===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(M)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`))):b.abort(),f(M instanceof ae?M:new ae(he.RequestTimeout,String(M))))},"cancel");this._responseHandlers.set(_,M=>{if(o?.signal?.aborted)return;if(v=!0,M instanceof Error)return f(M);let B;try{B=e.decodeResult(t.method,M.result)}catch(Z){return f(Z instanceof Error?Z:new Error(String(Z)))}if(B.kind==="invalid")return f(B.error);if(B.kind==="input_required"){if(o?.allowInputRequired===!0)return h(fv(B));let Z={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:d,retry:n((le,Pe)=>this._requestWithSchemaViaCodec(e,le===void 0?{method:t.method}:{method:t.method,params:le},r,Pe),"retry")};return h(this._resolveNonCompleteResult(B,Z))}let W=B.result;Na(r,W).then(Z=>{Z.success?h(Z.data):f(new ae(he.InvalidResult,`Invalid result for ${t.method}: ${Z.error}`))},f)}),u=n(()=>P(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",u,{once:!0});let N=o?.timeout??bf,A=n(()=>P(new ae(he.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(_,N,o?.maxTotalTimeout,A,o?.resetTimeoutOnProgress??!1),this._transport.send(R,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:b?.signal}).catch(M=>{this._progressHandlers.delete(_),f(M)})}).finally(()=>{u&&o?.signal?.removeEventListener("abort",u),p!==void 0&&(this._responseHandlers.delete(p),this._cleanupTimeout(p))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new ae(he.NotConnected,"Not connected");if(za(t.method)&&!e.hasNotificationMethod(t.method))throw new ae(he.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(!qa(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 fe(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)o=n(async(s,i)=>{let a=await Na(t.params,{...s.params});if(!a.success)throw new fe(I.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,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(!za(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 fe(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Na(t.params,{...o.params});if(!s.success)throw new fe(I.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ja(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ja,"isPlainObject$1");function Jh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Jh,"isPlainObject");function hv(e){let t={},r=[];if(!Jh(e))return{accepted:t,droppedKeys:r};for(let[o,s]of Object.entries(e)){if(!Jh(s)||"method"in s||"result"in s){r.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:r}}n(hv,"partitionInputResponses");function fv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}n(fv,"manualInputRequiredValue");var gv=Mh((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 u=d.indexOf(";"),p=u!==-1?d.slice(0,u).trim():d.trim();if(!o.test(p))throw new TypeError("invalid media type");var h=new a(p.toLowerCase());if(u!==-1){var f,y,b;for(t.lastIndex=u;y=t.exec(d);){if(y.index!==u)throw new TypeError("invalid parameter format");u+=y[0].length,f=y[1].toLowerCase(),b=y[2],b.charCodeAt(0)===34&&(b=b.slice(1,-1),b.indexOf("\\")!==-1&&(b=b.replace(r,"$1"))),h.parameters[f]=b}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}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")})),JU=Uh(gv(),1);var yv=10*1024*1024;var Sv=new Set([301,302,303,307,308]),Rv=5;function _v(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(_v,"isWithinOrigin");function wv(e,t){let r=Sv.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}n(wv,"redirectTarget");var bv=new WeakSet;function ci(e){return bv.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=wv(s,a);if(!c||i===Rv)return a;let d=new URL(s),u=o==="GET"||a.status===307||a.status===308,p=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!p||!_v(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}n(ci,"fetchWithinOrigin");function tc(){Va(),mt(),ub(),xb(),$b()}n(tc,"preloadSchemas");var n0=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 vv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cv=[0,31,28,31,30,31,30,31,31,30,31,30,31],Iv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Tv=/^(?=.{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,Ev=/^(?:[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,kv=/^(?:(?:[^\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,Av=/^(?:(?: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,Pv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Mv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ov=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Uv=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"),qv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,zv=/^((([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,Nv=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 it(e){return e.test.bind(e)}n(it,"bind");var o0={date:Cf,time:If.bind(void 0,!1),"date-time":$v,duration:Nv,uri:Bv,"uri-reference":it(Ev),"uri-template":it(kv),url:it(Av),email:Uv,hostname:it(Tv),ipv4:it(qv),ipv6:it(zv),regex:Jv,uuid:it(Pv),"json-pointer":it(xv),"json-pointer-uri-fragment":it(Mv),"relative-json-pointer":it(Ov)};function jv(e){return e%4===0&&(e%100!==0||e%400===0)}n(jv,"isLeapYear");function Cf(e){let t=e.match(vv);if(!t)return!1;let r=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o==2&&jv(r)?29:Cv[o])}n(Cf,"date");function If(e,t){let r=t.match(Iv);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(If,"time");var Dv=/t|\s/i;function $v(e){let t=e.split(Dv);return t.length==2&&Cf(t[0])&&If(!0,t[1])}n($v,"date_time");var Lv=/\/|:/,Hv=/^(?:[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 Bv(e){return Lv.test(e)&&Hv.test(e)}n(Bv,"uri");var Fv=/[^\\]\\Z/;function Jv(e){if(Fv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(Jv,"regex");tc();var Tf=!1;var rc;rc=globalThis.crypto;async function Gv(e){return(await rc).getRandomValues(new Uint8Array(e))}n(Gv,"getRandomValues");async function Kv(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let s=await Gv(e-o.length);for(let i of s)i<r&&(o+=t[i%t.length])}return o}n(Kv,"random");async function Wv(e){return await Kv(e)}n(Wv,"generateVerifier");async function Zv(e){let t=await(await rc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Zv,"generateChallenge");async function nc(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Wv(e),r=await Zv(t);return{code_verifier:t,code_challenge:r}}n(nc,"pkceChallenge");var jo=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e){super(e),this.name=new.target.name,lr(this,new.target)}},No=class extends jo{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}},cc=class extends jo{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}},li=class extends jo{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}},ui=class extends jo{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}},G0=class extends jo{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 ac(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}):Pf(e.issuer,t)?e:void 0}n(ac,"discardIfIssuerMismatch");function Pf(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(Pf,"issuersMatch");var K0=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",lr(this,new.target)}};function xf(e){return e?.authorization_response_iss_parameter_supported===!0}n(xf,"isIssParameterSupported");function Mf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new No("authorization_response",t,void 0);return}if(e!==t)throw new No("authorization_response",t,e)}}n(Mf,"validateAuthorizationResponseIssuer");function Yv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Yv,"isClientAuthMethod");var oc="code",sc="S256";function Xv(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Yv(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(Xv,"selectClientAuthMethod");function Qv(e,t,r,o){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":eC(s,i,r);return;case"client_secret_post":tC(s,i,o);return;case"none":rC(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Qv,"applyClientAuthentication");function eC(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(eC,"applyBasicAuth");function tC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(tC,"applyPostAuth");function rC(e,t){t.set("client_id",e)}n(rC,"applyPublicAuth");function Of(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Of,"isLoopbackHost");function nC(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Of(t.hostname))throw new li(t.href);return t}n(nC,"assertSecureTokenEndpoint");function oC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Of(r.hostname))return"native"}return"web"}n(oC,"deriveApplicationType");function sC(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??oC(t.redirect_uris)}}n(sC,"resolveClientMetadata");async function Ef(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=js.parse(JSON.parse(r));return Ut.fromResponse(o)}catch(o){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Ut(ce.ServerError,s)}}n(Ef,"parseErrorResponse");function kf(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`}n(kf,"warnCredentialInvalidation");async function dc(e,t){try{return await ic(e,t)}catch(r){if(r instanceof Ut){if(r.code===ce.InvalidClient||r.code===ce.UnauthorizedClient)return kf(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ic(e,t);if(r.code===ce.InvalidGrant||r.code===ce.InvalidDpopProof)return kf(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await ic(e,t)}throw r}}n(dc,"auth");function iC(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(iC,"determineScope");async function ic(e,{serverUrl:t,authorizationCode:r,iss:o,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=sC(e),p=await e.discoveryState?.(),h,f,y,b,_=i;if(!_&&p?.resourceMetadataUrl&&(_=new URL(p.resourceMetadataUrl)),p?.authorizationServerUrl){if(f=p.authorizationServerUrl,h=p.resourceMetadata,y=p.authorizationServerMetadata??await Nf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await qf(t,{resourceMetadataUrl:_},a)}catch(K){if(K instanceof TypeError)throw K}(y!==p.authorizationServerMetadata||h!==p.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:y})}else{let K=await mC(t,{resourceMetadataUrl:_,fetchFn:a,skipIssuerMetadataValidation:c});f=K.authorizationServerUrl,y=K.authorizationServerMetadata,h=K.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:y}}let S=y?.issuer??String(f),R={issuer:S};if(await e.saveAuthorizationServerUrl?.(S),r!==void 0){let K=p?.authorizationServerMetadata?.issuer??p?.authorizationServerUrl;if(K===void 0){if(e.saveDiscoveryState!==void 0)throw new ui("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",S);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Pf(K,S))throw new ui(K,S)}b&&await e.saveDiscoveryState?.(b);let v=await aC(t,e,h),P=v&&h&&!e.validateResourceURL?h.resource:v;P&&await e.saveResourceUrl?.(lc(P));let N=iC({requestedScope:s,resourceMetadata:h,authServerMetadata:y,clientMetadata:e.clientMetadata}),A=await Promise.resolve(e.clientInformation(R)),M=ac(A,S,{canPersistStamp:e.saveClientInformation!==void 0});if(M===void 0&&A?.issuer&&e.saveClientInformation===void 0)throw new ui(A.issuer,S);if(M&&M.issuer===void 0&&(M={...M,issuer:S},await e.saveClientInformation?.(M,R)),!M){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let K=y?.client_id_metadata_document_supported===!0,re=e.clientMetadataUrl;if(re&&!uc(re))throw new Ut(ce.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${re}`);if(K&&re)M={client_id:re,issuer:S},await e.saveClientInformation?.(M,R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");M={...await SC(f,{metadata:y,clientMetadata:u,scope:N,fetchFn:a}),issuer:S},await e.saveClientInformation(M,R)}}let B=!e.redirectUrl;if(r!==void 0||B){r!==void 0&&Mf({iss:o,expectedIssuer:y?.issuer,issParameterSupported:xf(y)});let K=await yC(e,f,{metadata:y,resource:P,authorizationCode:r,iss:o,scope:N,fetchFn:a});return await e.saveTokens({...K,issuer:S},R),"AUTHORIZED"}let W=ac(await e.tokens(R),S);if(W&&W.issuer===void 0&&(W={...W,issuer:S},await e.saveTokens(W,R)),W?.refresh_token&&!d){let K;try{K=await gC(f,{metadata:y,clientInformation:M,refreshToken:W.refresh_token,resource:P,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(re){if(re instanceof li||!(!(re instanceof Ut)||re.code===ce.ServerError))throw re}if(K)return await e.saveTokens({...K,issuer:S},R),"AUTHORIZED"}let Z=e.state?await e.state():void 0,{authorizationUrl:le,codeVerifier:Pe}=await hC(f,{metadata:y,clientInformation:M,state:Z,redirectUrl:e.redirectUrl,scope:N,resource:P});return await e.saveCodeVerifier(Pe),await e.redirectToAuthorization(le),"REDIRECT"}n(ic,"authInternal");function uc(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(uc,"isHttpsUrl");async function aC(e,t,r){let o=Gh(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!si({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(aC,"selectResourceURL");var cC=new Set(["bearer","dpop"]);function Uf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!cC.has(r.toLowerCase())||!o)return{};let s=di(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=di(e,"scope")||void 0,c=di(e,"error")||void 0,d=di(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}n(Uf,"extractWWWAuthenticateParams");function di(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(di,"extractFieldFromWwwAuth");async function qf(e,t,r=fetch){let o=await lC(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 Nr.parse(await o.json())}n(qf,"discoverOAuthProtectedResourceMetadata");async function zf(e,t,r=fetch){let o=ci(r);try{return await o(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Tf)throw s;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(zf,"fetchWithCorsRetry");function dC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(dC,"buildWellKnownPath");async function Af(e,t,r=fetch){return await zf(e,{"MCP-Protocol-Version":t},r)}n(Af,"tryMetadataDiscovery");function uC(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}n(uC,"shouldAttemptFallback");async function lC(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=dC(t,s.pathname);a=new URL(d,o?.metadataServerUrl??s),a.search=s.search}let c=await Af(a,i,r);return!o?.metadataUrl&&uC(c,s.pathname)&&(c=await Af(new URL(`/.well-known/${t}`,s),i,r)),c}n(lC,"discoverMetadataWithFallback");function pC(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(pC,"buildDiscoveryUrls");async function Nf(e,{fetchFn:t=fetch,protocolVersion:r=Os,skipIssuerValidation:o=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=pC(e);for(let{url:a,type:c}of i){let d=await zf(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"?jr.parse(await d.json()):Dr.parse(await d.json());if(!o){let p=typeof e=="string"?e:e.href;if(!(u.issuer===p||p.endsWith("/")&&u.issuer===p.slice(0,-1)))throw new No("metadata",p,u.issuer)}return u}}n(Nf,"discoverAuthorizationServerMetadata");async function mC(e,t){let r,o;try{r=await qf(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 Nf(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:s,resourceMetadata:r}}n(mC,"discoverOAuthServerInfo");function lc(e){return typeof e=="string"?e:e.href}n(lc,"resourceIndicatorToString");async function hC(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(oc))throw new Error(`Incompatible auth server: does not support response type ${oc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(sc))throw new Error(`Incompatible auth server: does not support code challenge method ${sc}`)}else c=new URL("/authorize",e);let d=await nc(),u=d.code_verifier,p=d.code_challenge;return c.searchParams.set("response_type",oc),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",sc),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",lc(a)),{authorizationUrl:c,codeVerifier:u}}n(hC,"startAuthorization");function fC(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(fC,"prepareAuthorizationCodeRequest");async function jf(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=nC(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",lc(i)),!s&&o&&Qv(Xv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=n(async()=>{let y=new Headers(u);return s&&await s(y,r,d,t),a&&y.set("DPoP",await a.buildProof({htm:"POST",htu:d})),ci(c??fetch)(d,{method:"POST",headers:y,body:r})},"requestOnce"),h=await p();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===ce.UseDpopNonce&&(a.observeNonce(h,d),h=await p()),a?.observeNonce(h,d),!h.ok)throw await Ef(h);let f=await h.json();try{return At.parse(Ja(f))}catch(y){throw typeof f=="object"&&f!==null&&"error"in f?await Ef(JSON.stringify(f)):y}}n(jf,"executeTokenRequest");async function gC(e,{metadata:t,clientInformation:r,refreshToken:o,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:o,...await jf(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}n(gC,"refreshAuthorization");async function yC(e,t,{metadata:r,resource:o,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&Mf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:xf(r)});let d=r?.issuer??String(t),u=n(async()=>{let y=await e.clientInformation({issuer:d}),b=ac(y,d,{canPersistStamp:!1});if(y&&b===void 0)throw new ui(String(y.issuer),d);return b},"readClientInformation"),p=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=fC(s,await e.codeVerifier(),e.redirectUrl)}return p??=await u(),jf(t,{metadata:r,tokenRequestParams:f,clientInformation:p,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:c})}n(yC,"fetchToken");async function SC(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 ci(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new cc({status:c.status,body:await c.text(),submittedMetadata:a});return ar.parse(Ja(await c.json()))}n(SC,"registerClient");var W0=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,lr(this,new.target)}};function ge(e){let t=ir.safeParse(e);return t.success?t.data.id:void 0}n(ge,"parseJsonRpcRequestId");function pc(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return ge(t)}catch{return}}n(pc,"readJsonRpcRequestIdFromBody");function Te(e){return _o.parse({jsonrpc:sr,...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(Te,"jsonRpcErrorResponse");function Df(e){return new ai([Ns.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Df,"urlElicitationRequiredError");var mc=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],Do=[cr,...mc],RC=0,_C="private",wC="0.0.0";function bC(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}n(bC,"buildGatewayDiscoverCapabilities");function hc(e){let{connection:t}=e,r=t.serverInfo,o=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...o===void 0?{}:{title:o},version:r?.version??wC,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}n(hc,"buildGatewayDiscoverServerInfo");function $f(e){let t=ge(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...e.supportedVersions??Do],capabilities:bC(e.capabilityFilter),_meta:{[Pt]:hc({connection:e.connection,icons:e.icons})},ttlMs:RC,cacheScope:_C}})}n($f,"gatewayDiscoverResponse");var vC=/^\d{4}-\d{2}-\d{2}$/;var mi="2026-07-28",$o;function CC(){return $o??=new Map,$o}n(CC,"store");function pi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(pi,"isRecord");function Lf(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string"&&vC.test(r)))].slice(0,32);return t.length===0?void 0:t}n(Lf,"readVersionList");function hi(e,t){if(!pi(t))return;if(e==="server/discover"&&pi(t.result))return Lf(t.result.supportedVersions);let r=t.error;if(pi(r)&&r.code===-32022&&pi(r.data))return Lf(r.data.supported)}n(hi,"readUpstreamSupportedVersions");function fi(e,t,r={}){let o=CC(),s=o.get(e),i=t.some(d=>d<mi),a=r.modernOnly===!0||s?.modernOnly===!0&&!i,c=!i&&!a&&s?.complete===!0?s.versions.filter(d=>d<mi):[];if(o.delete(e),o.set(e,{versions:[...t,...c],complete:a||i||c.length>0,modernOnly:a}),o.size>512){let d=o.keys().next().value;d!==void 0&&o.delete(d)}}n(fi,"recordUpstreamSupportedVersions");function gi(e,t){let r=e===void 0?void 0:$o?.get(e);if(r===void 0)return t;let o=t.filter(s=>r.versions.includes(s));return o.length===0?t:r.complete?o:t.filter(s=>s<mi||o.includes(s))}n(gi,"advertisedSupportedVersions");function Hf(e){let t=$o?.get(e);t?.modernOnly===!0&&$o?.set(e,{versions:t.versions,complete:t.versions.some(r=>r<mi),modernOnly:!1})}n(Hf,"recordUpstreamAcceptsInitialize");var IC=-32e3,TC="2025-11-25",EC=/^\d{4}-\d{2}-\d{2}$/,gc=I.InternalError;function fc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(fc,"isRecord");function kC(e,t){return typeof e=="string"&&EC.test(e)&&e>=t}n(kC,"isAtLeast");function AC(e){if(e.method!=="initialize")return!1;let t=fc(e.params)?e.params:void 0,o=(fc(t?.capabilities)?t.capabilities:void 0)?.elicitation,s=t?.protocolVersion;return kC(s,TC)&&!bo(s)&&fc(o)&&o.url!==void 0}n(AC,"acceptsUrlElicitation");function yc(e){let{payload:t}=e,r=t.authUrl===void 0||!e.urlElicitation?void 0:Df({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Te({...e.id===void 0?{}:{id:e.id},error:{code:r?.code??e.fallbackCode,message:t.message,data:{...r?.data??{},connectRequired:t}}})}n(yc,"legacyConnectRequiredError");function Bf(e,t){let r=Hr(e,t);if(r!==void 0)return{kind:"invalid",error:r};let o=e,s=ge(e);return s===void 0?{kind:"accepted",response:typeof o.method!="string"}:{kind:"request",id:s,message:o}}n(Bf,"classifyMessage");function en(e,t){return Response.json(Te({error:{code:e,message:t}}),{status:400})}n(en,"unidentifiedError");function Ff(){return new Response(null,{status:202})}n(Ff,"acceptedResponse");function PC(e,t){return Y()?qm(e,t):void 0}n(PC,"modernBatchVersion");function xC(e,t){let r=e.get("mcp-protocol-version"),o=PC(e,t)??(Ls(r)?r??void 0:void 0);return o===void 0?void 0:en(I.InvalidRequest,`Invalid Request: protocol version ${o} does not support JSON-RPC batches`)}n(xC,"batchRefusal");function Jf(e,t,r){let o=(Array.isArray(t)?t:[t]).filter(i=>Hr(i)===void 0);if(o.length===0)return;if(o.some(ym))return o.length>1?en(I.InvalidRequest,"Invalid Request: Only one initialization request is allowed"):void 0;let s=e.get("mcp-protocol-version");if(!(s===null||r.accepted(s)))return en(IC,`Bad Request: Unsupported protocol version: ${s} (supported versions: ${r.listed.join(", ")})`)}n(Jf,"transportVersionRefusal");function Vf(e,t){return Jf(e,t,{accepted:n(r=>Or.includes(r),"accepted"),listed:Or})}n(Vf,"handlerTransportVersionRefusal");function MC(e,t,r){let o=gi(r,Y()?Do:mc);return Jf(e,t,{accepted:n(s=>o.includes(s)||Y()&&s===cr,"accepted"),listed:o})}n(MC,"gatewayTransportVersionRefusal");function OC(e){return{jsonrpc:"2.0",id:e,result:{}}}n(OC,"pingResult");function Gf(e){if(e.parsed===void 0)return en(I.ParseError,"Parse error: Invalid JSON");let t=Array.isArray(e.parsed)?xC(e.headers,e.parsed):void 0;if(t!==void 0)return t;let r=MC(e.headers,e.parsed,e.payload.upstreamServerId);if(r!==void 0)return r;let o=n(i=>i.message.method==="ping"?OC(i.id):yc({id:i.id,payload:e.payload,urlElicitation:AC(i.message),fallbackCode:gc}),"answer");if(Array.isArray(e.parsed)){if(e.parsed.length===0)return en(I.InvalidRequest,"Invalid Request: empty batch");let i=e.parsed.map((c,d)=>Bf(c,d)),a=i.flatMap(c=>{switch(c.kind){case"request":return[o(c)];case"invalid":return[c.error];case"accepted":return[]}});return i.every(c=>c.kind==="invalid")?Response.json(a,{status:400}):a.length===0?Ff():Response.json(a)}let s=Bf(e.parsed);switch(s.kind){case"request":return Response.json(o(s));case"accepted":return s.response&&Y()&&bo(e.headers.get("mcp-protocol-version"))?en(I.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):Ff();case"invalid":return Response.json(s.error,{status:400})}}n(Gf,"legacyConnectRequiredResponse");function Ee(){return Is.instance.build.COMPATIBILITY_FLAGS.mcpGatewaySpecCompliance===!0}n(Ee,"isMcpGatewaySpecComplianceEnabled");var UC={Allow:"POST"};function yi(e,t){return Me.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},UC)}n(yi,"gatewayMethodNotAllowed");function He(e){return(e??"").split(";")[0].trim().toLowerCase()}n(He,"mediaTypeEssence");var Zf=new Set(["jsonrpc","method","id","params"]),_c=new Set(["name","uri","ref"]),Yf=new Set(["type","name","uri"]),qC="subscriptions/listen",wc="notifications",Xf="resourceSubscriptions",zC=new Set([..._c,ht(wc)]),NC=new Set([ht(Xf)]),jC=/[^\u0000-\u007f]/,DC=34,$C=92,Kf=123,LC=125,HC=91,BC=93,FC=58,Sc=44;function Lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Lo,"isRecord");function ht(e){return e.toUpperCase().toLowerCase()}n(ht,"foldCase");function Rc(e,t){return Object.keys(e).some(r=>{let o=ht(r);return o!==r&&t.has(o)})}n(Rc,"hasCaseVariant");function Wf(e,t){let r=ht(t);return Object.keys(e).some(o=>o!==t&&ht(o)===r)}n(Wf,"hasCaseVariantOf");function JC(e,t){let r=n(a=>{switch(a.role){case"member":return Zf;case"params":return t.has(a.member)?zC:_c;case"ref":return Yf;case"notifications":return NC;default:return}},"watchedFor"),o=[],s=0,i=n(a=>{let c=o.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===wc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===DC){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let p=0;for(;e.charCodeAt(d-1-p)===$C;)p++;if(p%2===0)break}let u=s>0?void 0:o.at(-1);if(u?.isObject&&u.expectKey){let p=e.slice(a,d+1),h=p.includes("\\")?JSON.parse(p):p.slice(1,-1);if(jC.test(h))return!0;u.key=h;let f=ht(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===Kf||c===HC){let d=c===Kf,u=s>0?void 0:i(d);if(u===void 0)s++;else{let p=o.at(-1)?.member??0;o.push({role:u,isObject:d,seen:new Set,member:p,expectKey:d})}}else if(c===LC||c===BC)s>0?s--:o.pop();else if(s===0&&(c===FC||c===Sc)){let d=o.at(-1);d?.isObject?d.expectKey=c===Sc:d?.role==="batch"&&c===Sc&&d.member++}}return!1}n(JC,"hasUnsafeKeyInText");function Qf(e){let t=new Set;for(let[r,o]of e.envelope.messages.entries()){let s=o.raw;if(Lo(s)){if(Rc(s,Zf)||e.checksListen===!0&&s.method===qC&&(t.add(r),Lo(s.params)&&(Wf(s.params,wc)||Lo(s.params.notifications)&&Wf(s.params.notifications,Xf))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!Lo(s.params))&&(Rc(s.params,_c)||Lo(s.params.ref)&&Rc(s.params.ref,Yf)))return!0}}return JC(e.text,t)}n(Qf,"hasAmbiguousIdentifyingKeys");var VC=n(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),GC=47,eg=44,KC=38,bc=n(e=>e!==GC&&e!==eg,"VALUE"),WC=n(e=>!VC(e),"ANY"),ZC=n(e=>e!==KC,"QUERY_VALUE"),YC=["+","#",".","/","?","&"],vc=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(bc),!t)return;let r=this.current,o=this.#e();this.edges[r].push({test:n(s=>s===eg,"test"),to:o}),this.edges[o].push({test:bc,to:r})}};function tg(e){let t=new vc,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=YC.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,p)=>{t.literal(`${p===0?a:"&"}${u}=`),t.plus(ZC)});break;case"+":case"#":t.plus(WC);break;case".":t.literal("."),t.plus(bc);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(tg,"compileUriTemplate");function rg(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 u of i)for(let p of r[u])s[p.to]!==a&&p.test(c)&&(s[p.to]=a,d.push(p.to));if(d.length===0)return!1;i=d}return i.includes(o)}n(rg,"matchesUriTemplate");var bi=m.record(m.string(),m.unknown()),XC=m.record(m.string(),m.unknown()),qt=m.array(m.string().min(1)).min(1).optional(),QC=m.object({name:m.string().min(1),description:m.string().min(1).optional(),annotations:XC.optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),eI=m.object({name:m.string().min(1),description:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),tI=m.object({uri:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),rI=m.object({uriTemplate:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),nI=m.array(m.union([m.string(),QC])),oI=m.array(m.union([m.string(),eI])),sI=m.array(m.union([m.string(),tI])),iI=m.array(m.union([m.string(),rI])),aI=m.object({module:m.unknown(),export:m.string().min(1)}).strict(),cI=m.object({mode:m.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:m.string().min(1).optional(),groupClaim:m.string().min(1).optional(),identifier:aI.optional()}).strict(),dI=m.object({tools:nI.optional(),prompts:oI.optional(),resources:sI.optional(),resourceTemplates:iI.optional(),accessControl:cI.optional()}).strict(),ft=[{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 uI(e,t){return Bm(dI,e,`MCP capability filter policy "${t}"`)}n(uI,"parseMcpCapabilityFilterOptions");function j(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(j,"isRecord");function Oe(e){return typeof e.method=="string"?e.method:void 0}n(Oe,"messageMethod");function Bo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Bo,"correlationKey");function pg(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(pg,"createReplyIdMatcher");function ng(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(ng,"asStringArray");function og(e,t){if(!j(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,s)=>j(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(og,"readClaimValues");function xc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!j(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:ng(e.roles),groups:ng(e.groups),public:e.public===!0}}n(xc,"normalizeEntry");function lI(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(lI,"isCallerAllowed");function Si(e,t,r,o){if(e===void 0)return;let s=[];for(let i of e){let a=xc(i,t);a!==void 0&&lI(a,r,o)&&s.push(a.key)}return s}n(Si,"allowedKeys");var mg=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(og(e.user?.data,o)),a=new Set(og(e.user?.data,s));return{tools:Si(r.tools,"name",i,a),prompts:Si(r.prompts,"name",i,a),resources:Si(r.resources,"uri",i,a),resourceTemplates:Si(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function pI(e,t){let r=[];for(let o of ft){let s=e[o.option];if(s!==void 0)for(let i of s){let a=xc(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 X(`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(pI,"assertNoConflictingMarkup");function mI(e,t){let r=[];for(let o of ft){let s=e[o.option];if(s!==void 0)for(let i of s){let a=xc(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 X(`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(mI,"assertNoMarkup");function hI(e,t){let r=e.identifier;if(r===void 0)throw new X(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new X(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new X(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new X(`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 E(`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 E(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}n(hI,"buildCustomResolver");function fI(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new X(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return hI(r,t)}if(o==="rolesAndGroups")return pI(e,t),mg;mI(e,t)}n(fI,"buildCapabilityResolver");function gI(e){let t={};for(let r of ft){let o=e[r.option];if(o===void 0)continue;let s=new Map;for(let i of o){let a=DI(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}n(gI,"buildProjectionMaps");function hg(e){return e===void 0?void 0:ft.find(t=>t.listMethod===e)}n(hg,"findListRule");function Mc(e){return e===void 0?void 0:ft.find(t=>t.directMethods.includes(e))}n(Mc,"findDirectRule");var vi="completion/complete",fg=["prompts","resources","resourceTemplates"];function gg(e){return e===vi||Mc(e)!==void 0}n(gg,"isCapabilityMethod");var wi="subscriptions/listen",yI=[...ft.flatMap(e=>[e.listMethod,...e.directMethods]),vi,wi];function SI(e){let t=ht(e.trim()),r=yI.find(o=>ht(o)===t);return r!==void 0&&r!==e?r:void 0}n(SI,"methodVariantOf");function sg(e,[t,r]){return{code:I.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}n(sg,"invalidParams");function Oc(e){return t=>({code:I.InvalidParams,message:`${e} "${$s(t)}" not found`})}n(Oc,"namedNotFound");function RI(e,t){return{code:Tm(t),message:"Resource not found",data:{uri:Ds(e,Em)}}}n(RI,"resourceNotFound");var _I={legacy:Oc("Tool"),modern:vo.tool},Cc={legacy:Oc("Prompt"),modern:vo.prompt},wI={legacy:RI,modern:vo.resource},bI={legacy:Oc("Resource template"),modern:vo.resourceTemplate};function vI(e){let t=Oe(e);if(t===void 0||!gg(t))return[];let r=j(e.raw)?e.raw.params:void 0,o=n((d,u)=>j(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=n(d=>j(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==vi){let d=Mc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:o(r,"uri"),issue:s("params.uri"),notFound:wI}]:[{options:[d.option],target:o(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?_I:Cc}]}let i=j(r)?r.ref:void 0,a=j(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:o(i,"name"),issue:["params.ref.name","a string"],notFound:Cc}];if(a==="ref/resource"){let d=o(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&CI(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:bI}]}let c=j(r)?j(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:fg,target:void 0,issue:c,notFound:Cc}]}n(vI,"capabilityAccesses");function CI(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 II(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}n(CI,"hasTemplateExpression");function II(e){return e>32&&e<127?!1:TI.test(String.fromCharCode(e))}n(II,"isWhitespaceCode");var TI=/\s/;function EI(e){return e.type==="invalid"&&(!j(e.raw)||e.raw.jsonrpc!=="2.0")}n(EI,"isNonJsonRpcMember");function kI(e){return j(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}n(kI,"hasNonStringMethod");function yg(e){return e.type==="request"||e.type==="invalid"&&Oe(e)!==void 0}n(yg,"awaitsReply");function AI(e){return j(e.raw)&&j(e.raw.params)?e.raw.params:void 0}n(AI,"rawParams");function PI(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:Y()&&$r(e.headers,r.raw)}n(PI,"isModernRequest");var ig={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Ic="=?base64?",Tc="?=",xI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function MI(e){if(!e.startsWith(Ic)||!e.endsWith(Tc)||e.length<Ic.length+Tc.length)return e;let t=e.slice(Ic.length,e.length-Tc.length);if(xI.test(t))try{let r=atob(t),o=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{return}}n(MI,"decodeMcpHeaderValue");var OI=-32020;function UI(e,t){let r=Oe(t);if(r===void 0)return;let o=j(t.raw)?t.raw.id:void 0,s=Fo(o)?o:void 0,i=e.headers.get("mcp-protocol-version"),a=Cm(t.raw);if(i!==null&&a!==void 0&&i!==a)return Ri(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 Ri(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(ig,r)?ig[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let p=MI(d);if(p===void 0)return Ri(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=AI(t)?.[u];if(typeof h=="string"&&p!==h)return Ri(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${p}"`)}n(UI,"headerMismatchResponse");function Ri(e,t,r){return Ye(400,{code:OI,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}n(Ri,"mismatchResponse");var qI={code:I.MethodNotFound,message:"Method not found"},ag={code:I.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},zI={code:I.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},NI="2025-06-18";function Fo(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}n(Fo,"isValidRequestId");function Sg(e){return j(e.raw)&&!Object.hasOwn(e.raw,"id")}n(Sg,"isSentAsNotification");function Ho(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}n(Ho,"jsonRpcError");function Ye(e,t,r){return Response.json(Ho(t,r),{status:e})}n(Ye,"jsonRpcErrorResponse");function _i(e){return Ye(400,{code:I.InvalidRequest,message:`Invalid Request: ${e}`})}n(_i,"invalidRequestResponse");function Ec(e,t,r=!1){if(Sg(e))return{status:400,body:Ho({code:I.InvalidRequest,message:`Invalid Request: a notification cannot use ${$s(Oe(e)??"this method")}; send it as a request with an id`})};let o=j(e.raw)?e.raw.id:void 0;return Fo(o)?{status:r&&t.code===I.MethodNotFound?404:200,body:Ho(t,o)}:{status:400,body:Ho({code:I.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}n(Ec,"refusalOf");var cg=-32e3;function jI(e,t){let r=e.headers.get("accept");if(r===null||!/application\/json/i.test(r))return Ye(406,{code:cg,message:"Not Acceptable: Client must accept both application/json and text/event-stream"});if(!Rm(e.headers.get("content-type")??void 0))return Ye(415,{code:cg,message:"Unsupported Media Type: Content-Type must be application/json"});if(!(t.shape==="batch"&&Ls(e.headers.get("mcp-protocol-version")))){if(t.shape==="single"){let o=Hr(t.messages[0]?.raw);if(o!==void 0)return Response.json(o,{status:400})}return Vf(e.headers,t.shape==="batch"?t.messages.map(o=>o.raw):t.messages[0]?.raw)}}n(jI,"legacyTransportRefusal");function dg(e,t,r=!1,o=!1){let[s]=[...t];if(e.shape!=="batch"){let{status:d,body:u}=Ec(s[0],s[1],r);return Response.json(u,{status:d})}let i=e.protocolVersion;if(i!==void 0&&i>=NI)return _i(`protocol version ${$s(i)} does not support JSON-RPC batches`);let a=0,c=e.messages.flatMap((d,u)=>{let p=o?Hr(d.raw,u):void 0;if(p!==void 0)return a+=1,[p];if(d.type==="result"||d.type==="error"||Sg(d))return[];let h=j(d.raw)?d.raw.id:void 0;return o&&!t.has(d)&&Oe(d)==="ping"&&Fo(h)?[{jsonrpc:"2.0",id:h,result:{}}]:[Ec(d,t.get(d)??zI).body]});if(c.length===0){let{status:d,body:u}=Ec(s[0],s[1]);return Response.json(u,{status:d})}return Response.json(c,{status:a===e.messages.length?400:200})}n(dg,"refusalResponse");function DI(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!j(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(DI,"buildProjection");function ug(e){let t=e.base[e.property],r=e.overlay[e.property];return j(r)?j(t)?{...t,...r}:r:t}n(ug,"mergeRecordProperty");function $I(e,t){let r={...e,...t.overlay},o=ug({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let s=ug({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}n($I,"applyProjection");var ke=Symbol("unreadable"),tn=Symbol("dropped");function LI(e,t,r,o,s){let i=e.result;if(!j(i))return ke;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?ke:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!j(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(o!==void 0&&!o.has(u))return[];let p=r.get(u);return p===void 0?[]:[$I(d,p)]})}}}n(LI,"filterAndProjectItems");var Rg="resources/read";function HI(e){let t=e.result;return!j(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}n(HI,"withPrivateReadScope");function _g(e,t){let r=hg(Oe(e)),o=r===void 0?void 0:t[r.option];return r===void 0||o===void 0?null:{rule:r,projections:o}}n(_g,"listTargetOf");function BI(e,t,r){return j(e)&&ft.some(o=>o!==t?.rule&&r[o.option]!==void 0&&Object.hasOwn(e,o.resultProperty))}n(BI,"carriesUnfilteredList");function FI(e){let{envelope:t,projectionMaps:r,allowedSets:o,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=n(S=>_g(S,r),"listTarget"),d=t.messages.filter(yg),u=new Map;for(let S of d){let R=Bo(S.id);R!==void 0&&!u.get(R)&&u.set(R,c(S))}let p=pg(d.map(S=>S.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&Oe(h)===Rg,y=n(S=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let R=p(S);return R===void 0?void 0:u.get(R)},"targetForReply"),b=n(S=>{if(!j(S))return ke;if(!("result"in S))return"method"in S&&!("error"in S)?_(S):"error"in S||"method"in S?S:ke;let R=y(S.id);return R===void 0||BI(S.result,R,r)?ke:R===null?f?HI(S):S:LI(S,R.rule,R.projections,o?.[R.rule.option],s)},"filterMessage"),_=n(S=>{if(a===void 0)return S;if(S.method==="notifications/resources/updated"){let R=j(S.params)?S.params.uri:void 0;return typeof R=="string"&&!a(R)?tn:S}if(S.method==="notifications/subscriptions/acknowledged"){let R=vg(S.params,a);return R===void 0?S:{...S,params:R}}return S},"filterServerMessage");return S=>{if(!Array.isArray(S))return b(S);if(t.shape!=="batch")return ke;let R=S.map(b);if(R.includes(ke))return ke;let v=R.filter(P=>P!==tn);return v.length===R.length?R:v.length===0?tn:v}}n(FI,"createReplyFilter");function JI(e){return He(e.headers.get("content-type")).includes("json")}n(JI,"isJsonResponse");function VI(e){return He(e.headers.get("content-type"))==="text/event-stream"}n(VI,"isEventStreamResponse");var GI=10*1024*1024,KI=/^[\w.~:/+=-]{0,256}$/;function WI(e){if(Ru(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"&&KI.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(WI,"inspectSseLines");var wg="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",ZI="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function Ac(e,t){let r=e.messages.filter(yg),o=new Map,s=new Set;for(let u of r){let p=u.id,h=Bo(p);p==null||h===void 0||(o.set(h,p),_g(u,t)!==null&&s.add(h))}let i=pg(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:Bo(a.id),d=new Set;return{keyOf(u){if(!(!j(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:n(u=>u!==void 0&&o.has(u),"isPending"),hasFailed:n(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&o.delete(u)},fail(u){return[...u].flatMap(p=>{let h=o.get(p);return h===void 0?[]:(o.delete(p),d.add(p),[{jsonrpc:"2.0",id:h,error:{code:I.InternalError,message:s.has(p)?wg:ZI}}])})},pendingKeys:n(()=>[...o.keys()],"pendingKeys")}}n(Ac,"createReplyTracker");function bg(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)?ke:t(i);c!==tn&&(c!==ke?(o.push(c),r.answer(a)):r.isPending(a)?o.push(...r.fail([a])):s++)}return{replies:o,dropped:s}}n(bg,"filterBatchMembers");function YI(e){let{response:t,envelope:r,projectionMaps:o,filterReply:s,warn:i}=e,a=Ac(r,o),c=!1,d=n(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=n(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),p=n(()=>a.pendingKeys().length===0,"isDone");return Ps(t,h=>{let f=WI(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let y;try{y=JSON.parse(f.data)}catch{return d("its data is not JSON")}let b=a.keyOf(y);if(b!==void 0&&a.hasFailed(b))return null;let _=s(y);if(_===tn)return null;if(_===ke&&r.shape==="batch"&&Array.isArray(y)){let{replies:S,dropped:R}=bg(y,s,a);if(R>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),S.length===0)return null;let v=yo(f,JSON.stringify(S));return p()?ca(v):v}if(_===ke){if(!a.isPending(b))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let S=u(a.fail([b]));return p()?ca(...S):S}for(let S of Array.isArray(_)?_:[_])a.answer(a.keyOf(S));return _===y?f:yo(f,JSON.stringify(_))},{maxEventChars:GI,onOversize:"discard",end:n(({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:n((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}n(YI,"filterEventStream");function Uc(e){return Oe(e)===wi}n(Uc,"isListenRequest");function XI(e){return Y()&&e.messages.some(Uc)}n(XI,"filtersListen");function vg(e,t){if(!j(e)||!j(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let o=r.filter(s=>typeof s=="string"&&t(s));if(o.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:o}}}n(vg,"narrowSubscriptionParams");function QI(e,t,r){let o=!1,s=t.messages.map(a=>{if(!Uc(a)||!j(a.raw))return a.raw;let c=vg(a.raw.params,r);return c===void 0?a.raw:(o=!0,{...a.raw,params:c})});if(!o)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])})}n(QI,"narrowListenSubscriptions");var kc=Symbol("access unresolved"),lg=10*1024*1024,Cg="the request body could not be read";async function eT(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:u}=await s.read(),p=d?i.decode():i.decode(u,{stream:!0});if(a+=p.length,c&&=!/\S/.test(p),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}n(eT,"scanBody");function qc(e){return Array.isArray(e)?`batch member 0: ${qc(e[0])}`:j(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}n(qc,"invalidMessageReason");async function tT(e,t){if(e.body===null)return;let r=n(()=>Me.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)>lg)return r();let s=He(e.headers.get("content-type")).includes("json"),i=n(()=>Me.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=n(()=>Ye(400,{code:I.ParseError,message:`Parse error: ${Cg}`}),"unreadable"),c;try{c=await eT(e,lg,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(p){return p instanceof SyntaxError?Ye(400,{code:I.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=j(d)?d.id:void 0;return Ye(400,{code:I.InvalidRequest,message:`Invalid Request: ${qc(d)}`},Fo(u)?u:void 0)}n(tT,"refuseUninspectable");var Pc=class extends xs{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let o=uI(t,r);super(o,r),this.#r=r,this.#e=gI(o),this.#t=fI(o,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,tg(i)]))}async handler(t,r){let o=await Om(t);if(o===null)return await tT(t,r)??t;let s=PI(t,o);if(s){let A=o.messages[0],M=A===void 0?void 0:UI(t,A);if(M!==void 0)return M}let i=o.messages.findIndex(EI);if(i!==-1)return _i(`batch member ${i}: ${qc(o.messages[i].raw)}`);let a=o.messages.findIndex(kI);if(a!==-1)return _i(o.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=Mm(o);if(c===void 0)try{c=await t.clone().text()}catch{return Ye(400,{code:I.ParseError,message:`Parse error: ${Cg}`})}if(Qf({envelope:o,text:c,isCapabilityMethod:gg,checksListen:this.#c()}))return _i("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 A of o.messages){let M=Oe(A),B=M===void 0?void 0:SI(M);B!==void 0&&this.#l(B)&&d.set(A,qI)}let u=XI(o),p=d.size===0&&this.#t!==void 0&&o.messages.some(A=>this.#a(A,u))?await this.#m(t,r):void 0,h=s&&bo(t.headers.get("mcp-protocol-version")),f=!s&&Ee();if(d.size===0)for(let A of o.messages){let M=p===kc?this.#a(A,u)?ag:void 0:this.#u(A,p,h,o.protocolVersion,f);M!==void 0&&d.set(A,M)}if(d.size>0){let A=o.messages[0],M=Y()&&(o.shape==="batch"?va(t.headers,o.messages.map(K=>K.raw))!==void 0:A!==void 0&&Hs(t.headers,A.raw));if(M){let K=Am(t);if(K!==void 0)return K;if(o.shape==="batch"){let re=va(t.headers,o.messages.map(_t=>_t.raw));if(re!==void 0)return Ye(re.status,re.error)}}let B=j(A?.raw)?A.raw.id:void 0,W=Fo(B)?B:void 0,Z=M&&o.shape==="single"&&A!==void 0?Um(t.headers,A.raw):void 0;if(Z!==void 0)return Ye(Z.status,Z.error,W);let le=M&&o.shape==="single"&&j(A?.raw)&&typeof A.raw.method=="string"?xm(A.raw,{modern:!0,protocolVersion:t.headers.get("mcp-protocol-version"),hasResource:n(()=>!0,"hasResource")}):void 0;return le!==void 0?Ye(200,le.error,W):(!s&&!M&&Ee()?jI(t,o):void 0)??dg(o,d,s,!s&&f)}if(p===kc)return dg(o,new Map(o.messages.map(A=>[A,ag])),s);let y=u||s?this.#d(p):void 0,b=y===void 0?t:QI(t,o,y),_=s&&this.#t!==void 0,S=_&&this.#o();if(!this.#p(o,u,S))return b;let R=FI({envelope:o,projectionMaps:this.#e,allowedSets:p,privateScope:_,privateReadScope:S,isResourceVisible:y}),v=n(A=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${A}`),"warn"),P=n((A,M)=>{v(`did not forward an upstream reply (${A}); answered -32603`);let B=Ac(o,this.#e),W=B.fail(B.pendingKeys()),Z=go(new Headers(M.headers));return Z.set("content-type","application/json"),W.length===0?new Response(JSON.stringify(Ho({code:I.InternalError,message:wg})),{status:502,headers:Z}):new Response(JSON.stringify(o.shape==="batch"?W:W[0]),{status:200,headers:Z})},"unreadable");r.addResponseSendingHook(async A=>{let M=!A.ok;if(A.body!==null&&Et(A.headers))return M?A:P("its body is still content-encoded",A);if(VI(A))return YI({response:A,envelope:o,projectionMaps:this.#e,filterReply:R,warn:v});if(!JI(A))return A.ok&&A.status!==202&&A.status!==204&&A.body!==null?P("no or an unknown media type",A):A;let B;try{B=await A.clone().json()}catch{return M?A:P("its body is not JSON",A)}if(M&&!Array.isArray(B)&&!(j(B)&&"result"in B))return A;let W=R(B);if(W===ke&&o.shape==="batch"&&Array.isArray(B)){let le=Ac(o,this.#e),{replies:Pe,dropped:K}=bg(B,R,le);K>0&&Pe.push(...le.fail(le.pendingKeys())),Pe.length>0&&(v("did not forward a batch reply member it could not read; sent the rest"),W=Pe)}if(W===ke||W===tn)return P("the filter could not read the reply",A);if(W===B)return A;let Z=go(new Headers(A.headers));return new Response(JSON.stringify(W),{status:A.status,statusText:A.statusText,headers:Z})});let N=new kt(b);return N.headers.set("accept-encoding","gzip, br"),N}#d(t){if(!this.#o())return;let r=n((o,s)=>{let i=t?.[o];return this.#e[o]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return o=>this.#s(o,r)}#o(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#u(t,r,o,s,i=!1){let a=n(d=>this.#e[d]!==void 0,"isConfigured"),c=n((d,u)=>{let p=r?.[d];return this.#e[d]?.has(u)===!0&&(p===void 0||p.has(u))},"isAllowed");for(let d of vI(t)){if(!(d.refusedBy??d.options).some(a))continue;let{target:u}=d;if(u===void 0)return sg(Oe(t)??"",d.issue);if(!(d.resource?this.#s(u,c):d.options.filter(a).some(h=>c(h,u)))){let h=Oe(t),f=j(t.raw)?t.raw.params:void 0,y=i&&h!==void 0?Pm(h,j(f)?f:void 0):void 0;return y!==void 0&&h!==void 0?sg(h,y):o?d.notFound.modern(u):d.notFound.legacy(u,s??null)}}}#s(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||!rg(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!o&&!s}#i(t){let r=n(o=>this.#e[o]!==void 0,"isConfigured");return t===vi?fg.some(r):Mc(t)?.option==="resources"&&r("resourceTemplates")?!0:ft.some(o=>r(o.option)&&(o.listMethod===t||o.directMethods.includes(t)))}#a(t,r){let o=Oe(t);return r&&o===wi&&this.#o()?!0:o!==void 0&&this.#i(o)}#c(){return Y()&&this.#o()}#l(t){return t===wi?this.#c():this.#i(t)}#p(t,r,o){return t.messages.some(s=>{if(r&&Uc(s))return this.#o();if(o&&t.shape==="single"&&Oe(s)===Rg)return!0;let i=hg(Oe(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#m(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),kc}let i={};for(let a of ft){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let p of d)typeof p=="string"&&c.has(p)&&u.add(p);i[a.option]=u}return i}};var zc="zuplo.com",rT=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),nT=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Ig(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Ig,"s2FaviconHref");function oT(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(oT,"strictFaviconHref");var Tg=Ig(zc);function Nc(e){let t=e.toLowerCase();return t===zc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Ig(zc):oT(e)}n(Nc,"resolveIconHref");function sT(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(sT,"hostnameFromHost");function iT(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(iT,"isLocalOrAddressHost");function aT(e){let t=sT(e).toLowerCase().replace(/\.$/,"");if(iT(t)||nT.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=rT.has(o)?3:2;return r.slice(-s).join(".")}n(aT,"inferFaviconDomain");function jc(e){return{src:Nc(aT(e)),mimeType:"image/png",sizes:["128x128"]}}n(jc,"resolveMcpFaviconIcon");function Ci(e){try{return jc(new URL(e).host)}catch{return}}n(Ci,"resolveMcpFaviconIconFromUrl");var cT=-32020,Dc="(missing)",dT=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"]),Eg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},kg="=?base64?",Ag="?=",uT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function lT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(lT,"isRecord");function Pg(e){return e===" "||e===" "}n(Pg,"isHttpOws");function pT(e){let t=0,r=e.length;for(;t<r&&Pg(e[t]);)t++;for(;r>t&&Pg(e[r-1]);)r--;return e.slice(t,r)}n(pT,"stripHttpOws");function rn(e,t){return e.get(t)??void 0}n(rn,"readHeader");function mT(e){if(!e.startsWith(kg)||!e.endsWith(Ag))return e;let t=e.slice(kg.length,e.length-Ag.length);if(uT.test(t))try{let r=Uint8Array.from(atob(t),o=>o.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}n(mT,"decodeMcpHeaderValue");function Lc(e,t,r){let o=ge(e);return Response.json(Te({...o===void 0?{}:{id:o},error:r}),{status:t})}n(Lc,"errorResponse");function Jo(e,t,r){return Lc(e,400,{code:cT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}n(Jo,"headerMismatchResponse");function hT(e,t,r){let o=t.method;if(rn(e,"mcp-protocol-version")===void 0)return Jo(t,Dc,`the body envelope names protocol version ${r} but the required MCP-Protocol-Version header is absent`);if(rn(e,"mcp-method")===void 0)return Jo(t,Dc,`the body names method ${String(o)} but the required Mcp-Method header is absent`);if(typeof o!="string"||!Object.hasOwn(Eg,o))return;let s=Eg[o],i=lT(t.params)?t.params[s]:void 0,a=typeof i=="string"?i:void 0,c=rn(e,"mcp-name");if(c===void 0)return a===void 0?void 0:Jo(t,Dc,`the body carries params.${s}="${a}" but the required Mcp-Name header is absent`);let d=pT(c),u=mT(d);if(u===void 0)return Jo(t,d,"the Mcp-Name header carries an invalid Base64 sentinel value");if(a!==void 0&&u!==a)return Jo(t,d,`the body carries params.${s}="${a}" but the Mcp-Name header names "${u}"`)}n(hT,"standardHeadersResponse");function xg(e){let{headers:t,message:r}=e,o=Sm({httpMethod:"POST",...$c("protocolVersionHeader",rn(t,"mcp-protocol-version")),...$c("mcpMethodHeader",rn(t,"mcp-method")),...$c("mcpNameHeader",rn(t,"mcp-name")),body:r});if(o.kind==="reject")return dT.has(o.cell)||o.cell==="initialize-with-modern-header"&&Ee()?Lc(r,o.httpStatus,{code:o.code,message:o.message,...o.data===void 0?{}:{data:o.data}}):void 0;if(o.kind!=="modern")return;let s=o.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new gm({supported:[...e.supportedVersions],requested:s??"unknown"});return Lc(r,400,{code:i.code,message:i.message,data:i.data})}return o.messageKind==="request"?hT(t,r,s):void 0}n(xg,"validateModernGatewayRequest");function $c(e,t){return t===void 0?{}:{[e]:t}}n($c,"optionalHeader");import{context as fT,TraceFlags as gT,trace as yT}from"@opentelemetry/api";var Mg="mcp-session-id",ST=256*1024;function Xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Xe,"isPlainObject");function Og(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Og,"isJsonContentType");function Bc(e,t,r){if(t===void 0||r===void 0||r.byteLength>kh||!Og(e))return;let o=t.value;if(!Xe(o)||typeof o.method!="string"||o.params!==void 0&&!Xe(o.params))return;let s=o.id;return{message:o,method:o.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...o.params===void 0?{}:{params:o.params},...typeof o.jsonrpc=="string"?{jsonrpc:o.jsonrpc}:{}}}n(Bc,"parseMcpRequestMessage");function Hc(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}n(Hc,"readStringParam");function RT(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Hc(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Hc(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Hc(e.params,"uri")};default:return{}}}n(RT,"readCapability");function Ug(e,t){let r=e.get(t);return r===null||r===""?void 0:r}n(Ug,"readHeader");function _T(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let o=new URL(r.__rewriteFunction(e,vu(t))),s=o.port!==""?Number(o.port):o.protocol==="https:"?443:o.protocol==="http:"?80:void 0;return{serverAddress:o.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}n(_T,"readUpstreamServer");function qg(e,t,r){let o=dr(e.headers,r.message),s=Ug(e.headers,Mg),i={methodName:r.method,...RT(r),...r.id===void 0?{}:{jsonRpcRequestId:r.id},...r.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:r.jsonrpc},...s===void 0?{}:{mcpSessionId:s}};return{common:i,server:{...i,mcpProtocolVersion:o??zm,clientAddress:t.incomingRequestProperties?.ip,params:r.params},requestedProtocolVersion:o}}n(qg,"readServerSpanInput");function zg(e){let{request:t,context:r,parsed:o}=e,{common:s,server:i,requestedProtocolVersion:a}=qg(t,r,o),c=Ca(i),d;try{Ms(c.span);let u=c.span.isRecording()||jm()?_T(t,r):{};d=fT.with(c.ctx,()=>Dm({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Ms(d.span);let p={server:c,client:d,captureToolCallContent:e.captureToolCallContent===!0};return wT(p,o),ba(r,c.span.spanContext()),p}catch(u){throw Ii(d===void 0?[c]:[d,c]),u}}n(zg,"startMcpProxySpans");function Ng(e,t,r){try{let o=e.filter(i=>i.span.isRecording());if(o.length===0)return;let s=$m(r);if(s===void 0)return;zt(o,i=>i.span.setAttribute(t,s))}catch{}}n(Ng,"setContentAttribute");function wT(e,t){e.captureToolCallContent!==!0||t.method!=="tools/call"||Ng([e.client,e.server],"gen_ai.tool.call.arguments",t.params?.arguments??{})}n(wT,"recordToolCallArguments");function bT(e,t){if(t.spans.captureToolCallContent!==!0||t.method!=="tools/call"||t.gatewayAnswered===!0)return;let r=t.tapResult.message?.result;!Xe(r)||r.isError===!0||Ng(e,"gen_ai.tool.call.result",r)}n(bT,"recordToolCallResult");var vT=["content-digest","repr-digest","digest","content-md5"];function CT(e){return vT.some(t=>e.has(t))}n(CT,"hasBodyIntegrityHeader");function jg(e,t,r,o){let s=yT.getSpanContext(t.client.ctx);if(r.byteLength>ST||o!==void 0&&CT(o)||s===void 0||(s.traceFlags&gT.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!Xe(i))return r;try{let a=Ia(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!Ah(r))return r;let c=Ia(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}n(jg,"injectTraceContextIntoBody");function Dg(e,t){if(e){if(Xe(e.error)){let r=e.error.code,o=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof o=="string"?{message:Ds(o,Nm)}:{},httpStatusCode:t}}if(Xe(e.result)&&e.result.isError===!0)return{isError:!0}}}n(Dg,"readSpanResponse");function IT(e,t,r){let o=Ug(t.headers,Mg),s=r?.result,i=km(Xe(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);zt(e,a=>{o!==void 0&&a.span.setAttribute("mcp.session.id",o),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}n(IT,"recordInitializeResult");function $g(e){let{spans:t}=e,r=[t.client,t.server];try{TT(r,e)}catch{}finally{Ii(r)}}n($g,"finishMcpProxySpans");function TT(e,t){let{spans:r,response:o,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&IT(e,o,s.message),bT(e,t);let i=Dg(s.message,o.status);i?zt(e,a=>a.setResponse(i)):s.ended==="errored"?zt(e,a=>a.fail(s.error)):o.status>=400&&s.message===void 0?zt(e,a=>a.setErrorType(String(o.status))):s.ended==="cancelled"&&!s.message?zt(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?zt(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&&zt(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}n(TT,"recordOutcome");function zt(e,t){for(let r of e)try{t(r)}catch{}}n(zt,"forEachHandle");function Ii(e){for(let t of e)try{t.end()}catch{}}n(Ii,"endEach");function Fc(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}n(Fc,"failMcpProxySpans");function Jc(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{Ii([t])}}n(Jc,"cancelMcpProxySpans");function ET(e){switch(e){case"connect_required":return"The gateway asked the client to connect the upstream server; the request was not forwarded.";case"no_upstream_tokens":return"The upstream connection returned no OAuth tokens; the request was not forwarded.";case"upstream_token_refresh_unavailable":return"The upstream token endpoint could not refresh the connection; the request was not forwarded."}}n(ET,"gatewayAnswerMessage");var kT=64*1024;async function AT(e){if(e.body===null||!Og(e))return;let t=await e.clone().text();if(t.length>kT)return;let r=JSON.parse(t);return Xe(r)?r:void 0}n(AT,"readGatewayAnswer");function PT(e){return Xe(e.error)?Xe(e.error.data)&&e.error.data.connectRequired!==void 0:Xe(e.result)&&e.result.resultType==="input_required"}n(PT,"isConnectRequiredAnswer");async function Lg(e){let t;try{let r=Bc(e.request,e.requestJson===void 0?void 0:{value:e.requestJson},e.requestBody);if(r===void 0)return;let{server:o}=qg(e.request,e.context,r);t=Ca({...o,startTime:e.startTime}),Ms(t.span),ba(e.context,t.span.spanContext());let s;try{s=await AT(e.response)}catch{}let i=Dg(s,e.response.status);i?t.setResponse(i):e.response.status>=400&&s===void 0&&t.setErrorType(String(e.response.status));let a=e.outcome??(s!==void 0&&PT(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,ET(a))}catch{}finally{t&&Ii([t])}}n(Lg,"recordGatewayAnsweredMcpSpan");function Nt(e){let t=we().connectionsById.get(e);if(!t)throw new X(`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(Nt,"getUpstreamServerConfig");function Ti(e){let t=we().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new X(`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(Ti,"getUpstreamAuthConfig");function nn(e,t){let r=Ti({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new X(`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(nn,"requireUpstreamOAuthConfig");function Hg(e,t){let r=Ti({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new X(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(Hg,"requireUpstreamIdJagConfig");import{base64url as Ei}from"jose";var xT="__Host-",MT=16,OT=32,Fg=".",UT=!1;function jt(){return UT}n(jt,"isBrowserBindingEnforced");var Vo=m.object({id:m.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:m.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function ki(e,t){return new URL(oe(e,t)).protocol==="https:"}n(ki,"isSecureGatewayOrigin");function Vc(e,t){return t?`${xT}${e}`:e}n(Vc,"gatewayCookieName");function Go(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}n(Go,"serializeGatewayCookie");function Gc(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(Gc,"parseCookieHeader");function Bg(e){return Ei.encode(crypto.getRandomValues(new Uint8Array(e)))}n(Bg,"randomBase64url");async function Jg(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Ei.encode(new Uint8Array(t))}n(Jg,"hashNonce");function qT(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(qT,"constantTimeEqual");function Vg(e,t,r){return Vc(`zuplo_mcp_${e}_${t}`,r)}n(Vg,"bindingCookieName");async function Ko(e){let t=Bg(MT),r=Bg(OT),o=ki(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${Fg}${Ei.encode(e.payload)}`;return{claim:{id:t,hash:await Jg(r)},setCookie:Go({name:Vg(e.purpose,t,o),value:s,maxAgeSeconds:e.ttlSeconds,secure:o})}}n(Ko,"startBrowserBinding");async function Ai(e){let t=ki(e.request.url,e.request.headers),r=Vg(e.purpose,e.claim.id,t),o=Go({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Gc(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:o};let i=s.indexOf(Fg),a=i<0?s:s.slice(0,i);if(!qT(await Jg(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(Ei.decode(s.slice(i+1))),clearCookie:o}}catch{return{matched:!1,clearCookie:o}}}n(Ai,"verifyBrowserBinding");function Gg(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(Gg,"mergeAbortSignals");async function zT(e){try{await e.cancel()}catch{}}n(zT,"cancelReader");async function Pi(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 zT(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(Pi,"readBoundedByteStream");var NT=2,jT=1024*1024,DT=1e4,$T=new Set([301,302,303,307,308]),LT=["authorization","proxy-authorization","cookie","cookie2"];function Kc(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Kc,"readRequestUrl");function on(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(on,"readRequestMethod");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 new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[x]:r}})}n(HT,"assertContentLengthWithinLimit");async function BT(e,t,r){return HT(e,t,r),Pi(e.body,{maxBytes:t,createLimitError:n(()=>new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[x]:r}}),"createLimitError")})}n(BT,"readBoundedResponseBody");function FT(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(FT,"responseFromBufferedBody");function JT(e,t){if(!$T.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(JT,"resolveRedirectUrl");function Kg(e,t){try{return t.validateUrl(e)}catch(r){throw new E({message:"Outbound URL was not allowed.",extensionMembers:{[x]:t.problemCode}},{cause:r})}}n(Kg,"validateOutboundUrl");var Wg=new WeakSet;function Zg(e){return e instanceof E&&Wg.has(e)}n(Zg,"isOutboundTransportFailure");function Yg(e,t){if(e instanceof E&&Bs(e.extensionMembers?.[x]))throw e;let r=new E({message:"Outbound fetch failed.",extensionMembers:{[x]:t}},{cause:e});throw Wg.add(r),r}n(Yg,"normalizeFetchError");function Wo(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&&Ie(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Wo,"logOutboundFailure");async function VT(e,t,r,o,s,i,a){let c=on(r,o);try{return await t(r,o)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Wo(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:te(i),error:d,extra:{abortReason:a()}}),Yg(d,s)}}n(VT,"fetchWithNormalizedError");function GT(e){if(e.redirects>=e.maxRedirects)throw new E({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[x]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new E({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[x]:e.problemCode}})}n(GT,"assertRedirectAllowed");function KT(e,t){let r=new Headers(e);for(let o of LT)r.delete(o);for(let o of t)r.delete(o);return r}n(KT,"stripCrossOriginHeaders");function WT(e,t,r,o,s){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=KT(e.headers,s)),i}n(WT,"buildRedirectInit");function ZT(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ZT,"buildInitialRequestInit");function YT(e){let t=on(e.currentInput,e.currentInit);GT({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Kg(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:WT(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(YT,"followRedirect");async function Wc(e,t,r){let o=r.problemCode??"invalid_request",s=r.maxRedirects??NT,i=r.maxResponseBytes??jT,a=r.timeoutMs??DT,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,p=new AbortController,h=Gg(p,t.signal),f=!1,y=setTimeout(()=>{f=!0,p.abort()},a),b=e,_=ZT(e,t,p.signal),S;try{S=Kg(Kc(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(v){throw Wo(u,{event:"outbound_url_blocked",problemCode:o,method:on(e,t),host:te(Kc(e)),error:v}),clearTimeout(y),h?.(),v}let R=0;try{for(;;){let v=await VT(u,c,b,_,o,S,()=>f?`timeout_after_${a}ms`:void 0),P=JT(v,S);if(P!==void 0)try{let N=YT({currentInput:b,currentInit:_,currentUrl:S,redirectUrl:P,redirects:R,maxRedirects:s,problemCode:o,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});b=N.currentInput,_=N.currentInit,S=N.currentUrl,R=N.redirects;continue}catch(N){throw Wo(u,{event:"outbound_redirect_blocked",problemCode:o,method:on(b,_),host:te(S),error:N,extra:{redirects:R,maxRedirects:s,redirectTargetHost:te(P)}}),N}try{return FT(v,await BT(v,i,o))}catch(N){let A=N instanceof E;Wo(u,{event:A?"outbound_response_size_exceeded":"outbound_response_body_failed",problemCode:o,method:on(b,_),host:te(S),error:N,extra:{maxResponseBytes:i,status:v.status}}),Yg(N,o)}}}finally{clearTimeout(y),h?.()}}n(Wc,"runSafeOutboundExchange");async function Zo(e,t,r){let o=await Wc(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(s){throw Wo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:on(e,t),host:te(Kc(e)),error:s,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new E({message:"Outbound JSON response could not be parsed.",extensionMembers:{[x]:r.problemCode??"invalid_request"}},{cause:s})}}n(Zo,"runSafeOutboundJsonExchange");function Xg(e,t={},r={}){return Wc(e,t,{...r,validateUrl:Ao})}n(Xg,"fetchConfiguredOutbound");function Qg(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Ao})}n(Qg,"fetchConfiguredOutboundJson");function xi(e,t={},r={}){return Zo(e,t,{...r,validateUrl:gh})}n(xi,"fetchIdentityProviderJson");function ey(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Ys})}n(ey,"fetchCimdClientMetadataJson");function ty(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Po})}n(ty,"fetchCimdClientJwksJson");import{errors as ay,jwtVerify as cy,SignJWT as dy}from"jose";var ue="zuplo-mcp-gateway",ye=ue,Se="HS256";import{base64url as XT}from"jose";var QT=new TextEncoder,eE="MCP gateway could not initialize secure key material.",tE=32,ry=new Map,ny=new Map,rE;function nE(){return rE??Is.instance.authPrivateKey}n(nE,"readAuthPrivateKey");function oy(e){return new ve(eE,e===void 0?void 0:{cause:e})}n(oy,"createGeneratedKeyMaterialError");function sy(e,t){let r=XT.decode(t);if(r.byteLength!==tE)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(sy,"decodeJwkKeyField");function oE(e){let t=nE();if(!t)throw oy();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=sy("d",r.d);sy("x",r.x);let s=QT.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 oy(r)}}n(oE,"decodeGeneratedKeyMaterial");function sE(e){let t=ry.get(e);return t||(t=oE(e),ry.set(e,t)),t}n(sE,"getMasterKeyMaterial");async function Be(e){let t=ny.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(sE(e.keyMaterialPurpose));return ny.set(e.purpose,r),r}n(Be,"readCachedDerivedKey");var iE="SHA-256",aE=32,cE="zuplo-mcp-gateway:",dE=new TextEncoder,iy=new WeakMap;async function at(e,t){let r=iy.get(e);r||(r=new Map,iy.set(e,r));let o=r.get(t);if(o)return o;let s=await uE(e,t);return r.set(t,s),s}n(at,"deriveGatewaySigningKey");async function uE(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=dE.encode(`${cE}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:iE,salt:new Uint8Array,info:me(s)},o,aE*8);return new Uint8Array(i)}n(uE,"hkdfExpand");var uy=900,lE=900,pE=Qm.extend({id:wh,browserBinding:Vo.optional()}),mE=pE.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),ly=Ta.extend({id:bh,purpose:m.literal("browser_connect")}),hE=Ta.extend({purpose:m.literal("browser_connect")}),fE=ly.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),Mi=uy*1e3;async function py(){return Be({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"oauth-state"),"derive")})}n(py,"getOAuthStateKey");async function my(){return Be({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"browser-connect"),"derive")})}n(my,"getBrowserConnectKey");async function hy(e){let t=Math.floor(Date.now()/1e3)+uy;return new dy(e).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(t).sign(await py())}n(hy,"signOAuthState");async function Oi(e){try{let{payload:t}=await cy(e,await py(),{algorithms:[Se],issuer:ue,audience:ye});return mE.parse(t)}catch(t){throw t instanceof ay.JWTExpired?new E({message:"OAuth state has expired",extensionMembers:{[x]:"oauth_state_expired"}},{cause:t}):new E({message:"OAuth state could not be verified",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:t})}}n(Oi,"verifyOAuthState");async function fy(e){let t=Math.floor(Date.now()/1e3)+lE,r=hE.parse(e),o=ly.parse({...r,id:Th()});return new dy(o).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(t).sign(await my())}n(fy,"signBrowserConnectTicket");async function gy(e){try{let{payload:t}=await cy(e,await my(),{algorithms:[Se],issuer:ue,audience:ye});return fE.parse(t)}catch(t){throw t instanceof ay.JWTExpired?new E({message:"Browser connect ticket has expired",extensionMembers:{[x]:"oauth_state_expired"}},{cause:t}):new E({message:"Browser connect ticket could not be verified",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:t})}}n(gy,"verifyBrowserConnectTicket");async function yy(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new E({message:"Browser connect ticket has already been used",extensionMembers:{[x]:"oauth_state_reused"}})}n(yy,"consumeBrowserConnectTicket");function gE(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(gE,"buildConnectRequiredMessage");async function yE(e){let t=oe(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 fy({...Eo(e),purpose:"browser_connect"})),r.toString()}n(yE,"buildGatewayBrowserTicketUrl");function SE(e){return pe().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(SE,"buildGatewayConnectPath");async function Zc(e){return yE({...e,path:SE(e.upstreamServerId),redirect:!0})}n(Zc,"buildGatewayConnectUrl");async function Ui(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 Zc(t),message:gE(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ui,"buildRedirectConnectRequiredResponse");function Sy(e){return Ry({...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(Sy,"buildAdminConnectRequiredResponse");function Ry(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(Ry,"buildAdminSetupRequiredResponse");function _y(e){return we().byOperationId.get(e)?.downstreamOAuth!==void 0}n(_y,"routeSupportsBrowserConnect");function wy(e){return Ry({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}n(wy,"buildBrowserConnectUnavailableResponse");var by=12;async function vy(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(vy,"sha256Hex");async function pr(e){if(e)return(await vy(e)).slice(0,by)}n(pr,"fingerprintSecret");async function sn(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await vy(t)).slice(0,by)}n(sn,"fingerprintConnectionIdentity");var RE=6e4;function an(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(an,"credentialGenerationChanged");function Ae(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()+RE)return"near_expiry"}return"usable"}n(Ae,"describeAccessTokenState");var Cy=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _E(e,t){return e&&e.length>0?e.join(t):void 0}n(_E,"joinOAuthScopes");function wE(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Cy)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(wE,"sanitizeAuthorizationServerMetadata");function Iy(e){let t=wE(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Iy,"sanitizeOAuthDiscoveryState");function Ty(e){let t=new URL(e);for(let r of Cy){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Ty,"dedupeSingletonAuthorizationRequestParams");function qi(e){let t=new URL(e);return ze(t)&&Hm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(qi,"normalizeLoopbackOAuthRedirectUri");function Ey(e){return _E(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Ey,"readProtectedResourceMetadataScope");function bE(e){return`Zuplo MCP Gateway - ${e}`}n(bE,"buildGatewayOAuthClientName");function vE(e,t){return e&&e.length>0?e.join(t):void 0}n(vE,"joinOAuthScopeList");function CE(e){if(e.clientRegistration.mode!=="auto")return vE(e.scopes,e.scopeDelimiter)}n(CE,"readPublicClientMetadataScope");function Yc(e){return new URL(pe().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Yc,"buildOAuthClientMetadataDocumentUrl");function Xc(e){let t=Nt(e.upstreamServerId);return{client_name:bE(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(Xc,"buildGatewayOAuthClientMetadata");function ky(e,t,r){let o=nn(t,r),s=CE(o);return{client_id:Yc({origin:e,upstreamServerId:t}),...Xc({origin:e,upstreamServerId:t,redirectUri:qi(new URL(o.redirectPath,e)).toString(),scope:s})}}n(ky,"buildOAuthClientMetadataDocument");import{base64url as Dt}from"jose";var IE="SHA-256",cn="AES-GCM",TE=12,ed="zuplo-secret",td=1,Ay="generated:auth_private_key:token-encryption",EE=m.object({version:m.literal(td),keyId:m.literal(Ay),algorithm:m.literal(cn),iv:m.string().min(1),ciphertext:m.string().min(1)}).strict();async function Qc(){return Be({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(IE,me(e));return crypto.subtle.importKey("raw",t,{name:cn},!1,["encrypt","decrypt"])},"derive")})}n(Qc,"getEncryptionKey");function Py(e){return me(new TextEncoder().encode(`${ed}:v${e.version}:${e.keyId}`))}n(Py,"getAssociatedData");function kE(e){return`${ed}:v${e.version}:${Dt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(kE,"encodeEnvelope");function AE(e){let t=`${ed}:v${td}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Dt.decode(r));return EE.parse(JSON.parse(o))}n(AE,"decodeEnvelope");async function gt(e){let t=await Qc(),r=crypto.getRandomValues(new Uint8Array(TE)),o={version:td,keyId:Ay},s=await crypto.subtle.encrypt({name:cn,iv:r,additionalData:Py(o)},t,new TextEncoder().encode(e));return kE({...o,algorithm:cn,iv:Dt.encode(r),ciphertext:Dt.encode(new Uint8Array(s))})}n(gt,"encryptSecret");async function yt(e){let t=AE(e);if(t){let a=await Qc(),c=await crypto.subtle.decrypt({name:cn,iv:me(Dt.decode(t.iv)),additionalData:Py(t)},a,me(Dt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ve("Encrypted payload is malformed");let s=await Qc(),i=await crypto.subtle.decrypt({name:cn,iv:me(Dt.decode(r))},s,me(Dt.decode(o)));return new TextDecoder().decode(i)}n(yt,"decryptSecret");var xy={issuer:m.string().min(1).optional()},PE=m.union([ar.extend(xy),wo.extend(xy)]),My=m.object({authorizationServerUrl:m.url(),resourceMetadataUrl:m.url().optional(),resourceMetadata:Nr.optional(),authorizationServerMetadata:m.union([jr,Dr]).optional()}).passthrough(),xE="Bearer",ME="__zuplo_refresh_only_upstream_access_token__";function rd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(rd,"splitScopes");function nd(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(nd,"scopesCover");function OE(e){return Fr.parse(e)}n(OE,"parsePkceCodeVerifier");function UE(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}n(UE,"readTokenExpiry");async function od(e){if(e!==void 0)return gt(JSON.stringify(e))}n(od,"encryptJson");async function Oy(e,t){if(!e)return;let r=await yt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new E({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:o})}}n(Oy,"decryptJson");function qE(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(qE,"clientInformationAllowsRedirectUri");function zE(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(zE,"clientInformationMatchesCurrentClientMetadataUrl");function NE(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(NE,"isUrlBasedClientInformation");function jE(e,t){return t===void 0?e:{...e,scope:t}}n(jE,"applyOAuthClientMetadataScope");function DE(e,t){return Ey({state:e,delimiter:t})}n(DE,"readResourceMetadataScope");function $E(e,t){return e&&e.length>0?e.join(t):void 0}n($E,"joinOAuthScopeList");function LE(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new X(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return ar.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(LE,"buildManualOAuthClientInformation");function HE(e,t){let r=Yc({origin:new URL(t).origin,upstreamServerId:e});return uc(r)?r:void 0}n(HE,"buildClientMetadataUrl");function BE(e){for(let t of e)if(t!==void 0)return t}n(BE,"firstDefined");function FE(e){let t=nn(e.target.upstreamServerId,e.target.authProfileId),r=$E(t.scopes,t.scopeDelimiter),o=Xc({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,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:LE({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=HE(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}n(FE,"buildInitialOAuthClientSetup");function JE(e,t){if(t===void 0)return BE([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(JE,"readEncryptedClientInformation");function VE(e){return e.pendingState?.encryptedDiscoveryState}n(VE,"readEncryptedDiscoveryState");function zi(e,t){return t===void 0?e:{...e,issuer:t}}n(zi,"applyIssuerStamp");var $t=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;authorizationParams;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=FE({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.authorizationParams=r.authorizationParams,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=JE(t,this.configuredClientInformation),this.encryptedDiscoveryState=VE(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=rd(this.configuredScope??r??this.readEffectiveScope());return nd(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Ae(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=ee();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 sn({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await pr(await yt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(o){let s=ee();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 jE(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return hy({id:t.id,...Eo({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?zi(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,ee()?.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"),!NE({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await od(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!si({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=Iy(My.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await od(r),await this.syncPendingState(!1),ee()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:te(r.authorizationServerUrl),resourceMetadataHost:te(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=DE(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let s=rd(this.configuredScope).filter(i=>!o.includes(i));s.length>0&&ee()?.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 zi(r,t?.issuer)}async saveTokens(t){let r=At.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 gt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:At.parse({...r,refresh_token:await yt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Xs(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await gt(r.access_token),encryptedRefreshToken:a,scopes:rd(r.scope??this.readEffectiveScope()),expiresAt:UE(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),p=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Ae(u.connection)!=="usable"||!nd(u.connection.scopes,c.scopes)||!an(s,u.connection))){p=!0;let f=u.connection,y={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};ee()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(y,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,an(s,u.connection)&&Ae(u.connection)==="usable"&&nd(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),p){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";ee()?.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;ee()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await pr(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:p,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Ty(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride);for(let[o,s]of Object.entries(this.authorizationParams??{}))r.searchParams.set(o,s);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:OE(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new E({message:"OAuth code verifier is missing",extensionMembers:{[x]:"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:Ih(),...Eo({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()+Mi)),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 Oy(this.encryptedClientInformation,PE)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!qE(r,this.redirectUriValue)||!zE({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r!==void 0&&r.issuer===void 0&&t?.issuer!==void 0&&(r=zi(r,t.issuer),this.encryptedClientInformation=await od(r)),r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=zi(wo.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 Oy(this.encryptedDiscoveryState,My)}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"){ee()?.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 yt(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await yt(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let s=ee();this.usedRefreshTokenFingerprintValue=s?await pr(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=At.parse({access_token:r??ME,token_type:xE,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,an(r,a.connection)&&Ae(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=ee();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:o,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 GE=3e4,KE=256*1024,WE=2,ZE="does not support dynamic client registration",YE=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],XE=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],QE=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],ek="Protected resource ",tk=" does not match expected ",rk=["HTTP 403 Forbidden","Access Denied","permission to access"],nk=new Set([ce.AccessDenied,ce.InvalidClient,ce.InvalidGrant,ce.InvalidRequest,ce.InvalidScope,ce.InvalidTarget,ce.UnauthorizedClient,ce.UnsupportedGrantType]);function ok(e){return e instanceof Error&&e.message.includes(ZE)}n(ok,"isDynamicClientRegistrationUnsupported");function sk(e){return e instanceof Error&&YE.some(t=>e.message.includes(t))}n(sk,"isProtectedResourceMetadataUnavailable");function ik(e){return e instanceof Error&&XE.some(t=>e.message.includes(t))}n(ik,"isAuthorizationServerMetadataUnavailable");function ak(e){return e instanceof Error&&QE.some(t=>e.message.includes(t))}n(ak,"isAuthorizationServerIncompatible");function ck(e){return e instanceof Error&&e.message.includes(ek)&&e.message.includes(tk)}n(ck,"isProtectedResourceMismatch");function dk(e){return e instanceof Error&&rk.some(t=>e.message.includes(t))}n(dk,"isUpstreamProviderAccessDenied");function Uy(e){return e instanceof Ut&&nk.has(e.code)}n(Uy,"isStoredConnectionReconsentError");function St(e){let t=e.diagnostics??{};return new E({message:e.message,extensionMembers:{[x]:e.code,[Co]:e.upstreamServerId,[Gr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[st]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[ot]:t.httpStatus},...t.providerError===void 0?{}:{[Kr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Wr]:t.providerErrorDescription}}},{cause:e.cause})}n(St,"buildUpstreamSetupProblem");function uk(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(uk,"describeIssuerMetadataMismatch");var lk=128,Ni=256;function Yo(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Yo,"truncateProviderDetail");function pk(e){let{error:t,errorDescription:r}=ji(e.body),o=Yo(t,lk),s=Yo(r,Ni);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...s===void 0?{}:{providerErrorDescription:s}}}n(pk,"readRegistrationRejectionDiagnostics");function mk(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}n(mk,"describeRegistrationRejection");function hk(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(hk,"readDiscoveryEndpointUrl");function fk(e){if(e.error instanceof E&&e.error.extensionMembers?.[x]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(ok(e.error))return St({...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 cc){let r=pk(e.error);return St({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${mk(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof No&&e.error.kind==="metadata")return St({...t,code:"upstream_oauth_issuer_mismatch",message:uk(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof li)return St({...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(ak(e.error))return St({...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(ik(e.error)){let r=hk(e.error.message);return St({...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(ck(e.error))return St({...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(sk(e.error))return St({...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(dk(e.error))return St({...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(fk,"mapUpstreamOAuthSetupError");function gk(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(gk,"readOAuthFetchRequest");function yk(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(yk,"readOAuthFetchMethod");function Sk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Sk,"responseLooksJson");function Rk(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(Rk,"responseLooksHtml");var _k=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function wk(e){return _k.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(wk,"isMetadataDiscoveryRequest");function bk(e,t,r){return e!=="GET"||!wk(t)?!1:r>=400&&r<500||r===502}n(bk,"sdkRetriesDiscoveryCandidate");function vk(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new E({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[x]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ot]:e.response.status,[Jr]:r,[st]:e.request.url.toString(),[Vr]:e.body}})}n(vk,"throwUpstreamHtmlError");var Ck=["message","error_message","detail","title"];function qy(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}n(qy,"readStringField");function Ik(e){for(let r of Ck){let o=qy(e,r);if(o!==void 0)return o}let t=e.error;if(typeof t=="object"&&t!==null)return qy(t,"message")}n(Ik,"readProviderMessage");function ji(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t,o=typeof r.error=="string"?r.error:void 0,s=typeof r.error_description=="string"?r.error_description:void 0;return{error:o,errorDescription:s,providerMessage:s===void 0?Ik(r):void 0}}catch{return{}}}n(ji,"readUpstreamOAuthErrorBody");function Tk(e){let{error:t,errorDescription:r,providerMessage:o}=ji(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:te(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:Yo(r,Ni),providerMessage:Yo(o,Ni)},"Upstream OAuth HTTP request returned an error response")}n(Tk,"logUpstreamOAuthHttpError");function Ek(e,t){if(e!=="POST")return!1;let r=t?.body;return r instanceof URLSearchParams?r.get("grant_type")==="refresh_token":typeof r=="string"?new URLSearchParams(r).get("grant_type")==="refresh_token":!1}n(Ek,"isRefreshTokenGrant");var kk=new Set([void 0,ce.ServerError,ce.TemporarilyUnavailable]);function Ak(e,t){return e.status<500&&e.status!==429?!1:kk.has(ji(t).error)}n(Ak,"isTransientTokenEndpointResponse");var Pk=[/\b(?:unknown|unrecognized|unrecognised)\s+client(?:[\s_-]?id)?(?=\s*(?:$|[.,:;!?'"`(]))/i,/\bclient(?:[\s_-]?id)?\s+(?:not\s+found|is\s+unknown|does\s+not\s+exist)\b/i];function xk(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}n(xk,"isTokenEndpointRequest");function Mk(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:o}=ji(t);if(!(r!==void 0||o===void 0))return Pk.some(s=>s.test(o))?o:void 0}n(Mk,"readUnknownClientRejection");function Ok(e,t){let r=new Headers(e.headers);return r.set("content-type","application/json"),r.delete("content-length"),r.delete("content-encoding"),new Response(JSON.stringify({error:"invalid_client",error_description:t}),{status:e.status,statusText:e.statusText,headers:r})}n(Ok,"rewriteUnknownClientRejection");function zy(e,t){return async(r,o)=>{let s=gk(r),i=yk(r,o),a=t!==void 0&&Ek(i,o),c=ee(),d=Date.now(),u;try{u=await Xg(r,o,{maxRedirects:WE,maxResponseBytes:KE,problemCode:"upstream_token_exchange_failed",timeoutMs:GE})}catch(h){throw a&&Zg(h)&&(t.failure={url:s.url,cause:h}),h}let p=await u.clone().text();if(c?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,host:te(s.url),path:s.url.pathname,status:u.status,durationMs:Date.now()-d,responseChars:p.length},"Upstream OAuth HTTP request completed"),u.ok||Tk({log:c,upstreamServerId:e,method:i,request:s,response:u,body:p}),a&&Ak(u,p)&&(t.failure={url:s.url,status:u.status}),bk(i,s.url,u.status))return u;if(xk(i,o)){let h=Mk(u.status,p);if(h!==void 0)return c?.info({event:"upstream_oauth_unknown_client_rejected",upstreamServerId:e,host:te(s.url),path:s.url.pathname,status:u.status,providerMessage:Yo(h,Ni)},"Upstream OAuth provider no longer recognizes the gateway's client; treating it as invalid_client"),Ok(u,h)}if(!u.ok&&Rk(u,p)&&vk({upstreamServerId:e,request:s,response:u,body:p}),!Sk(u,p))return u;try{JSON.parse(p)}catch(h){throw new E({message:`Upstream OAuth fetch ${s.url.origin}${s.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[x]:"upstream_token_exchange_failed"}},{cause:h})}return u}}n(zy,"createUpstreamOAuthFetch");function Ny(e){ee()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:te(e.serverUrl),resourceMetadataHost:te(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Ny,"logUpstreamOAuthFlowStarted");function jy(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=te(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof E?e.error.extensionMembers?.[x]:void 0;typeof o=="string"&&(t.code=o),Ie(t,"error",e.error),ee()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(jy,"logUpstreamOAuthFlowFailed");function Dy(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Dy,"readAuthorizationRequestScope");async function $y(e,t){e.applyChallengeScope(t.requestedScope),Ny({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:zy(t.upstreamServerId,t.refreshFailures)},o=Dy(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await dc(e,r)}catch(r){jy({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=fk({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n($y,"runUpstreamOAuth");async function Uk(e,t){e.applyChallengeScope(t.requestedScope),Ny({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:zy(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Dy(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await dc(e,r)}catch(s){throw jy({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}n(Uk,"exchangeUpstreamAuthorizationCode");async function sd(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||Ae(r)!=="usable"||!an(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(sd,"adoptPeerCredentialAtResolutionBoundary");async function Ly(e,t){let r=await $y(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new E({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}}):new E({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}})}n(Ly,"requireUpstreamAuthorizationRedirect");function qk(e,t){let r=t.status===void 0?"did not respond":`answered HTTP ${t.status}`;return new E({message:`The token endpoint for ${e} ${r} while the gateway refreshed a stored connection. The connection was kept; retry the request.`,extensionMembers:{[x]:"upstream_token_refresh_unavailable",[Co]:e,[st]:`${t.url.origin}${t.url.pathname}`,...t.status===void 0?{}:{[ot]:t.status}}},t.cause===void 0?void 0:{cause:t.cause})}n(qk,"buildTransientRefreshProblem");function zk(e){e.log?.warn({event:"upstream_oauth_refresh_unavailable",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:e.connection?.id,host:te(e.failure.url),path:e.failure.url.pathname,status:e.failure.status},"Upstream token endpoint could not refresh the connection; the connection was kept")}n(zk,"logTransientRefreshFailure");async function Hy(e){let t=Ae(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=ee(),i=s?await sn({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={},c=n(u=>{throw zk({log:s,target:e.target,connection:e.connection,connectionFingerprint:i,failure:u}),qk(e.target.upstreamServerId,u)},"rejectTransientRefreshFailure"),d;try{d=await $y(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,refreshFailures:a,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(u){if(a.failure!==void 0&&!Uy(u)){if(await sd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope}))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};c(a.failure)}if(e.connection===void 0||!Uy(u))throw u;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:u.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await sd({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 id({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(d==="AUTHORIZED"){let u=e.provider.readUsablePeerAdoption(e.requestedScope);return u!==void 0&&await e.provider.adoptConnectionForDirectResolution(u,"cas_loss"),!e.provider.tokenWriteWasPersisted&&u===void 0?{kind:"connect_required",payload:await id({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(d!=="REDIRECT")throw new E({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${d}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new E({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});return await sd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:(a.failure!==void 0&&c(a.failure),{kind:"connect_required",payload:await id({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(Hy,"authorizeUpstreamOAuthSession");async function Nk(e){let t=await Oi(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),o=jk(r);return Dk({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),$k(o),o}n(Nk,"consumeStoredCallbackState");function jk(e){switch(e.kind){case"consumed":throw new E({message:"OAuth state has already been used",extensionMembers:{[x]:"oauth_state_reused"}});case"missing":throw new E({message:"OAuth state is missing or expired",extensionMembers:{[x]:"oauth_state_expired"}});case"available":return e.record}}n(jk,"readConsumedCallbackState");function Dk(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 E({message:"OAuth callback did not match the initiating request",extensionMembers:{[x]:"oauth_callback_mismatch"}})}n(Dk,"assertStoredCallbackStateMatches");function $k(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new E({message:"OAuth state has expired",extensionMembers:{[x]:"oauth_state_expired"}})}n($k,"assertStoredCallbackStateFresh");async function id(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),Sy(r)}if(jt()&&!_y(e.operationId))return ee()?.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"),wy({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),Ui(t)}n(id,"buildOAuthConnectRequiredResponse");async function By(e){let t=await Nk({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Js(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 $t(s),a=await Uk(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 E({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new E({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}}):new E({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}})}n(By,"finishUpstreamOAuthCallback");import{importPKCS8 as Lk,SignJWT as Hk}from"jose";var Jy=1e4,Vy=64*1024,Gy=2,Bk=300,Qe=m.string().min(1),Fk=m.object({access_token:Qe,issued_token_type:m.literal(ka),token_type:m.string().optional(),expires_in:m.number().int().positive().optional(),scope:Qe.optional()}).passthrough(),Jk=m.object({id_token:Qe,token_type:Qe.optional(),expires_in:m.number().int().positive().optional(),refresh_token:Qe.optional(),scope:Qe.optional()}).passthrough(),Vk=m.object({access_token:Qe,token_type:Qe,expires_in:m.number().int().positive().optional(),scope:Qe.optional(),resource:Qe.optional(),refresh_token:Qe.optional()}).passthrough();function Fy(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Fy,"formEncodeClientCredential");function Gk(e){return e.replaceAll("\\n",`
12
+ import{$a as pa,$b as op,$c as Vp,$d as Ia,$f as Wr,$g as ah,Aa as Nu,Ab as xl,Ac as Us,Ad as mm,Ag as Ta,Ah as Ch,Ba as ju,Bb as Ml,Bc as qs,Bd as wo,Bg as Qm,Bh as Xs,Ca as Du,Cb as Ol,Cc as fa,Cd as ar,Cg as Eo,Ch as Ih,D as Me,Da as $u,Db as Ul,Dc as ga,Dd as hm,Dg as Js,Dh as Th,E as wu,Ea as Lu,Eb as ql,Ec as ya,Ed as fm,Eg as eh,Eh as H,Fa as ir,Fb as zl,Fc as Ap,Fd as gm,Fg as th,Fh as Q,G as V,Ga as da,Gb as Nl,Gc as Sa,Gd as ym,Gg as rh,Gh as Oa,Ha as ua,Hb as jl,Hc as Ra,Hd as Sm,Hg as nh,Hh as me,Ia as _o,Ib as Dl,Ic as Pp,Id as Rm,Ig as we,Ih as pt,Ja as la,Jb as $l,Jc as xp,Jd as _m,Jf as Hm,Jg as pe,Jh as se,Ka as Hu,Kb as Ll,Kc as _a,Kd as dr,Kf as ze,Kg as oh,Kh as Qs,L as bu,La as Bu,Lb as Hl,Lc as zs,Ld as km,Lf as Bm,Lg as Xr,Lh as Ie,Ma as Fu,Mb as Bl,Mc as Ns,Md as ba,Mf as Fm,Mg as J,Mh as te,N as xs,Na as Ju,Nb as Fl,Nc as Mp,Nd as Hr,Nf as Jm,Ng as ut,Nh as Eh,Oa as Vu,Ob as Jl,Oc as Op,Od as Ls,Of as oe,Og as Mt,Oh as ee,Pa as Gu,Pb as Vl,Pc as Up,Pd as Am,Pf as Vm,Pg as sh,Ph as kh,Q as Ms,Qa as Ku,Qb as Gl,Qc as qp,Qd as Pm,Qf as Br,Qg as Ot,Qh as Ah,Ra as Wu,Rb as Kl,Rc as zp,Rd as xm,Rf as Gm,Rg as Ea,Rh as Ph,Sa as Zu,Sb as Wl,Sc as Np,Sd as Hs,Sf as Fr,Sg as Vs,Sh as xh,Ta as Yu,Tb as Zl,Tc as jp,Td as Um,Tf as x,Tg as ka,Th as qw,Ua as Xu,Ub as Yl,Uc as Dp,Ud as qm,Uf as Jr,Ug as Gs,Uh as zw,Va as Qu,Vb as Xl,Vc as $p,Vd as va,Vf as Vr,Vg as ko,W as vu,Wa as el,Wb as Ql,Wc as Lp,Wd as zm,Wf as ot,Wg as Qr,Xa as tl,Xb as ep,Xc as Hp,Xd as Nm,Xf as st,Xg as ih,Ya as rl,Yb as tp,Yc as Bp,Yd as jm,Yf as Co,Yg as lt,Z as Cu,Za as nl,Zb as rp,Zc as Fp,Zd as Ca,Zf as Gr,Zg as Aa,_a as ol,_b as np,_c as Jp,_d as Dm,_f as Kr,_g as Ks,aa as Iu,ab as sl,ac as sp,ad as Gp,ae as $m,ag as Bs,ah as Ws,b as ks,bb as il,bc as ip,bd as Kp,bg as Km,bh as Pa,cb as al,cc as ap,cd as Wp,cg as Ze,ch as Zs,db as cl,dc as cp,dd as Zp,dg as Wm,dh as ch,eb as dl,ec as dp,ed as Yp,eg as Ne,eh as de,fb as ul,fc as up,fd as Xp,fg as q,fh as dh,gb as ll,gc as lp,gd as Qp,gg as Zr,gh as uh,ha as Os,hb as pl,hc as pp,hd as em,he as Lm,hg as Ce,hh as lh,ia as Or,ib as ml,ic as ma,id as tm,ig as xt,ih as xa,ja as Ur,jb as hl,jc as mp,jd as rm,jg as Iw,jh as ph,ka as So,kb as fl,kc as hp,kd as nm,kg as Tw,kh as mh,la as qr,lb as gl,lc as fp,ld as om,lg as Ew,lh as Ma,ma as zr,mb as yl,mc as gp,md as sm,mg as kw,mh as hh,na as Ro,nb as Sl,nc as yp,nd as im,ng as Aw,nh as ur,oa as sr,ob as Rl,oc as Sp,od as am,og as Pw,oh as fh,p as go,pa as Tu,pb as _l,pc as Rp,pd as cm,pg as xw,ph as Ao,q as Et,qa as Eu,qb as wl,qc as _p,qd as dm,qg as Mw,qh as gh,r as yu,ra as ku,rb as bl,rc as wp,rd as um,rg as Ow,rh as Ys,s as Su,sa as Au,sb as vl,sc as bp,sd as lm,sg as Uw,sh as Po,t as As,ta as Pu,tb as Cl,tc as vp,td as Nr,tg as Zm,th as yh,u as Ru,ua as xu,ub as Il,uc as Cp,ud as jr,ug as Ym,uh as Sh,v as yo,va as Mu,vb as Tl,vc as Ip,vd as pm,vg as Fs,vh as Rh,w as ca,wa as Ou,wb as El,wc as Tp,wd as Dr,wg as Io,wh as _h,x as _u,xa as Uu,xb as kl,xc as Ep,xd as At,xg as To,xh as wh,y as Ps,ya as qu,yb as Al,yc as kp,yd as wa,yg as Yr,yh as bh,za as zu,zb as Pl,zc as ha,zd as js,zg as Xm,zh as vh}from"../chunk-HMKEMARF.js";import{M as Tm,N as vo,P as Em,R as Ds,S as $s,c as nt}from"../chunk-KZBZ5KM5.js";import"../chunk-MWNVPFFM.js";import{a as kt,b as Y,c as cr,d as wm,e as bm,f as vm,g as Pt,i as bo,j as Cm,k as Im,l as $r,m as Lr,t as Mm,u as Om}from"../chunk-APWLPHXH.js";import"../chunk-R6UNMRUU.js";import{A as m,b as sa,c as hu,d as l,e as fu,f as gu,g as k,h as z,i as Ts,k as D,l as C,m as g,n as L,o as U,p as ia,q as ho,r as O,s as F,t as w,u as $,v as aa,w as Es,y as fo}from"../chunk-5XXEIH5B.js";import"../chunk-5JGLAPFA.js";import{X as Is,Y as mu}from"../chunk-I65Y62VQ.js";import{a as n,e as ve,g as E,h as X}from"../chunk-VXPFMOL5.js";var Nw=Object.create,ei=Object.defineProperty,jw=Object.getOwnPropertyDescriptor,Dw=Object.getOwnPropertyNames,$w=Object.getPrototypeOf,Lw=Object.prototype.hasOwnProperty,Mh=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),Oh=n((e,t)=>{let r={};for(var o in e)ei(r,o,{get:e[o],enumerable:!0});return t&&ei(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Hw=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=Dw(t),i=0,a=s.length,c;i<a;i++)c=s[i],!Lw.call(e,c)&&c!==r&&ei(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(o=jw(t,c))||o.enumerable});return e},"__copyProps"),Uh=n((e,t,r)=>(r=e!=null?Nw($w(e)):{},Hw(t||!e||!e.__esModule?ei(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Bw=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function qh(e){return typeof e=="string"&&Bw.has(e.replace(/#$/,""))}n(qh,"declares2019Dialect");var Da=Symbol.for("mcp.sdk.errorBrands");function lr(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,Da,{value:r,enumerable:!1,configurable:!0})}n(lr,"stampErrorBrands");function je(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Da)){let r=t[Da];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(je,"brandedHasInstance");var ce=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Ut=class Vh extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return je(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 je(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",lr(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 Vh(t.error,t.error_description??t.error,t.error_uri)}},he=(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})({}),ae=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",lr(this,new.target)}},tb=class extends ae{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 Gh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Gh,"resourceUrlFromServerUrl");function Ja(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}n(Ja,"withoutIssuer");function si({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(si,"checkResourceAllowed");var rb="2026-07-28";function Kh(e){return e>=rb}n(Kh,"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)}]}}n(Wh,"appendTextFallbackForNonObject");var Zh=["task","inputRequests","requestState"];function nb(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Zh.some(t=>t in e)?e:{...e,content:[]}}n(nb,"normalizeContentlessToolResult");function ob(){let e=aa(()=>U([l(),k(),z(),Ts(),O(l(),e),C(e)])),t=O(l(),e),r=U([l(),k().int()]),o=l(),s=g({ttl:k().optional()}),i=g({taskId:l()}),a=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),p=g({_meta:a.optional()}),h=g({method:l(),params:p.loose().optional()}),f=L({_meta:a.optional()}),y=U([l(),k().int()]),b=f.strict(),_=p.extend({requestId:y.optional(),reason:l().optional()}),S=h.extend({method:w("notifications/cancelled"),params:_}),R=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),v=g({icons:C(R).optional()}),P=g({name:l(),title:l().optional()}),N=P.extend({...P.shape,...v.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),A=ho(g({applyDefaults:z().optional()}),t),M=Es(_e=>_e&&typeof _e=="object"&&!Array.isArray(_e)&&Object.keys(_e).length===0?{form:{}}:_e,ho(g({form:A.optional(),url:t.optional()}),t.optional())),B=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),W=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),Z=g({experimental:O(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:M.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:B.optional(),extensions:O(l(),t).optional()}),le=c.extend({protocolVersion:l(),capabilities:Z,clientInfo:N}),Pe=u.extend({method:w("initialize"),params:le}),K=g({experimental:O(l(),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:W.optional(),extensions:O(l(),t).optional()}),re=f.extend({protocolVersion:l(),capabilities:K,serverInfo:N,instructions:l().optional()}),_t=h.extend({method:w("notifications/initialized"),params:p.optional()}),wt=u.extend({method:w("ping"),params:c.optional()}),Vt=g({progress:k(),total:$(k()),message:$(l())}),tt=g({...p.shape,...Vt.shape,progressToken:r}),bt=h.extend({method:w("notifications/progress"),params:tt}),yr=c.extend({cursor:o.optional()}),ct=u.extend({params:yr.optional()}),dt=f.extend({nextCursor:o.optional()}),Sr=g({uri:l(),mimeType:$(l()),_meta:O(l(),D()).optional()}),Rr=Sr.extend({text:l()}),Gt=l().refine(_e=>{try{return atob(_e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_r=Sr.extend({blob:Gt}),rt=F(["user","assistant"]),Ke=g({audience:C(rt).optional(),priority:k().min(0).max(1).optional(),lastModified:fo.datetime({offset:!0}).optional()}),Kt=g({...P.shape,...v.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(k()),annotations:Ke.optional(),_meta:$(L({}))}),_n=g({...P.shape,...v.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:Ke.optional(),_meta:$(L({}))}),wn=ct.extend({method:w("resources/list")}),bn=dt.extend({resources:C(Kt)}),vt=ct.extend({method:w("resources/templates/list")}),wr=dt.extend({resourceTemplates:C(_n)}),Wt=c.extend({uri:l()}),vn=Wt,Cn=u.extend({method:w("resources/read"),params:vn}),In=f.extend({contents:C(U([Rr,_r]))}),Tn=h.extend({method:w("notifications/resources/list_changed"),params:p.optional()}),En=Wt,kn=u.extend({method:w("resources/subscribe"),params:En}),An=Wt,Pn=u.extend({method:w("resources/unsubscribe"),params:An}),xn=p.extend({uri:l()}),Mn=h.extend({method:w("notifications/resources/updated"),params:xn}),On=g({name:l(),description:$(l()),required:$(z())}),Un=g({...P.shape,...v.shape,description:$(l()),arguments:$(C(On)),_meta:$(L({}))}),qn=ct.extend({method:w("prompts/list")}),zn=dt.extend({prompts:C(Un)}),Nn=c.extend({name:l(),arguments:O(l(),l()).optional()}),jn=u.extend({method:w("prompts/get"),params:Nn}),Zt=g({type:w("text"),text:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Yt=g({type:w("image"),data:Gt,mimeType:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Xt=g({type:w("audio"),data:Gt,mimeType:l(),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),Dn=g({type:w("tool_use"),name:l(),id:l(),input:O(l(),D()),_meta:O(l(),D()).optional()}),Ct=g({type:w("resource"),resource:U([Rr,_r]),annotations:Ke.optional(),_meta:O(l(),D()).optional()}),$n=Kt.extend({type:w("resource_link")}),Le=U([Zt,Yt,Xt,$n,Ct]),br=g({role:rt,content:Le}),vr=f.extend({description:l().optional(),messages:C(br)}),Qt=h.extend({method:w("notifications/prompts/list_changed"),params:p.optional()}),Ln=g({title:l().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),Cr=g({taskSupport:F(["required","optional","forbidden"]).optional()}),er=g({...P.shape,...v.shape,description:l().optional(),inputSchema:g({type:w("object"),properties:O(l(),e).optional(),required:C(l()).optional()}).catchall(D()),outputSchema:g({type:w("object"),properties:O(l(),e).optional(),required:C(l()).optional()}).catchall(D()).optional(),annotations:Ln.optional(),execution:Cr.optional(),_meta:O(l(),D()).optional()}),Ir=ct.extend({method:w("tools/list")}),Tr=dt.extend({tools:C(er)}),Er=f.extend({content:C(Le),structuredContent:O(l(),D()).optional(),isError:z().optional()}),Re=d.extend({name:l(),arguments:O(l(),D()).optional()}),Hn=u.extend({method:w("tools/call"),params:Re}),ds=h.extend({method:w("notifications/tools/list_changed"),params:p.optional()}),kr=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Bn=c.extend({level:kr}),Fn=u.extend({method:w("logging/setLevel"),params:Bn}),Jn=p.extend({level:kr,logger:l().optional(),data:D()}),Vn=h.extend({method:w("notifications/message"),params:Jn}),Gn=g({name:l().optional()}),Kn=g({hints:C(Gn).optional(),costPriority:k().min(0).max(1).optional(),speedPriority:k().min(0).max(1).optional(),intelligencePriority:k().min(0).max(1).optional()}),Wn=g({mode:F(["auto","required","none"]).optional()}),us=g({type:w("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Le),structuredContent:g({}).loose().optional(),isError:z().optional(),_meta:O(l(),D()).optional()}),Zn=ia("type",[Zt,Yt,Xt]),It=ia("type",[Zt,Yt,Xt,Dn,us]),Yn=g({role:rt,content:U([It,C(It)]),_meta:O(l(),D()).optional()}),Xn=d.extend({messages:C(Yn),modelPreferences:Kn.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:k().optional(),maxTokens:k().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(er).optional(),toolChoice:Wn.optional()}),Qn=u.extend({method:w("sampling/createMessage"),params:Xn}),eo=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens"]).or(l())),role:rt,content:Zn}),to=f.extend({model:l(),stopReason:$(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:rt,content:U([It,C(It)])}),ro=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:z().optional()}),no=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:k().optional(),maxLength:k().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),oo=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:k().optional(),maximum:k().optional(),default:k().optional()}),so=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),io=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),ao=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),co=U([so,io]),tr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),rr=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),ls=U([tr,rr]),ps=U([ao,co,ls]),Ue=U([ps,ro,no,oo]),qe=d.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:O(l(),Ue),required:C(l()).optional()}).catchall(D())}),uo=d.extend({mode:w("url"),message:l(),elicitationId:l(),url:l().url()}),We=U([qe,uo]),ms=u.extend({method:w("elicitation/create"),params:We}),hs=p.extend({elicitationId:l()}),fs=h.extend({method:w("notifications/elicitation/complete"),params:hs}),gs=f.extend({action:F(["accept","decline","cancel"]),content:Es(_e=>_e===null?void 0:_e,O(l(),U([l(),k(),z(),C(l())])).optional())}),ys=g({type:w("ref/resource"),uri:l()}),Ss=g({type:w("ref/prompt"),name:l()}),Rs=c.extend({ref:U([Ss,ys]),argument:g({name:l(),value:l()}),context:g({arguments:O(l(),l()).optional()}).optional()}),lo=u.extend({method:w("completion/complete"),params:Rs}),_s=f.extend({completion:L({values:C(l()).max(100),total:$(k().int()),hasMore:$(z())})}),ws=g({uri:l().startsWith("file://"),name:l().optional(),_meta:O(l(),D()).optional()}),Ar=u.extend({method:w("roots/list"),params:c.optional()}),po=f.extend({roots:C(ws)}),bs=h.extend({method:w("notifications/roots/list_changed"),params:p.optional()}),vs=L({ttl:k().optional(),pollInterval:k().optional()}),mo=F(["working","input_required","completed","failed","cancelled"]),Tt=g({taskId:l(),status:mo,ttl:U([k(),Ts()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:$(k()),statusMessage:$(l())}),xe=f.extend({task:Tt}),Cs=p.merge(Tt),nr=h.extend({method:w("notifications/tasks/status"),params:Cs}),Pr=u.extend({method:w("tasks/get"),params:c.extend({taskId:l()})}),xr=f.merge(Tt),Mr=u.extend({method:w("tasks/result"),params:c.extend({taskId:l()})}),oa=f.loose(),be=ct.extend({method:w("tasks/list")}),ne=dt.extend({tasks:C(Tt)}),or=u.extend({method:w("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:p,NotificationSchema:h,ResultSchema:f,RequestIdSchema:y,EmptyResultSchema:b,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:S,IconSchema:R,IconsSchema:v,BaseMetadataSchema:P,ImplementationSchema:N,ClientTasksCapabilitySchema:B,ServerTasksCapabilitySchema:W,ClientCapabilitiesSchema:Z,InitializeRequestParamsSchema:le,InitializeRequestSchema:Pe,ServerCapabilitiesSchema:K,InitializeResultSchema:re,InitializedNotificationSchema:_t,PingRequestSchema:wt,ProgressSchema:Vt,ProgressNotificationParamsSchema:tt,ProgressNotificationSchema:bt,PaginatedRequestParamsSchema:yr,PaginatedRequestSchema:ct,PaginatedResultSchema:dt,ResourceContentsSchema:Sr,TextResourceContentsSchema:Rr,BlobResourceContentsSchema:_r,RoleSchema:rt,AnnotationsSchema:Ke,ResourceSchema:Kt,ResourceTemplateSchema:_n,ListResourcesRequestSchema:wn,ListResourcesResultSchema:bn,ListResourceTemplatesRequestSchema:vt,ListResourceTemplatesResultSchema:wr,ResourceRequestParamsSchema:Wt,ReadResourceRequestParamsSchema:vn,ReadResourceRequestSchema:Cn,ReadResourceResultSchema:In,ResourceListChangedNotificationSchema:Tn,SubscribeRequestParamsSchema:En,SubscribeRequestSchema:kn,UnsubscribeRequestParamsSchema:An,UnsubscribeRequestSchema:Pn,ResourceUpdatedNotificationParamsSchema:xn,ResourceUpdatedNotificationSchema:Mn,PromptArgumentSchema:On,PromptSchema:Un,ListPromptsRequestSchema:qn,ListPromptsResultSchema:zn,GetPromptRequestParamsSchema:Nn,GetPromptRequestSchema:jn,TextContentSchema:Zt,ImageContentSchema:Yt,AudioContentSchema:Xt,ToolUseContentSchema:Dn,EmbeddedResourceSchema:Ct,ResourceLinkSchema:$n,ContentBlockSchema:Le,PromptMessageSchema:br,GetPromptResultSchema:vr,PromptListChangedNotificationSchema:Qt,ToolAnnotationsSchema:Ln,ToolExecutionSchema:Cr,ToolSchema:er,ListToolsRequestSchema:Ir,ListToolsResultSchema:Tr,CallToolResultSchema:Er,CallToolRequestParamsSchema:Re,CallToolRequestSchema:Hn,ToolListChangedNotificationSchema:ds,LoggingLevelSchema:kr,SetLevelRequestParamsSchema:Bn,SetLevelRequestSchema:Fn,LoggingMessageNotificationParamsSchema:Jn,LoggingMessageNotificationSchema:Vn,ModelHintSchema:Gn,ModelPreferencesSchema:Kn,ToolChoiceSchema:Wn,ToolResultContentSchema:us,SamplingContentSchema:Zn,SamplingMessageContentBlockSchema:It,SamplingMessageSchema:Yn,CreateMessageRequestParamsSchema:Xn,CreateMessageRequestSchema:Qn,CreateMessageResultSchema:eo,CreateMessageResultWithToolsSchema:to,BooleanSchemaSchema:ro,StringSchemaSchema:no,NumberSchemaSchema:oo,UntitledSingleSelectEnumSchemaSchema:so,TitledSingleSelectEnumSchemaSchema:io,LegacyTitledEnumSchemaSchema:ao,SingleSelectEnumSchemaSchema:co,UntitledMultiSelectEnumSchemaSchema:tr,TitledMultiSelectEnumSchemaSchema:rr,MultiSelectEnumSchemaSchema:ls,EnumSchemaSchema:ps,PrimitiveSchemaDefinitionSchema:Ue,ElicitRequestFormParamsSchema:qe,ElicitRequestURLParamsSchema:uo,ElicitRequestParamsSchema:We,ElicitRequestSchema:ms,ElicitationCompleteNotificationParamsSchema:hs,ElicitationCompleteNotificationSchema:fs,ElicitResultSchema:gs,ResourceTemplateReferenceSchema:ys,PromptReferenceSchema:Ss,CompleteRequestParamsSchema:Rs,CompleteRequestSchema:lo,CompleteResultSchema:_s,RootSchema:ws,ListRootsRequestSchema:Ar,ListRootsResultSchema:po,RootsListChangedNotificationSchema:bs,TaskCreationParamsSchema:vs,TaskStatusSchema:mo,TaskSchema:Tt,CreateTaskResultSchema:xe,TaskStatusNotificationParamsSchema:Cs,TaskStatusNotificationSchema:nr,GetTaskRequestSchema:Pr,GetTaskResultSchema:xr,GetTaskPayloadRequestSchema:Mr,GetTaskPayloadResultSchema:oa,ListTasksRequestSchema:be,ListTasksResultSchema:ne,CancelTaskRequestSchema:or,CancelTaskResultSchema:f.merge(Tt),ClientRequestSchema:U([wt,Pe,lo,Fn,jn,qn,wn,vt,Cn,kn,Pn,Hn,Ir,Pr,Mr,be,or]),ClientNotificationSchema:U([S,bt,_t,bs,nr]),ClientResultSchema:U([b,eo,to,gs,po,xr,ne,xe]),ServerRequestSchema:U([wt,Qn,ms,Ar,Pr,Mr,be,or]),ServerNotificationSchema:U([S,bt,Vn,Mn,Tn,ds,Qt,nr,fs]),ServerResultSchema:U([b,re,_s,vr,zn,bn,wr,In,Er,Tr,xr,ne,xe]),CallToolResultWireSchema:D().superRefine((_e,Cw)=>{if(!(typeof _e!="object"||_e===null||Array.isArray(_e)||_e.content!==void 0)){for(let pu of Zh)if(pu in _e){Cw.addIssue({code:"custom",message:`content is required when the body carries '${pu}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(nb).pipe(Er)}}n(ob,"build$1");var sb;function Va(){return sb??=ob()}n(Va,"buildSchemas2025");function Yh(e){return e.type!=="object"}n(Yh,"isNonObjectJsonSchemaRoot");var ib=new Set(["const","enum","default","examples"]),ab=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function zh(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(zh,"establishesNewBase");function cb(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(zh(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=qh(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&&zh(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=o(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:ib.has(d)?a[d]=u:ab.has(d)?a[d]=o(u,!0):a[d]=o(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:o(e,!1)},required:["result"]}}n(cb,"wrapOutputSchemaForLegacy");var Xh={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},Qh={"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},db={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},ti;function ii(){if(ti)return ti;let e=Va();return ti={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}},ti}n(ii,"registryMaps");function ub(){ii()}n(ub,"warmRegistryMaps2025");function ef(e){return Object.prototype.hasOwnProperty.call(Xh,e)}n(ef,"hasRequestMethod2025");function tf(e){return Object.prototype.hasOwnProperty.call(Qh,e)}n(tf,"hasNotificationMethod2025");function lb(e){return Object.prototype.hasOwnProperty.call(db,e)}n(lb,"hasResultMethod");function pb(e){return lb(e)?ii().resultSchemas[e]:void 0}n(pb,"getResultSchema");function mb(e){return ef(e)?ii().requestSchemas[e]:void 0}n(mb,"getRequestSchema");function hb(e){return tf(e)?ii().notificationSchemas[e]:void 0}n(hb,"getNotificationSchema");var jU=Object.keys(Xh),DU=Object.keys(Qh);function $a(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n($a,"isPlainObject$5");function ri(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(ri,"triState$1");var Nh={ok:!1,reason:"not-in-era"};function jh(e){return $a(e)&&$a(e.outputSchema)&&Yh(e.outputSchema)}n(jh,"toolNeedsLegacyWrap");var Ga={era:"2025-11-25",hasRequestMethod:ef,hasNotificationMethod:tf,validateRequest:n((e,t)=>ri(mb(e),t),"validateRequest"),validateResult:n((e,t)=>ri(pb(e),t),"validateResult"),validateNotification:n((e,t)=>ri(hb(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>Nh,"validateInputRequest"),validateInputResponse:n(()=>Nh,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=Va();return ri(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Wh(e),o=r.structuredContent;if(o===void 0)return r;let s=typeof o!="object"||o===null||Array.isArray(o),i=t!==void 0&&Yh(t);return!s&&!i?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if($a(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=>jh(o))?t:{...t,tools:r.map(o=>jh(o)?{...o,outputSchema:cb(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function fb(){let e=aa(()=>U([l(),k(),z(),Ts(),O(l(),e),C(e)])),t=O(l(),e),r=U([l(),k().int()]),o=l(),s=U([l(),k().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(ne=>{try{return atob(ne),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:k().optional()}),u=g({taskId:l()}),p=L({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:p.optional()}),f=h.extend({task:d.optional()}),y=g({_meta:p.optional()}),b=g({method:l(),params:y.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:F(["light","dark"]).optional()}),S=g({icons:C(_).optional()}),R=g({name:l(),title:l().optional()}),v=R.extend({...R.shape,...S.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),P=ho(g({applyDefaults:z().optional()}),t),N=Es(ne=>ne&&typeof ne=="object"&&!Array.isArray(ne)&&Object.keys(ne).length===0?{form:{}}:ne,ho(g({form:P.optional(),url:t.optional()}),t.optional())),A=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),M=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),B=g({experimental:O(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:z().optional()}).optional(),tasks:A.optional(),extensions:O(l(),t).optional()}),W=g({experimental:O(l(),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:M.optional(),extensions:O(l(),t).optional()}),Z=g({progress:k(),total:$(k()),message:$(l())}),le=g({...y.shape,...Z.shape,progressToken:r}),Pe=b.extend({method:w("notifications/progress"),params:le}),K=y.extend({level:a,logger:l().optional(),data:D()}),re=b.extend({method:w("notifications/message"),params:K}),_t=g({uri:l(),mimeType:$(l()),_meta:O(l(),D()).optional()}),wt=_t.extend({text:l()}),Vt=_t.extend({blob:c}),tt=g({audience:C(i).optional(),priority:k().min(0).max(1).optional(),lastModified:fo.datetime({offset:!0}).optional()}),bt=g({...R.shape,...S.shape,uri:l(),description:$(l()),mimeType:$(l()),size:$(k()),annotations:tt.optional(),_meta:$(L({}))}),yr=g({...R.shape,...S.shape,uriTemplate:l(),description:$(l()),mimeType:$(l()),annotations:tt.optional(),_meta:$(L({}))}),ct=b.extend({method:w("notifications/resources/list_changed"),params:y.optional()}),dt=y.extend({uri:l()}),Sr=b.extend({method:w("notifications/resources/updated"),params:dt}),Rr=g({name:l(),description:$(l()),required:$(z())}),Gt=g({...R.shape,...S.shape,description:$(l()),arguments:$(C(Rr)),_meta:$(L({}))}),_r=b.extend({method:w("notifications/prompts/list_changed"),params:y.optional()}),rt=g({type:w("text"),text:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),Ke=g({type:w("image"),data:c,mimeType:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),Kt=g({type:w("audio"),data:c,mimeType:l(),annotations:tt.optional(),_meta:O(l(),D()).optional()}),_n=g({type:w("tool_use"),name:l(),id:l(),input:O(l(),D()),_meta:O(l(),D()).optional()}),wn=g({type:w("resource"),resource:U([wt,Vt]),annotations:tt.optional(),_meta:O(l(),D()).optional()}),bn=bt.extend({type:w("resource_link")}),vt=U([rt,Ke,Kt,bn,wn]),wr=g({role:i,content:vt}),Wt=g({title:l().optional(),readOnlyHint:z().optional(),destructiveHint:z().optional(),idempotentHint:z().optional(),openWorldHint:z().optional()}),vn=b.extend({method:w("notifications/tools/list_changed"),params:y.optional()}),Cn=g({name:l().optional()}),In=g({hints:C(Cn).optional(),costPriority:k().min(0).max(1).optional(),speedPriority:k().min(0).max(1).optional(),intelligencePriority:k().min(0).max(1).optional()}),Tn=g({mode:F(["auto","required","none"]).optional()}),En=g({type:w("boolean"),title:l().optional(),description:l().optional(),default:z().optional()}),kn=g({type:w("string"),title:l().optional(),description:l().optional(),minLength:k().optional(),maxLength:k().optional(),format:F(["email","uri","date","date-time"]).optional(),default:l().optional()}),An=g({type:F(["number","integer"]),title:l().optional(),description:l().optional(),minimum:k().optional(),maximum:k().optional(),default:k().optional()}),Pn=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),xn=g({type:w("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),Mn=g({type:w("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),On=U([Pn,xn]),Un=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({type:w("string"),enum:C(l())}),default:C(l()).optional()}),qn=g({type:w("array"),title:l().optional(),description:l().optional(),minItems:k().optional(),maxItems:k().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),zn=U([Un,qn]),Nn=U([Mn,On,zn]),jn=U([Nn,En,kn,An]),Zt=f.extend({mode:w("form").optional(),message:l(),requestedSchema:g({type:w("object"),properties:O(l(),jn),required:C(l()).optional()}).catchall(D())}),Yt=g({type:w("ref/resource"),uri:l()}),Xt=g({type:w("ref/prompt"),name:l()}),Dn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:O(l(),D()).optional()}),Ct=B.shape,$n=g({experimental:Ct.experimental,sampling:Ct.sampling,elicitation:Ct.elicitation,roots:Ct.roots,extensions:Ct.extensions}),Le=W.shape,br=g({experimental:Le.experimental,logging:Le.logging,completions:Le.completions,prompts:Le.prompts,resources:Le.resources,tools:Le.tools,extensions:Le.extensions}),vr=L({progressToken:r.optional(),[Ur]:l(),[So]:v.optional(),[zr]:$n,[Ro]:a.optional()}),Qt=g({...R.shape,...S.shape,description:l().optional(),inputSchema:L({$schema:l().optional(),type:w("object")}),outputSchema:L({$schema:l().optional()}).optional(),annotations:Wt.optional(),_meta:O(l(),D()).optional()}),Ln=g({type:w("tool_result"),toolUseId:l(),content:C(vt),structuredContent:D().optional(),isError:z().optional(),_meta:O(l(),D()).optional()}),Cr=U([rt,Ke,Kt,_n,Ln]),er=g({role:i,content:U([Cr,C(Cr)]),_meta:O(l(),D()).optional()}),Ir=l(),Tr=L({[qr]:v.optional().catch(void 0)}),Er=Tr.optional();function Re(ne){return L({_meta:Er,resultType:Ir.default("complete"),...ne})}n(Re,"wireResult");let Hn=Re({}),ds=Re({nextCursor:o.optional()}),kr=Re({content:C(vt),structuredContent:D().optional(),isError:z().optional()}),Bn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),tools:C(Qt),nextCursor:o.optional()}),Fn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),prompts:C(Gt),nextCursor:o.optional()}),Jn=Re({description:l().optional(),messages:C(wr)}),Vn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resources:C(bt),nextCursor:o.optional()}),Gn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(yr),nextCursor:o.optional()}),Kn=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),contents:C(U([wt,Vt]))}),Wn=Re({completion:g({values:C(l()).max(100),total:k().int().optional(),hasMore:z().optional()}).loose()}),us=Re({ttlMs:k().int().min(0),cacheScope:F(["public","private"])}),Zn=Re({ttlMs:k().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:br,instructions:l().optional()}),It=g({messages:C(er),modelPreferences:In.optional(),systemPrompt:l().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:k().optional(),maxTokens:k().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(Qt).optional(),toolChoice:Tn.optional()}),Yn=g({method:w("sampling/createMessage"),params:It}),Xn=g({method:w("roots/list"),params:g({_meta:O(l(),D()).optional()}).optional()}),Qn=g({...er.shape,model:l(),stopReason:l().optional()}),eo=g({roots:C(Dn)}),to=g({action:F(["accept","decline","cancel"]),content:O(l(),U([l(),k(),z(),C(l())])).optional()}),ro=g({mode:w("url"),message:l(),url:l().url()}),no=U([Zt,ro]),oo=g({method:w("elicitation/create"),params:no}),so=U([Yn,Xn,oo]),io=U([Qn,eo,to]),ao=O(l(),so),co=O(l(),io),tr=Re({inputRequests:ao.optional(),requestState:l().optional()}),rr={inputResponses:co.optional(),requestState:l().optional()},ls=g({_meta:vr,...rr}),ps=L({progressToken:r.optional()});function Ue(ne,or){return g({method:w(ne),params:g({_meta:vr,...or})})}n(Ue,"wireRequest");function qe(ne,or){return g({method:w(ne),params:g({_meta:ps.optional(),...or}).optional()})}n(qe,"dispatchRequest");let uo={name:l(),arguments:O(l(),D()).optional(),...rr},We={cursor:o.optional()},ms=Ue("tools/call",uo),hs=Ue("tools/list",We),fs=Ue("prompts/list",We),gs=Ue("prompts/get",{name:l(),arguments:O(l(),l()).optional(),...rr}),ys=Ue("resources/list",We),Ss=Ue("resources/templates/list",We),Rs=Ue("resources/read",{uri:l(),...rr}),lo={ref:U([Xt,Yt]),argument:g({name:l(),value:l()}),context:g({arguments:O(l(),l()).optional()}).optional()},_s=Ue("completion/complete",lo),ws=Ue("server/discover",{}),Ar=g({toolsListChanged:z().optional(),promptsListChanged:z().optional(),resourcesListChanged:z().optional(),resourceSubscriptions:C(l()).optional()}),po={notifications:Ar},bs=Ue("subscriptions/listen",po),vs=Tr.extend({"io.modelcontextprotocol/subscriptionId":s}),mo=L({_meta:vs,resultType:Ir.default("complete")}),Tt={"tools/call":qe("tools/call",uo),"tools/list":qe("tools/list",We),"prompts/get":qe("prompts/get",{name:l(),arguments:O(l(),l()).optional()}),"prompts/list":qe("prompts/list",We),"resources/list":qe("resources/list",We),"resources/templates/list":qe("resources/templates/list",We),"resources/read":qe("resources/read",{uri:l()}),"completion/complete":qe("completion/complete",lo),"server/discover":qe("server/discover",{}),"subscriptions/listen":qe("subscriptions/listen",po)};function xe(ne){return L({_meta:Er,...ne})}n(xe,"liftedResult");let Cs={"tools/call":xe({content:C(vt),structuredContent:D().optional(),isError:z().optional()}),"tools/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),tools:C(Qt),nextCursor:o.optional()}),"prompts/get":xe({description:l().optional(),messages:C(wr)}),"prompts/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),prompts:C(Gt),nextCursor:o.optional()}),"resources/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resources:C(bt),nextCursor:o.optional()}),"resources/templates/list":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:C(yr),nextCursor:o.optional()}),"resources/read":xe({ttlMs:k().int().min(0),cacheScope:F(["public","private"]),contents:C(U([wt,Vt]))}),"completion/complete":xe({completion:g({values:C(l()).max(100),total:k().int().optional(),hasMore:z().optional()}).loose()}),"server/discover":xe({ttlMs:k().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:br,instructions:l().optional()}),"subscriptions/listen":xe({})},nr=L({"io.modelcontextprotocol/subscriptionId":s.optional()}),Pr=g({method:w("notifications/subscriptions/acknowledged"),params:g({_meta:nr.optional(),notifications:Ar})}),xr=g({_meta:nr.optional(),requestId:s,reason:l().optional()}),Mr=g({method:w("notifications/cancelled"),params:xr}),oa={"notifications/cancelled":Mr,"notifications/progress":Pe,"notifications/message":re,"notifications/resources/updated":Sr,"notifications/resources/list_changed":ct,"notifications/tools/list_changed":vn,"notifications/prompts/list_changed":_r,"notifications/subscriptions/acknowledged":Pr},be=n(ne=>g({jsonrpc:w("2.0"),id:U([l(),k().int()]),result:ne}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:p,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:y,NotificationSchema:b,IconSchema:_,IconsSchema:S,BaseMetadataSchema:R,ImplementationSchema:v,ClientTasksCapabilitySchema:A,ServerTasksCapabilitySchema:M,ClientCapabilitiesSchema:B,ServerCapabilitiesSchema:W,ProgressSchema:Z,ProgressNotificationParamsSchema:le,ProgressNotificationSchema:Pe,LoggingMessageNotificationParamsSchema:K,LoggingMessageNotificationSchema:re,ResourceContentsSchema:_t,TextResourceContentsSchema:wt,BlobResourceContentsSchema:Vt,AnnotationsSchema:tt,ResourceSchema:bt,ResourceTemplateSchema:yr,ResourceListChangedNotificationSchema:ct,ResourceUpdatedNotificationParamsSchema:dt,ResourceUpdatedNotificationSchema:Sr,PromptArgumentSchema:Rr,PromptSchema:Gt,PromptListChangedNotificationSchema:_r,TextContentSchema:rt,ImageContentSchema:Ke,AudioContentSchema:Kt,ToolUseContentSchema:_n,EmbeddedResourceSchema:wn,ResourceLinkSchema:bn,ContentBlockSchema:vt,PromptMessageSchema:wr,ToolAnnotationsSchema:Wt,ToolListChangedNotificationSchema:vn,ModelHintSchema:Cn,ModelPreferencesSchema:In,ToolChoiceSchema:Tn,BooleanSchemaSchema:En,StringSchemaSchema:kn,NumberSchemaSchema:An,UntitledSingleSelectEnumSchemaSchema:Pn,TitledSingleSelectEnumSchemaSchema:xn,LegacyTitledEnumSchemaSchema:Mn,SingleSelectEnumSchemaSchema:On,UntitledMultiSelectEnumSchemaSchema:Un,TitledMultiSelectEnumSchemaSchema:qn,MultiSelectEnumSchemaSchema:zn,EnumSchemaSchema:Nn,PrimitiveSchemaDefinitionSchema:jn,ElicitRequestFormParamsSchema:Zt,ResourceTemplateReferenceSchema:Yt,PromptReferenceSchema:Xt,RootSchema:Dn,ClientCapabilities2026Schema:$n,ServerCapabilities2026Schema:br,RequestMetaEnvelopeSchema:vr,ToolSchema:Qt,ToolResultContentSchema:Ln,SamplingMessageContentBlockSchema:Cr,SamplingMessageSchema:er,ResultTypeSchema:Ir,ResultMetaSchema:Tr,ResultSchema:Hn,PaginatedResultSchema:ds,CallToolResultSchema:kr,ListToolsResultSchema:Bn,ListPromptsResultSchema:Fn,GetPromptResultSchema:Jn,ListResourcesResultSchema:Vn,ListResourceTemplatesResultSchema:Gn,ReadResourceResultSchema:Kn,CompleteResultSchema:Wn,CacheableResultSchema:us,DiscoverResultSchema:Zn,CreateMessageRequestParamsSchema:It,CreateMessageRequestSchema:Yn,ListRootsRequestSchema:Xn,CreateMessageResultSchema:Qn,ListRootsResultSchema:eo,ElicitResultSchema:to,ElicitRequestURLParamsSchema:ro,ElicitRequestParamsSchema:no,ElicitRequestSchema:oo,InputRequestSchema:so,InputResponseSchema:io,InputRequestsSchema:ao,InputResponsesSchema:co,InputRequiredResultSchema:tr,InputResponseRequestParamsSchema:ls,CallToolRequestSchema:ms,ListToolsRequestSchema:hs,ListPromptsRequestSchema:fs,GetPromptRequestSchema:gs,ListResourcesRequestSchema:ys,ListResourceTemplatesRequestSchema:Ss,ReadResourceRequestSchema:Rs,CompleteRequestSchema:_s,DiscoverRequestSchema:ws,SubscriptionFilterSchema:Ar,SubscriptionsListenRequestSchema:bs,SubscriptionsListenResultMetaSchema:vs,SubscriptionsListenResultSchema:mo,dispatchRequestSchemas:Tt,dispatchResultSchemas:Cs,NotificationMetaSchema:nr,SubscriptionsAcknowledgedNotificationSchema:Pr,CancelledNotificationParamsSchema:xr,CancelledNotificationSchema:Mr,notificationSchemas2026:oa,JSONRPCResultResponseSchema:be(Hn),CallToolResultResponseSchema:be(U([kr,tr])),ListToolsResultResponseSchema:be(Bn),ListPromptsResultResponseSchema:be(Fn),GetPromptResultResponseSchema:be(U([Jn,tr])),ListResourcesResultResponseSchema:be(Vn),ListResourceTemplatesResultResponseSchema:be(Gn),ReadResourceResultResponseSchema:be(U([Kn,tr])),CompleteResultResponseSchema:be(Wn),DiscoverResultResponseSchema:be(Zn),SubscriptionsListenResultResponseSchema:be(mo)}}n(fb,"build");var gb;function mt(){return gb??=fb()}n(mt,"buildSchemas2026");var yb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Sb(e){return yb.includes(e)}n(Sb,"isCacheableResultMethod");var Ka=Symbol("modelcontextprotocol.resultCacheHintFallback");function Rb(e){return e[Ka]}n(Rb,"cacheHintFallbackOf");function rf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n(rf,"isValidCacheTtlMs");function nf(e){return e==="public"||e==="private"}n(nf,"isValidCacheScope");var I=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),fe=class of extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return je(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 je(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",lr(this,new.target)}static fromError(t,r,o){if(t===I.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new ai(s.elicitations,r)}if(t===I.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new af({supported:s.supported,requested:s.requested},r)}if(t===I.InvalidParams||t===I.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===I.ResourceNotFound||Object.keys(s).length===1))return new sf(s.uri,r)}if(t===I.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new cf({requiredCapabilities:s.requiredCapabilities},r)}return new of(t,r,o)}},sf=class extends fe{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(I.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ai=class extends fe{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},af=class extends fe{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(I.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},cf=class extends fe{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(I.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},_b=0,wb="private",bb=["tools/call","prompts/get","resources/read"];function vb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||bb.includes(e))return t;throw new fe(I.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(vb,"stampResultType");function Cb(e,t){let r=Rb(t);if(t.resultType!=="complete"||!Sb(e))return r===void 0?t:Ab(t);let o=t,s=rf(o.ttlMs)?o.ttlMs:Eb(r),i=nf(o.cacheScope)?o.cacheScope:kb(r),a={...o,ttlMs:s,cacheScope:i};return delete a[Ka],a}n(Cb,"fillCacheFields");function Ib(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ib,"isPlainObject$4");function Tb(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[qr]:t}}:!Ib(r)||r[qr]!==void 0?e:{...e,_meta:{...r,[qr]:t}}}n(Tb,"stampServerInfoMeta");function Eb(e){return e!==void 0&&rf(e.ttlMs)?e.ttlMs:_b}n(Eb,"resolveTtlMs");function kb(e){return e!==void 0&&nf(e.cacheScope)?e.cacheScope:wb}n(kb,"resolveCacheScope");function Ab(e){let t={...e};return delete t[Ka],t}n(Ab,"stripCacheHintFallback");var Pb=["elicitation/create","sampling/createMessage","roots/list"],ni;function Wa(){if(ni)return ni;let e=mt();return ni={request:{"elicitation/create":g({method:w("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:w("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:w("roots/list"),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ni}n(Wa,"inputSchemaMaps");function xb(){Wa()}n(xb,"warmInputSchemaMaps2026");function df(e){return Pb.includes(e)}n(df,"isInputRequestMethod2026");function Ua(e){return df(e)?Wa().request[e]:void 0}n(Ua,"getInputRequestSchema2026");function Mb(e){return df(e)?Wa().response[e]:void 0}n(Mb,"getInputResponseSchema2026");var Za={"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},uf={"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 lf(e){return Object.prototype.hasOwnProperty.call(Za,e)}n(lf,"hasRequestMethod2026");function pf(e){return Object.prototype.hasOwnProperty.call(uf,e)}n(pf,"hasNotificationMethod2026");function Ob(e){return Object.prototype.hasOwnProperty.call(Za,e)}n(Ob,"hasResultMethod2026");function Ub(e){return lf(e)?mt().dispatchRequestSchemas[e]:void 0}n(Ub,"getRequestSchema2026");function qb(e){return Ob(e)?mt().dispatchResultSchemas[e]:void 0}n(qb,"getResultSchema2026");function zb(e){return pf(e)?mt().notificationSchemas2026[e]:void 0}n(zb,"getNotificationSchema2026");var $U=Object.keys(Za),LU=Object.keys(uf);function Oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Oo,"isPlainObject$3");function xo(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(xo,"triState");var Nb={ok:!1,reason:"not-in-era"},jb=[Ur,zr];function Db(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=>Oo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!Oo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(Oo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}n(Db,"enforceDeletedFields");var Ya={era:"2026-07-28",hasRequestMethod:lf,hasNotificationMethod:pf,hasInputRequestMethod:n(e=>Ua(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>xo(Ub(e),t),"validateRequest"),validateResult:n((e,t)=>xo(qb(e),t),"validateResult"),validateNotification:n((e,t)=>xo(zb(e),t),"validateNotification"),validateInputRequest:n((e,t)=>xo(Ua(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>xo(Mb(e),t),"validateInputResponse"),samplingResultVariant:n(()=>Nb,"samplingResultVariant"),outboundEnvelope(e){return{[Ur]:e.protocolVersion,[So]:e.clientInfo,[zr]:e.clientCapabilities,...e.logLevel!==void 0&&{[Ro]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of jb)o in e||t.push({key:o,problem:"missing"});let r=mt().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=>Wh(e),"projectCallToolResult"),inputRequestSchema:Ua,decodeResult(e,t){if(!Oo(t))return{kind:"invalid",error:new ae(he.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new ae(he.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 ae(he.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=Oo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:mt().ResultMetaSchema.safeParse(t._meta),p=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new ae(he.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...p!==void 0&&{_meta:p}}}if(r!=="complete")return{kind:"invalid",error:new ae(he.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=mf(),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 ae(he.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 Tb(Cb(e,vb(e,Db(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=mt().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("; ")}`}},oi;function mf(){if(oi)return oi;let e=mt();return oi={"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},oi}n(mf,"getWireResultSchemas");function $b(){mf()}n($b,"warmWireResultSchemas2026");var Xa="2026-07-28";function qo(e){return e!==void 0&&Kh(e)?Ya:Ga}n(qo,"codecForVersion");function Dh(e){return e.revision!==void 0?qo(e.revision).era:e.era==="modern"?Ya.era:Ga.era}n(Dh,"classifiedWireEra");function qa(e){return hf.some(t=>t.hasRequestMethod(e))}n(qa,"isSpecRequestMethod");function za(e){return hf.some(t=>t.hasNotificationMethod(e))}n(za,"isSpecNotificationMethod");function $h(e){return e==="tasks/get"||e==="tasks/cancel"}n($h,"isExtensionReusedRequestMethod");var hf=[Ga,Ya],Lb=Oh({AnnotationsSchema:n(()=>gl,"AnnotationsSchema"),AudioContentSchema:n(()=>Wl,"AudioContentSchema"),BaseMetadataSchema:n(()=>Ku,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>Uu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>hl,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>ha,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>up,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>lp,"CallToolRequestSchema"),CallToolResultSchema:n(()=>cp,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>om,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>sm,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>Fu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>Ju,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>Xu,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>am,"ClientNotificationSchema"),ClientRequestSchema:n(()=>im,"ClientRequestSchema"),ClientResultSchema:n(()=>cm,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>Zu,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>dp,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Dp,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>$p,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Lp,"CompleteResultSchema"),ContentBlockSchema:n(()=>Ql,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>Ip,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Tp,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Ep,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>kp,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>Wp,"CreateTaskResultSchema"),CursorSchema:n(()=>Pu,"CursorSchema"),DiscoverRequestSchema:n(()=>ol,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>pa,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>zs,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Mp,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>Op,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Ns,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>zp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>Up,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>qp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>Yl,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Bu,"EmptyResultSchema"),EnumSchemaSchema:n(()=>xp,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>Jl,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>Vl,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>tp,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>em,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>tm,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>Xp,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>Qp,"GetTaskResultSchema"),IconSchema:n(()=>Vu,"IconSchema"),IconsSchema:n(()=>Gu,"IconsSchema"),ImageContentSchema:n(()=>Kl,"ImageContentSchema"),ImplementationSchema:n(()=>Wu,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>Qu,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>el,"InitializeRequestSchema"),InitializeResultSchema:n(()=>rl,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>nl,"InitializedNotificationSchema"),JSONArraySchema:n(()=>ku,"JSONArraySchema"),JSONObjectSchema:n(()=>Eu,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>_o,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>la,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>da,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>ir,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Hu,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>ua,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Tu,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>ya,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>ma,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Bl,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>Fl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>wl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>bl,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Rl,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>_l,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Bp,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>Fp,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>rm,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>nm,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>ip,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>ap,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>mp,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>gp,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>yp,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Sp,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Rp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Pp,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>ju,"NotificationSchema"),NotificationsParamsSchema:n(()=>Nu,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>qs,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>dl,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>ul,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>ll,"PaginatedResultSchema"),PingRequestSchema:n(()=>sl,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>_a,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>al,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>cl,"ProgressNotificationSchema"),ProgressSchema:n(()=>il,"ProgressSchema"),ProgressTokenSchema:n(()=>Au,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Ll,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>rp,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>ep,"PromptMessageSchema"),PromptReferenceSchema:n(()=>jp,"PromptReferenceSchema"),PromptSchema:n(()=>Hl,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>Cl,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>Il,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Tl,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Mu,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Lu,"RequestIdSchema"),RequestMetaSchema:n(()=>Ou,"RequestMetaSchema"),RequestSchema:n(()=>zu,"RequestSchema"),ResourceContentsSchema:n(()=>pl,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>Xl,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>El,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>vl,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>yl,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Np,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Sl,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Dl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>$l,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Du,"ResultMetaObjectSchema"),ResultSchema:n(()=>$u,"ResultSchema"),RoleSchema:n(()=>fl,"RoleSchema"),RootSchema:n(()=>Hp,"RootSchema"),RootsListChangedNotificationSchema:n(()=>Jp,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>bp,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>vp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>Cp,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>tl,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>um,"ServerNotificationSchema"),ServerRequestSchema:n(()=>dm,"ServerRequestSchema"),ServerResultSchema:n(()=>lm,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>Yu,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>hp,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>fp,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>Ap,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Us,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>kl,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>Al,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Ml,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>ql,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>zl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>Ol,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>Ul,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Nl,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>jl,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>qu,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>Vp,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>xu,"TaskMetadataSchema"),TaskSchema:n(()=>Kp,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>Zp,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>Yp,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>Gp,"TaskStatusSchema"),TextContentSchema:n(()=>Gl,"TextContentSchema"),TextResourceContentsSchema:n(()=>ml,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>Ra,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>ga,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>np,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>_p,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>op,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>pp,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>wp,"ToolResultContentSchema"),ToolSchema:n(()=>sp,"ToolSchema"),ToolUseContentSchema:n(()=>Zl,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Pl,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>xl,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Sa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>fa,"UntitledSingleSelectEnumSchemaSchema")});var ff=n(e=>ir.safeParse(e).success,"isJSONRPCRequest"),gf=n(e=>da.safeParse(e).success,"isJSONRPCNotification"),La=n(e=>ua.safeParse(e).success,"isJSONRPCResultResponse"),yf=n(e=>_o.safeParse(e).success,"isJSONRPCErrorResponse");var Uo=-32020,HU=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[I.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Uo,I.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[I.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[I.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[I.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Uo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[I.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Uo],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."}],BU={[I.ParseError]:400,[I.InvalidRequest]:400,[I.MethodNotFound]:404,[I.UnsupportedProtocolVersion]:400,[I.MissingRequiredClientCapability]:400,[Uo]:400};function Qa(e,t){return hu(e,t)}n(Qa,"parseSchema");function Mo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Mo,"shapeKeys");function Ha(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(Ha,"isStandardSchema");var Lh=!1,Ba="draft-2020-12";function Hb(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:Ba});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Lh||(Lh=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=sa(e,{target:Ba,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:Sf(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(Hb,"standardSchemaToJsonSchema");function Sf(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"||Sf(o)))}return!1}n(Sf,"isProvablyObjectShapedRoot");function Bb(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Bb,"formatIssue");async function Na(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Bb(o)).join(", ")}:{success:!0,data:r.value}}n(Na,"validateStandardSchema");function Fb(e){let t=sa(e,{target:Ba,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(Fb,"zodEmittedPattern");var Jb=/\\\.\\d\{(\d+)\}/;function Vb(e){let t=Jb.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=>fo.datetime({local:o,offset:s,precision:i}))))}n(Vb,"datetimeReferenceSchemas");function Gb(e,t){let r;switch(e){case"email":r=[fu()];break;case"uri":r=[gu()];break;case"date":r=[fo.date()];break;case"date-time":r=Vb(t);break}return new Set(r.map(o=>Fb(o)).filter(o=>o!==void 0))}n(Gb,"referencePatternsForFormat");function Kb(e,t,r){return r!=="zod"?!0:Gb(e,t).has(t)}n(Kb,"isLibraryFormatPattern");function zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(zo,"isJsonObject");function Wb(e){try{return Hb(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new fe(I.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(Wb,"convertStandardElicitationSchema");var Zb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function ec(e){return Zb.has(e)||e.startsWith("x-")}n(ec,"isAnnotationOnlyJsonSchemaKeyword");var Yb=new Set(["$schema",...Object.keys(zs.shape.requestedSchema.shape)]),Hh={string:Mo([Us,fa,ga,ya]),number:Mo([qs]),integer:Mo([qs]),boolean:Mo([ha]),array:Mo([Sa,Ra])},Xb=new Set(Us.shape.format.unwrap().options);function Qb(e,t,r,o){if(!zo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Hh,e.type)?Hh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||ec(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?Xb.has(e.format)?(typeof c!="string"||!Kb(e.format,c,r))&&o.push(`${t}.${a}`):i[a]=c:o.push(`${t}.${a}`);return i}n(Qb,"walkProperty");function ev(e,t){let r={},o=[];for(let[s,i]of Object.entries(e))s==="properties"&&zo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Qb(c,`properties.${a}`,t,o)])):Yb.has(s)?r[s]=i:ec(s)||o.push(s);if(o.length>0)throw new fe(I.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n(ev,"walkRequestedSchema");function tv(e,t){if(!zo(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Qa(_a,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(tv,"describeUnsupportedProperties");function Fa(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Fa(o,t[s],`${r}[${s}]`)):!zo(e)||!zo(t)?[]:Object.entries(e).flatMap(([o,s])=>{let i=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Fa(s,t[o],i):ec(o)?[]:[i]})}n(Fa,"findDroppedConstraintPaths");function rv(e){if(!Ha(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=ev(Wb(e.requestedSchema),t),o=Qa(zs.shape.requestedSchema,r);if(!o.success)throw new fe(I.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${tv(r,o.error.message)}`);let s=Fa(r,o.data);if(s.length>0)throw new fe(I.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 fe(I.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(rv,"normalizeElicitInputParams");function nv(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(nv,"buildInputRequired");var FU=Object.assign(nv,{elicit(e){try{return{method:"elicitation/create",params:rv(e)}}catch(t){throw t instanceof fe?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 ov=["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"],sv={IdJagTokenExchangeResponseSchema:wa,OAuthClientInformationFullSchema:ar,OAuthClientInformationSchema:wo,OAuthClientMetadataSchema:mm,OAuthClientRegistrationErrorSchema:hm,OAuthErrorResponseSchema:js,OAuthMetadataSchema:jr,OAuthProtectedResourceMetadataSchema:Nr,OAuthTokenRevocationRequestSchema:fm,OAuthTokensSchema:At,OpenIdProviderDiscoveryMetadataSchema:Dr,OpenIdProviderMetadataSchema:pm},Rf={},_f={};function wf(e,t){let r=e.slice(0,-6);Rf[r]=t,_f[r]=o=>t.safeParse(o).success}n(wf,"register");for(let e of ov)wf(e,Lb[e]);for(let[e,t]of Object.entries(sv))wf(e,t);var iv=Object.freeze(Rf),av=Object.freeze(_f);function cv(e){switch(e){case"initialize":case"notifications/initialized":return qo(void 0);case"server/discover":return qo(Xa);default:return}}n(cv,"bootstrapOutboundCodec");var bf=6e4,dv=[Ur,So,zr,Ro],uv=["inputResponses","requestState"];function Bh(e,t){let r=e.params;if(!ja(r))return{message:e,lifted:{}};let o=r._meta,s=ja(o)?dv.filter(d=>d in o):[],i=t==="request"?uv.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&ja(o)){let d={},u={...o};for(let p of s)d[p]=o[p],delete u[p];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}n(Bh,"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(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(Fh,"codecResultValidator");function vf(e){return()=>e}n(vf,"requestStateAccessor");var lv=vf(void 0),pv,mv=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{pv=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Or,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 ae(he.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 ae(he.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),La(s)||yf(s)?this._onresponse(s):ff(s)?this._onrequest(s,i):gf(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 ae(he.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}=Bh(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Dh(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(za(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}=Bh(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,R)=>{let v={jsonrpc:"2.0",id:r.id,error:{code:_,message:S,...R!==void 0&&{data:R}}};i?.send(v).catch(P=>this._onerror(new Error(`Failed to send an error response: ${P}`)))},"sendErrorResponse");if(t?.classification!==void 0){let _=Dh(t.classification);if(_!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${_} but this instance serves ${s.era}`));let S=t.classification.revision??_;a(I.UnsupportedProtocolVersion,`Unsupported protocol version: ${S}`,{supported:this._supportedProtocolVersions,requested:S});return}}if(qa(r.method)&&!s.hasRequestMethod(r.method)&&!($h(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(I.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(I.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(o);if(d!==void 0){a(I.InvalidParams,d);return}let u=n((_,S)=>this._notificationViaCodec(this._resolveOutboundCodec(_.method),_,{...S,relatedRequestId:r.id}),"sendNotification"),p=n((_,S,R)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(_.method),_,S,{...R,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=o.inputResponses===void 0?void 0:hv(o.inputResponses),y={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?lv:vf(o.requestState),signal:h.signal,send:n(((_,S,R)=>{let v=this._resolveOutboundCodec(_.method);if(this._assertOutboundRequestInEra(v,_.method),Ha(S))return p(_,S,R);let P=Fh(v,_.method);if(P===void 0)throw new TypeError(`'${_.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(_,P,S)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(y,t);Promise.resolve().then(()=>c(r,b)).then(async _=>{if(h.signal.aborted)return;let S;try{S=s.encodeResult(r.method,_,this._outboundServerInfo())}catch(v){this._onerror(new Error(`Failed to encode result for ${r.method}: ${v}`)),a(I.InternalError,"Internal error");return}let R={result:S,jsonrpc:"2.0",id:r.id};await i?.send(R)},async _=>{if(h.signal.aborted)return;let S=Number.isSafeInteger(_.code)?_.code:I.InternalError,R={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(S),message:_.message??"Internal error",..._.data!==void 0&&{data:_.data}}};await i?.send(R)}).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,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),La(e)?r(e):r(fe.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(Ha(t))return $h(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let s=Fh(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 qo(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=cv(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(qa(t)&&!e.hasRequestMethod(t))throw new ae(he.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(),u,p;return new Promise((h,f)=>{let y=n(M=>{f(M)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(M){y(M);return}if(o?.signal?.aborted){let M=o.signal.reason;throw M instanceof ae?M:new ae(he.RequestTimeout,String(M))}let b=e.era===Xa&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;p=_;let S={...t,jsonrpc:"2.0",id:_};o?.onprogress&&(this._progressHandlers.set(_,o.onprogress),S.params={...t.params,_meta:{...t.params?._meta,progressToken:_}});let R=this._envelopeOutbound(S),v=!1,P=n(M=>{v||(this._progressHandlers.delete(_),b===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(M)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`))):b.abort(),f(M instanceof ae?M:new ae(he.RequestTimeout,String(M))))},"cancel");this._responseHandlers.set(_,M=>{if(o?.signal?.aborted)return;if(v=!0,M instanceof Error)return f(M);let B;try{B=e.decodeResult(t.method,M.result)}catch(Z){return f(Z instanceof Error?Z:new Error(String(Z)))}if(B.kind==="invalid")return f(B.error);if(B.kind==="input_required"){if(o?.allowInputRequired===!0)return h(fv(B));let Z={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:d,retry:n((le,Pe)=>this._requestWithSchemaViaCodec(e,le===void 0?{method:t.method}:{method:t.method,params:le},r,Pe),"retry")};return h(this._resolveNonCompleteResult(B,Z))}let W=B.result;Na(r,W).then(Z=>{Z.success?h(Z.data):f(new ae(he.InvalidResult,`Invalid result for ${t.method}: ${Z.error}`))},f)}),u=n(()=>P(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",u,{once:!0});let N=o?.timeout??bf,A=n(()=>P(new ae(he.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(_,N,o?.maxTotalTimeout,A,o?.resetTimeoutOnProgress??!1),this._transport.send(R,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:b?.signal}).catch(M=>{this._progressHandlers.delete(_),f(M)})}).finally(()=>{u&&o?.signal?.removeEventListener("abort",u),p!==void 0&&(this._responseHandlers.delete(p),this._cleanupTimeout(p))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new ae(he.NotConnected,"Not connected");if(za(t.method)&&!e.hasNotificationMethod(t.method))throw new ae(he.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(!qa(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 fe(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)o=n(async(s,i)=>{let a=await Na(t.params,{...s.params});if(!a.success)throw new fe(I.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,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(!za(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 fe(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Na(t.params,{...o.params});if(!s.success)throw new fe(I.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ja(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ja,"isPlainObject$1");function Jh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Jh,"isPlainObject");function hv(e){let t={},r=[];if(!Jh(e))return{accepted:t,droppedKeys:r};for(let[o,s]of Object.entries(e)){if(!Jh(s)||"method"in s||"result"in s){r.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:r}}n(hv,"partitionInputResponses");function fv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}n(fv,"manualInputRequiredValue");var gv=Mh((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 u=d.indexOf(";"),p=u!==-1?d.slice(0,u).trim():d.trim();if(!o.test(p))throw new TypeError("invalid media type");var h=new a(p.toLowerCase());if(u!==-1){var f,y,b;for(t.lastIndex=u;y=t.exec(d);){if(y.index!==u)throw new TypeError("invalid parameter format");u+=y[0].length,f=y[1].toLowerCase(),b=y[2],b.charCodeAt(0)===34&&(b=b.slice(1,-1),b.indexOf("\\")!==-1&&(b=b.replace(r,"$1"))),h.parameters[f]=b}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}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")})),JU=Uh(gv(),1);var yv=10*1024*1024;var Sv=new Set([301,302,303,307,308]),Rv=5;function _v(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(_v,"isWithinOrigin");function wv(e,t){let r=Sv.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}n(wv,"redirectTarget");var bv=new WeakSet;function ci(e){return bv.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=wv(s,a);if(!c||i===Rv)return a;let d=new URL(s),u=o==="GET"||a.status===307||a.status===308,p=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!p||!_v(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}n(ci,"fetchWithinOrigin");function tc(){Va(),mt(),ub(),xb(),$b()}n(tc,"preloadSchemas");var n0=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 vv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cv=[0,31,28,31,30,31,30,31,31,30,31,30,31],Iv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Tv=/^(?=.{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,Ev=/^(?:[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,kv=/^(?:(?:[^\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,Av=/^(?:(?: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,Pv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Mv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ov=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Uv=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"),qv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,zv=/^((([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,Nv=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 it(e){return e.test.bind(e)}n(it,"bind");var o0={date:Cf,time:If.bind(void 0,!1),"date-time":$v,duration:Nv,uri:Bv,"uri-reference":it(Ev),"uri-template":it(kv),url:it(Av),email:Uv,hostname:it(Tv),ipv4:it(qv),ipv6:it(zv),regex:Jv,uuid:it(Pv),"json-pointer":it(xv),"json-pointer-uri-fragment":it(Mv),"relative-json-pointer":it(Ov)};function jv(e){return e%4===0&&(e%100!==0||e%400===0)}n(jv,"isLeapYear");function Cf(e){let t=e.match(vv);if(!t)return!1;let r=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o==2&&jv(r)?29:Cv[o])}n(Cf,"date");function If(e,t){let r=t.match(Iv);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(If,"time");var Dv=/t|\s/i;function $v(e){let t=e.split(Dv);return t.length==2&&Cf(t[0])&&If(!0,t[1])}n($v,"date_time");var Lv=/\/|:/,Hv=/^(?:[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 Bv(e){return Lv.test(e)&&Hv.test(e)}n(Bv,"uri");var Fv=/[^\\]\\Z/;function Jv(e){if(Fv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(Jv,"regex");tc();var Tf=!1;var rc;rc=globalThis.crypto;async function Gv(e){return(await rc).getRandomValues(new Uint8Array(e))}n(Gv,"getRandomValues");async function Kv(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let s=await Gv(e-o.length);for(let i of s)i<r&&(o+=t[i%t.length])}return o}n(Kv,"random");async function Wv(e){return await Kv(e)}n(Wv,"generateVerifier");async function Zv(e){let t=await(await rc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Zv,"generateChallenge");async function nc(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Wv(e),r=await Zv(t);return{code_verifier:t,code_challenge:r}}n(nc,"pkceChallenge");var jo=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e){super(e),this.name=new.target.name,lr(this,new.target)}},No=class extends jo{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}},cc=class extends jo{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}},li=class extends jo{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}},ui=class extends jo{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}},G0=class extends jo{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 ac(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}):Pf(e.issuer,t)?e:void 0}n(ac,"discardIfIssuerMismatch");function Pf(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(Pf,"issuersMatch");var K0=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",lr(this,new.target)}};function xf(e){return e?.authorization_response_iss_parameter_supported===!0}n(xf,"isIssParameterSupported");function Mf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new No("authorization_response",t,void 0);return}if(e!==t)throw new No("authorization_response",t,e)}}n(Mf,"validateAuthorizationResponseIssuer");function Yv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Yv,"isClientAuthMethod");var oc="code",sc="S256";function Xv(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Yv(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(Xv,"selectClientAuthMethod");function Qv(e,t,r,o){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":eC(s,i,r);return;case"client_secret_post":tC(s,i,o);return;case"none":rC(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Qv,"applyClientAuthentication");function eC(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(eC,"applyBasicAuth");function tC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(tC,"applyPostAuth");function rC(e,t){t.set("client_id",e)}n(rC,"applyPublicAuth");function Of(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(Of,"isLoopbackHost");function nC(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Of(t.hostname))throw new li(t.href);return t}n(nC,"assertSecureTokenEndpoint");function oC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||Of(r.hostname))return"native"}return"web"}n(oC,"deriveApplicationType");function sC(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??oC(t.redirect_uris)}}n(sC,"resolveClientMetadata");async function Ef(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=js.parse(JSON.parse(r));return Ut.fromResponse(o)}catch(o){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Ut(ce.ServerError,s)}}n(Ef,"parseErrorResponse");function kf(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`}n(kf,"warnCredentialInvalidation");async function dc(e,t){try{return await ic(e,t)}catch(r){if(r instanceof Ut){if(r.code===ce.InvalidClient||r.code===ce.UnauthorizedClient)return kf(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ic(e,t);if(r.code===ce.InvalidGrant||r.code===ce.InvalidDpopProof)return kf(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await ic(e,t)}throw r}}n(dc,"auth");function iC(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(iC,"determineScope");async function ic(e,{serverUrl:t,authorizationCode:r,iss:o,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=sC(e),p=await e.discoveryState?.(),h,f,y,b,_=i;if(!_&&p?.resourceMetadataUrl&&(_=new URL(p.resourceMetadataUrl)),p?.authorizationServerUrl){if(f=p.authorizationServerUrl,h=p.resourceMetadata,y=p.authorizationServerMetadata??await Nf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await qf(t,{resourceMetadataUrl:_},a)}catch(K){if(K instanceof TypeError)throw K}(y!==p.authorizationServerMetadata||h!==p.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:y})}else{let K=await mC(t,{resourceMetadataUrl:_,fetchFn:a,skipIssuerMetadataValidation:c});f=K.authorizationServerUrl,y=K.authorizationServerMetadata,h=K.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:_?.toString(),resourceMetadata:h,authorizationServerMetadata:y}}let S=y?.issuer??String(f),R={issuer:S};if(await e.saveAuthorizationServerUrl?.(S),r!==void 0){let K=p?.authorizationServerMetadata?.issuer??p?.authorizationServerUrl;if(K===void 0){if(e.saveDiscoveryState!==void 0)throw new ui("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",S);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Pf(K,S))throw new ui(K,S)}b&&await e.saveDiscoveryState?.(b);let v=await aC(t,e,h),P=v&&h&&!e.validateResourceURL?h.resource:v;P&&await e.saveResourceUrl?.(lc(P));let N=iC({requestedScope:s,resourceMetadata:h,authServerMetadata:y,clientMetadata:e.clientMetadata}),A=await Promise.resolve(e.clientInformation(R)),M=ac(A,S,{canPersistStamp:e.saveClientInformation!==void 0});if(M===void 0&&A?.issuer&&e.saveClientInformation===void 0)throw new ui(A.issuer,S);if(M&&M.issuer===void 0&&(M={...M,issuer:S},await e.saveClientInformation?.(M,R)),!M){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let K=y?.client_id_metadata_document_supported===!0,re=e.clientMetadataUrl;if(re&&!uc(re))throw new Ut(ce.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${re}`);if(K&&re)M={client_id:re,issuer:S},await e.saveClientInformation?.(M,R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");M={...await SC(f,{metadata:y,clientMetadata:u,scope:N,fetchFn:a}),issuer:S},await e.saveClientInformation(M,R)}}let B=!e.redirectUrl;if(r!==void 0||B){r!==void 0&&Mf({iss:o,expectedIssuer:y?.issuer,issParameterSupported:xf(y)});let K=await yC(e,f,{metadata:y,resource:P,authorizationCode:r,iss:o,scope:N,fetchFn:a});return await e.saveTokens({...K,issuer:S},R),"AUTHORIZED"}let W=ac(await e.tokens(R),S);if(W&&W.issuer===void 0&&(W={...W,issuer:S},await e.saveTokens(W,R)),W?.refresh_token&&!d){let K;try{K=await gC(f,{metadata:y,clientInformation:M,refreshToken:W.refresh_token,resource:P,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(re){if(re instanceof li||!(!(re instanceof Ut)||re.code===ce.ServerError))throw re}if(K)return await e.saveTokens({...K,issuer:S},R),"AUTHORIZED"}let Z=e.state?await e.state():void 0,{authorizationUrl:le,codeVerifier:Pe}=await hC(f,{metadata:y,clientInformation:M,state:Z,redirectUrl:e.redirectUrl,scope:N,resource:P});return await e.saveCodeVerifier(Pe),await e.redirectToAuthorization(le),"REDIRECT"}n(ic,"authInternal");function uc(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(uc,"isHttpsUrl");async function aC(e,t,r){let o=Gh(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!si({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(aC,"selectResourceURL");var cC=new Set(["bearer","dpop"]);function Uf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!cC.has(r.toLowerCase())||!o)return{};let s=di(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=di(e,"scope")||void 0,c=di(e,"error")||void 0,d=di(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}n(Uf,"extractWWWAuthenticateParams");function di(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(di,"extractFieldFromWwwAuth");async function qf(e,t,r=fetch){let o=await lC(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 Nr.parse(await o.json())}n(qf,"discoverOAuthProtectedResourceMetadata");async function zf(e,t,r=fetch){let o=ci(r);try{return await o(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Tf)throw s;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(zf,"fetchWithCorsRetry");function dC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(dC,"buildWellKnownPath");async function Af(e,t,r=fetch){return await zf(e,{"MCP-Protocol-Version":t},r)}n(Af,"tryMetadataDiscovery");function uC(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}n(uC,"shouldAttemptFallback");async function lC(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=dC(t,s.pathname);a=new URL(d,o?.metadataServerUrl??s),a.search=s.search}let c=await Af(a,i,r);return!o?.metadataUrl&&uC(c,s.pathname)&&(c=await Af(new URL(`/.well-known/${t}`,s),i,r)),c}n(lC,"discoverMetadataWithFallback");function pC(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(pC,"buildDiscoveryUrls");async function Nf(e,{fetchFn:t=fetch,protocolVersion:r=Os,skipIssuerValidation:o=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=pC(e);for(let{url:a,type:c}of i){let d=await zf(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"?jr.parse(await d.json()):Dr.parse(await d.json());if(!o){let p=typeof e=="string"?e:e.href;if(!(u.issuer===p||p.endsWith("/")&&u.issuer===p.slice(0,-1)))throw new No("metadata",p,u.issuer)}return u}}n(Nf,"discoverAuthorizationServerMetadata");async function mC(e,t){let r,o;try{r=await qf(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 Nf(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:s,resourceMetadata:r}}n(mC,"discoverOAuthServerInfo");function lc(e){return typeof e=="string"?e:e.href}n(lc,"resourceIndicatorToString");async function hC(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(oc))throw new Error(`Incompatible auth server: does not support response type ${oc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(sc))throw new Error(`Incompatible auth server: does not support code challenge method ${sc}`)}else c=new URL("/authorize",e);let d=await nc(),u=d.code_verifier,p=d.code_challenge;return c.searchParams.set("response_type",oc),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",sc),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",lc(a)),{authorizationUrl:c,codeVerifier:u}}n(hC,"startAuthorization");function fC(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(fC,"prepareAuthorizationCodeRequest");async function jf(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=nC(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",lc(i)),!s&&o&&Qv(Xv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=n(async()=>{let y=new Headers(u);return s&&await s(y,r,d,t),a&&y.set("DPoP",await a.buildProof({htm:"POST",htu:d})),ci(c??fetch)(d,{method:"POST",headers:y,body:r})},"requestOnce"),h=await p();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===ce.UseDpopNonce&&(a.observeNonce(h,d),h=await p()),a?.observeNonce(h,d),!h.ok)throw await Ef(h);let f=await h.json();try{return At.parse(Ja(f))}catch(y){throw typeof f=="object"&&f!==null&&"error"in f?await Ef(JSON.stringify(f)):y}}n(jf,"executeTokenRequest");async function gC(e,{metadata:t,clientInformation:r,refreshToken:o,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:o,...await jf(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}n(gC,"refreshAuthorization");async function yC(e,t,{metadata:r,resource:o,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&Mf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:xf(r)});let d=r?.issuer??String(t),u=n(async()=>{let y=await e.clientInformation({issuer:d}),b=ac(y,d,{canPersistStamp:!1});if(y&&b===void 0)throw new ui(String(y.issuer),d);return b},"readClientInformation"),p=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=fC(s,await e.codeVerifier(),e.redirectUrl)}return p??=await u(),jf(t,{metadata:r,tokenRequestParams:f,clientInformation:p,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:c})}n(yC,"fetchToken");async function SC(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 ci(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new cc({status:c.status,body:await c.text(),submittedMetadata:a});return ar.parse(Ja(await c.json()))}n(SC,"registerClient");var W0=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return je(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 je(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,lr(this,new.target)}};function ge(e){let t=ir.safeParse(e);return t.success?t.data.id:void 0}n(ge,"parseJsonRpcRequestId");function pc(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return ge(t)}catch{return}}n(pc,"readJsonRpcRequestIdFromBody");function Te(e){return _o.parse({jsonrpc:sr,...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(Te,"jsonRpcErrorResponse");function Df(e){return new ai([Ns.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Df,"urlElicitationRequiredError");var mc=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],Do=[cr,...mc],RC=0,_C="private",wC="0.0.0";function bC(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}n(bC,"buildGatewayDiscoverCapabilities");function hc(e){let{connection:t}=e,r=t.serverInfo,o=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...o===void 0?{}:{title:o},version:r?.version??wC,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}n(hc,"buildGatewayDiscoverServerInfo");function $f(e){let t=ge(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...e.supportedVersions??Do],capabilities:bC(e.capabilityFilter),_meta:{[Pt]:hc({connection:e.connection,icons:e.icons})},ttlMs:RC,cacheScope:_C}})}n($f,"gatewayDiscoverResponse");var vC=/^\d{4}-\d{2}-\d{2}$/;var mi="2026-07-28",$o;function CC(){return $o??=new Map,$o}n(CC,"store");function pi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(pi,"isRecord");function Lf(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string"&&vC.test(r)))].slice(0,32);return t.length===0?void 0:t}n(Lf,"readVersionList");function hi(e,t){if(!pi(t))return;if(e==="server/discover"&&pi(t.result))return Lf(t.result.supportedVersions);let r=t.error;if(pi(r)&&r.code===-32022&&pi(r.data))return Lf(r.data.supported)}n(hi,"readUpstreamSupportedVersions");function fi(e,t,r={}){let o=CC(),s=o.get(e),i=t.some(d=>d<mi),a=r.modernOnly===!0||s?.modernOnly===!0&&!i,c=!i&&!a&&s?.complete===!0?s.versions.filter(d=>d<mi):[];if(o.delete(e),o.set(e,{versions:[...t,...c],complete:a||i||c.length>0,modernOnly:a}),o.size>512){let d=o.keys().next().value;d!==void 0&&o.delete(d)}}n(fi,"recordUpstreamSupportedVersions");function gi(e,t){let r=e===void 0?void 0:$o?.get(e);if(r===void 0)return t;let o=t.filter(s=>r.versions.includes(s));return o.length===0?t:r.complete?o:t.filter(s=>s<mi||o.includes(s))}n(gi,"advertisedSupportedVersions");function Hf(e){let t=$o?.get(e);t?.modernOnly===!0&&$o?.set(e,{versions:t.versions,complete:t.versions.some(r=>r<mi),modernOnly:!1})}n(Hf,"recordUpstreamAcceptsInitialize");var IC=-32e3,TC="2025-11-25",EC=/^\d{4}-\d{2}-\d{2}$/,gc=I.InternalError;function fc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(fc,"isRecord");function kC(e,t){return typeof e=="string"&&EC.test(e)&&e>=t}n(kC,"isAtLeast");function AC(e){if(e.method!=="initialize")return!1;let t=fc(e.params)?e.params:void 0,o=(fc(t?.capabilities)?t.capabilities:void 0)?.elicitation,s=t?.protocolVersion;return kC(s,TC)&&!bo(s)&&fc(o)&&o.url!==void 0}n(AC,"acceptsUrlElicitation");function yc(e){let{payload:t}=e,r=t.authUrl===void 0||!e.urlElicitation?void 0:Df({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Te({...e.id===void 0?{}:{id:e.id},error:{code:r?.code??e.fallbackCode,message:t.message,data:{...r?.data??{},connectRequired:t}}})}n(yc,"legacyConnectRequiredError");function Bf(e,t){let r=Hr(e,t);if(r!==void 0)return{kind:"invalid",error:r};let o=e,s=ge(e);return s===void 0?{kind:"accepted",response:typeof o.method!="string"}:{kind:"request",id:s,message:o}}n(Bf,"classifyMessage");function en(e,t){return Response.json(Te({error:{code:e,message:t}}),{status:400})}n(en,"unidentifiedError");function Ff(){return new Response(null,{status:202})}n(Ff,"acceptedResponse");function PC(e,t){return Y()?qm(e,t):void 0}n(PC,"modernBatchVersion");function xC(e,t){let r=e.get("mcp-protocol-version"),o=PC(e,t)??(Ls(r)?r??void 0:void 0);return o===void 0?void 0:en(I.InvalidRequest,`Invalid Request: protocol version ${o} does not support JSON-RPC batches`)}n(xC,"batchRefusal");function Jf(e,t,r){let o=(Array.isArray(t)?t:[t]).filter(i=>Hr(i)===void 0);if(o.length===0)return;if(o.some(ym))return o.length>1?en(I.InvalidRequest,"Invalid Request: Only one initialization request is allowed"):void 0;let s=e.get("mcp-protocol-version");if(!(s===null||r.accepted(s)))return en(IC,`Bad Request: Unsupported protocol version: ${s} (supported versions: ${r.listed.join(", ")})`)}n(Jf,"transportVersionRefusal");function Vf(e,t){return Jf(e,t,{accepted:n(r=>Or.includes(r),"accepted"),listed:Or})}n(Vf,"handlerTransportVersionRefusal");function MC(e,t,r){let o=gi(r,Y()?Do:mc);return Jf(e,t,{accepted:n(s=>o.includes(s)||Y()&&s===cr,"accepted"),listed:o})}n(MC,"gatewayTransportVersionRefusal");function OC(e){return{jsonrpc:"2.0",id:e,result:{}}}n(OC,"pingResult");function Gf(e){if(e.parsed===void 0)return en(I.ParseError,"Parse error: Invalid JSON");let t=Array.isArray(e.parsed)?xC(e.headers,e.parsed):void 0;if(t!==void 0)return t;let r=MC(e.headers,e.parsed,e.payload.upstreamServerId);if(r!==void 0)return r;let o=n(i=>i.message.method==="ping"?OC(i.id):yc({id:i.id,payload:e.payload,urlElicitation:AC(i.message),fallbackCode:gc}),"answer");if(Array.isArray(e.parsed)){if(e.parsed.length===0)return en(I.InvalidRequest,"Invalid Request: empty batch");let i=e.parsed.map((c,d)=>Bf(c,d)),a=i.flatMap(c=>{switch(c.kind){case"request":return[o(c)];case"invalid":return[c.error];case"accepted":return[]}});return i.every(c=>c.kind==="invalid")?Response.json(a,{status:400}):a.length===0?Ff():Response.json(a)}let s=Bf(e.parsed);switch(s.kind){case"request":return Response.json(o(s));case"accepted":return s.response&&Y()&&bo(e.headers.get("mcp-protocol-version"))?en(I.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):Ff();case"invalid":return Response.json(s.error,{status:400})}}n(Gf,"legacyConnectRequiredResponse");function Ee(){return Is.instance.build.COMPATIBILITY_FLAGS.mcpGatewaySpecCompliance===!0}n(Ee,"isMcpGatewaySpecComplianceEnabled");var UC={Allow:"POST"};function yi(e,t){return Me.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},UC)}n(yi,"gatewayMethodNotAllowed");function He(e){return(e??"").split(";")[0].trim().toLowerCase()}n(He,"mediaTypeEssence");var Zf=new Set(["jsonrpc","method","id","params"]),_c=new Set(["name","uri","ref"]),Yf=new Set(["type","name","uri"]),qC="subscriptions/listen",wc="notifications",Xf="resourceSubscriptions",zC=new Set([..._c,ht(wc)]),NC=new Set([ht(Xf)]),jC=/[^\u0000-\u007f]/,DC=34,$C=92,Kf=123,LC=125,HC=91,BC=93,FC=58,Sc=44;function Lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Lo,"isRecord");function ht(e){return e.toUpperCase().toLowerCase()}n(ht,"foldCase");function Rc(e,t){return Object.keys(e).some(r=>{let o=ht(r);return o!==r&&t.has(o)})}n(Rc,"hasCaseVariant");function Wf(e,t){let r=ht(t);return Object.keys(e).some(o=>o!==t&&ht(o)===r)}n(Wf,"hasCaseVariantOf");function JC(e,t){let r=n(a=>{switch(a.role){case"member":return Zf;case"params":return t.has(a.member)?zC:_c;case"ref":return Yf;case"notifications":return NC;default:return}},"watchedFor"),o=[],s=0,i=n(a=>{let c=o.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===wc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===DC){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let p=0;for(;e.charCodeAt(d-1-p)===$C;)p++;if(p%2===0)break}let u=s>0?void 0:o.at(-1);if(u?.isObject&&u.expectKey){let p=e.slice(a,d+1),h=p.includes("\\")?JSON.parse(p):p.slice(1,-1);if(jC.test(h))return!0;u.key=h;let f=ht(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===Kf||c===HC){let d=c===Kf,u=s>0?void 0:i(d);if(u===void 0)s++;else{let p=o.at(-1)?.member??0;o.push({role:u,isObject:d,seen:new Set,member:p,expectKey:d})}}else if(c===LC||c===BC)s>0?s--:o.pop();else if(s===0&&(c===FC||c===Sc)){let d=o.at(-1);d?.isObject?d.expectKey=c===Sc:d?.role==="batch"&&c===Sc&&d.member++}}return!1}n(JC,"hasUnsafeKeyInText");function Qf(e){let t=new Set;for(let[r,o]of e.envelope.messages.entries()){let s=o.raw;if(Lo(s)){if(Rc(s,Zf)||e.checksListen===!0&&s.method===qC&&(t.add(r),Lo(s.params)&&(Wf(s.params,wc)||Lo(s.params.notifications)&&Wf(s.params.notifications,Xf))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!Lo(s.params))&&(Rc(s.params,_c)||Lo(s.params.ref)&&Rc(s.params.ref,Yf)))return!0}}return JC(e.text,t)}n(Qf,"hasAmbiguousIdentifyingKeys");var VC=n(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),GC=47,eg=44,KC=38,bc=n(e=>e!==GC&&e!==eg,"VALUE"),WC=n(e=>!VC(e),"ANY"),ZC=n(e=>e!==KC,"QUERY_VALUE"),YC=["+","#",".","/","?","&"],vc=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(bc),!t)return;let r=this.current,o=this.#e();this.edges[r].push({test:n(s=>s===eg,"test"),to:o}),this.edges[o].push({test:bc,to:r})}};function tg(e){let t=new vc,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=YC.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,p)=>{t.literal(`${p===0?a:"&"}${u}=`),t.plus(ZC)});break;case"+":case"#":t.plus(WC);break;case".":t.literal("."),t.plus(bc);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(tg,"compileUriTemplate");function rg(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 u of i)for(let p of r[u])s[p.to]!==a&&p.test(c)&&(s[p.to]=a,d.push(p.to));if(d.length===0)return!1;i=d}return i.includes(o)}n(rg,"matchesUriTemplate");var bi=m.record(m.string(),m.unknown()),XC=m.record(m.string(),m.unknown()),qt=m.array(m.string().min(1)).min(1).optional(),QC=m.object({name:m.string().min(1),description:m.string().min(1).optional(),annotations:XC.optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),eI=m.object({name:m.string().min(1),description:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),tI=m.object({uri:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),rI=m.object({uriTemplate:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:bi.optional(),roles:qt,groups:qt,public:m.boolean().optional()}).strict(),nI=m.array(m.union([m.string(),QC])),oI=m.array(m.union([m.string(),eI])),sI=m.array(m.union([m.string(),tI])),iI=m.array(m.union([m.string(),rI])),aI=m.object({module:m.unknown(),export:m.string().min(1)}).strict(),cI=m.object({mode:m.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:m.string().min(1).optional(),groupClaim:m.string().min(1).optional(),identifier:aI.optional()}).strict(),dI=m.object({tools:nI.optional(),prompts:oI.optional(),resources:sI.optional(),resourceTemplates:iI.optional(),accessControl:cI.optional()}).strict(),ft=[{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 uI(e,t){return Bm(dI,e,`MCP capability filter policy "${t}"`)}n(uI,"parseMcpCapabilityFilterOptions");function j(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(j,"isRecord");function Oe(e){return typeof e.method=="string"?e.method:void 0}n(Oe,"messageMethod");function Bo(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Bo,"correlationKey");function pg(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(pg,"createReplyIdMatcher");function ng(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(ng,"asStringArray");function og(e,t){if(!j(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,s)=>j(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(og,"readClaimValues");function xc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!j(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:ng(e.roles),groups:ng(e.groups),public:e.public===!0}}n(xc,"normalizeEntry");function lI(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(lI,"isCallerAllowed");function Si(e,t,r,o){if(e===void 0)return;let s=[];for(let i of e){let a=xc(i,t);a!==void 0&&lI(a,r,o)&&s.push(a.key)}return s}n(Si,"allowedKeys");var mg=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(og(e.user?.data,o)),a=new Set(og(e.user?.data,s));return{tools:Si(r.tools,"name",i,a),prompts:Si(r.prompts,"name",i,a),resources:Si(r.resources,"uri",i,a),resourceTemplates:Si(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function pI(e,t){let r=[];for(let o of ft){let s=e[o.option];if(s!==void 0)for(let i of s){let a=xc(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 X(`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(pI,"assertNoConflictingMarkup");function mI(e,t){let r=[];for(let o of ft){let s=e[o.option];if(s!==void 0)for(let i of s){let a=xc(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 X(`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(mI,"assertNoMarkup");function hI(e,t){let r=e.identifier;if(r===void 0)throw new X(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new X(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new X(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new X(`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 E(`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 E(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}n(hI,"buildCustomResolver");function fI(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new X(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return hI(r,t)}if(o==="rolesAndGroups")return pI(e,t),mg;mI(e,t)}n(fI,"buildCapabilityResolver");function gI(e){let t={};for(let r of ft){let o=e[r.option];if(o===void 0)continue;let s=new Map;for(let i of o){let a=DI(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}n(gI,"buildProjectionMaps");function hg(e){return e===void 0?void 0:ft.find(t=>t.listMethod===e)}n(hg,"findListRule");function Mc(e){return e===void 0?void 0:ft.find(t=>t.directMethods.includes(e))}n(Mc,"findDirectRule");var vi="completion/complete",fg=["prompts","resources","resourceTemplates"];function gg(e){return e===vi||Mc(e)!==void 0}n(gg,"isCapabilityMethod");var wi="subscriptions/listen",yI=[...ft.flatMap(e=>[e.listMethod,...e.directMethods]),vi,wi];function SI(e){let t=ht(e.trim()),r=yI.find(o=>ht(o)===t);return r!==void 0&&r!==e?r:void 0}n(SI,"methodVariantOf");function sg(e,[t,r]){return{code:I.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}n(sg,"invalidParams");function Oc(e){return t=>({code:I.InvalidParams,message:`${e} "${$s(t)}" not found`})}n(Oc,"namedNotFound");function RI(e,t){return{code:Tm(t),message:"Resource not found",data:{uri:Ds(e,Em)}}}n(RI,"resourceNotFound");var _I={legacy:Oc("Tool"),modern:vo.tool},Cc={legacy:Oc("Prompt"),modern:vo.prompt},wI={legacy:RI,modern:vo.resource},bI={legacy:Oc("Resource template"),modern:vo.resourceTemplate};function vI(e){let t=Oe(e);if(t===void 0||!gg(t))return[];let r=j(e.raw)?e.raw.params:void 0,o=n((d,u)=>j(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=n(d=>j(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==vi){let d=Mc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:o(r,"uri"),issue:s("params.uri"),notFound:wI}]:[{options:[d.option],target:o(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?_I:Cc}]}let i=j(r)?r.ref:void 0,a=j(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:o(i,"name"),issue:["params.ref.name","a string"],notFound:Cc}];if(a==="ref/resource"){let d=o(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&CI(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:bI}]}let c=j(r)?j(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:fg,target:void 0,issue:c,notFound:Cc}]}n(vI,"capabilityAccesses");function CI(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 II(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}n(CI,"hasTemplateExpression");function II(e){return e>32&&e<127?!1:TI.test(String.fromCharCode(e))}n(II,"isWhitespaceCode");var TI=/\s/;function EI(e){return e.type==="invalid"&&(!j(e.raw)||e.raw.jsonrpc!=="2.0")}n(EI,"isNonJsonRpcMember");function kI(e){return j(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}n(kI,"hasNonStringMethod");function yg(e){return e.type==="request"||e.type==="invalid"&&Oe(e)!==void 0}n(yg,"awaitsReply");function AI(e){return j(e.raw)&&j(e.raw.params)?e.raw.params:void 0}n(AI,"rawParams");function PI(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:Y()&&$r(e.headers,r.raw)}n(PI,"isModernRequest");var ig={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Ic="=?base64?",Tc="?=",xI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function MI(e){if(!e.startsWith(Ic)||!e.endsWith(Tc)||e.length<Ic.length+Tc.length)return e;let t=e.slice(Ic.length,e.length-Tc.length);if(xI.test(t))try{let r=atob(t),o=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{return}}n(MI,"decodeMcpHeaderValue");var OI=-32020;function UI(e,t){let r=Oe(t);if(r===void 0)return;let o=j(t.raw)?t.raw.id:void 0,s=Fo(o)?o:void 0,i=e.headers.get("mcp-protocol-version"),a=Cm(t.raw);if(i!==null&&a!==void 0&&i!==a)return Ri(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 Ri(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(ig,r)?ig[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let p=MI(d);if(p===void 0)return Ri(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=AI(t)?.[u];if(typeof h=="string"&&p!==h)return Ri(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${p}"`)}n(UI,"headerMismatchResponse");function Ri(e,t,r){return Ye(400,{code:OI,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}n(Ri,"mismatchResponse");var qI={code:I.MethodNotFound,message:"Method not found"},ag={code:I.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},zI={code:I.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},NI="2025-06-18";function Fo(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}n(Fo,"isValidRequestId");function Sg(e){return j(e.raw)&&!Object.hasOwn(e.raw,"id")}n(Sg,"isSentAsNotification");function Ho(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}n(Ho,"jsonRpcError");function Ye(e,t,r){return Response.json(Ho(t,r),{status:e})}n(Ye,"jsonRpcErrorResponse");function _i(e){return Ye(400,{code:I.InvalidRequest,message:`Invalid Request: ${e}`})}n(_i,"invalidRequestResponse");function Ec(e,t,r=!1){if(Sg(e))return{status:400,body:Ho({code:I.InvalidRequest,message:`Invalid Request: a notification cannot use ${$s(Oe(e)??"this method")}; send it as a request with an id`})};let o=j(e.raw)?e.raw.id:void 0;return Fo(o)?{status:r&&t.code===I.MethodNotFound?404:200,body:Ho(t,o)}:{status:400,body:Ho({code:I.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}n(Ec,"refusalOf");var cg=-32e3;function jI(e,t){let r=e.headers.get("accept");if(r===null||!/application\/json/i.test(r))return Ye(406,{code:cg,message:"Not Acceptable: Client must accept both application/json and text/event-stream"});if(!Rm(e.headers.get("content-type")??void 0))return Ye(415,{code:cg,message:"Unsupported Media Type: Content-Type must be application/json"});if(!(t.shape==="batch"&&Ls(e.headers.get("mcp-protocol-version")))){if(t.shape==="single"){let o=Hr(t.messages[0]?.raw);if(o!==void 0)return Response.json(o,{status:400})}return Vf(e.headers,t.shape==="batch"?t.messages.map(o=>o.raw):t.messages[0]?.raw)}}n(jI,"legacyTransportRefusal");function dg(e,t,r=!1,o=!1){let[s]=[...t];if(e.shape!=="batch"){let{status:d,body:u}=Ec(s[0],s[1],r);return Response.json(u,{status:d})}let i=e.protocolVersion;if(i!==void 0&&i>=NI)return _i(`protocol version ${$s(i)} does not support JSON-RPC batches`);let a=0,c=e.messages.flatMap((d,u)=>{let p=o?Hr(d.raw,u):void 0;if(p!==void 0)return a+=1,[p];if(d.type==="result"||d.type==="error"||Sg(d))return[];let h=j(d.raw)?d.raw.id:void 0;return o&&!t.has(d)&&Oe(d)==="ping"&&Fo(h)?[{jsonrpc:"2.0",id:h,result:{}}]:[Ec(d,t.get(d)??zI).body]});if(c.length===0){let{status:d,body:u}=Ec(s[0],s[1]);return Response.json(u,{status:d})}return Response.json(c,{status:a===e.messages.length?400:200})}n(dg,"refusalResponse");function DI(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!j(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(DI,"buildProjection");function ug(e){let t=e.base[e.property],r=e.overlay[e.property];return j(r)?j(t)?{...t,...r}:r:t}n(ug,"mergeRecordProperty");function $I(e,t){let r={...e,...t.overlay},o=ug({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let s=ug({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}n($I,"applyProjection");var ke=Symbol("unreadable"),tn=Symbol("dropped");function LI(e,t,r,o,s){let i=e.result;if(!j(i))return ke;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?ke:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!j(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(o!==void 0&&!o.has(u))return[];let p=r.get(u);return p===void 0?[]:[$I(d,p)]})}}}n(LI,"filterAndProjectItems");var Rg="resources/read";function HI(e){let t=e.result;return!j(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}n(HI,"withPrivateReadScope");function _g(e,t){let r=hg(Oe(e)),o=r===void 0?void 0:t[r.option];return r===void 0||o===void 0?null:{rule:r,projections:o}}n(_g,"listTargetOf");function BI(e,t,r){return j(e)&&ft.some(o=>o!==t?.rule&&r[o.option]!==void 0&&Object.hasOwn(e,o.resultProperty))}n(BI,"carriesUnfilteredList");function FI(e){let{envelope:t,projectionMaps:r,allowedSets:o,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=n(S=>_g(S,r),"listTarget"),d=t.messages.filter(yg),u=new Map;for(let S of d){let R=Bo(S.id);R!==void 0&&!u.get(R)&&u.set(R,c(S))}let p=pg(d.map(S=>S.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&Oe(h)===Rg,y=n(S=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let R=p(S);return R===void 0?void 0:u.get(R)},"targetForReply"),b=n(S=>{if(!j(S))return ke;if(!("result"in S))return"method"in S&&!("error"in S)?_(S):"error"in S||"method"in S?S:ke;let R=y(S.id);return R===void 0||BI(S.result,R,r)?ke:R===null?f?HI(S):S:LI(S,R.rule,R.projections,o?.[R.rule.option],s)},"filterMessage"),_=n(S=>{if(a===void 0)return S;if(S.method==="notifications/resources/updated"){let R=j(S.params)?S.params.uri:void 0;return typeof R=="string"&&!a(R)?tn:S}if(S.method==="notifications/subscriptions/acknowledged"){let R=vg(S.params,a);return R===void 0?S:{...S,params:R}}return S},"filterServerMessage");return S=>{if(!Array.isArray(S))return b(S);if(t.shape!=="batch")return ke;let R=S.map(b);if(R.includes(ke))return ke;let v=R.filter(P=>P!==tn);return v.length===R.length?R:v.length===0?tn:v}}n(FI,"createReplyFilter");function JI(e){return He(e.headers.get("content-type")).includes("json")}n(JI,"isJsonResponse");function VI(e){return He(e.headers.get("content-type"))==="text/event-stream"}n(VI,"isEventStreamResponse");var GI=10*1024*1024,KI=/^[\w.~:/+=-]{0,256}$/;function WI(e){if(Ru(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"&&KI.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(WI,"inspectSseLines");var wg="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",ZI="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function Ac(e,t){let r=e.messages.filter(yg),o=new Map,s=new Set;for(let u of r){let p=u.id,h=Bo(p);p==null||h===void 0||(o.set(h,p),_g(u,t)!==null&&s.add(h))}let i=pg(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:Bo(a.id),d=new Set;return{keyOf(u){if(!(!j(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:n(u=>u!==void 0&&o.has(u),"isPending"),hasFailed:n(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&o.delete(u)},fail(u){return[...u].flatMap(p=>{let h=o.get(p);return h===void 0?[]:(o.delete(p),d.add(p),[{jsonrpc:"2.0",id:h,error:{code:I.InternalError,message:s.has(p)?wg:ZI}}])})},pendingKeys:n(()=>[...o.keys()],"pendingKeys")}}n(Ac,"createReplyTracker");function bg(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)?ke:t(i);c!==tn&&(c!==ke?(o.push(c),r.answer(a)):r.isPending(a)?o.push(...r.fail([a])):s++)}return{replies:o,dropped:s}}n(bg,"filterBatchMembers");function YI(e){let{response:t,envelope:r,projectionMaps:o,filterReply:s,warn:i}=e,a=Ac(r,o),c=!1,d=n(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=n(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),p=n(()=>a.pendingKeys().length===0,"isDone");return Ps(t,h=>{let f=WI(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let y;try{y=JSON.parse(f.data)}catch{return d("its data is not JSON")}let b=a.keyOf(y);if(b!==void 0&&a.hasFailed(b))return null;let _=s(y);if(_===tn)return null;if(_===ke&&r.shape==="batch"&&Array.isArray(y)){let{replies:S,dropped:R}=bg(y,s,a);if(R>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),S.length===0)return null;let v=yo(f,JSON.stringify(S));return p()?ca(v):v}if(_===ke){if(!a.isPending(b))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let S=u(a.fail([b]));return p()?ca(...S):S}for(let S of Array.isArray(_)?_:[_])a.answer(a.keyOf(S));return _===y?f:yo(f,JSON.stringify(_))},{maxEventChars:GI,onOversize:"discard",end:n(({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:n((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}n(YI,"filterEventStream");function Uc(e){return Oe(e)===wi}n(Uc,"isListenRequest");function XI(e){return Y()&&e.messages.some(Uc)}n(XI,"filtersListen");function vg(e,t){if(!j(e)||!j(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let o=r.filter(s=>typeof s=="string"&&t(s));if(o.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:o}}}n(vg,"narrowSubscriptionParams");function QI(e,t,r){let o=!1,s=t.messages.map(a=>{if(!Uc(a)||!j(a.raw))return a.raw;let c=vg(a.raw.params,r);return c===void 0?a.raw:(o=!0,{...a.raw,params:c})});if(!o)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])})}n(QI,"narrowListenSubscriptions");var kc=Symbol("access unresolved"),lg=10*1024*1024,Cg="the request body could not be read";async function eT(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:u}=await s.read(),p=d?i.decode():i.decode(u,{stream:!0});if(a+=p.length,c&&=!/\S/.test(p),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}n(eT,"scanBody");function qc(e){return Array.isArray(e)?`batch member 0: ${qc(e[0])}`:j(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}n(qc,"invalidMessageReason");async function tT(e,t){if(e.body===null)return;let r=n(()=>Me.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)>lg)return r();let s=He(e.headers.get("content-type")).includes("json"),i=n(()=>Me.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=n(()=>Ye(400,{code:I.ParseError,message:`Parse error: ${Cg}`}),"unreadable"),c;try{c=await eT(e,lg,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(p){return p instanceof SyntaxError?Ye(400,{code:I.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=j(d)?d.id:void 0;return Ye(400,{code:I.InvalidRequest,message:`Invalid Request: ${qc(d)}`},Fo(u)?u:void 0)}n(tT,"refuseUninspectable");var Pc=class extends xs{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let o=uI(t,r);super(o,r),this.#r=r,this.#e=gI(o),this.#t=fI(o,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,tg(i)]))}async handler(t,r){let o=await Om(t);if(o===null)return await tT(t,r)??t;let s=PI(t,o);if(s){let A=o.messages[0],M=A===void 0?void 0:UI(t,A);if(M!==void 0)return M}let i=o.messages.findIndex(EI);if(i!==-1)return _i(`batch member ${i}: ${qc(o.messages[i].raw)}`);let a=o.messages.findIndex(kI);if(a!==-1)return _i(o.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=Mm(o);if(c===void 0)try{c=await t.clone().text()}catch{return Ye(400,{code:I.ParseError,message:`Parse error: ${Cg}`})}if(Qf({envelope:o,text:c,isCapabilityMethod:gg,checksListen:this.#c()}))return _i("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 A of o.messages){let M=Oe(A),B=M===void 0?void 0:SI(M);B!==void 0&&this.#l(B)&&d.set(A,qI)}let u=XI(o),p=d.size===0&&this.#t!==void 0&&o.messages.some(A=>this.#a(A,u))?await this.#m(t,r):void 0,h=s&&bo(t.headers.get("mcp-protocol-version")),f=!s&&Ee();if(d.size===0)for(let A of o.messages){let M=p===kc?this.#a(A,u)?ag:void 0:this.#u(A,p,h,o.protocolVersion,f);M!==void 0&&d.set(A,M)}if(d.size>0){let A=o.messages[0],M=Y()&&(o.shape==="batch"?va(t.headers,o.messages.map(K=>K.raw))!==void 0:A!==void 0&&Hs(t.headers,A.raw));if(M){let K=Am(t);if(K!==void 0)return K;if(o.shape==="batch"){let re=va(t.headers,o.messages.map(_t=>_t.raw));if(re!==void 0)return Ye(re.status,re.error)}}let B=j(A?.raw)?A.raw.id:void 0,W=Fo(B)?B:void 0,Z=M&&o.shape==="single"&&A!==void 0?Um(t.headers,A.raw):void 0;if(Z!==void 0)return Ye(Z.status,Z.error,W);let le=M&&o.shape==="single"&&j(A?.raw)&&typeof A.raw.method=="string"?xm(A.raw,{modern:!0,protocolVersion:t.headers.get("mcp-protocol-version"),hasResource:n(()=>!0,"hasResource")}):void 0;return le!==void 0?Ye(200,le.error,W):(!s&&!M&&Ee()?jI(t,o):void 0)??dg(o,d,s,!s&&f)}if(p===kc)return dg(o,new Map(o.messages.map(A=>[A,ag])),s);let y=u||s?this.#d(p):void 0,b=y===void 0?t:QI(t,o,y),_=s&&this.#t!==void 0,S=_&&this.#o();if(!this.#p(o,u,S))return b;let R=FI({envelope:o,projectionMaps:this.#e,allowedSets:p,privateScope:_,privateReadScope:S,isResourceVisible:y}),v=n(A=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${A}`),"warn"),P=n((A,M)=>{v(`did not forward an upstream reply (${A}); answered -32603`);let B=Ac(o,this.#e),W=B.fail(B.pendingKeys()),Z=go(new Headers(M.headers));return Z.set("content-type","application/json"),W.length===0?new Response(JSON.stringify(Ho({code:I.InternalError,message:wg})),{status:502,headers:Z}):new Response(JSON.stringify(o.shape==="batch"?W:W[0]),{status:200,headers:Z})},"unreadable");r.addResponseSendingHook(async A=>{let M=!A.ok;if(A.body!==null&&Et(A.headers))return M?A:P("its body is still content-encoded",A);if(VI(A))return YI({response:A,envelope:o,projectionMaps:this.#e,filterReply:R,warn:v});if(!JI(A))return A.ok&&A.status!==202&&A.status!==204&&A.body!==null?P("no or an unknown media type",A):A;let B;try{B=await A.clone().json()}catch{return M?A:P("its body is not JSON",A)}if(M&&!Array.isArray(B)&&!(j(B)&&"result"in B))return A;let W=R(B);if(W===ke&&o.shape==="batch"&&Array.isArray(B)){let le=Ac(o,this.#e),{replies:Pe,dropped:K}=bg(B,R,le);K>0&&Pe.push(...le.fail(le.pendingKeys())),Pe.length>0&&(v("did not forward a batch reply member it could not read; sent the rest"),W=Pe)}if(W===ke||W===tn)return P("the filter could not read the reply",A);if(W===B)return A;let Z=go(new Headers(A.headers));return new Response(JSON.stringify(W),{status:A.status,statusText:A.statusText,headers:Z})});let N=new kt(b);return N.headers.set("accept-encoding","gzip, br"),N}#d(t){if(!this.#o())return;let r=n((o,s)=>{let i=t?.[o];return this.#e[o]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return o=>this.#s(o,r)}#o(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#u(t,r,o,s,i=!1){let a=n(d=>this.#e[d]!==void 0,"isConfigured"),c=n((d,u)=>{let p=r?.[d];return this.#e[d]?.has(u)===!0&&(p===void 0||p.has(u))},"isAllowed");for(let d of vI(t)){if(!(d.refusedBy??d.options).some(a))continue;let{target:u}=d;if(u===void 0)return sg(Oe(t)??"",d.issue);if(!(d.resource?this.#s(u,c):d.options.filter(a).some(h=>c(h,u)))){let h=Oe(t),f=j(t.raw)?t.raw.params:void 0,y=i&&h!==void 0?Pm(h,j(f)?f:void 0):void 0;return y!==void 0&&h!==void 0?sg(h,y):o?d.notFound.modern(u):d.notFound.legacy(u,s??null)}}}#s(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||!rg(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!o&&!s}#i(t){let r=n(o=>this.#e[o]!==void 0,"isConfigured");return t===vi?fg.some(r):Mc(t)?.option==="resources"&&r("resourceTemplates")?!0:ft.some(o=>r(o.option)&&(o.listMethod===t||o.directMethods.includes(t)))}#a(t,r){let o=Oe(t);return r&&o===wi&&this.#o()?!0:o!==void 0&&this.#i(o)}#c(){return Y()&&this.#o()}#l(t){return t===wi?this.#c():this.#i(t)}#p(t,r,o){return t.messages.some(s=>{if(r&&Uc(s))return this.#o();if(o&&t.shape==="single"&&Oe(s)===Rg)return!0;let i=hg(Oe(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#m(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),kc}let i={};for(let a of ft){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let p of d)typeof p=="string"&&c.has(p)&&u.add(p);i[a.option]=u}return i}};var zc="zuplo.com",rT=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),nT=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Ig(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Ig,"s2FaviconHref");function oT(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(oT,"strictFaviconHref");var Tg=Ig(zc);function Nc(e){let t=e.toLowerCase();return t===zc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Ig(zc):oT(e)}n(Nc,"resolveIconHref");function sT(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(sT,"hostnameFromHost");function iT(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(iT,"isLocalOrAddressHost");function aT(e){let t=sT(e).toLowerCase().replace(/\.$/,"");if(iT(t)||nT.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=rT.has(o)?3:2;return r.slice(-s).join(".")}n(aT,"inferFaviconDomain");function jc(e){return{src:Nc(aT(e)),mimeType:"image/png",sizes:["128x128"]}}n(jc,"resolveMcpFaviconIcon");function Ci(e){try{return jc(new URL(e).host)}catch{return}}n(Ci,"resolveMcpFaviconIconFromUrl");var cT=-32020,Dc="(missing)",dT=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"]),Eg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},kg="=?base64?",Ag="?=",uT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function lT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(lT,"isRecord");function Pg(e){return e===" "||e===" "}n(Pg,"isHttpOws");function pT(e){let t=0,r=e.length;for(;t<r&&Pg(e[t]);)t++;for(;r>t&&Pg(e[r-1]);)r--;return e.slice(t,r)}n(pT,"stripHttpOws");function rn(e,t){return e.get(t)??void 0}n(rn,"readHeader");function mT(e){if(!e.startsWith(kg)||!e.endsWith(Ag))return e;let t=e.slice(kg.length,e.length-Ag.length);if(uT.test(t))try{let r=Uint8Array.from(atob(t),o=>o.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}n(mT,"decodeMcpHeaderValue");function Lc(e,t,r){let o=ge(e);return Response.json(Te({...o===void 0?{}:{id:o},error:r}),{status:t})}n(Lc,"errorResponse");function Jo(e,t,r){return Lc(e,400,{code:cT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}n(Jo,"headerMismatchResponse");function hT(e,t,r){let o=t.method;if(rn(e,"mcp-protocol-version")===void 0)return Jo(t,Dc,`the body envelope names protocol version ${r} but the required MCP-Protocol-Version header is absent`);if(rn(e,"mcp-method")===void 0)return Jo(t,Dc,`the body names method ${String(o)} but the required Mcp-Method header is absent`);if(typeof o!="string"||!Object.hasOwn(Eg,o))return;let s=Eg[o],i=lT(t.params)?t.params[s]:void 0,a=typeof i=="string"?i:void 0,c=rn(e,"mcp-name");if(c===void 0)return a===void 0?void 0:Jo(t,Dc,`the body carries params.${s}="${a}" but the required Mcp-Name header is absent`);let d=pT(c),u=mT(d);if(u===void 0)return Jo(t,d,"the Mcp-Name header carries an invalid Base64 sentinel value");if(a!==void 0&&u!==a)return Jo(t,d,`the body carries params.${s}="${a}" but the Mcp-Name header names "${u}"`)}n(hT,"standardHeadersResponse");function xg(e){let{headers:t,message:r}=e,o=Sm({httpMethod:"POST",...$c("protocolVersionHeader",rn(t,"mcp-protocol-version")),...$c("mcpMethodHeader",rn(t,"mcp-method")),...$c("mcpNameHeader",rn(t,"mcp-name")),body:r});if(o.kind==="reject")return dT.has(o.cell)||o.cell==="initialize-with-modern-header"&&Ee()?Lc(r,o.httpStatus,{code:o.code,message:o.message,...o.data===void 0?{}:{data:o.data}}):void 0;if(o.kind!=="modern")return;let s=o.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new gm({supported:[...e.supportedVersions],requested:s??"unknown"});return Lc(r,400,{code:i.code,message:i.message,data:i.data})}return o.messageKind==="request"?hT(t,r,s):void 0}n(xg,"validateModernGatewayRequest");function $c(e,t){return t===void 0?{}:{[e]:t}}n($c,"optionalHeader");import{context as fT,TraceFlags as gT,trace as yT}from"@opentelemetry/api";var Mg="mcp-session-id",ST=256*1024;function Xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Xe,"isPlainObject");function Og(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Og,"isJsonContentType");function Bc(e,t,r){if(t===void 0||r===void 0||r.byteLength>kh||!Og(e))return;let o=t.value;if(!Xe(o)||typeof o.method!="string"||o.params!==void 0&&!Xe(o.params))return;let s=o.id;return{message:o,method:o.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...o.params===void 0?{}:{params:o.params},...typeof o.jsonrpc=="string"?{jsonrpc:o.jsonrpc}:{}}}n(Bc,"parseMcpRequestMessage");function Hc(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}n(Hc,"readStringParam");function RT(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Hc(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Hc(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Hc(e.params,"uri")};default:return{}}}n(RT,"readCapability");function Ug(e,t){let r=e.get(t);return r===null||r===""?void 0:r}n(Ug,"readHeader");function _T(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let o=new URL(r.__rewriteFunction(e,vu(t))),s=o.port!==""?Number(o.port):o.protocol==="https:"?443:o.protocol==="http:"?80:void 0;return{serverAddress:o.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}n(_T,"readUpstreamServer");function qg(e,t,r){let o=dr(e.headers,r.message),s=Ug(e.headers,Mg),i={methodName:r.method,...RT(r),...r.id===void 0?{}:{jsonRpcRequestId:r.id},...r.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:r.jsonrpc},...s===void 0?{}:{mcpSessionId:s}};return{common:i,server:{...i,mcpProtocolVersion:o??zm,clientAddress:t.incomingRequestProperties?.ip,params:r.params},requestedProtocolVersion:o}}n(qg,"readServerSpanInput");function zg(e){let{request:t,context:r,parsed:o}=e,{common:s,server:i,requestedProtocolVersion:a}=qg(t,r,o),c=Ca(i),d;try{Ms(c.span);let u=c.span.isRecording()||jm()?_T(t,r):{};d=fT.with(c.ctx,()=>Dm({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Ms(d.span);let p={server:c,client:d,captureToolCallContent:e.captureToolCallContent===!0};return wT(p,o),ba(r,c.span.spanContext()),p}catch(u){throw Ii(d===void 0?[c]:[d,c]),u}}n(zg,"startMcpProxySpans");function Ng(e,t,r){try{let o=e.filter(i=>i.span.isRecording());if(o.length===0)return;let s=$m(r);if(s===void 0)return;zt(o,i=>i.span.setAttribute(t,s))}catch{}}n(Ng,"setContentAttribute");function wT(e,t){e.captureToolCallContent!==!0||t.method!=="tools/call"||Ng([e.client,e.server],"gen_ai.tool.call.arguments",t.params?.arguments??{})}n(wT,"recordToolCallArguments");function bT(e,t){if(t.spans.captureToolCallContent!==!0||t.method!=="tools/call"||t.gatewayAnswered===!0)return;let r=t.tapResult.message?.result;!Xe(r)||r.isError===!0||Ng(e,"gen_ai.tool.call.result",r)}n(bT,"recordToolCallResult");var vT=["content-digest","repr-digest","digest","content-md5"];function CT(e){return vT.some(t=>e.has(t))}n(CT,"hasBodyIntegrityHeader");function jg(e,t,r,o){let s=yT.getSpanContext(t.client.ctx);if(r.byteLength>ST||o!==void 0&&CT(o)||s===void 0||(s.traceFlags&gT.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!Xe(i))return r;try{let a=Ia(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!Ah(r))return r;let c=Ia(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}n(jg,"injectTraceContextIntoBody");function Dg(e,t){if(e){if(Xe(e.error)){let r=e.error.code,o=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof o=="string"?{message:Ds(o,Nm)}:{},httpStatusCode:t}}if(Xe(e.result)&&e.result.isError===!0)return{isError:!0}}}n(Dg,"readSpanResponse");function IT(e,t,r){let o=Ug(t.headers,Mg),s=r?.result,i=km(Xe(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);zt(e,a=>{o!==void 0&&a.span.setAttribute("mcp.session.id",o),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}n(IT,"recordInitializeResult");function $g(e){let{spans:t}=e,r=[t.client,t.server];try{TT(r,e)}catch{}finally{Ii(r)}}n($g,"finishMcpProxySpans");function TT(e,t){let{spans:r,response:o,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&IT(e,o,s.message),bT(e,t);let i=Dg(s.message,o.status);i?zt(e,a=>a.setResponse(i)):s.ended==="errored"?zt(e,a=>a.fail(s.error)):o.status>=400&&s.message===void 0?zt(e,a=>a.setErrorType(String(o.status))):s.ended==="cancelled"&&!s.message?zt(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?zt(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&&zt(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}n(TT,"recordOutcome");function zt(e,t){for(let r of e)try{t(r)}catch{}}n(zt,"forEachHandle");function Ii(e){for(let t of e)try{t.end()}catch{}}n(Ii,"endEach");function Fc(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}n(Fc,"failMcpProxySpans");function Jc(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{Ii([t])}}n(Jc,"cancelMcpProxySpans");function ET(e){switch(e){case"connect_required":return"The gateway asked the client to connect the upstream server; the request was not forwarded.";case"no_upstream_tokens":return"The upstream connection returned no OAuth tokens; the request was not forwarded.";case"upstream_token_refresh_unavailable":return"The upstream token endpoint could not refresh the connection; the request was not forwarded."}}n(ET,"gatewayAnswerMessage");var kT=64*1024;async function AT(e){if(e.body===null||!Og(e))return;let t=await e.clone().text();if(t.length>kT)return;let r=JSON.parse(t);return Xe(r)?r:void 0}n(AT,"readGatewayAnswer");function PT(e){return Xe(e.error)?Xe(e.error.data)&&e.error.data.connectRequired!==void 0:Xe(e.result)&&e.result.resultType==="input_required"}n(PT,"isConnectRequiredAnswer");async function Lg(e){let t;try{let r=Bc(e.request,e.requestJson===void 0?void 0:{value:e.requestJson},e.requestBody);if(r===void 0)return;let{server:o}=qg(e.request,e.context,r);t=Ca({...o,startTime:e.startTime}),Ms(t.span),ba(e.context,t.span.spanContext());let s;try{s=await AT(e.response)}catch{}let i=Dg(s,e.response.status);i?t.setResponse(i):e.response.status>=400&&s===void 0&&t.setErrorType(String(e.response.status));let a=e.outcome??(s!==void 0&&PT(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,ET(a))}catch{}finally{t&&Ii([t])}}n(Lg,"recordGatewayAnsweredMcpSpan");function Nt(e){let t=we().connectionsById.get(e);if(!t)throw new X(`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(Nt,"getUpstreamServerConfig");function Ti(e){let t=we().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new X(`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(Ti,"getUpstreamAuthConfig");function nn(e,t){let r=Ti({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new X(`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(nn,"requireUpstreamOAuthConfig");function Hg(e,t){let r=Ti({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new X(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(Hg,"requireUpstreamIdJagConfig");import{base64url as Ei}from"jose";var xT="__Host-",MT=16,OT=32,Fg=".",UT=!1;function jt(){return UT}n(jt,"isBrowserBindingEnforced");var Vo=m.object({id:m.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:m.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function ki(e,t){return new URL(oe(e,t)).protocol==="https:"}n(ki,"isSecureGatewayOrigin");function Vc(e,t){return t?`${xT}${e}`:e}n(Vc,"gatewayCookieName");function Go(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}n(Go,"serializeGatewayCookie");function Gc(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(Gc,"parseCookieHeader");function Bg(e){return Ei.encode(crypto.getRandomValues(new Uint8Array(e)))}n(Bg,"randomBase64url");async function Jg(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Ei.encode(new Uint8Array(t))}n(Jg,"hashNonce");function qT(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(qT,"constantTimeEqual");function Vg(e,t,r){return Vc(`zuplo_mcp_${e}_${t}`,r)}n(Vg,"bindingCookieName");async function Ko(e){let t=Bg(MT),r=Bg(OT),o=ki(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${Fg}${Ei.encode(e.payload)}`;return{claim:{id:t,hash:await Jg(r)},setCookie:Go({name:Vg(e.purpose,t,o),value:s,maxAgeSeconds:e.ttlSeconds,secure:o})}}n(Ko,"startBrowserBinding");async function Ai(e){let t=ki(e.request.url,e.request.headers),r=Vg(e.purpose,e.claim.id,t),o=Go({name:r,value:"",maxAgeSeconds:0,secure:t}),s=Gc(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:o};let i=s.indexOf(Fg),a=i<0?s:s.slice(0,i);if(!qT(await Jg(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(Ei.decode(s.slice(i+1))),clearCookie:o}}catch{return{matched:!1,clearCookie:o}}}n(Ai,"verifyBrowserBinding");function Gg(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(Gg,"mergeAbortSignals");async function zT(e){try{await e.cancel()}catch{}}n(zT,"cancelReader");async function Pi(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 zT(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(Pi,"readBoundedByteStream");var NT=2,jT=1024*1024,DT=1e4,$T=new Set([301,302,303,307,308]),LT=["authorization","proxy-authorization","cookie","cookie2"];function Kc(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Kc,"readRequestUrl");function on(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(on,"readRequestMethod");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 new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[x]:r}})}n(HT,"assertContentLengthWithinLimit");async function BT(e,t,r){return HT(e,t,r),Pi(e.body,{maxBytes:t,createLimitError:n(()=>new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[x]:r}}),"createLimitError")})}n(BT,"readBoundedResponseBody");function FT(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(FT,"responseFromBufferedBody");function JT(e,t){if(!$T.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(JT,"resolveRedirectUrl");function Kg(e,t){try{return t.validateUrl(e)}catch(r){throw new E({message:"Outbound URL was not allowed.",extensionMembers:{[x]:t.problemCode}},{cause:r})}}n(Kg,"validateOutboundUrl");var Wg=new WeakSet;function Zg(e){return e instanceof E&&Wg.has(e)}n(Zg,"isOutboundTransportFailure");function Yg(e,t){if(e instanceof E&&Bs(e.extensionMembers?.[x]))throw e;let r=new E({message:"Outbound fetch failed.",extensionMembers:{[x]:t}},{cause:e});throw Wg.add(r),r}n(Yg,"normalizeFetchError");function Wo(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&&Ie(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Wo,"logOutboundFailure");async function VT(e,t,r,o,s,i,a){let c=on(r,o);try{return await t(r,o)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Wo(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:te(i),error:d,extra:{abortReason:a()}}),Yg(d,s)}}n(VT,"fetchWithNormalizedError");function GT(e){if(e.redirects>=e.maxRedirects)throw new E({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[x]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new E({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[x]:e.problemCode}})}n(GT,"assertRedirectAllowed");function KT(e,t){let r=new Headers(e);for(let o of LT)r.delete(o);for(let o of t)r.delete(o);return r}n(KT,"stripCrossOriginHeaders");function WT(e,t,r,o,s){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=KT(e.headers,s)),i}n(WT,"buildRedirectInit");function ZT(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ZT,"buildInitialRequestInit");function YT(e){let t=on(e.currentInput,e.currentInit);GT({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Kg(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:WT(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(YT,"followRedirect");async function Wc(e,t,r){let o=r.problemCode??"invalid_request",s=r.maxRedirects??NT,i=r.maxResponseBytes??jT,a=r.timeoutMs??DT,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,p=new AbortController,h=Gg(p,t.signal),f=!1,y=setTimeout(()=>{f=!0,p.abort()},a),b=e,_=ZT(e,t,p.signal),S;try{S=Kg(Kc(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(v){throw Wo(u,{event:"outbound_url_blocked",problemCode:o,method:on(e,t),host:te(Kc(e)),error:v}),clearTimeout(y),h?.(),v}let R=0;try{for(;;){let v=await VT(u,c,b,_,o,S,()=>f?`timeout_after_${a}ms`:void 0),P=JT(v,S);if(P!==void 0)try{let N=YT({currentInput:b,currentInit:_,currentUrl:S,redirectUrl:P,redirects:R,maxRedirects:s,problemCode:o,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});b=N.currentInput,_=N.currentInit,S=N.currentUrl,R=N.redirects;continue}catch(N){throw Wo(u,{event:"outbound_redirect_blocked",problemCode:o,method:on(b,_),host:te(S),error:N,extra:{redirects:R,maxRedirects:s,redirectTargetHost:te(P)}}),N}try{return FT(v,await BT(v,i,o))}catch(N){let A=N instanceof E;Wo(u,{event:A?"outbound_response_size_exceeded":"outbound_response_body_failed",problemCode:o,method:on(b,_),host:te(S),error:N,extra:{maxResponseBytes:i,status:v.status}}),Yg(N,o)}}}finally{clearTimeout(y),h?.()}}n(Wc,"runSafeOutboundExchange");async function Zo(e,t,r){let o=await Wc(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(s){throw Wo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:on(e,t),host:te(Kc(e)),error:s,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new E({message:"Outbound JSON response could not be parsed.",extensionMembers:{[x]:r.problemCode??"invalid_request"}},{cause:s})}}n(Zo,"runSafeOutboundJsonExchange");function Xg(e,t={},r={}){return Wc(e,t,{...r,validateUrl:Ao})}n(Xg,"fetchConfiguredOutbound");function Qg(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Ao})}n(Qg,"fetchConfiguredOutboundJson");function xi(e,t={},r={}){return Zo(e,t,{...r,validateUrl:gh})}n(xi,"fetchIdentityProviderJson");function ey(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Ys})}n(ey,"fetchCimdClientMetadataJson");function ty(e,t={},r={}){return Zo(e,t,{...r,validateUrl:Po})}n(ty,"fetchCimdClientJwksJson");import{errors as ay,jwtVerify as cy,SignJWT as dy}from"jose";var ue="zuplo-mcp-gateway",ye=ue,Se="HS256";import{base64url as XT}from"jose";var QT=new TextEncoder,eE="MCP gateway could not initialize secure key material.",tE=32,ry=new Map,ny=new Map,rE;function nE(){return rE??Is.instance.authPrivateKey}n(nE,"readAuthPrivateKey");function oy(e){return new ve(eE,e===void 0?void 0:{cause:e})}n(oy,"createGeneratedKeyMaterialError");function sy(e,t){let r=XT.decode(t);if(r.byteLength!==tE)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(sy,"decodeJwkKeyField");function oE(e){let t=nE();if(!t)throw oy();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=sy("d",r.d);sy("x",r.x);let s=QT.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 oy(r)}}n(oE,"decodeGeneratedKeyMaterial");function sE(e){let t=ry.get(e);return t||(t=oE(e),ry.set(e,t)),t}n(sE,"getMasterKeyMaterial");async function Be(e){let t=ny.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(sE(e.keyMaterialPurpose));return ny.set(e.purpose,r),r}n(Be,"readCachedDerivedKey");var iE="SHA-256",aE=32,cE="zuplo-mcp-gateway:",dE=new TextEncoder,iy=new WeakMap;async function at(e,t){let r=iy.get(e);r||(r=new Map,iy.set(e,r));let o=r.get(t);if(o)return o;let s=await uE(e,t);return r.set(t,s),s}n(at,"deriveGatewaySigningKey");async function uE(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=dE.encode(`${cE}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:iE,salt:new Uint8Array,info:me(s)},o,aE*8);return new Uint8Array(i)}n(uE,"hkdfExpand");var uy=900,lE=900,pE=Qm.extend({id:wh,browserBinding:Vo.optional()}),mE=pE.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),ly=Ta.extend({id:bh,purpose:m.literal("browser_connect")}),hE=Ta.extend({purpose:m.literal("browser_connect")}),fE=ly.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),Mi=uy*1e3;async function py(){return Be({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"oauth-state"),"derive")})}n(py,"getOAuthStateKey");async function my(){return Be({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"browser-connect"),"derive")})}n(my,"getBrowserConnectKey");async function hy(e){let t=Math.floor(Date.now()/1e3)+uy;return new dy(e).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(t).sign(await py())}n(hy,"signOAuthState");async function Oi(e){try{let{payload:t}=await cy(e,await py(),{algorithms:[Se],issuer:ue,audience:ye});return mE.parse(t)}catch(t){throw t instanceof ay.JWTExpired?new E({message:"OAuth state has expired",extensionMembers:{[x]:"oauth_state_expired"}},{cause:t}):new E({message:"OAuth state could not be verified",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:t})}}n(Oi,"verifyOAuthState");async function fy(e){let t=Math.floor(Date.now()/1e3)+lE,r=hE.parse(e),o=ly.parse({...r,id:Th()});return new dy(o).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(t).sign(await my())}n(fy,"signBrowserConnectTicket");async function gy(e){try{let{payload:t}=await cy(e,await my(),{algorithms:[Se],issuer:ue,audience:ye});return fE.parse(t)}catch(t){throw t instanceof ay.JWTExpired?new E({message:"Browser connect ticket has expired",extensionMembers:{[x]:"oauth_state_expired"}},{cause:t}):new E({message:"Browser connect ticket could not be verified",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:t})}}n(gy,"verifyBrowserConnectTicket");async function yy(e){if((await H().consumeBrowserConnectTicket({id:e.id,expiresAt:J(new Date(e.exp*1e3)),now:J(new Date)})).kind==="consumed")throw new E({message:"Browser connect ticket has already been used",extensionMembers:{[x]:"oauth_state_reused"}})}n(yy,"consumeBrowserConnectTicket");function gE(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(gE,"buildConnectRequiredMessage");async function yE(e){let t=oe(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 fy({...Eo(e),purpose:"browser_connect"})),r.toString()}n(yE,"buildGatewayBrowserTicketUrl");function SE(e){return pe().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(SE,"buildGatewayConnectPath");async function Zc(e){return yE({...e,path:SE(e.upstreamServerId),redirect:!0})}n(Zc,"buildGatewayConnectUrl");async function Ui(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 Zc(t),message:gE(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ui,"buildRedirectConnectRequiredResponse");function Sy(e){return Ry({...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(Sy,"buildAdminConnectRequiredResponse");function Ry(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(Ry,"buildAdminSetupRequiredResponse");function _y(e){return we().byOperationId.get(e)?.downstreamOAuth!==void 0}n(_y,"routeSupportsBrowserConnect");function wy(e){return Ry({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}n(wy,"buildBrowserConnectUnavailableResponse");var by=12;async function vy(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(vy,"sha256Hex");async function pr(e){if(e)return(await vy(e)).slice(0,by)}n(pr,"fingerprintSecret");async function sn(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await vy(t)).slice(0,by)}n(sn,"fingerprintConnectionIdentity");var RE=6e4;function an(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(an,"credentialGenerationChanged");function Ae(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()+RE)return"near_expiry"}return"usable"}n(Ae,"describeAccessTokenState");var Cy=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _E(e,t){return e&&e.length>0?e.join(t):void 0}n(_E,"joinOAuthScopes");function wE(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Cy)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(wE,"sanitizeAuthorizationServerMetadata");function Iy(e){let t=wE(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Iy,"sanitizeOAuthDiscoveryState");function Ty(e){let t=new URL(e);for(let r of Cy){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Ty,"dedupeSingletonAuthorizationRequestParams");function qi(e){let t=new URL(e);return ze(t)&&Hm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(qi,"normalizeLoopbackOAuthRedirectUri");function Ey(e){return _E(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Ey,"readProtectedResourceMetadataScope");function bE(e){return`Zuplo MCP Gateway - ${e}`}n(bE,"buildGatewayOAuthClientName");function vE(e,t){return e&&e.length>0?e.join(t):void 0}n(vE,"joinOAuthScopeList");function CE(e){if(e.clientRegistration.mode!=="auto")return vE(e.scopes,e.scopeDelimiter)}n(CE,"readPublicClientMetadataScope");function Yc(e){return new URL(pe().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Yc,"buildOAuthClientMetadataDocumentUrl");function Xc(e){let t=Nt(e.upstreamServerId);return{client_name:bE(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(Xc,"buildGatewayOAuthClientMetadata");function ky(e,t,r){let o=nn(t,r),s=CE(o);return{client_id:Yc({origin:e,upstreamServerId:t}),...Xc({origin:e,upstreamServerId:t,redirectUri:qi(new URL(o.redirectPath,e)).toString(),scope:s})}}n(ky,"buildOAuthClientMetadataDocument");import{base64url as Dt}from"jose";var IE="SHA-256",cn="AES-GCM",TE=12,ed="zuplo-secret",td=1,Ay="generated:auth_private_key:token-encryption",EE=m.object({version:m.literal(td),keyId:m.literal(Ay),algorithm:m.literal(cn),iv:m.string().min(1),ciphertext:m.string().min(1)}).strict();async function Qc(){return Be({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(IE,me(e));return crypto.subtle.importKey("raw",t,{name:cn},!1,["encrypt","decrypt"])},"derive")})}n(Qc,"getEncryptionKey");function Py(e){return me(new TextEncoder().encode(`${ed}:v${e.version}:${e.keyId}`))}n(Py,"getAssociatedData");function kE(e){return`${ed}:v${e.version}:${Dt.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(kE,"encodeEnvelope");function AE(e){let t=`${ed}:v${td}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Dt.decode(r));return EE.parse(JSON.parse(o))}n(AE,"decodeEnvelope");async function gt(e){let t=await Qc(),r=crypto.getRandomValues(new Uint8Array(TE)),o={version:td,keyId:Ay},s=await crypto.subtle.encrypt({name:cn,iv:r,additionalData:Py(o)},t,new TextEncoder().encode(e));return kE({...o,algorithm:cn,iv:Dt.encode(r),ciphertext:Dt.encode(new Uint8Array(s))})}n(gt,"encryptSecret");async function yt(e){let t=AE(e);if(t){let a=await Qc(),c=await crypto.subtle.decrypt({name:cn,iv:me(Dt.decode(t.iv)),additionalData:Py(t)},a,me(Dt.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ve("Encrypted payload is malformed");let s=await Qc(),i=await crypto.subtle.decrypt({name:cn,iv:me(Dt.decode(r))},s,me(Dt.decode(o)));return new TextDecoder().decode(i)}n(yt,"decryptSecret");var xy={issuer:m.string().min(1).optional()},PE=m.union([ar.extend(xy),wo.extend(xy)]),My=m.object({authorizationServerUrl:m.url(),resourceMetadataUrl:m.url().optional(),resourceMetadata:Nr.optional(),authorizationServerMetadata:m.union([jr,Dr]).optional()}).passthrough(),xE="Bearer",ME="__zuplo_refresh_only_upstream_access_token__";function rd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(rd,"splitScopes");function nd(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(nd,"scopesCover");function OE(e){return Fr.parse(e)}n(OE,"parsePkceCodeVerifier");function UE(e){if(typeof e.expires_in=="number")return J(new Date(Date.now()+e.expires_in*1e3))}n(UE,"readTokenExpiry");async function od(e){if(e!==void 0)return gt(JSON.stringify(e))}n(od,"encryptJson");async function Oy(e,t){if(!e)return;let r=await yt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new E({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[x]:"oauth_state_invalid"}},{cause:o})}}n(Oy,"decryptJson");function qE(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(qE,"clientInformationAllowsRedirectUri");function zE(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(zE,"clientInformationMatchesCurrentClientMetadataUrl");function NE(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(NE,"isUrlBasedClientInformation");function jE(e,t){return t===void 0?e:{...e,scope:t}}n(jE,"applyOAuthClientMetadataScope");function DE(e,t){return Ey({state:e,delimiter:t})}n(DE,"readResourceMetadataScope");function $E(e,t){return e&&e.length>0?e.join(t):void 0}n($E,"joinOAuthScopeList");function LE(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new X(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return ar.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(LE,"buildManualOAuthClientInformation");function HE(e,t){let r=Yc({origin:new URL(t).origin,upstreamServerId:e});return uc(r)?r:void 0}n(HE,"buildClientMetadataUrl");function BE(e){for(let t of e)if(t!==void 0)return t}n(BE,"firstDefined");function FE(e){let t=nn(e.target.upstreamServerId,e.target.authProfileId),r=$E(t.scopes,t.scopeDelimiter),o=Xc({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,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:LE({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=HE(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,authorizationParams:t.authorizationParams,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}n(FE,"buildInitialOAuthClientSetup");function JE(e,t){if(t===void 0)return BE([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(JE,"readEncryptedClientInformation");function VE(e){return e.pendingState?.encryptedDiscoveryState}n(VE,"readEncryptedDiscoveryState");function zi(e,t){return t===void 0?e:{...e,issuer:t}}n(zi,"applyIssuerStamp");var $t=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;authorizationParams;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=FE({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.authorizationParams=r.authorizationParams,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=JE(t,this.configuredClientInformation),this.encryptedDiscoveryState=VE(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=rd(this.configuredScope??r??this.readEffectiveScope());return nd(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Ae(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=ee();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 sn({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await pr(await yt(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await H().conditionalUpsertUpstreamConnection(t,r)}catch(o){let s=ee();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 jE(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return hy({id:t.id,...Eo({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?zi(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,ee()?.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"),!NE({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await od(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!si({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=Iy(My.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await od(r),await this.syncPendingState(!1),ee()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:te(r.authorizationServerUrl),resourceMetadataHost:te(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=DE(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let s=rd(this.configuredScope).filter(i=>!o.includes(i));s.length>0&&ee()?.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 zi(r,t?.issuer)}async saveTokens(t){let r=At.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 gt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:At.parse({...r,refresh_token:await yt(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Xs(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await gt(r.access_token),encryptedRefreshToken:a,scopes:rd(r.scope??this.readEffectiveScope()),expiresAt:UE(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),p=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Ae(u.connection)!=="usable"||!nd(u.connection.scopes,c.scopes)||!an(s,u.connection))){p=!0;let f=u.connection,y={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};ee()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(y,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,an(s,u.connection)&&Ae(u.connection)==="usable"&&nd(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),p){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";ee()?.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;ee()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await pr(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:p,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Ty(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride);for(let[o,s]of Object.entries(this.authorizationParams??{}))r.searchParams.set(o,s);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:OE(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new E({message:"OAuth code verifier is missing",extensionMembers:{[x]:"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:Ih(),...Eo({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()+Mi)),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 Oy(this.encryptedClientInformation,PE)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!qE(r,this.redirectUriValue)||!zE({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r!==void 0&&r.issuer===void 0&&t?.issuer!==void 0&&(r=zi(r,t.issuer),this.encryptedClientInformation=await od(r)),r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=zi(wo.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 Oy(this.encryptedDiscoveryState,My)}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"){ee()?.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 yt(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await yt(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let s=ee();this.usedRefreshTokenFingerprintValue=s?await pr(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=At.parse({access_token:r??ME,token_type:xE,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,an(r,a.connection)&&Ae(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=ee();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:o,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 GE=3e4,KE=256*1024,WE=2,ZE="does not support dynamic client registration",YE=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],XE=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],QE=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],ek="Protected resource ",tk=" does not match expected ",rk=["HTTP 403 Forbidden","Access Denied","permission to access"],nk=new Set([ce.AccessDenied,ce.InvalidClient,ce.InvalidGrant,ce.InvalidRequest,ce.InvalidScope,ce.InvalidTarget,ce.UnauthorizedClient,ce.UnsupportedGrantType]);function ok(e){return e instanceof Error&&e.message.includes(ZE)}n(ok,"isDynamicClientRegistrationUnsupported");function sk(e){return e instanceof Error&&YE.some(t=>e.message.includes(t))}n(sk,"isProtectedResourceMetadataUnavailable");function ik(e){return e instanceof Error&&XE.some(t=>e.message.includes(t))}n(ik,"isAuthorizationServerMetadataUnavailable");function ak(e){return e instanceof Error&&QE.some(t=>e.message.includes(t))}n(ak,"isAuthorizationServerIncompatible");function ck(e){return e instanceof Error&&e.message.includes(ek)&&e.message.includes(tk)}n(ck,"isProtectedResourceMismatch");function dk(e){return e instanceof Error&&rk.some(t=>e.message.includes(t))}n(dk,"isUpstreamProviderAccessDenied");function Uy(e){return e instanceof Ut&&nk.has(e.code)}n(Uy,"isStoredConnectionReconsentError");function St(e){let t=e.diagnostics??{};return new E({message:e.message,extensionMembers:{[x]:e.code,[Co]:e.upstreamServerId,[Gr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[st]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[ot]:t.httpStatus},...t.providerError===void 0?{}:{[Kr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Wr]:t.providerErrorDescription}}},{cause:e.cause})}n(St,"buildUpstreamSetupProblem");function uk(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(uk,"describeIssuerMetadataMismatch");var lk=128,Ni=256;function Yo(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}n(Yo,"truncateProviderDetail");function pk(e){let{error:t,errorDescription:r}=ji(e.body),o=Yo(t,lk),s=Yo(r,Ni);return{httpStatus:e.status,...o===void 0?{}:{providerError:o},...s===void 0?{}:{providerErrorDescription:s}}}n(pk,"readRegistrationRejectionDiagnostics");function mk(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}n(mk,"describeRegistrationRejection");function hk(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}n(hk,"readDiscoveryEndpointUrl");function fk(e){if(e.error instanceof E&&e.error.extensionMembers?.[x]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(ok(e.error))return St({...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 cc){let r=pk(e.error);return St({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${mk(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof No&&e.error.kind==="metadata")return St({...t,code:"upstream_oauth_issuer_mismatch",message:uk(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof li)return St({...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(ak(e.error))return St({...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(ik(e.error)){let r=hk(e.error.message);return St({...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(ck(e.error))return St({...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(sk(e.error))return St({...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(dk(e.error))return St({...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(fk,"mapUpstreamOAuthSetupError");function gk(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(gk,"readOAuthFetchRequest");function yk(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(yk,"readOAuthFetchMethod");function Sk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Sk,"responseLooksJson");function Rk(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(Rk,"responseLooksHtml");var _k=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function wk(e){return _k.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}n(wk,"isMetadataDiscoveryRequest");function bk(e,t,r){return e!=="GET"||!wk(t)?!1:r>=400&&r<500||r===502}n(bk,"sdkRetriesDiscoveryCandidate");function vk(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new E({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[x]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ot]:e.response.status,[Jr]:r,[st]:e.request.url.toString(),[Vr]:e.body}})}n(vk,"throwUpstreamHtmlError");var Ck=["message","error_message","detail","title"];function qy(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}n(qy,"readStringField");function Ik(e){for(let r of Ck){let o=qy(e,r);if(o!==void 0)return o}let t=e.error;if(typeof t=="object"&&t!==null)return qy(t,"message")}n(Ik,"readProviderMessage");function ji(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t,o=typeof r.error=="string"?r.error:void 0,s=typeof r.error_description=="string"?r.error_description:void 0;return{error:o,errorDescription:s,providerMessage:s===void 0?Ik(r):void 0}}catch{return{}}}n(ji,"readUpstreamOAuthErrorBody");function Tk(e){let{error:t,errorDescription:r,providerMessage:o}=ji(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:te(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:Yo(r,Ni),providerMessage:Yo(o,Ni)},"Upstream OAuth HTTP request returned an error response")}n(Tk,"logUpstreamOAuthHttpError");function Ek(e,t){if(e!=="POST")return!1;let r=t?.body;return r instanceof URLSearchParams?r.get("grant_type")==="refresh_token":typeof r=="string"?new URLSearchParams(r).get("grant_type")==="refresh_token":!1}n(Ek,"isRefreshTokenGrant");var kk=new Set([void 0,ce.ServerError,ce.TemporarilyUnavailable]);function Ak(e,t){return e.status<500&&e.status!==429?!1:kk.has(ji(t).error)}n(Ak,"isTransientTokenEndpointResponse");var Pk=[/\b(?:unknown|unrecognized|unrecognised)\s+client(?:[\s_-]?id)?(?=\s*(?:$|[.,:;!?'"`(]))/i,/\bclient(?:[\s_-]?id)?\s+(?:not\s+found|is\s+unknown|does\s+not\s+exist)\b/i];function xk(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}n(xk,"isTokenEndpointRequest");function Mk(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:o}=ji(t);if(!(r!==void 0||o===void 0))return Pk.some(s=>s.test(o))?o:void 0}n(Mk,"readUnknownClientRejection");function Ok(e,t){let r=new Headers(e.headers);return r.set("content-type","application/json"),r.delete("content-length"),r.delete("content-encoding"),new Response(JSON.stringify({error:"invalid_client",error_description:t}),{status:e.status,statusText:e.statusText,headers:r})}n(Ok,"rewriteUnknownClientRejection");function zy(e,t){return async(r,o)=>{let s=gk(r),i=yk(r,o),a=t!==void 0&&Ek(i,o),c=ee(),d=Date.now(),u;try{u=await Xg(r,o,{maxRedirects:WE,maxResponseBytes:KE,problemCode:"upstream_token_exchange_failed",timeoutMs:GE})}catch(h){throw a&&Zg(h)&&(t.failure={url:s.url,cause:h}),h}let p=await u.clone().text();if(c?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,host:te(s.url),path:s.url.pathname,status:u.status,durationMs:Date.now()-d,responseChars:p.length},"Upstream OAuth HTTP request completed"),u.ok||Tk({log:c,upstreamServerId:e,method:i,request:s,response:u,body:p}),a&&Ak(u,p)&&(t.failure={url:s.url,status:u.status}),bk(i,s.url,u.status))return u;if(xk(i,o)){let h=Mk(u.status,p);if(h!==void 0)return c?.info({event:"upstream_oauth_unknown_client_rejected",upstreamServerId:e,host:te(s.url),path:s.url.pathname,status:u.status,providerMessage:Yo(h,Ni)},"Upstream OAuth provider no longer recognizes the gateway's client; treating it as invalid_client"),Ok(u,h)}if(!u.ok&&Rk(u,p)&&vk({upstreamServerId:e,request:s,response:u,body:p}),!Sk(u,p))return u;try{JSON.parse(p)}catch(h){throw new E({message:`Upstream OAuth fetch ${s.url.origin}${s.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[x]:"upstream_token_exchange_failed"}},{cause:h})}return u}}n(zy,"createUpstreamOAuthFetch");function Ny(e){ee()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:te(e.serverUrl),resourceMetadataHost:te(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Ny,"logUpstreamOAuthFlowStarted");function jy(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=te(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof E?e.error.extensionMembers?.[x]:void 0;typeof o=="string"&&(t.code=o),Ie(t,"error",e.error),ee()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(jy,"logUpstreamOAuthFlowFailed");function Dy(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Dy,"readAuthorizationRequestScope");async function $y(e,t){e.applyChallengeScope(t.requestedScope),Ny({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:zy(t.upstreamServerId,t.refreshFailures)},o=Dy(e,t);return o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await dc(e,r)}catch(r){jy({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=fk({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n($y,"runUpstreamOAuth");async function Uk(e,t){e.applyChallengeScope(t.requestedScope),Ny({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:zy(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=Dy(e,t);o!==void 0&&(r.scope=o),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await dc(e,r)}catch(s){throw jy({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}n(Uk,"exchangeUpstreamAuthorizationCode");async function sd(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||Ae(r)!=="usable"||!an(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(sd,"adoptPeerCredentialAtResolutionBoundary");async function Ly(e,t){let r=await $y(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new E({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}}):new E({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}})}n(Ly,"requireUpstreamAuthorizationRedirect");function qk(e,t){let r=t.status===void 0?"did not respond":`answered HTTP ${t.status}`;return new E({message:`The token endpoint for ${e} ${r} while the gateway refreshed a stored connection. The connection was kept; retry the request.`,extensionMembers:{[x]:"upstream_token_refresh_unavailable",[Co]:e,[st]:`${t.url.origin}${t.url.pathname}`,...t.status===void 0?{}:{[ot]:t.status}}},t.cause===void 0?void 0:{cause:t.cause})}n(qk,"buildTransientRefreshProblem");function zk(e){e.log?.warn({event:"upstream_oauth_refresh_unavailable",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:e.connection?.id,host:te(e.failure.url),path:e.failure.url.pathname,status:e.failure.status},"Upstream token endpoint could not refresh the connection; the connection was kept")}n(zk,"logTransientRefreshFailure");async function Hy(e){let t=Ae(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=ee(),i=s?await sn({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={},c=n(u=>{throw zk({log:s,target:e.target,connection:e.connection,connectionFingerprint:i,failure:u}),qk(e.target.upstreamServerId,u)},"rejectTransientRefreshFailure"),d;try{d=await $y(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,refreshFailures:a,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(u){if(a.failure!==void 0&&!Uy(u)){if(await sd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope}))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};c(a.failure)}if(e.connection===void 0||!Uy(u))throw u;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:u.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await sd({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 id({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(d==="AUTHORIZED"){let u=e.provider.readUsablePeerAdoption(e.requestedScope);return u!==void 0&&await e.provider.adoptConnectionForDirectResolution(u,"cas_loss"),!e.provider.tokenWriteWasPersisted&&u===void 0?{kind:"connect_required",payload:await id({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(d!=="REDIRECT")throw new E({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${d}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new E({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});return await sd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:(a.failure!==void 0&&c(a.failure),{kind:"connect_required",payload:await id({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(Hy,"authorizeUpstreamOAuthSession");async function Nk(e){let t=await Oi(e.stateToken),r=await H().consumeUpstreamOAuthState({id:t.id,now:J(new Date)}),o=jk(r);return Dk({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),$k(o),o}n(Nk,"consumeStoredCallbackState");function jk(e){switch(e.kind){case"consumed":throw new E({message:"OAuth state has already been used",extensionMembers:{[x]:"oauth_state_reused"}});case"missing":throw new E({message:"OAuth state is missing or expired",extensionMembers:{[x]:"oauth_state_expired"}});case"available":return e.record}}n(jk,"readConsumedCallbackState");function Dk(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 E({message:"OAuth callback did not match the initiating request",extensionMembers:{[x]:"oauth_callback_mismatch"}})}n(Dk,"assertStoredCallbackStateMatches");function $k(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new E({message:"OAuth state has expired",extensionMembers:{[x]:"oauth_state_expired"}})}n($k,"assertStoredCallbackStateFresh");async function id(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),Sy(r)}if(jt()&&!_y(e.operationId))return ee()?.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"),wy({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),Ui(t)}n(id,"buildOAuthConnectRequiredResponse");async function By(e){let t=await Nk({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Js(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 $t(s),a=await Uk(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 E({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[x]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new E({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}}):new E({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[x]:"upstream_token_exchange_failed"}})}n(By,"finishUpstreamOAuthCallback");import{importPKCS8 as Lk,SignJWT as Hk}from"jose";var Jy=1e4,Vy=64*1024,Gy=2,Bk=300,Qe=m.string().min(1),Fk=m.object({access_token:Qe,issued_token_type:m.literal(ka),token_type:m.string().optional(),expires_in:m.number().int().positive().optional(),scope:Qe.optional()}).passthrough(),Jk=m.object({id_token:Qe,token_type:Qe.optional(),expires_in:m.number().int().positive().optional(),refresh_token:Qe.optional(),scope:Qe.optional()}).passthrough(),Vk=m.object({access_token:Qe,token_type:Qe,expires_in:m.number().int().positive().optional(),scope:Qe.optional(),resource:Qe.optional(),refresh_token:Qe.optional()}).passthrough();function Fy(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Fy,"formEncodeClientCredential");function Gk(e){return e.replaceAll("\\n",`
13
13
  `)}n(Gk,"normalizePem");async function Kk(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??Bk,o=await Lk(Gk(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new Hk({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(Kk,"createPrivateKeyJwtClientAssertion");async function Wk(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=Fy(e.clientAuth.clientId),r=Fy(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",Gs),e.form.set("client_assertion",await Kk({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(Wk,"appendClientAuthentication");async function ad(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await Wk({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(ad,"buildFormRequest");function Ky(e){return(t,r)=>xi(t,r,{context:e,maxRedirects:Gy,maxResponseBytes:Vy,problemCode:"upstream_token_exchange_failed",timeoutMs:Jy})}n(Ky,"defaultIdpFetchJson");function Zk(e){return(t,r)=>Qg(t,r,{context:e,maxRedirects:Gy,maxResponseBytes:Vy,problemCode:"upstream_token_exchange_failed",timeoutMs:Jy})}n(Zk,"defaultResourceAsFetchJson");function Di(e){let t={[x]:e.code,[st]:e.tokenUrl};return e.response!==void 0&&(t[ot]=e.response.status),new E({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(Di,"runtimeError");function cd(e){if(!e.response.ok)throw Di({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(cd,"assertTokenEndpointSucceeded");function Yk(e){let t=Jk.safeParse(e.json);if(!t.success)throw Di({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(Yk,"parseIdpRefreshTokenResponse");function Xk(e){let t=Fk.safeParse(e.json);if(!t.success)throw Di({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(Xk,"parseIdJagTokenExchangeResponse");function Qk(e){let t=Vk.safeParse(e.json);if(!t.success)throw Di({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(Qk,"parseAccessTokenResponse");async function Wy(e){let t=new URLSearchParams({grant_type:Vs,requested_token_type:ka,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??Ky(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await ad({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return cd({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),Xk({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Wy,"requestIdJag");async function Zy(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Ky(e.context),{response:o,json:s}=await r(e.idp.tokenUrl,await ad({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return cd({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),Yk({json:s,response:o,tokenUrl:e.idp.tokenUrl})}n(Zy,"refreshIdpSubjectToken");async function Yy(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??Zk(e.context),{response:o,json:s}=await r(e.resourceAs.tokenUrl,await ad({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return cd({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),Qk({json:s,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Yy,"exchangeIdJagForAccessToken");function eA(e){return Ae(e)==="usable"}n(eA,"hasUsableAccessToken");function tA(e){if(e.tokenType.toLowerCase()!=="bearer")throw new E({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[x]:"upstream_token_response_invalid"}})}n(tA,"assertBearerToken");function Xy(e,t){if(t===Qr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Xy,"hasExpiredSubjectToken");async function rA(e){let t=await yt(e.encryptedSubjectToken);if(e.subjectTokenType!==Qr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Zy({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:ko};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 gt(r.refreshToken),idpSubjectTokenType:Qr,idpSubjectTokenExpiresAt:void 0}});return ee()?.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 pr(t),newSubjectRefreshTokenFingerprint:await pr(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:ko}}n(rA,"resolveIdJagSubjectToken");async function Qy(e){let t="preloadedConnection"in e?e.preloadedConnection:(await H().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Ae(t),o=!!e.forceRefresh,s=!o&&r==="usable",i=ee(),a=i?await sn({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&&eA(t))return{kind:"authorized",credential:{type:"bearer_token",token:await yt(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||Xy(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&&Xy(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=Nt(e.upstreamServerId),p=Hg(e.upstreamServerId,e.authProfileId),h=p.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(p.scopes.length===0?void 0:p.scopes.join(p.scopeDelimiter)),y=await rA({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:p.idp.tokenUrl},clientAuth:p.idp.clientAuth,context:e.context}),b=await Wy({idp:{tokenUrl:p.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:p.resourceAs.audience,resource:h,scope:f,clientAuth:p.idp.clientAuth,context:e.context}),_=b.scope??f,S=await Yy({resourceAs:{tokenUrl:p.resourceAs.tokenUrl},assertion:b.assertion,resource:h,scope:_,clientAuth:p.resourceAs.clientAuth,context:e.context});if(tA(S),t!==void 0){let v=(S.scope??_)?.split(/[,\s]+/).filter(Boolean)??[],P=S.expiresIn===void 0?void 0:J(new Date(Date.now()+S.expiresIn*1e3)),N=await H().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await gt(S.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:v,expiresAt:P,metadata:y.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:v.length,expiresAt:P},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:S.accessToken}}}n(Qy,"authorizeUpstreamIdJagRequest");var $i=new Map;function nA(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(nA,"normalizeRefreshFlightScope");function oA(e){return qi(new URL(e.callbackPath,oe(e.requestUrl,e.requestHeaders))).toString()}n(oA,"buildGatewayOAuthRedirectUri");async function dd(e){let t=Nt(e.upstreamServerId),r=nn(e.upstreamServerId,e.authProfileId),o=oA({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:oe(e.request.url,e.request.headers)}}}n(dd,"prepareUpstreamOAuthRequest");async function eS(e){let t=await dd(e),r=new $t({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ly(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(eS,"startUpstreamConnect");async function tS(e){let t=await dd(e),r=new $t({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>Hy({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&&Ae(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o();let s=vh({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,nA(r.configuredAuthorizationScope??e.requestedScope)]),a=$i.get(i);if(a!==void 0){ee()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let u=await a;if(u.kind==="usable"&&r.connectionSatisfiesRequestedScope(u.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(u.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:p,...h}=e;if(t=await dd(h),r=new $t({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Ae(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o()}let c=o(),d;return d=c.then(()=>{let u=r.currentConnection;return u!==void 0&&Ae(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{$i.get(i)===d&&$i.delete(i)}),$i.set(i,d),c}n(tS,"authorizeUpstreamRequest");async function Li(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return tS({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 Qy({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 ve(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Li,"resolveUpstreamCredentialForRoute");async function rS(e){if(e.connectRequest.authMode==="id-jag")throw new ve(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await eS({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(rS,"startUpstreamConnectForRequest");async function sA(e,t){if(t===void 0)throw new E({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[x]:"oauth_callback_mismatch"}});let r=await Ai({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new E({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[x]:"oauth_callback_mismatch"}})}n(sA,"requireCallbackBrowser");async function nS(e){let t=await Oi(e.callbackRequest.state);jt()&&await sA(e,t.browserBinding);let r=t.authProfileId;if(Ti({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new ve(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return By({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:Nt(e.callbackRequest.upstreamServerId)})}n(nS,"finishUpstreamCallbackForRequest");function iA(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(iA,"buildRouteAuthBaseFromConnection");function oS(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:eh(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(oS,"buildRouteAuthBaseFromPolicyOptions");function Hi(e,t){let o=we().byOperationId.get(t);if(!o)throw new X(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new X(`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 X(`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 iA({connection:o.connection,operationId:t})}n(Hi,"resolveRouteAuthBase");function ud(e,t){switch(e){case"user":return Yr(t);case"shared":return Xm()}}n(ud,"buildOwnerForSubject");function dn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:ud("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:ud("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:ud("user",t),initiatedBySubjectId:t}}}n(dn,"resolveRouteAuthForSubject");import{base64url as aA,errors as sS,jwtVerify as cA,SignJWT as dA}from"jose";var ld="zuplo-connect.",uA=600,iS="mcp_connect_request_state",lA=m.object({purpose:m.literal(iS),binding:m.string().min(1),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),pA=new TextEncoder;async function aS(){return Be({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"connect-request-state"),"derive")})}n(aS,"getConnectRequestStateKey");async function cS(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",pA.encode(t));return aA.encode(new Uint8Array(r))}n(cS,"digestBinding");function pd(e){return typeof e=="string"&&e.startsWith(ld)}n(pd,"isConnectRequestState");async function dS(e,t=new Date){let r=Math.floor(t.getTime()/1e3),o=await new dA({purpose:iS,binding:await cS(e)}).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt(r).setExpirationTime(r+uA).sign(await aS());return`${ld}${o}`}n(dS,"signConnectRequestState");async function uS(e,t,r=new Date){if(!pd(e))return"foreign";let o;try{let{payload:s}=await cA(e.slice(ld.length),await aS(),{algorithms:[Se],issuer:ue,audience:ye,currentDate:r,clockTolerance:0});o=lA.parse(s)}catch(s){return s instanceof sS.JWTExpired?"expired":s instanceof sS.JWTClaimValidationFailed||s instanceof m.ZodError?"invalid":"foreign"}return o.binding===await cS(t)?void 0:"mismatch"}n(uS,"verifyConnectRequestState");var mA=new Set(["initialize","ping","logging/setLevel","resources/subscribe","resources/unsubscribe","tasks/list","tasks/result"]);function lS(e){if(!Ee()||!mA.has(e.method))return;let t=ge(e.message);return Response.json(Te({...t===void 0?{}:{id:t},error:{code:I.MethodNotFound,message:"Method not found"}}),{status:404})}n(lS,"modernMethodNotFoundResponse");var hA=new Map([["tools/list","tools"],["prompts/list","prompts"],["resources/list","resources"],["resources/templates/list","resourceTemplates"]]),fA=0,gA="private",yA=new Set(["tools/call","prompts/get","resources/read"]);var SA=-32021,RA="Invalid or expired requestState";function mr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(mr,"isRecord");function _A(e,t){if(!(!Y()||!mr(t)||typeof t.method!="string"||!$r(e,t)))return{message:t,method:t.method}}n(_A,"readModernMcpRequest");async function pS(e,t){return Ee()?!Y()||!mr(t)||typeof t.method!="string"||!Hs(e.headers,t)||await _m(e.clone(),t,{maxRequestBodySize:Number.MAX_SAFE_INTEGER})?void 0:{message:t,method:t.method}:_A(e.headers,t)}n(pS,"classifyModernMcpRequest");function md(e){return!Object.hasOwn(e.message,"id")}n(md,"isModernNotification");function hd(){return new Response(null,{status:202})}n(hd,"acceptedNotificationResponse");function fd(e){let t=e.message.params;return mr(t)?t:void 0}n(fd,"readParams");function mS(e){if(!yA.has(e.method))return;let t=fd(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}n(mS,"readInputRequiredTarget");function hS(e,t,r){return{...e,method:t.method,target:r}}n(hS,"buildBinding");function wA(e){let t=ge(e.message);return Response.json(Te({...t===void 0?{}:{id:t},error:{code:I.InvalidParams,message:RA,data:{reason:"invalid_request_state"}}}))}n(wA,"invalidRequestStateResponse");function bA(e){if(!mr(e))return;let t=e[Lr],r=mr(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}n(bA,"readElicitationAction");function vA(e){let t={...fd(e)};if(delete t.requestState,mr(t.inputResponses)){let r={...t.inputResponses};delete r[Lr],Object.keys(r).length===0?delete t.inputResponses:t.inputResponses=r}return{...e.message,params:t}}n(vA,"stripConnectState");async function fS(e){let t=fd(e.request),r=t?.requestState;if(!pd(r))return{kind:"none"};let o=mS(e.request),s=o===void 0?"mismatch":await uS(r,hS(e.binding,e.request,o),e.now);if(s==="foreign")return{kind:"none"};if(s!==void 0)return{kind:"rejected",reason:s,response:wA(e.request)};let i=vA(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:bA(t?.inputResponses)}}n(fS,"readModernConnectRetry");function CA(e){let t=Im(e.message)?.elicitation;return mr(t)&&t.url!==void 0}n(CA,"declaresUrlElicitation");function IA(e,t){return Response.json(Te({...e===void 0?{}:{id:e},error:{code:gc,message:t.message,data:{connectRequired:t}}}))}n(IA,"connectRequiredErrorResponse");async function gS(e){if(md(e.request))return hd();let t=ge(e.request.message),r=hA.get(e.request.method);if(r!==void 0)return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",[r]:[],ttlMs:fA,cacheScope:gA,_meta:{[Pt]:e.serverInfo}}});let o=mS(e.request),s=e.payload.authUrl;if(o===void 0||s===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return IA(t,e.payload);if(!CA(e.request))return Response.json(Te({...t===void 0?{}:{id:t},error:{code:SA,message:`${e.payload.message} The client must declare URL elicitation (clientCapabilities.elicitation.url) to be sent the connect link.`,data:{requiredCapabilities:{elicitation:{url:{}}},connectRequired:e.payload}}}),{status:400});let i=await dS(hS(e.binding,e.request,o),e.now);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"input_required",inputRequests:{[Lr]:{method:"elicitation/create",params:{mode:"url",message:e.payload.message,url:s}}},requestState:i,_meta:{[Pt]:e.serverInfo}}})}n(gS,"modernConnectRequiredResponse");var gd=new WeakMap;function yS(e,t){gd.set(e,t)}n(yS,"setUpstreamAuthRetry");function SS(e){let t=gd.get(e);return gd.delete(e),t}n(SS,"takeUpstreamAuthRetry");var RS=new WeakSet;function _S(e){RS.add(e)}n(_S,"markGatewayUpstreamCredential");function wS(e){return RS.has(e)}n(wS,"sentGatewayUpstreamCredential");async function bS(e){try{return await Li(e)}catch(t){if(Ne(t)==="upstream_token_refresh_unavailable")return{kind:"refresh_unavailable"};throw t}}n(bS,"resolveCredentialOrRefreshUnavailable");function vS(e,t){return Zr(e,t,{code:"upstream_token_refresh_unavailable"})}n(vS,"refreshUnavailableResponse");var TA="The upstream connection returned no OAuth tokens.";function CS(e){let t=pc(e);return Response.json(Te({id:t,error:{code:I.InternalError,message:TA}}),{status:t===void 0?500:200})}n(CS,"noUpstreamTokensJsonRpcResponse");function EA(e,t){return{credentialType:e.type,forceRefresh:t}}n(EA,"buildCredentialResolvedAttributes");function kA(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(kA,"connectRequiredReasonCode");function IS(e){Q(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:EA(e.credential,e.forceRefresh===!0)})}n(IS,"emitCredentialResolvedAnalyticsEvent");function TS(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(Q(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"){Q(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}Q(e.context,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:kA(e.payload.state),reasonClass:"auth",attributes:t})}n(TS,"emitCredentialMissingAnalyticsEvents");function AA(e){let t=e.route.raw();return Fs.parse(t?.operationId)}n(AA,"readOperationId");async function PA(e,t,r,o,s){let i=await bS({request:e,context:o,routeAuth:t});if(i.kind==="refresh_unavailable")return i;if(i.kind==="connect_required")return TS({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(IS({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(PA,"buildCredentialHeaders");var xA=new Set(["authorization","cookie","cookie2"]);function ES(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}n(ES,"parseJsonRequestBody");function MA(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}n(MA,"readJsonRequestMethod");function OA(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(OA,"isJsonResponse");function Lt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Lt,"isRecord");function kS(e){return Array.isArray(e)&&e.length>0}n(kS,"hasIconList");function AS(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Ci(Zm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(AS,"readFallbackServerIcons");function UA(e){if(!Lt(e.body))return e.body;let t=e.body.result;if(!Lt(t))return e.body;let r=t.serverInfo;return!Lt(r)||kS(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(UA,"addMissingServerIcons");function qA(e){if(!Lt(e.body))return e.body;let t=e.body.result;if(!Lt(t))return e.body;let r=t._meta;if(!Lt(r))return e.body;let o=r[Pt];return!Lt(o)||kS(o.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[Pt]:{...o,icons:e.icons}}}}}n(qA,"addMissingDiscoverServerIcons");function zA(e,t){let r=PS(e.headers);for(let o of xA)r.delete(o);for(let[o,s]of t)r.set(o,s);return new kt(e,{headers:r})}n(zA,"applyUpstreamHeaders");function PS(e){let t=new Headers(e);return Iu(t),t}n(PS,"buildProxyHeaders");async function NA(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(NA,"readRetryBody");function jA(e){return Ee()&&e.httpMethod==="POST"?Gf({body:e.requestBody,parsed:ES(e.requestBody),headers:e.headers,payload:e.payload}):Response.json(yc({id:pc(e.requestBody),payload:e.payload,urlElicitation:!0,fallbackCode:I.InvalidRequest}))}n(jA,"connectRequiredJsonRpcResponse");function DA(e){let t=e.modern;if(t===void 0)return{respond:n(async i=>Ee()&&e.httpMethod!=="POST"?await yi(e.request,e.context):jA({requestBody:e.requestBody,httpMethod:e.httpMethod,headers:e.headers,payload:i}),"respond")};let r=n(()=>AS({connection:e.connection,context:e.context}),"readIcons"),o=gi(t.binding.upstreamServerId,Do),s=t.request.method==="server/discover"?async()=>$f({request:t.request,supportedVersions:o,connection:e.connection,capabilityFilter:$A(e.context),icons:r()}):i=>gS({request:t.request,payload:i,binding:t.binding,previousAction:t.previousAction,serverInfo:hc({connection:e.connection,icons:r()})});return{respond:n(async i=>{let a=xg({headers:e.headers,message:t.request.message,supportedVersions:o});return a!==void 0?a:md(t.request)?hd():lS(t.request)??s(i)},"respond")}}n(DA,"createConnectRequiredResponder");function $A(e){return Xr()?.byRoutePath.get(e.route.path)?.capabilityFilter}n($A,"readRouteCapabilityFilter");async function LA(e){let{scope:t}=Uf(e.upstreamResponse),r=await bS({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="refresh_unavailable")return r;if(r.kind==="connect_required")return TS({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(IS({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(LA,"applyRefreshedCredentialHeaders");function HA(e){yS(e.context,{refresh:n(async(t,r)=>{let o=await LA({request:e.request,context:e.context,headers:PS(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return o.kind==="connect_required"?{kind:"response",response:await e.connectRequired.respond(o.payload)}:o.kind==="no_tokens"?{kind:"response",response:CS(e.requestBody)}:o.kind==="refresh_unavailable"?{kind:"response",response:await vS(e.request,e.context)}:o},"refresh")})}n(HA,"registerUpstreamAuthRetry");function BA(e){return e.body!==null&&e.status>=200&&e.status<=299&&He(e.headers.get("content-type"))==="text/event-stream"&&!Et(e.headers)}n(BA,"isRewritableEventStream");function FA(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}n(FA,"answersRequestId");function JA(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(!(!Lt(r)||"method"in r||!("result"in r||"error"in r)||!FA(r.id,t)))return r}n(JA,"readResponseInEvent");function VA(e){let t=!1;return Ps(e.response,r=>{if(t)return;let o=JA(r,e.requestId);if(o===void 0)return;t=!0;let s=e.addMissingIcons({body:o,icons:e.icons});return s===o?void 0:yo(r,JSON.stringify(s))},{failureMode:"open"})}n(VA,"addMissingIconsToEventStream");function GA(e){let t=MA(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?UA:qA,o=AS({connection:e.connection,context:e.context});if(o===void 0||o.length===0)return;let s=Y()?ge(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!OA(i))return s!==void 0&&BA(i)?VA({response:i,requestId:s,addMissingIcons:r,icons:o}):i;let a;try{a=await i.clone().json()}catch{return i}let c=r({body:a,icons:o});if(c===a)return i;let d=yu(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}n(GA,"installInitializeIconHook");function KA(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new kt(e,{headers:r,body:t})}n(KA,"withRequestBody");async function yd(e,t,r){let o=Date.now(),s=AA(t),i=e,a=await NA(i),c=ES(a),d=n(async(P,N)=>(await Lg({request:i,context:t,requestJson:c,requestBody:a,response:P,startTime:o,...N===void 0?{}:{outcome:N}}),P),"answer"),u=dr(i.headers,c),p=oS({connection:r,operationId:s}),h=ur(i.user,i.url,i.headers);Eh(t,h);let f=dn(p,h.subjectId),y=await pS(i,c),b={subjectId:h.subjectId,operationId:s,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId},_;if(y!==void 0){let P=await fS({request:y,binding:b});if(P.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:P.reason,upstreamServerId:f.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),d(P.response);P.kind==="accepted"&&(i=KA(i,P.body),a=P.body,c=P.request.message,y=P.request,_=P.action)}let S=DA({request:i,requestBody:a,httpMethod:i.method,headers:i.headers,modern:y===void 0?void 0:{request:y,binding:b,previousAction:_},context:t,connection:r}),R=await PA(i,f,r,t,u);if(R.kind==="connect_required")return d(await S.respond(R.payload));if(R.kind==="no_tokens")return d(CS(a),"no_upstream_tokens");if(R.kind==="refresh_unavailable")return d(await vS(i,t),"upstream_token_refresh_unavailable");let v=zA(i,R.headers);return _S(t),HA({request:v,context:t,requestBody:a,connectRequired:S,routeAuth:f,mcpProtocolVersion:u}),GA({context:t,requestJson:c,connection:r,modern:y!==void 0}),v}n(yd,"mcpTokenExchangePolicy");var Sd=class extends xs{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=th(t,r);super(o,r),this.#e=o}async handler(t,r){return yd(t,r,this.#e)}};var xS=Symbol("Html");function WA(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(WA,"escapeHtml");function ZA(e){return e===null||typeof e!="object"?!1:e[xS]===!0}n(ZA,"isHtml");function Bi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Bi).join(""):ZA(e)?e.value:WA(String(e))}n(Bi,"renderValue");function Fe(e){return{[xS]:!0,value:e}}n(Fe,"trustedHtml");var Je=Fe("");function G(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Bi(t[o]),r+=e[o+1]??"";return Fe(r)}n(G,"html");function un(e,t=Je){let r=Bi(t),o="",s=!0;for(let i of e)s||(o+=r),o+=Bi(i),s=!1;return Fe(o)}n(un,"joinHtml");function ln(e){return e.value}n(ln,"renderHtml");function MS(e){return G`<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(MS,"renderBrowserErrorPage");var OS=Fe('<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>'),US=Fe('<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>'),pn=Fe('*,: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 mn(e){return G`<!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>
14
14
  ${e.styles}
15
15
  </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(mn,"renderShell");function Fi(e){return G`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?OS:US}</div>`}n(Fi,"renderStatusIcon");var YA="text/html; charset=utf-8";function Ht(e){try{return new URL(e).host}catch{return""}}n(Ht,"safeHostFromUrl");function Ve(e){let t=e.kind??"authorization_failed",r=QA(t),o=XA(e),s=e.title??r.title;return new Response(ln(mn({title:s,iconHref:"",styles:pn,headerIcon:Fi(t==="access_denied"?"neutral":"error"),heading:s,subhead:G`<p class="card__subtitle">${e.detail}</p>`,body:MS({steps:un(r.steps.map(i=>G`<li>${i}</li>`)),action:rP(e.action),reference:nP(o),diagnostics:oP({diagnostic:o,detail:e.detail}),upstreamResponse:sP(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":YA,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Ve,"browserErrorPageResponse");function XA(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??eP(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??tP(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(XA,"buildBrowserErrorDiagnostic");function QA(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(QA,"readBrowserErrorPagePresentation");function eP(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_refresh_unavailable":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(eP,"readBrowserErrorStage");function tP(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}n(tP,"readBrowserErrorSuggestedFix");function rP(e){return e===void 0?Je:G`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(rP,"renderAction");function Ji(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 G`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}n(Ji,"renderRow");function De(e){return Ji({label:e.label,value:e.value===void 0?void 0:G`<code>${e.value}</code>`})}n(De,"renderCodeRow");function nP(e){return un([Ji({label:"Error code",value:G`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),De({label:"Request ID",value:e.requestId}),De({label:"Time",value:e.timestamp})])}n(nP,"renderReference");function oP(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return un([Ji({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Ji({label:"Reason",value:r,block:!0}),De({label:"Stage",value:t.stage}),De({label:"Gateway route",value:t.routePath}),De({label:"Operation ID",value:t.operationId}),De({label:"Upstream",value:t.upstreamServerId}),De({label:"Auth profile",value:t.authProfileId}),De({label:"Upstream URL",value:t.upstreamUrl}),De({label:"Metadata URL",value:t.metadataUrl}),De({label:"HTTP status",value:t.httpStatus}),De({label:"Content type",value:t.contentType}),De({label:"Provider error",value:t.providerError}),De({label:"Provider error description",value:t.providerErrorDescription})])}n(oP,"renderDiagnostics");function sP(e){return e===void 0?Je:G`<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(sP,"renderUpstreamHtml");var qS="application/json",iP="application/x-www-form-urlencoded";function Vi(e,t){return new E({message:e,extensionMembers:{[x]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(Vi,"invalidRequestError");function aP(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(aP,"normalizeContentType");function cP(e,t){return e===t?!0:t===qS&&e.endsWith("+json")}n(cP,"contentTypeMatches");function dP(e,t){if(!t||t.length===0)return;let r=aP(e.headers.get("content-type"));if(!t.some(o=>cP(r,o)))throw Vi(`Request body must be ${t.join(" or ")}.`)}n(dP,"assertExpectedContentType");function uP(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 Vi(`${r} exceeded the maximum allowed size.`)}n(uP,"assertContentLengthWithinLimit");async function zS(e,t){let r=t.label??"Request body";dP(e,t.expectedContentTypes),uP(e,t.maxBytes,r);let o=await Pi(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>Vi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(zS,"readBoundedTextBody");async function NS(e,t){let r=await zS(e,{...t,expectedContentTypes:[qS]});try{return JSON.parse(r)}catch(o){throw Vi("Request body must be valid JSON.",o)}}n(NS,"readBoundedJsonBody");async function jS(e,t){let r=await zS(e,{...t,expectedContentTypes:[iP]});return new URLSearchParams(r)}n(jS,"readBoundedFormUrlEncodedBody");import{errors as $S,jwtVerify as LS,SignJWT as _d}from"jose";import{base64url as lP}from"jose";var pP="mcp-browser-login-pkce:",mP=new TextEncoder;async function hP(e){return crypto.subtle.importKey("raw",me(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}n(hP,"importHmacKey");async function Rd(e){let t=await hP(e.signingKey),r=mP.encode(`${pP}${e.stateId}`),o=await crypto.subtle.sign("HMAC",t,me(r));return Fr.parse(lP.encode(new Uint8Array(o)))}n(Rd,"deriveBrowserLoginPkceVerifier");async function DS(e){let t=await Rd(e),r=await Qs(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Br}}n(DS,"deriveBrowserLoginPkceParams");var fP={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{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=fP[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var gP=300,HS=m.string().min(1).optional(),yP=m.object({purpose:m.literal("gateway_browser_login"),transactionId:Aa,stateId:Ks,binding:Vo,authorizationServerIssuer:HS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),SP=m.object({purpose:m.literal("gateway_browser_login_return"),stateId:Ks,binding:Vo,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),RP=m.discriminatedUnion("purpose",[yP,SP]),_P=m.object({purpose:m.literal("gateway_authorization_setup"),transactionId:Aa,stateId:Ks,authorizationServerIssuer:HS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()});async function hn(){return Be({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"browser-login"),"derive")})}n(hn,"getBrowserLoginKey");async function BS(){return Be({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"authorization-csrf"),"derive")})}n(BS,"getCsrfKey");function FS(e){return{now:e.now??new Date,ttlSeconds:wd()}}n(FS,"readPendingTransactionDependencies");function wd(){return Ce().browserLogin.stateTtlSeconds}n(wd,"readBrowserLoginStateTtlSeconds");function wP(e){let t=pe();return ze(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(wP,"isLoopbackDevLoginUrl");async function JS(e){let t=Ce().browserLogin,r=pe(),o=new URL(xt("url")),s=new URL(r.actionPath("/oauth/callback"),Mt(e.requestUrl,e.requestHeaders));if(wP(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",xt("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===Br){let i=await DS({stateId:e.stateId,signingKey:await hn()});o.searchParams.set("code_challenge",i.codeChallenge),o.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return o}n(JS,"buildBrowserLoginUrl");function bP(e,t){return e.subjectId===t.subjectId}n(bP,"principalsMatch");function VS(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(VS,"toPendingPrincipal");function GS(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(ut(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 q("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:VS(e.principal)}}n(GS,"createTransactionRecord");async function KS(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 q("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.")}}n(KS,"startPendingTransaction");async function vP(e){return new _d({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await hn())}n(vP,"signBrowserLoginState");async function WS(e){return new _d({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Zs(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await BS())}n(WS,"signCsrfToken");async function bd(e){try{let{payload:t}=await LS(e,await hn(),{algorithms:[Se],issuer:ue,audience:ye}),r=RP.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 $S.JWTExpired?q("oauth_state_expired","Browser login state has expired.",t):q("oauth_state_invalid","Browser login state could not be verified.",t)}}n(bd,"verifyAnyBrowserLoginStateToken");async function CP(e){let t=await bd(e);if(t.kind!=="authorization")throw q("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}}n(CP,"verifyBrowserLoginStateToken");async function Gi(e){try{let{payload:t}=await LS(e,await BS(),{algorithms:[Se],issuer:ue,audience:ye}),r=_P.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof $S.JWTExpired?q("oauth_state_expired","Authorization setup state has expired.",t):q("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(Gi,"verifyCsrfToken");function vd(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(vd,"pendingStateErrorCode");function IP(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(IP,"toPendingAuthorizationGetResult");function TP(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(TP,"toPendingAuthorizationAdvanceResult");function Cd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":vd(e==="consumed_already"?"consumed_already":e)}n(Cd,"setupDecisionErrorCode");async function ZS(e){let t=e.now??new Date,r=await Gi(e.csrfToken),o=await H().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await se(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(t)});if(o.kind!=="marked")throw q(Cd(o.kind),"Authorization setup state is invalid, expired, or already used.");return YS({kind:"available",record:o.transaction})}n(ZS,"markSetupApproved");function YS(e){if(e.kind!=="available")throw q(vd(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw q("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(YS,"requireAwaitingSetup");function EP(e){if(!bP(e.currentBrowserPrincipal,e.transaction.principal))throw q("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(EP,"requireCurrentPrincipalMatches");async function XS(e){let t=e.now??new Date,r=wd(),o=Pa(),s=Zs(),i=await Ko({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await vP({transactionId:o,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=GS({id:o,transaction:e.transaction,currentStateHash:await se(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw q("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await KS({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw q("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await JS({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}}n(XS,"startAwaitingLogin");async function QS(e){let t=wd(),r=Zs(),o=await Ko({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new _d({purpose:"gateway_browser_login_return",stateId:r,binding:o.claim}).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await hn());return{browserLoginUrl:await JS({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:o.setCookie}}n(QS,"startReturnToBrowserLogin");async function eR(e){let{now:t,ttlSeconds:r}=FS(e),o=Pa(),s=await WS({transactionId:o,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=GS({id:o,transaction:e.transaction,currentStateHash:await se(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw q("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await KS({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw q("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}n(eR,"startAwaitingSetup");async function tR(e){let{now:t,ttlSeconds:r}=FS(e),o=await CP(e.browserLoginStateToken),s=await WS({transactionId:o.transactionId,ttlSeconds:r,authorizationServerIssuer:o.authorizationServerIssuer}),i=TP(await H().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await se(e.browserLoginStateToken),nextStateHash:await se(s),nextPhase:"awaiting_setup",principal:VS(e.principal),now:J(t)}));if(i.kind!=="advanced")throw q(vd(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw q("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}n(tR,"completeLogin");async function rR(e){let t=await Id(e);return EP({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(rR,"getSetup");async function Id(e){let t=e.now??new Date,r=await Gi(e.csrfToken);return YS(IP(await H().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await se(e.csrfToken),now:J(t)})))}n(Id,"getSetupTransaction");async function kP(e){let t=await Gi(e.csrfToken),r=pt(),o=J(ut(e.now,gP)),s=await H().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await se(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await se(r),authorizationCodeExpiresAt:o,grantId:ch(),now:J(e.now)});if(s.kind!=="approved")throw q(s.kind==="cancelled"?"oauth_state_invalid":Cd(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),Ki(i,t.authorizationServerIssuer),i}n(kP,"createAuthorizationCodeRedirectWithDecision");async function AP(e){let t=await Gi(e.csrfToken),r=await H().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await se(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:J(e.now)});if(r.kind!=="cancelled")throw q(r.kind==="approved"?"oauth_state_invalid":Cd(r.kind),"Authorization setup state is invalid, expired, or already used.");return PP({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}n(AP,"createCancelRedirectWithDecision");function Ki(e,t){t!==void 0&&Y()&&e.searchParams.set("iss",t)}n(Ki,"setAuthorizationResponseIssuer");function PP(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),Ki(t,e.authorizationServerIssuer),t}n(PP,"buildClientCancelRedirect");async function nR(e){let t=e.now??new Date;return kP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(nR,"approve");async function oR(e){let t=e.now??new Date;return AP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(oR,"cancel");import{createRemoteJWKSet as xP,errors as fn,jwtVerify as sR,SignJWT as MP}from"jose";var OP="zuplo_mcp_session",UP=m.object({purpose:m.literal("gateway_browser_session"),sub:Io,browserLoginOrigin:m.string().min(1),roles:m.array(m.string().min(1)).optional(),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),qP=m.object({id_token:m.string().min(1),token_type:m.string().min(1).optional(),expires_in:m.number().optional(),access_token:m.string().min(1).optional(),refresh_token:m.string().min(1).optional(),scope:m.string().min(1).optional()}),zP=m.object({error:m.string().min(1).optional(),error_description:m.string().min(1).optional(),error_uri:m.string().min(1).optional()}),NP=m.object({sub:Io,nonce:m.string().min(1)}).catchall(m.unknown()),Td;async function iR(){return Be({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>at(e,"browser-session"),"derive")})}n(iR,"getBrowserSessionKey");function kd(e,t){let r=ki(e,t);return{name:Vc(OP,r),secure:r}}n(kd,"browserSessionCookieName");function Ed(e,t){let{name:r,secure:o}=kd(e,t);return Go({name:r,value:"",maxAgeSeconds:0,secure:o})}n(Ed,"buildBrowserSessionEvictionCookie");function jP(e){let{name:t,secure:r}=kd(e.requestUrl,e.requestHeaders);return Go({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}n(jP,"serializeSessionCookie");function aR(){return new URL(xt("url")).origin}n(aR,"readBrowserLoginOrigin");function DP(e){let t=zP.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(DP,"readIdpErrorFields");function $P(e){return e instanceof fn.JWTExpired?"expired":e instanceof fn.JWTClaimValidationFailed?"claim":e instanceof fn.JWSSignatureVerificationFailed?"signature":e instanceof fn.JWKSNoMatchingKey?"jwks_no_match":e instanceof fn.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}n($P,"readJwtFailureKind");function LP(e){return e instanceof Error&&"cause"in e?e.cause:e}n(LP,"readErrorCause");function HP(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(HP,"readRuntimeGatewayCode");function BP(){if(!Td){let e=Ce();Td=xP(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Td}n(BP,"readFederatedJwks");function cR(e){if(!e.user)throw q("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ur(e.user,e.url)}n(cR,"resolveCurrentRequestPrincipal");async function gn(e,t={}){let r=Gc(e.headers.get("cookie")).get(kd(e.url,e.headers).name);if(!r)return{};try{let{payload:o}=await sR(r,await iR(),{algorithms:[Se],issuer:ue,audience:ye}),s=UP.parse(o);if(s.browserLoginOrigin!==aR())return{evictCookie:Ed(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 fn.JWTExpired?{evictCookie:Ed(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:Ed(e.url,e.headers)})}}n(gn,"readBrowserSession");async function Xo(e){let t=Ce().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:aR()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new MP(r).setProtectedHeader({alg:Se,typ:"JWT"}).setIssuer(ue).setAudience(ye).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await iR());return jP({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(Xo,"createBrowserSessionCookie");async function FP(e){let t=Ce(),r=xt("tokenUrl"),o=xt("clientId"),s=xt("clientSecret"),i=new URL(pe().actionPath("/oauth/callback"),Mt(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===Br){let c=await Rd({stateId:e.stateId,signingKey:await hn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await xi(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let y=DP(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:te(r),idpStatus:c.status,...y},"Federated browser login token exchange returned non-2xx from the identity provider"),q({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${y.idpError?` idp_error=${y.idpError}`:""}${y.idpErrorDescription?` idp_error_description=${y.idpErrorDescription}`:""})`)})}let u=qP.parse(d),p;try{({payload:p}=await sR(u.id_token,BP(),{issuer:t.oidc.issuer,audience:o}))}catch(y){let b={};throw Ie(b,"error",y),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:$P(y),idpHost:te(r),expectedIssuer:t.oidc.issuer,...b},"Federated id_token failed jose verification"),y}if(p.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:te(r),nonceMissingFromIdToken:p.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),q("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=NP.parse(p);return{principal:ur({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:ko,expiresAt:typeof p.exp=="number"?J(new Date(p.exp*1e3)):void 0}}}catch(c){let d=Ne(c)??HP(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:q("browser_login_verification_failed","Federated browser login callback could not be verified.",LP(c))}}n(FP,"exchangeFederatedAuthorizationCode");async function Ad(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return FP({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await gn(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw q("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(Ad,"resolveBrowserLoginCallbackIdentity");var JP=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function VP(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(VP,"readScheme");function GP(e){return e.protocol==="https:"}n(GP,"isSpecCompliantRedirectUri");function KP(e){let t=VP(e);return t.length>0&&t!=="http"&&t!=="https"&&!JP.has(t)}n(KP,"isNativeAppCustomSchemeRedirectUri");var uR=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>GP(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>ze(e),"accepts"),matches:n((e,t)=>ze(e)&&ze(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>KP(e),"accepts")}];function lR(e){let t=uR.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(lR,"evaluateBuiltInRedirectUriCompatibility");function dR(e){try{return new URL(e)}catch{return}}n(dR,"parseUrl");function pR(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=dR(e.registeredRedirectUri),r=dR(e.requestedRedirectUri);return t===void 0||r===void 0?!1:uR.some(o=>o.matches?.(t,r))}n(pR,"redirectUriMatchesBuiltInCompatibility");var WP=1e4,ZP=5*1024,YP=0,XP=2160*60*60,mR=["authorization_code","refresh_token",Vs,Ot],QP=["authorization_code","refresh_token"],hR=[sh],ex=["code"],tx=m.object({client_name:m.string().min(1).optional(),redirect_uris:m.array(m.string().min(1)).min(1),grant_types:m.array(m.enum(mR)).min(1).max(mR.length).optional(),authorization_grant_profiles_supported:m.array(m.enum(hR)).min(1).max(hR.length).optional(),response_types:m.array(m.enum(ex)).min(1).max(1).optional(),scope:m.literal(de).optional(),token_endpoint_auth_method:ah.optional(),jwks_uri:m.string().min(1).optional()});function rx(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&ze(t))&&t.pathname!=="/"}catch{return!1}}n(rx,"isCimdClientIdCandidate");function fR(e,t){throw new T("invalid_client",yh({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(fR,"invalidCimdClientError");function yn(e,t="invalid_request"){if(nx(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(lR({url:r}).kind==="rejected")throw new T(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(yn,"assertValidRedirectUri");function nx(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(nx,"hasForbiddenRawRedirectUriCharacter");async function ox(e){let{response:t,json:r}=await ey(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:YP,maxResponseBytes:ZP,timeoutMs:WP});if(!t.ok)throw q("invalid_request","CIMD metadata could not be fetched.");let o=Ws(r);for(let s of o.redirect_uris)yn(s,"invalid_request");if(o.jwks_uri!==void 0&&Po(o.jwks_uri),o.client_id!==e.clientId)throw q("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(ox,"fetchCimdMetadata");async function sx(e){let t=Ys(e),r=await ox({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(sx,"resolveCimdClient");async function Wi(e,t){let r=lt.parse(e);if(rx(r)){Ce().gateway.downstreamCimdEnabled||fR(r);try{return await sx(r)}catch(s){fR(r,s)}}let o=await H().readClient({clientId:r});if(o.kind==="found"){let s=o.client,i=Rh(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=Ws({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.")}n(Wi,"resolveClient");function gR(e,t){if(!e.metadata.redirect_uris.some(r=>pR({registeredRedirectUri:r,requestedRedirectUri:t})))throw q("invalid_request","redirect_uri is not registered for the client.")}n(gR,"assertRedirectRegistered");function ix(e){return e===void 0?[...QP]:Array.from(new Set(e))}n(ix,"normalizeGrantTypes");function ax(e){try{Po(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})}}n(ax,"assertValidDcrJwksUri");function cx(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?lt.parse(Sh({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):lt.parse(`dcr:${crypto.randomUUID()}`)}n(cx,"createDcrClientId");function Sn(e){if(e===void 0||e===de)return de;throw new T("invalid_request",`Only the ${de} scope is supported.`)}n(Sn,"assertSupportedOAuthScope");function hr(e,t,r){let o;try{o=new URL(t)}catch{throw new T("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new T("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!ze(o))throw new T("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=oe(e,r),i=Xr(),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}n(hr,"resolveResource");async function yR(e){let t;try{t=tx.parse(e)}catch(y){if(y instanceof m.ZodError){let b=y.issues.some(_=>_.path[0]==="redirect_uris");throw new T(b?"invalid_redirect_uri":"invalid_client_metadata",y.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:y})}throw y}for(let y of t.redirect_uris)yn(y,"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&&ax(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",s=o==="private_key_jwt"?"none":o,i=cx({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),a=Ws({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=ut(r,XP),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),p={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:ix(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:de,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 y=pt();h.hashedClientSecret=await se(y),h.clientSecretExpiresAt=J(c),p.client_secret=y,p.client_secret_expires_at=u,p.client_secret_issued_at=d}if((await H().registerClient(h)).kind==="already_exists")throw q("invalid_request","OAuth client is already registered.");return p}n(yR,"registerDownstreamClient");function dx(e){return e?.metadata?.idpSubjectTokenType!==Qr&&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(dx,"hasStoredIdJagSubjectTokenBinding");async function SR(e){let t=Yr(e.principal.subjectId);return(await H().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(SR,"readIdJagSubjectConnection");async function Pd(e){let t=we().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await SR({connection:t.connection,principal:e.principal});return!dx(r)}n(Pd,"requiresIdJagSubjectTokenBinding");async function RR(e){if(e.subjectToken===void 0)return;let t=we().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 SR({connection:t.connection,principal:e.principal});return H().upsertUpstreamConnection({id:r?.id??Xs(),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 gt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(RR,"bindIdJagSubjectTokenForAuthorizationTransaction");function _R(e){return G`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(_R,"renderShellIcon");function wR(e){return G`<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(wR,"renderActions");var bR=Fe('<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 vR(e){return G`<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(vR,"renderBannerWarning");var iH=Fe('<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>'),aH=Fe('<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 cH=Fe('<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 ux="data:,",CR=G`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);"`,IR=G`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 lx(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(lx,"safeGatewayConnectHref");function px(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(px,"deriveMode");function mx(e){return wR({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:CR,authorizeAttrs:Je})}n(mx,"renderActions");function xd(e,t,r,o){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=lx(s.connectUrl,t,o);if(i)return i}}n(xd,"firstUserConnectHref");function hx(e){let t=e.connectHref===void 0?Je:G`<a class="button button--primary" href="${e.connectHref}" ${IR}>Connect</a>`;return G`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${CR}><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(hx,"renderSetupActions");function fx(e){return e?G`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${IR}>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(fx,"renderReconnectAction");function gx(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(gx,"isRenderableIconHref");function TR(e){return e?.find(t=>gx(t.src))?.src}n(TR,"readIconHref");function yx(e){return TR(e.serverIcons)??(e.transportHost===void 0?void 0:jc(e.transportHost).src)}n(yx,"readUpstreamIconHref");function Sx(e){let t=TR(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=yx(r);if(o!==void 0)return o}}n(Sx,"readHeaderIconHref");function Rx(e){let t=e.setupMessage===void 0?Je:vR({icon:bR,message:e.setupMessage});return G`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(Rx,"renderBody");function Md(e){let t=px(e.upstreams),r=xd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=xd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=xd(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o: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=Sx({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?G`<footer class="card__footer">${hx({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:G`<footer class="card__footer">${fx(s)}${mx({state:e.state,gateway:e.gateway})}</footer>`;return ln(mn({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??ux,styles:pn,headerIcon:c===void 0?Je:_R({iconHref:c,fallbackIconHref:Tg}),heading:"Authorize access",subhead:Je,body:Rx({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}n(Md,"renderConsentPage");var _x=1e4,wx=2e3,bx=64*1024,ER=1024*1024,qR={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},Od="mcp-session-id",zR=1,vx=/^\d{4}-\d{2}-\d{2}$/,Cx;function Ud(){return{tools:[],prompts:[],resources:[]}}n(Ud,"emptyCapabilities");function kR(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":xa})}n(kR,"buildReadinessHeaders");async function AR(e){if(e.type==="bearer_token"){let o=kR();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=kR();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(AR,"buildAsyncCredentialHeaders");function Ix(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(ir.parse({jsonrpc:sr,id:zR,method:"initialize",params:{protocolVersion:xa,capabilities:{},clientInfo:qR}}))})}n(Ix,"buildInitializePreflight");function Tx(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",cr),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:sr,id:1,method:"server/discover",params:{_meta:{[wm]:cr,[bm]:{},[vm]:qR}}})})}n(Tx,"buildDiscoverPreflight");async function Ex(e){if(e.status!==400&&e.status!==404)return!1;let t=await NR(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}}n(Ex,"isModernRejectionOfInitialize");async function NR(e,t=bx){let r=new TextDecoder,o="";return jR(e,t,s=>{if(s===void 0)return o+r.decode();o+=r.decode(s,{stream:!0})})}n(NR,"readBoundedBody");async function jR(e,t,r){let o=e.body?.getReader();if(o===void 0)return;let s,i=new Promise(c=>{s=setTimeout(()=>c("timeout"),wx)}),a=(async()=>{let c=0;for(;;){let{done:d,value:u}=await o.read();if(d)return r(void 0);if(c+=u.byteLength,c>t)return;let p=r(u);if(p!==void 0)return p}})();try{let c=await Promise.race([a,i]);return c==="timeout"?void 0:c}catch{return}finally{clearTimeout(s),o.cancel().catch(()=>{})}}n(jR,"readBoundedChunks");async function qd(e){Ao(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),_x);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await mu.fetch(o)}finally{clearTimeout(r)}}n(qd,"runPreflight");function Qo(e){e.body?.cancel().catch(()=>{})}n(Qo,"releasePreflightBody");async function DR(e){if(He(e.headers.get("content-type"))!=="text/event-stream"){let o=await NR(e,ER);return o===void 0?void 0:PR(xR(o))?.result}let t=new As;return(await jR(e,ER,o=>{let s=o===void 0?t.end():t.push(o);for(let i of s){let a=i.data===void 0?void 0:PR(xR(i.data));if(a!==void 0)return a}}))?.result}n(DR,"readProbeResult");async function kx(e){let t=(await DR(e))?.protocolVersion;return typeof t=="string"&&vx.test(t)?t:void 0}n(kx,"readNegotiatedProtocolVersion");function PR(e){if(!(!MR(e)||e.id!==zR))return{result:MR(e.result)?e.result:void 0}}n(PR,"probeAnswer");function xR(e){try{return JSON.parse(e)}catch{return}}n(xR,"parseJson");function MR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(MR,"isRecord");async function Ax(e){let t=e.response.headers.get(Od);if(!t)return;let r=new Headers(e.headers);r.set(Od,t),r.delete("content-type"),e.protocolVersion!==void 0&&r.set("mcp-protocol-version",e.protocolVersion);try{let o=await qd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Qo(o)}catch{}}n(Ax,"terminatePreflightSession");async function $R(e){let{response:t}=e;if(e.discover===!0){let s=await DR(t),i=hi("server/discover",{result:s});return i!==void 0&&e.upstreamServerId!==void 0&&fi(e.upstreamServerId,i,{modernOnly:!0}),{kind:"ready",upstreamStatus:t.status,capabilities:Ud()}}let r=Ee()&&t.status>=200&&t.status<300&&t.headers.has(Od),o=r?await kx(t):void 0;return r||Qo(t),t.status>=200&&t.status<300?(Y()&&e.upstreamServerId!==void 0&&Hf(e.upstreamServerId),await Ax({...e,protocolVersion:o}),{kind:"ready",upstreamStatus:t.status,capabilities:Ud()}):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($R,"classifyResponse");function OR(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(OR,"connectRequiredResult");async function LR(e){let t=await qd(Ix(e));if(!Y()||!await Ex(t))return{response:t,discover:!1};try{let r=await qd(Tx(e));if(r.status>=200&&r.status<300)return Qo(t),{response:r,discover:!0};Qo(r)}catch{}return{response:t,discover:!1}}n(LR,"probeUpstream");async function Px(e){try{let t=await LR(e);return $R({response:t.response,discover:t.discover,upstreamUrl:e.upstreamUrl,headers:e.headers,upstreamServerId:e.upstreamServerId})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Px,"classifyPreflight");async function UR(e){try{return await Li(e)}catch(t){if(Ne(t)!=="upstream_token_refresh_unavailable")throw t;return{kind:"upstream_unavailable",message:"The upstream token endpoint could not refresh the connection. Retry later."}}}n(UR,"resolveReadinessCredential");async function xx(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:Ud()};let r=Hi(t.upstreamServerId,e.route.operationId),o=dn(r,e.subjectId),s=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await UR({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="upstream_unavailable")return a;if(a.kind==="connect_required")return OR(a.payload);let c=await AR(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 LR({upstreamUrl:t.mcpUrl,headers:c})}catch(f){return{kind:"upstream_unavailable",message:f instanceof Error?f.message:"Upstream MCP server readiness preflight failed."}}let{response:u}=d;if(u.status!==401)return $R({response:u,discover:d.discover,upstreamUrl:t.mcpUrl,headers:c,upstreamServerId:t.upstreamServerId});Qo(u);let p=await UR({request:i,routeAuth:s,forceRefresh:!0});if(p.kind==="upstream_unavailable")return p;if(p.kind==="connect_required")return OR(p.payload);let h=await AR(p.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Px({upstreamUrl:t.mcpUrl,headers:h,upstreamServerId:t.upstreamServerId})}n(xx,"checkUpstreamRouteReadinessImpl");function HR(e){return(Cx??xx)(e)}n(HR,"checkUpstreamRouteReadiness");function Mx(e){try{return new URL(e).host}catch{return}}n(Mx,"safeUrlHost");function BR(e){return e!==void 0&&e.length>0}n(BR,"hasItems");function Ox(e){let t=e.serverInfo?.icons;if(BR(t))return t;let r=Ci(e.mcpUrl);return r===void 0?void 0:[r]}n(Ox,"readServerIcons");async function Ux(e){let{authConfig:t,authMode:r,description:o,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",p=u&&r!=="id-jag",h=e.readiness??(u?Ch(e.connection):{connected:!0,status:"active"}),f=p?e.readiness?.connectUrl??(e.returnTo!==void 0?await Zc({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,y=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:o,transportHost:Mx(i),scopesRequested:BR(y)?y:void 0,serverIcons:Ox(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}}n(Ux,"buildSetupRequirement");function FR(e){let t=we().byOperationId.get(e);if(!t)throw q("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(FR,"requireRoute");async function zd(e){let t=FR(e.transaction.operationId),r=Yr(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 HR({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 Ux({connection:i,registeredConnection:o,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}})]}n(zd,"requirementsForSetup");async function Nd(e){let t=FR(e.transaction.operationId),r=await H().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,s={gatewayOrigin:oe(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(Nd,"consentContext");function jd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(jd,"hasUnresolvedUserUpstream");var qx=["mcp_user"],zx="dev-browser-user",Nx=["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(" "),jx=m.object({response_type:m.literal("code"),client_id:m.string().min(1),redirect_uri:m.string().min(1),resource:m.url(),code_challenge:m.string().min(43),code_challenge_method:Gm,state:m.string().min(1).optional(),scope:m.literal(de).default(de)}),Dx=m.enum(["continue","approve","cancel"]).default("continue"),$x=m.object({state:m.string().min(1),decision:Dx}),Bt=class extends Error{static{n(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 JR(e){return typeof e=="string"&&e.length>0?e:void 0}n(JR,"readQueryString");function Lx(e,t){let r=JR(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new T("invalid_target",Nx)}let o=mh(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new T("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(Lx,"requireAuthorizeResource");async function Hx(e,t){let r={};t!==void 0&&(r.context=t);let o=await gn(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let s=cR(e);return{principal:s,setCookie:await Xo({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(Hx,"resolveBrowserPrincipal");async function Bx(e,t){let r={};t!==void 0&&(r.context=t);let o=await gn(e,r);if(!o.principal)throw q("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(Bx,"requireSetupPrincipal");function VR(e){return`${pe().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(VR,"buildSetupReturnTo");async function GR(e){let t=await zd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:VR(e.csrfToken)}),r=await Nd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:Md({state:e.csrfToken,operationId:e.transaction.operationId,gateway:pe(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(o.setCookies=e.setCookies),o}n(GR,"renderSetup");function Fx(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(Fx,"toAuthorizationTransactionClient");async function Dd(e,t={}){let r=jx.parse({...e.query,resource:Lx(e,t.operationId),state:JR(e.query.state)}),o=Sn(r.scope);yn(r.redirect_uri,"invalid_request");let s=Y()?t.operationId===void 0?Mt(e.url,e.headers):dh({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=lt.parse(r.client_id),c=await Wi(r.client_id,i);gR(c,r.redirect_uri);try{let d=hr(e.url,r.resource,e.headers),u=Fx(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:d.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&Q(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type}});let p={clientId:c?.clientId??a,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state},authorizationServerIssuer:s},{principal:h,setCookie:f}=await Hx(e,t.context),y=h===void 0?!1:await Pd({operationId:d.operationId,principal:h});if(!h||y){let _=await XS({transaction:p,requestUrl:e.url,requestHeaders:e.headers,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:d.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:_.browserLoginUrl,setCookies:[...f===void 0?[]:[f],_.browserBindingCookie]}}let b=await eR({transaction:p,principal:h,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:d.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&Q(t.context,{eventType:V.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),GR({transaction:b.transaction,csrfToken:b.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw Jx({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}n(Dd,"authorizeDownstreamClient");function Jx(e){if(e.cause instanceof Bt)return e.cause;let t=Vx(e.cause);return t?new Bt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}n(Jx,"toDownstreamAuthorizeRedirectError");function Vx(e){if(e instanceof T)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof m.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(Vx,"mapToOAuthRedirectError");async function KR(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let u=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,p=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...u===void 0?{}:{idpErrorDescription:u},...p===void 0?{}:{idpErrorUri:p}},"Identity provider redirected browser-login callback with an error"),q("provider_access_denied",u??"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"),q("oauth_state_invalid","Browser login callback is missing state.");let s=await bd(o),i=await Ai({purpose:"login",claim:s.binding,request:e});if(!i.matched&&jt())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"),q("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=Gx(i.payload),p=await Ad(a);return{kind:"redirect",location:new URL(u,oe(e.url,e.headers)),setCookies:[await Xo({principal:p.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await Ad(a),d=await tR({browserLoginStateToken:o,principal:c.principal});if(await RR({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await Pd({operationId:d.transaction.operationId,principal:c.principal}))throw q("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return GR({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await Xo({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}n(KR,"completeBrowserLoginCallback");function Gx(e){let t=To(e),r=pe().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 q("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}n(Gx,"readConnectReturnTo");async function WR(e){let t=await QS(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}n(WR,"startConnectBrowserLogin");async function ZR(e){let t=Ce(),r=new URL(e.url);if(!ze(r))throw q("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 q("oauth_state_invalid","Local browser login is missing state.");let s=pe().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,oe(e.url)),a=new URL(oe(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw q("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",o);let c={subjectId:Io.parse(zx),roles:qx};return{kind:"redirect",location:i,setCookies:[await Xo({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}n(ZR,"completeLocalDevBrowserLogin");function Kx(e){let t=e.method==="POST"?e.body:e.query;return $x.parse(t)}n(Kx,"readSetupContinueRequest");async function YR(e){let{state:t,decision:r}=Kx({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,s=await Id({csrfToken:t,now:o}),i=await Bx(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await oR({csrfToken:t,currentBrowserPrincipal:i,now:o})};let a=await rR({csrfToken:t,currentBrowserPrincipal:i,now:o}),c=await zd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:VR(t)});if(r==="approve"&&jd(c)&&await ZS({csrfToken:t,currentBrowserPrincipal:i,now:o}),jd(c)){let d=await Nd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:Md({state:t,operationId:a.operationId,gateway:pe(),upstreams:c,...d})}}return{kind:"redirect",location:await nR({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(YR,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as aM,decodeJwt as cM,errors as ts,jwtVerify as dM}from"jose";import{createRemoteJWKSet as Wx,decodeJwt as Zx,decodeProtectedHeader as Yx,errors as es,jwtVerify as Xx}from"jose";var r_=30,ie=m.string().min(1),Qx=m.union([ie,m.array(ie).min(1)]),eM=m.union([ie,m.array(ie).min(1)]),tM=m.object({type:ie,locations:m.array(ie).optional(),actions:m.array(ie).optional(),datatypes:m.array(ie).optional(),identifier:ie.optional(),privileges:m.array(ie).optional()}).passthrough(),rM=m.object({iss:m.url(),sub:ie,aud:Qx,client_id:ie,resource:eM.optional(),scope:ie.optional(),authorization_details:m.array(tM).optional(),jti:ie,iat:m.number().int(),nbf:m.number().int().optional(),exp:m.number().int(),tenant:ie.optional(),aud_tenant:ie.optional(),aud_sub:ie.optional(),sub_id:ie.optional(),act:m.unknown().optional(),email:ie.optional(),auth_time:m.number().int().optional(),acr:ie.optional(),amr:m.array(ie).optional(),cnf:m.unknown().optional()}).passthrough();function $e(e){throw new T("invalid_grant",e)}n($e,"throwInvalidGrant");function nM(e){return e instanceof es.JWTExpired?"expired":e instanceof es.JWTClaimValidationFailed?"claim":e instanceof es.JWSSignatureVerificationFailed?"signature":e instanceof es.JWKSNoMatchingKey?"jwks_no_match":e instanceof es.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}n(nM,"readJwtFailureKind");function oM(e){return Array.isArray(e.aud)?(e.aud.length!==1&&$e("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(oM,"readSingleAudience");function XR(e){try{let t=rM.parse(e);return oM(t),t}catch(t){if(t instanceof T)throw t;$e("ID-JAG claims are invalid.")}}n(XR,"parseIdJagClaims");function sM(e,t){e.idJag.enabled||$e("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&$e("ID-JAG issuer is not trusted."),r}n(sM,"readTrustedIssuer");function iM(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(iM,"readGrantedAuthorizationDetails");function QR(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.")}n(QR,"assertClientBinding");function e_(e){e.cnf!==void 0&&$e("ID-JAG cnf-bound assertions require DPoP support.")}n(e_,"assertProofOfPossessionNotDeferred");function t_(e){let t=Math.floor(e.now.getTime()/1e3)+r_;e.claims.iat>t&&$e("ID-JAG iat must not be in the future.")}n(t_,"assertIssuedAtNotInFuture");async function n_(e){let t;try{t=Yx(e.assertion)}catch{$e("ID-JAG assertion is malformed.")}t.typ!==Ea&&$e('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=XR(Zx(e.assertion))}catch(c){if(c instanceof T)throw c;$e("ID-JAG assertion is malformed.")}let o=Mt(e.requestUrl,e.requestHeaders),s=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&s.push(e.requestedResource);let i=sM(e.config,r.iss);s.includes(r.iss)&&$e("ID-JAG issuer must be different from the gateway."),QR({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),e_(r),t_({claims:r,now:e.now});let a;try{let c=Wx(new URL(i.jwksUrl)),{payload:d}=await Xx(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:r_,typ:Ea});a=XR(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:nM(c)},"OAuth ID-JAG assertion verification failed"),$e("ID-JAG assertion verification failed.")}return QR({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),e_(a),t_({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:hh({issuer:a.iss,subject:a.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:iM({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(n_,"verifyIdJagAssertion");var uM=new Set(["authorization_code","refresh_token",Ot]),lM=1e4,pM=32*1024,mM=2,hM=3600,$d=m.object({client_id:m.string().min(1).optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),fM=m.discriminatedUnion("grant_type",[$d.extend({grant_type:m.literal("authorization_code"),code:m.string().min(1),redirect_uri:m.string().min(1),code_verifier:Fr,resource:m.url().optional(),scope:m.literal(de).optional()}),$d.extend({grant_type:m.literal("refresh_token"),refresh_token:m.string().min(1),resource:m.url().optional(),scope:m.literal(de).optional()}),$d.extend({grant_type:m.literal(Ot),assertion:m.string().min(1),resource:m.url().optional(),scope:m.literal(de).optional(),authorization_details:m.string().min(1).optional()})]);function gM(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!uM.has(t)))throw new T("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(gM,"assertSupportedGrantType");var yM=m.object({token:m.string().min(1),client_id:m.string().min(1).optional(),token_type_hint:m.string().optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),SM=m.object({keys:m.array(m.record(m.string(),m.unknown())).min(1)}).passthrough();function s_(){return Ce().gateway.accessTokenTtlSeconds}n(s_,"readAccessTokenTtlSeconds");function RM(){return Ce().gateway.refreshTokenTtlSeconds}n(RM,"readRefreshTokenTtlSeconds");function o_(e,t){let r=s_(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,o);return{expiresAt:J(ut(e,s)),expiresIn:s}}n(o_,"calculateAccessTokenExpiresAt");function _M(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]}n(_M,"readIdJagResource");function wM(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}n(wM,"readIdJagGrantedAuthorizationDetails");function bM(e){if(e.claimScope?.split(/\s+/).includes(de)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return de;if(e.claimScope===void 0)throw new T("invalid_grant",`ID-JAG must include ${de} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(de))throw new T("invalid_grant",`ID-JAG scope must include ${de}.`);return de}n(bM,"readIdJagGrantedScope");function vM(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.")}n(vM,"assertNoDpopProofForIdJag");function i_(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.")}}n(i_,"readBasicClientSecret");function a_(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=cM(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.")}n(a_,"resolveAuthenticatedClientId");function CM(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"}:{}}n(CM,"resolveClientSecretInput");function IM(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(IM,"hasClientAssertion");function TM(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(pe().actionPath(e.pathname),oe(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(TM,"buildEndpointAudience");function EM(e){return e instanceof ts.JWTExpired?"expired":e instanceof ts.JWTClaimValidationFailed?"claim":e instanceof ts.JWSSignatureVerificationFailed?"signature":e instanceof ts.JWKSNoMatchingKey?"jwks_no_match":e instanceof ts.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}n(EM,"readJwtFailureKind");async function kM(e){let{response:t,json:r}=await ty(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:mM,maxResponseBytes:pM,timeoutMs:lM});if(!t.ok)throw new T("invalid_client","Client JWKS could not be fetched.");return SM.parse(r)}n(kM,"fetchClientJwks");async function AM(e){if(e.clientAssertionType!==Gs||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=lt.parse(e.clientId),r=await Wi(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 o=r.metadata.jwks_uri;if(o===void 0)throw new T("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=TM({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await kM({jwksUri:o,context:e.context}),{payload:a}=await dM(e.clientAssertion,aM(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+hM;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:EM(i)},"OAuth private_key_jwt client authentication failed"),new T("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(AM,"verifyPrivateKeyJwtClientAssertion");async function PM(e){let t=lt.parse(e.clientId);if(_h(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 se(e.clientSecret)}}n(PM,"buildRuntimeHttpClientAuth");async function c_(e){if(IM({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 AM(e)}let t=CM({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return PM({clientId:e.clientId,...t})}n(c_,"resolveRuntimeHttpClientAuth");async function d_(e){gM(e.body);let t=fM.parse(e.body),r=i_(e.authorizationHeader),o=a_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await c_({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 xM({parsed:t,clientId:o,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(d_,"exchangeDownstreamToken");async function xM(e){if(e.parsed.grant_type==="authorization_code"){yn(e.parsed.redirect_uri,"invalid_request"),Sn(e.parsed.scope),e.parsed.resource!==void 0&&hr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=pt(),d=pt(),u=J(ut(e.now,RM())),p=o_(e.now,u),h=await H().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await se(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Qs(e.parsed.code_verifier),currentRefreshTokenHash:await se(c),accessTokenHash:await se(d),grantExpiresAt:u,accessTokenExpiresAt:p.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&&Q(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:p.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===Ot){Sn(e.parsed.scope),vM(e.requestHeaders);let c=await n_({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:Ce()}),d=_M({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=hr(e.requestUrl??d,d,e.requestHeaders),p=wM({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=bM({claimScope:c.claims.scope,grantedAuthorizationDetails:p}),f=pt(),y=J(new Date(c.claims.exp*1e3)),b=o_(e.now,y),_=await H().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await se(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:p,accessTokenExpiresAt:b.expiresAt,now:J(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:y}});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&&Q(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:b.expiresIn,scope:_.grant.scope,resource:_.grant.resource,...p===void 0?{}:{authorization_details:p}}}Sn(e.parsed.scope),e.parsed.resource!==void 0&&hr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await se(e.parsed.refresh_token),r=e.parsed.refresh_token,o=pt(),s=J(ut(e.now,s_())),i=await H().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await se(o),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.");hr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&Q(e.context,{eventType:V.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(xM,"exchangeDownstreamTokenWithRuntimeHttp");async function u_(e){let t=yM.parse(e.body),r=i_(e.authorizationHeader),o=a_({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await H().revokeOAuthToken({clientAuth:await c_({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 se(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:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&Q(e.context,{eventType:V.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(u_,"revokeDownstreamToken");var MM=64*1024,OM=16*1024,UM="text/html; charset=utf-8";function qM(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(qM,"formDataToObject");async function zM(e){return NS(e,{maxBytes:MM,label:"Request body"})}n(zM,"readJsonBody");async function Hd(e){return qM(await jS(e,{maxBytes:OM,label:"Request body"}))}n(Hd,"readFormBody");async function l_(e,t,r){let o=Ne(r),s=r instanceof m.ZodError?Ft(r):void 0,i={code:o??(r instanceof m.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),Zr(e,t,i)}n(l_,"handleProblem");function p_(e){return e?.requestId}n(p_,"readBrowserRequestId");function m_(e){if(!(e instanceof E))return;let t=e.extensionMembers?.[Vr];return typeof t=="string"?t:void 0}n(m_,"readUpstreamHtmlError");function Rn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Rn,"readRuntimeErrorExtensionString");function NM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(NM,"readRuntimeErrorExtensionNumber");function jM(e){try{return new URL(e.url).pathname}catch{return}}n(jM,"readBrowserRequestPath");function fr(e){let t={code:e.code,requestId:e.requestId,routePath:jM(e.request),underlyingError:e.underlyingError};return e.error instanceof E&&(t.httpStatus=NM(e.error,ot),t.contentType=Rn(e.error,Jr),t.upstreamUrl=Rn(e.error,st),t.upstreamServerId=Rn(e.error,Co),t.metadataUrl=Rn(e.error,Gr),t.providerError=Rn(e.error,Kr),t.providerErrorDescription=Rn(e.error,Wr)),t}n(fr,"buildBrowserErrorDiagnostic");function rs(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(rs,"oauthErrorResponse");function DM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(DM,"readOAuthProtocolHeaders");function $M(e,t){let r=Ze("internal_server_error");return rs({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:DM(e,t)})}n($M,"oauthProtocolErrorResponse");function Ld(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Ld,"readZodOAuthErrorCode");function LM(e){let t={error:Ld(e)},r=Ft(e);return r!==void 0&&(t.errorDescription=r),rs(t)}n(LM,"oauthZodErrorResponse");function HM(e){let t=Ne(e);if(t===void 0)return;let r=Ze(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:FM(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,rs(o)}n(HM,"oauthGatewayProblemResponse");function BM(){let t={error:"server_error",status:500,errorDescription:Ze("internal_server_error").publicDetail};return rs(t)}n(BM,"oauthFallbackErrorResponse");function FM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(FM,"readOAuthStatus");function Bd(e,t={}){return e instanceof Bt?g_(e):e instanceof T?$M(e,t):e instanceof m.ZodError?LM(e):HM(e)??BM()}n(Bd,"oauthProblemResponse");function Fd(e,t,r){let o=Ht(e.url),s=p_(t);if(r instanceof Bt)return g_(r);if(r instanceof T){let c=Ze("internal_server_error");return Ve({host:o,kind:JM(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:fr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof m.ZodError)return Ve({host:o,kind:"invalid_request",detail:Ft(r)??"The authorization request was invalid.",developerDetail:Ft(r)??"The authorization request was invalid.",code:Ld(r),diagnostic:fr({request:e,requestId:s,code:Ld(r),underlyingError:Ft(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=Ne(r);if(i!==void 0){let c=Ze(i);return Ve({host:o,kind:f_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:fr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:m_(r),status:c.status})}let a=Ze("internal_server_error");return Ve({host:o,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:fr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}n(Fd,"browserOAuthProblemResponse");function h_(e,t,r){let o=Ht(e.url),s=p_(t),i=Ne(r);if(i!==void 0){let c=Ze(i);return Ve({host:o,kind:f_(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:fr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:m_(r),status:c.status})}if(r instanceof m.ZodError)return Ve({host:o,kind:"invalid_request",detail:Ft(r)??"The authorization request was invalid.",developerDetail:Ft(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:fr({request:e,requestId:s,code:"invalid_request",underlyingError:Ft(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=Ze("internal_server_error");return Ve({host:o,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:fr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}n(h_,"browserGatewayProblemResponse");function JM(e){return e==="server_error"?"internal_error":"invalid_request"}n(JM,"readOAuthBrowserErrorKind");function f_(e){if(Ze(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":case"upstream_token_refresh_unavailable":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(f_,"readGatewayBrowserErrorKind");function Rt(e,t,r){let o={event:t},s=!1;if(r instanceof T)o.oauthError=r.errorCode,o.status=r.status,Ie(o,"error",r);else if(r instanceof Bt)o.oauthError=r.errorCode,Ie(o,"error",r);else if(r instanceof m.ZodError){o.code="invalid_request",Ie(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=Ne(r);if(i!==void 0){let a=Ze(i);o.code=i,o.status=a.status,a.oauthError!==void 0&&(o.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",Ie(o,"error",r)}else s=!0,Ie(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(Rt,"logUnexpectedOAuthHandlerError");function g_(e){let t;try{t=new URL(e.redirectUri)}catch{return rs({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),Ki(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(g_,"downstreamAuthorizeRedirectErrorResponse");function Ft(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(Ft,"formatZodErrorDetail");function VM(e,t){let r={event:"browser_login_callback_failed",code:Ne(t)??"invalid_request"};Ie(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(VM,"logBrowserLoginCallbackFailure");function y_(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(y_,"redirectResultResponse");function Zi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":UM,"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 y_(e)}n(Zi,"authorizeResultResponse");async function S_(e,t){try{return Response.json(uh(e.url,e.headers))}catch(r){return Rt(t,"oauth_authorization_server_metadata_failed",r),l_(e,t,r)}}n(S_,"authorizationServerMetadataHandler");async function R_(e,t){try{let r=Ma(e.params.routePath);return Response.json(lh({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return Rt(t,"oauth_authorization_server_metadata_failed",r),l_(e,t,r)}}n(R_,"scopedAuthorizationServerMetadataHandler");async function __(e,t){try{let r=await yR(await zM(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"),Q(t,{eventType:V.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 Rt(t,"oauth_register_failed",r),Bd(r)}}n(__,"registerHandler");async function w_(e,t){try{return Zi(await Dd(e,{context:t}))}catch(r){return Rt(t,"oauth_authorize_failed",r),Fd(e,t,r)}}n(w_,"authorizeHandler");async function b_(e,t){try{let r=Ma(e.params.routePath);return Zi(await Dd(e,{operationId:r.operationId,context:t}))}catch(r){return Rt(t,"oauth_authorize_scoped_failed",r),Fd(e,t,r)}}n(b_,"scopedAuthorizeHandler");async function v_(e,t){try{let r=await KR(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Zi(r)}catch(r){return VM(t,r),h_(e,t,r)}}n(v_,"callbackHandler");async function C_(e,t){try{return y_(await ZR(e))}catch(r){return Rt(t,"oauth_dev_login_failed",r),Fd(e,t,r)}}n(C_,"devLoginHandler");async function I_(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await YR({request:e,body:e.method==="POST"?await Hd(e):void 0,context:t});return Zi(r)}catch(r){return Rt(t,"oauth_setup_failed",r),h_(e,t,r)}}n(I_,"setupHandler");async function T_(e,t){try{return Response.json(await d_({body:await Hd(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 Rt(t,"oauth_token_failed",r),Bd(r)}}n(T_,"tokenHandler");async function E_(e,t){try{return await u_({body:await Hd(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 Rt(t,"oauth_revoke_failed",r),Bd(r)}}n(E_,"revokeHandler");var k_="0.0.0",GM=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function ns(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}n(ns,"firstNonBlank");function os(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}n(os,"clampToCodePoints");function KM(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(KM,"shortHash");function A_(e,t){let r=[...e];if(r.length<=t)return e;let o=`-${KM(e)}`;return t<=o.length?r.slice(0,t).join(""):`${r.slice(0,t-o.length).join("")}${o}`}n(A_,"clampNameSegment");function WM(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}n(WM,"sanitizeRegistryNameSegment");var ZM=/^\d{1,3}(\.\d{1,3}){3}$/u;function YM(e){let t=new URL(e).hostname.toLowerCase();if(ZM.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(YM,"buildRegistryNamespaceFromOrigin");function XM(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(XM,"sanitizeWebsiteUrl");function QM(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&&!GM.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(QM,"sanitizeIcons");function eO(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}n(eO,"localNameFromRoutePath");function P_(e){return e.includes("{")||e.includes(":")}n(P_,"isParameterizedRoutePath");var tO=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function x_(e){let t=ns(e)??k_;return tO.test(t)?k_:os(t,255)}n(x_,"sanitizeRegistryVersion");function M_(e){let t=A_(YM(e.origin),150),r=200-t.length-1,o=new Set,s=[];function i(c){let d=A_(WM(c),r),u=d;for(let p=2;o.has(u);p++){let h=`-${p}`;u=`${[...d].slice(0,r-h.length).join("")}${h}`}return o.add(u),u}n(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}}}})}n(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if(P_(c.routePath))continue;let d=c.connection,u=d?.serverInfo,p=os(ns(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=ns(u?.title,d?.displayName),f=XM(u?.websiteUrl),y=QM(u?.icons);a(c.operationId,{description:p,...h===void 0?{}:{title:os(h,100)},version:x_(u?.version),...f===void 0?{}:{websiteUrl:f},...y===void 0?{}:{icons:y},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if(P_(c.routePath))continue;let d=c.operationId??eO(c.routePath),u=os(ns(c.summary,c.description,c.serverName,c.operationId,d)??d,100),p=ns(c.serverName);a(d,{description:u,...p===void 0?{}:{title:os(p,100)},version:x_(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}n(M_,"buildMcpRegistryDirectory");var rO=30,O_=100;function et(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}n(et,"registryErrorResponse");function Vd(e){return M_({registry:we(),origin:oe(e.url,e.headers)})}n(Vd,"readEntries");function Jd(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}n(Jd,"decodePathParam");function U_(e,t){return e.find(r=>r.name===t)}n(U_,"findEntryByName");function nO(e){let t=e.get("limit");return t===null?{ok:!0,value:rO}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),O_)}}n(nO,"parseLimit");function oO(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(oO,"parseCursor");var sO=/^(\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 iO(e){let t=sO.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(iO,"isValidRfc3339Timestamp");async function q_(e,t){let r=new URL(e.url).searchParams,o=nO(r);if(!o.ok)return et(400,`Invalid 'limit' parameter: expected a positive integer (max ${O_}).`);let s=oO(r);if(!s.ok)return et(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&&!iO(i))return et(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=Vd(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+o.value),p=s.value+o.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...p<d.length?{nextCursor:String(p)}:{}}})}n(q_,"listMcpRegistryServersHandler");async function z_(e,t){let r=Jd(e.params.serverName);if(!r.ok)return et(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=U_(Vd(e),r.value);return o===void 0?et(404,"Server not found"):Response.json({servers:[o.response],metadata:{count:1}})}n(z_,"listMcpRegistryServerVersionsHandler");async function N_(e,t){let r=Jd(e.params.serverName);if(!r.ok)return et(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let o=Jd(e.params.version);if(!o.ok)return et(400,"Invalid version: malformed encoding.");let s=U_(Vd(e),r.value);return s===void 0?et(404,"Server not found"):o.value!=="latest"&&o.value!==s.response.server.version?et(404,"Server or version not found"):Response.json(s.response)}n(N_,"getMcpRegistryServerVersionHandler");function Yi(e,t){return(r,o)=>et(e,t)}n(Yi,"createWriteNotSupportedHandler");async function j_(e,t){return et(404,"Not found")}n(j_,"mcpRegistryNotFoundHandler");var D_=Yi(501,"Publishing is not supported by this registry"),$_=Yi(501,"Updates are not supported by this registry"),L_=Yi(501,"Deletion is not supported by this registry"),Gd=Yi(403,"You do not have publish or edit permissions for this server");function H_(e){return G`<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(H_,"renderBrowserResult");var aO="text/html; charset=utf-8";function cO(e){return mn({title:e.title,iconHref:Nc(e.host),styles:pn,headerIcon:Fi("success"),heading:e.title,subhead:G`<p class="card__subtitle">${e.detail}</p>`,body:H_({steps:un(e.steps.map(t=>G`<li>${t}</li>`))}),footer:""})}n(cO,"browserResultHtml");function dO(e,t=200){return new Response(ln(e),{status:t,headers:{"content-type":aO,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(dO,"browserResultResponse");function B_(e){return dO(cO(e))}n(B_,"browserConnectionSuccessResponse");function Xi(e,t,r={}){let o=Wm(t);return Ve({host:e,kind:uO(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(Xi,"browserConnectionFailureResponse");function uO(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(uO,"readCallbackFailureBrowserErrorKind");var lO={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},F_=Symbol("upstream-request");function ss(e,t){Object.defineProperty(e,F_,{configurable:!0,value:t})}n(ss,"setUpstreamRequestContext");function pO(e){let t=e[F_];if(!t)throw new ve("Upstream request context has not been set");return t}n(pO,"readUpstreamRequestContext");function mO(e,t){return t.some(r=>r===e)}n(mO,"requestContextMatchesKind");function hO(e){return typeof e=="string"?[e]:e}n(hO,"toExpectedKinds");function is(e,t){let r=pO(e),o=hO(t);if(!mO(r.kind,o)){let s=lO[o[0]];throw new ve(`${s} request context has not been set`)}return r}n(is,"requireUpstreamRequestContext");function Jt(e){if(typeof e=="string"&&e.length!==0)return e}n(Jt,"readOptionalQueryString");function fO(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new ve(`Validated path parameter ${t} is missing`);return gO(r,t)}n(fO,"requirePathString");function gO(e,t){try{return decodeURIComponent(e)}catch(r){throw new E({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[x]:"invalid_request"}},{cause:r})}}n(gO,"decodePathString");function yO(e){let t=Jt(e);return t?Fs.parse(t):void 0}n(yO,"readOptionalOperationId");function SO(e){let t=we().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new E({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[x]:"unknown_upstream_server"}})}n(SO,"readRegisteredAuthProfileId");function RO(e){let t=yO(e);if(!t)throw new E({message:"operationId query parameter is required.",extensionMembers:{[x]:"invalid_request"}});return t}n(RO,"readRequiredOperationId");async function Kd(e){return e.redirect?Ve({host:Ht(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?Me.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):Me.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}n(Kd,"browserConnectRefusal");function _O(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(_O,"withSetCookies");async function wO(e){let{request:t,context:r,ticket:o,redirect:s}=e;if(Jm(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 Kd({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 gn(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return _O(await Kd({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=To(`${d.pathname}${d.search}`);if(u===void 0)throw new ve("Connect request path is empty");let p=await WR({returnTo:u,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:p.location.toString(),"cache-control":"no-store"});for(let f of[...a,p.setCookie])h.append("set-cookie",f);return new Response(null,{status:302,headers:h})}let c=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 Kd({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(wO,"requireTicketOwnerBrowser");async function bO(e,t,r){let o=Hi(r,RO(e.query.operationId));if(o.authMode==="id-jag")throw new E({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[x]:"invalid_request"}});let s=e.query.redirect==="true",i=Jt(e.query.browserTicket);if(e.user){if(i)throw new E({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[x]:"invalid_request"}});let d=ur(e.user,e.url),u={kind:"connect",...dn(o,d.subjectId),redirect:s},p=To(Jt(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!i)throw new E({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[x]:"authentication_required"}});let a=await gy(i);if(a.ownerMode!==o.ownerMode||a.upstreamServerId!==o.upstreamServerId||a.authProfileId!==o.authProfileId||a.operationId!==o.operationId)throw new E({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[x]:"oauth_callback_mismatch"}});if(jt()){let d=await wO({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await yy(a);let c=Js(a);switch(o.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new E({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[x]:"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 E({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[x]:"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(bO,"resolveConnectContext");async function vO(e,t,r){let o=Ym.parse(fO(e,"connection"));switch(r){case"connect":{let s=await bO(e,t,o);if(s instanceof Response)return s;ss(e,s);return}case"callback":{let s=Jt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:o,error:s},d=Jt(e.query.error_description);d!==void 0&&(c.errorDescription=d),ss(e,c);return}let i=Jt(e.query.code),a=Jt(e.query.state);if(i&&a){let c=Jt(e.query.iss);ss(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:a,...c===void 0?{}:{iss:c}});return}ss(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":ss(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:SO(o)});return}}n(vO,"resolveUpstreamRequestInbound");async function CO(e,t,r){try{return await vO(e,t,r)}catch(o){let s=o instanceof E?o.extensionMembers?.[x]:void 0,i=o instanceof Error?o.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return Me.badRequest(e,t,{code:s,detail:i});case"authentication_required":return Me.unauthorized(e,t,{code:s,detail:i});default:throw o}}}n(CO,"applyUpstreamRequestContext");function Qi(e,t){return n(async(o,s)=>{let i=await CO(o,s,e);return i||t(o,s)},"wrapped")}n(Qi,"withUpstreamRequestContext");var IO=["callback_authorization_code","callback_provider_error","callback_invalid"];function Wd(e){try{return new URL(e.url).pathname}catch{return}}n(Wd,"readBrowserRequestPath");function TO(e){return"cause"in e?e.cause:void 0}n(TO,"readErrorCause");function EO(e){return e.stack?.split(`