@zuplo/cli 7.15.0 → 7.15.3
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.
- package/LICENSE.third-party.txt +236 -0
- package/LICENSE.txt +5 -78
- package/README.md +18 -3
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/package.json +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
- package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.js +17 -2
- package/node_modules/@posthog/core/dist/featureFlagLocalEvaluation.mjs +17 -2
- package/node_modules/@posthog/core/dist/logs/index.d.ts +18 -1
- package/node_modules/@posthog/core/dist/logs/index.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/logs/index.js +22 -3
- package/node_modules/@posthog/core/dist/logs/index.mjs +22 -3
- package/node_modules/@posthog/core/dist/metrics/index.d.ts +9 -0
- package/node_modules/@posthog/core/dist/metrics/index.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/metrics/index.js +13 -0
- package/node_modules/@posthog/core/dist/metrics/index.mjs +13 -0
- package/node_modules/@posthog/core/dist/privacy.d.ts +6 -1
- package/node_modules/@posthog/core/dist/privacy.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/privacy.js +69 -10
- package/node_modules/@posthog/core/dist/privacy.mjs +65 -9
- package/node_modules/@posthog/core/dist/traces/span.d.ts +6 -0
- package/node_modules/@posthog/core/dist/traces/span.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/traces/span.js +18 -0
- package/node_modules/@posthog/core/dist/traces/span.mjs +18 -0
- package/node_modules/@posthog/core/package.json +2 -2
- package/node_modules/@posthog/core/src/featureFlagLocalEvaluation.ts +23 -2
- package/node_modules/@posthog/core/src/logs/index.spec.ts +119 -0
- package/node_modules/@posthog/core/src/logs/index.ts +57 -3
- package/node_modules/@posthog/core/src/metrics/index.spec.ts +70 -0
- package/node_modules/@posthog/core/src/metrics/index.ts +30 -0
- package/node_modules/@posthog/core/src/privacy.ts +100 -18
- package/node_modules/@posthog/core/src/traces/span.spec.ts +15 -1
- package/node_modules/@posthog/core/src/traces/span.ts +23 -0
- package/node_modules/@posthog/types/dist/posthog-config.d.ts +4 -0
- package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/traces.d.ts +10 -0
- package/node_modules/@posthog/types/dist/traces.d.ts.map +1 -1
- package/node_modules/@posthog/types/package.json +1 -1
- package/node_modules/@posthog/types/src/posthog-config.ts +4 -0
- package/node_modules/@posthog/types/src/traces.ts +12 -0
- package/node_modules/@zuplo/core/LICENSE.third-party.txt +622 -0
- package/node_modules/@zuplo/core/LICENSE.txt +5 -78
- package/node_modules/@zuplo/core/README.md +7 -0
- package/node_modules/@zuplo/core/constants.minified.js +7 -20
- package/node_modules/@zuplo/core/customer.cli.minified.js +243 -256
- package/node_modules/@zuplo/core/index.minified.js +248 -261
- package/node_modules/@zuplo/core/package.json +4 -2
- package/node_modules/@zuplo/core/zeno.js +7 -20
- package/node_modules/@zuplo/graphql/LICENSE.third-party.txt +29 -0
- package/node_modules/@zuplo/graphql/LICENSE.txt +5 -78
- package/node_modules/@zuplo/graphql/README.md +7 -0
- package/node_modules/@zuplo/graphql/out/esm/index.js +7 -20
- package/node_modules/@zuplo/graphql/out/esm/index.js.map +1 -1
- package/node_modules/@zuplo/graphql/package.json +3 -2
- package/node_modules/@zuplo/openapi-tools/LICENSE.txt +7 -0
- package/node_modules/@zuplo/openapi-tools/README.md +7 -0
- package/node_modules/@zuplo/openapi-tools/package.json +3 -2
- package/node_modules/@zuplo/otel/LICENSE.third-party.txt +243 -0
- package/node_modules/@zuplo/otel/LICENSE.txt +5 -78
- package/node_modules/@zuplo/otel/README.md +33 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js +13 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js.map +1 -0
- package/node_modules/@zuplo/otel/out/esm/index.js +8 -21
- package/node_modules/@zuplo/otel/out/types/index.d.ts +41 -0
- package/node_modules/@zuplo/otel/package.json +3 -2
- package/node_modules/@zuplo/runtime/LICENSE.third-party.txt +511 -0
- package/node_modules/@zuplo/runtime/LICENSE.txt +5 -78
- package/node_modules/@zuplo/runtime/README.md +7 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-SX6JF7A6.js → chunk-AJ3MMWJS.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-AJ3MMWJS.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-G42UYZ6V.js +24 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-M4IZPJP6.js.map → chunk-G42UYZ6V.js.map} +1 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js +431 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-GWGCD6Z7.js → chunk-T2WKOG7J.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-T2WKOG7J.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-HTXNM72E.js → chunk-TOJD4RET.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-TOJD4RET.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/internal/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mcp/messages/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +11 -39
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +248 -6
- package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +101 -0
- package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +127 -0
- package/node_modules/@zuplo/runtime/package.json +3 -2
- package/node_modules/express-rate-limit/dist/index.cjs +33 -4
- package/node_modules/express-rate-limit/dist/index.mjs +33 -4
- package/node_modules/express-rate-limit/package.json +1 -1
- package/package.json +12 -11
- package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js +0 -26
- package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-F4G3YEN2.js +0 -429
- package/node_modules/@zuplo/runtime/out/esm/chunk-F4G3YEN2.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-GWGCD6Z7.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-HTXNM72E.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-M4IZPJP6.js +0 -37
- package/node_modules/@zuplo/runtime/out/esm/chunk-SX6JF7A6.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-M4IZPJP6.js.LEGAL.txt → chunk-G42UYZ6V.js.LEGAL.txt} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-F4G3YEN2.js.LEGAL.txt → chunk-OE2WMJXK.js.LEGAL.txt} +0 -0
|
@@ -1,46 +1,18 @@
|
|
|
1
1
|
|
|
2
|
-
|
|
3
|
-
*
|
|
2
|
+
/*!
|
|
3
|
+
* Copyright (c) Zuplo, Inc. All rights reserved.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* Development Devices solely for the above stated purpose.
|
|
5
|
+
* Use of this software is governed by the Zuplo Terms of Service at
|
|
6
|
+
* https://zuplo.com/legal/terms, or by a separate agreement your company has
|
|
7
|
+
* signed with Zuplo.
|
|
9
8
|
*
|
|
10
|
-
*
|
|
11
|
-
|
|
12
|
-
* sublicense, host, and/or sell copies of the Software.
|
|
13
|
-
*
|
|
14
|
-
* The software may include third party components with separate legal notices or governed by
|
|
15
|
-
* other agreements, as described in licenses either embedded in or accompanying the Software.
|
|
16
|
-
*
|
|
17
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
18
|
-
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
19
|
-
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
20
|
-
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
21
|
-
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
-
* DEALINGS IN THE SOFTWARE.
|
|
23
|
-
*--------------------------------------------------------------------------------------------*/
|
|
9
|
+
* See https://zuplo.com/legal/eula for more information.
|
|
10
|
+
*/
|
|
24
11
|
|
|
25
|
-
import{$ as Nr,$a as gl,$b as fa,$c as om,$f as Xm,$g as lh,Aa as ma,Ab as Bl,Ac as Up,Ad as vm,Ag as nh,Ah as G,Ba as Ju,Bb as Fl,Bc as ba,Bd as Am,Bg as oh,Bh as ne,C as Iu,Ca as Vu,Cb as Jl,Cc as Ns,Cd as Io,Cg as sh,Ch as qa,Da as Gu,Db as Vl,Dc as js,Dd as Pm,Dg as ih,Dh as ye,E as Os,Ea as Ku,Eb as Gl,Ec as qp,Ed as Ls,Eg as Ie,Eh as St,Fa as Wu,Fb as Kl,Fc as zp,Fd as $s,Ff as Jm,Fg as ge,Fh as de,Ga as Zu,Gb as Wl,Gc as Np,Gd as lr,Gf as He,Gg as ah,Gh as ei,H as Ms,Ha as Yu,Hb as Zl,Hc as jp,Hd as xm,Hf as Vm,Hg as rn,Hh as Ae,Ia as Xu,Ib as Yl,Ic as Dp,Id as Ca,If as Gm,Ig as W,Ih as ie,Ja as Qu,Jb as Xl,Jc as Lp,Jd as Vr,Jf as Km,Jg as gt,Jh as Ph,Ka as el,Kb as Ql,Kc as $p,Kd as Hs,Kf as ce,Kg as qt,Kh as se,La as tl,Lb as ep,Lc as Hp,Ld as Om,Lf as Wm,Lg as ch,Lh as xh,Ma as rl,Mb as tp,Mc as Bp,Md as Mm,Mf as Gr,Mg as zt,Mh as Oh,N as Tu,Na as nl,Nb as rp,Nc as Fp,Nd as Um,Nf as Zm,Ng as Aa,Nh as Mh,Oa as ol,Ob as np,Oc as Jp,Od as Bs,Of as Kr,Og as Gs,Oh as Uh,Pa as sl,Pb as op,Pc as Vp,Pd as Nm,Pf as M,Pg as Pa,Ph as V_,Q as Eu,Qa as il,Qb as sp,Qc as Gp,Qd as jm,Qf as Wr,Qg as Ks,Qh as G_,Ra as al,Rb as ip,Rc as Kp,Rd as Ia,Rf as Zr,Rg as Po,Sa as ha,Sb as ap,Sc as Wp,Sd as Dm,Sf as lt,Sg as nn,T as ku,Ta as cl,Tb as cp,Tc as Zp,Td as Lm,Tf as pt,Tg as dh,Ua as dl,Ub as dp,Uc as Yp,Ud as $m,Uf as To,Ug as yt,Va as ul,Vb as up,Vc as Xp,Vd as Ta,Vf as Yr,Vg as xa,Wa as ll,Wb as lp,Wc as Qp,Wd as Hm,Wf as Xr,Wg as Ws,Xa as pl,Xb as pp,Xc as em,Xd as Ea,Xf as Qr,Xg as uh,Ya as ml,Yb as mp,Yc as tm,Yd as Bm,Yf as Fs,Yg as Zs,Za as hl,Zb as hp,Zc as rm,Zf as Ym,Zg as Oa,_ as Us,_a as fl,_b as fp,_c as nm,_f as ot,_g as Ys,aa as jr,ab as yl,ac as gp,ad as sm,ag as Be,ah as he,b as xs,ba as wo,bb as Sl,bc as yp,bd as im,bg as z,bh as ph,ca as Dr,cb as Rl,cc as Sp,cd as am,cg as en,ch as mh,da as Lr,db as wl,dc as Rp,dd as cm,de as Fm,dg as ke,dh as hh,ea as _o,eb as _l,ec as wp,ed as dm,eg as Ut,eh as Ma,fa as ar,fb as bl,fc as _p,fd as um,fg as z_,fh,ga as Au,gb as vl,gc as bp,gd as lm,gg as N_,gh,ha as Pu,hb as Cl,hc as vp,hd as pm,hg as j_,hh as Ua,ia as xu,ib as Il,ic as Cp,id as mm,ig as D_,ih as yh,ja as Ou,jb as Tl,jc as Ip,jd as hm,jg as L_,jh as pr,ka as Mu,kb as El,kc as Tp,kd as $r,kg as $_,kh as Sh,la as Uu,lb as kl,lc as Ep,ld as Hr,lg as H_,lh as xo,ma as qu,mb as Al,mc as kp,md as fm,mg as B_,mh as Rh,n as ut,na as zu,nb as Pl,nc as Ap,nd as Br,ng as F_,nh as Xs,oa as Nu,ob as xl,oc as Pp,od as Ot,og as J_,oh as Oo,pa as ju,pb as Ol,pc as xp,pd as va,pg as Qm,ph as wh,qa as Du,qb as Ml,qc as ga,qd as Ds,qg as eh,qh as _h,ra as Lu,rb as Ul,rc as qs,rd as gm,rg as Js,rh as bh,sa as $u,sb as ql,sc as zs,sd as vo,sg as Eo,sh as vh,ta as Hu,tb as zl,tc as ya,td as dr,tg as ko,th as Ch,u as Ne,ua as Bu,ub as Nl,uc as Sa,ud as ym,ug as tn,uh as Ih,v as Cu,va as Fu,vb as jl,vc as Ra,vd as Sm,vg as th,vh as Th,wa as cr,wb as Dl,wc as Op,wd as Rm,wg as ka,wh as Eh,x as Z,xa as la,xb as Ll,xc as wa,xd as wm,xg as rh,xh as Qs,ya as pa,yb as $l,yc as _a,yd as _m,yg as Ao,yh as kh,za as bo,zb as Hl,zc as Mp,zd as bm,zg as Vs,zh as Ah}from"../chunk-F4G3YEN2.js";import"../chunk-VP5Q3DEN.js";import"../chunk-HTXNM72E.js";import{a as xt,b as te,c as ur,d as Cm,e as Im,f as Tm,g as Mt,i as Co,j as Em,k as km,l as Fr,m as Jr,t as qm,u as zm}from"../chunk-GWGCD6Z7.js";import"../chunk-A3QGJZO7.js";import{A as m,b as ca,c as _u,d as l,e as bu,f as vu,g as A,h as D,i as As,k as F,l as C,m as g,n as V,o as q,p as da,q as So,r as U,s as K,t as _,u as J,v as ua,w as Ps,y as Ro}from"../chunk-SX6JF7A6.js";import"../chunk-UKQQD2JN.js";import{$ as zr,a as Ee,aa as wu,c as k,d as re}from"../chunk-M4IZPJP6.js";import{a as o}from"../chunk-TYV53J3B.js";var K_=Object.create,ti=Object.defineProperty,W_=Object.getOwnPropertyDescriptor,Z_=Object.getOwnPropertyNames,Y_=Object.getPrototypeOf,X_=Object.prototype.hasOwnProperty,qh=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),zh=o((e,t)=>{let r={};for(var n in e)ti(r,n,{get:e[n],enumerable:!0});return t&&ti(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),Q_=o((e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=Z_(t),i=0,a=s.length,c;i<a;i++)c=s[i],!X_.call(e,c)&&c!==r&&ti(e,c,{get:(d=>t[d]).bind(null,c),enumerable:!(n=W_(t,c))||n.enumerable});return e},"__copyProps"),Nh=o((e,t,r)=>(r=e!=null?K_(Y_(e)):{},Q_(t||!e||!e.__esModule?ti(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var eb=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function jh(e){return typeof e=="string"&&eb.has(e.replace(/#$/,""))}o(jh,"declares2019Dialect");var $a=Symbol.for("mcp.sdk.errorBrands");function mr(e,t){let r=new Set,n=t;for(;typeof n=="function";){let s=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof s=="string"&&r.add(s),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,$a,{value:r,enumerable:!1,configurable:!0})}o(mr,"stampErrorBrands");function Fe(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,$a)){let r=t[$a];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}o(Fe,"brandedHasInstance");var me=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),Nt=class Wh extends Error{static{o(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Fe(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",mr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Wh(t.error,t.error_description??t.error,t.error_uri)}},Se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),pe=class extends Error{static{o(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Fe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",mr(this,new.target)}},pb=class extends pe{static{o(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,n){super(e,t,r,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Zh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Zh,"resourceUrlFromServerUrl");function Ga(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}o(Ga,"withoutIssuer");function ii({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(i)}o(ii,"checkResourceAllowed");var mb="2026-07-28";function Yh(e){return e>=mb}o(Yh,"isModernProtocolVersion");function Xh(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}o(Xh,"appendTextFallbackForNonObject");var Qh=["task","inputRequests","requestState"];function hb(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Qh.some(t=>t in e)?e:{...e,content:[]}}o(hb,"normalizeContentlessToolResult");function fb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),A().int()]),n=l(),s=g({ttl:A().optional()}),i=g({taskId:l()}),a=V({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=g({_meta:a.optional()}),d=c.extend({task:s.optional()}),u=g({method:l(),params:c.loose().optional()}),p=g({_meta:a.optional()}),h=g({method:l(),params:p.loose().optional()}),f=V({_meta:a.optional()}),y=q([l(),A().int()]),b=f.strict(),w=p.extend({requestId:y.optional(),reason:l().optional()}),S=h.extend({method:_("notifications/cancelled"),params:w}),R=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:K(["light","dark"]).optional()}),v=g({icons:C(R).optional()}),x=g({name:l(),title:l().optional()}),N=x.extend({...x.shape,...v.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),T=So(g({applyDefaults:D().optional()}),t),O=Ps(Ce=>Ce&&typeof Ce=="object"&&!Array.isArray(Ce)&&Object.keys(Ce).length===0?{form:{}}:Ce,So(g({form:T.optional(),url:t.optional()}),t.optional())),L=V({list:t.optional(),cancel:t.optional(),requests:V({sampling:V({createMessage:t.optional()}).optional(),elicitation:V({create:t.optional()}).optional()}).optional()}),Q=V({list:t.optional(),cancel:t.optional(),requests:V({tools:V({call:t.optional()}).optional()}).optional()}),P=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:O.optional(),roots:g({listChanged:D().optional()}).optional(),tasks:L.optional(),extensions:U(l(),t).optional()}),$=c.extend({protocolVersion:l(),capabilities:P,clientInfo:N}),j=u.extend({method:_("initialize"),params:$}),B=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:D().optional()}).optional(),resources:g({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:g({listChanged:D().optional()}).optional(),tasks:Q.optional(),extensions:U(l(),t).optional()}),ee=f.extend({protocolVersion:l(),capabilities:B,serverInfo:N,instructions:l().optional()}),Ue=h.extend({method:_("notifications/initialized"),params:p.optional()}),De=u.extend({method:_("ping"),params:c.optional()}),Ge=g({progress:A(),total:J(A()),message:J(l())}),Y=g({...p.shape,...Ge.shape,progressToken:r}),le=h.extend({method:_("notifications/progress"),params:Y}),qe=c.extend({cursor:n.optional()}),oe=u.extend({params:qe.optional()}),tt=f.extend({nextCursor:n.optional()}),_r=g({uri:l(),mimeType:J(l()),_meta:U(l(),F()).optional()}),br=_r.extend({text:l()}),Wt=l().refine(Ce=>{try{return atob(Ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),vr=_r.extend({blob:Wt}),dt=K(["user","assistant"]),rt=g({audience:C(dt).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),Zt=g({...x.shape,...v.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:rt.optional(),_meta:J(V({}))}),Cn=g({...x.shape,...v.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:rt.optional(),_meta:J(V({}))}),In=oe.extend({method:_("resources/list")}),Tn=tt.extend({resources:C(Zt)}),Et=oe.extend({method:_("resources/templates/list")}),Cr=tt.extend({resourceTemplates:C(Cn)}),Yt=c.extend({uri:l()}),En=Yt,kn=u.extend({method:_("resources/read"),params:En}),An=f.extend({contents:C(q([br,vr]))}),Pn=h.extend({method:_("notifications/resources/list_changed"),params:p.optional()}),xn=Yt,On=u.extend({method:_("resources/subscribe"),params:xn}),Mn=Yt,Un=u.extend({method:_("resources/unsubscribe"),params:Mn}),qn=p.extend({uri:l()}),zn=h.extend({method:_("notifications/resources/updated"),params:qn}),Nn=g({name:l(),description:J(l()),required:J(D())}),jn=g({...x.shape,...v.shape,description:J(l()),arguments:J(C(Nn)),_meta:J(V({}))}),Dn=oe.extend({method:_("prompts/list")}),Ln=tt.extend({prompts:C(jn)}),$n=c.extend({name:l(),arguments:U(l(),l()).optional()}),Hn=u.extend({method:_("prompts/get"),params:$n}),Xt=g({type:_("text"),text:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Qt=g({type:_("image"),data:Wt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),er=g({type:_("audio"),data:Wt,mimeType:l(),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Bn=g({type:_("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),kt=g({type:_("resource"),resource:q([br,vr]),annotations:rt.optional(),_meta:U(l(),F()).optional()}),Fn=Zt.extend({type:_("resource_link")}),Ke=q([Xt,Qt,er,Fn,kt]),Ir=g({role:dt,content:Ke}),Tr=f.extend({description:l().optional(),messages:C(Ir)}),tr=h.extend({method:_("notifications/prompts/list_changed"),params:p.optional()}),Jn=g({title:l().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Er=g({taskSupport:K(["required","optional","forbidden"]).optional()}),rr=g({...x.shape,...v.shape,description:l().optional(),inputSchema:g({type:_("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(F()),outputSchema:g({type:_("object"),properties:U(l(),e).optional(),required:C(l()).optional()}).catchall(F()).optional(),annotations:Jn.optional(),execution:Er.optional(),_meta:U(l(),F()).optional()}),kr=oe.extend({method:_("tools/list")}),Ar=tt.extend({tools:C(rr)}),Pr=f.extend({content:C(Ke),structuredContent:U(l(),F()).optional(),isError:D().optional()}),ve=d.extend({name:l(),arguments:U(l(),F()).optional()}),Vn=u.extend({method:_("tools/call"),params:ve}),ms=h.extend({method:_("notifications/tools/list_changed"),params:p.optional()}),xr=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Gn=c.extend({level:xr}),Kn=u.extend({method:_("logging/setLevel"),params:Gn}),Wn=p.extend({level:xr,logger:l().optional(),data:F()}),Zn=h.extend({method:_("notifications/message"),params:Wn}),Yn=g({name:l().optional()}),Xn=g({hints:C(Yn).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Qn=g({mode:K(["auto","required","none"]).optional()}),hs=g({type:_("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:C(Ke),structuredContent:g({}).loose().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),eo=da("type",[Xt,Qt,er]),At=da("type",[Xt,Qt,er,Bn,hs]),to=g({role:dt,content:q([At,C(At)]),_meta:U(l(),F()).optional()}),ro=d.extend({messages:C(to),modelPreferences:Xn.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(rr).optional(),toolChoice:Qn.optional()}),no=u.extend({method:_("sampling/createMessage"),params:ro}),oo=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens"]).or(l())),role:dt,content:eo}),so=f.extend({model:l(),stopReason:J(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:dt,content:q([At,C(At)])}),io=g({type:_("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),ao=g({type:_("string"),title:l().optional(),description:l().optional(),minLength:A().optional(),maxLength:A().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),co=g({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),uo=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),lo=g({type:_("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),po=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),mo=q([uo,lo]),nr=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:_("string"),enum:C(l())}),default:C(l()).optional()}),or=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),fs=q([nr,or]),gs=q([po,mo,fs]),Le=q([gs,io,ao,co]),$e=d.extend({mode:_("form").optional(),message:l(),requestedSchema:g({type:_("object"),properties:U(l(),Le),required:C(l()).optional()}).catchall(F())}),ho=d.extend({mode:_("url"),message:l(),elicitationId:l(),url:l().url()}),nt=q([$e,ho]),ys=u.extend({method:_("elicitation/create"),params:nt}),Ss=p.extend({elicitationId:l()}),Rs=h.extend({method:_("notifications/elicitation/complete"),params:Ss}),ws=f.extend({action:K(["accept","decline","cancel"]),content:Ps(Ce=>Ce===null?void 0:Ce,U(l(),q([l(),A(),D(),C(l())])).optional())}),_s=g({type:_("ref/resource"),uri:l()}),bs=g({type:_("ref/prompt"),name:l()}),vs=c.extend({ref:q([bs,_s]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()}),fo=u.extend({method:_("completion/complete"),params:vs}),Cs=f.extend({completion:V({values:C(l()).max(100),total:J(A().int()),hasMore:J(D())})}),Is=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),F()).optional()}),Or=u.extend({method:_("roots/list"),params:c.optional()}),go=f.extend({roots:C(Is)}),Ts=h.extend({method:_("notifications/roots/list_changed"),params:p.optional()}),Es=V({ttl:A().optional(),pollInterval:A().optional()}),yo=K(["working","input_required","completed","failed","cancelled"]),Pt=g({taskId:l(),status:yo,ttl:q([A(),As()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:J(A()),statusMessage:J(l())}),ze=f.extend({task:Pt}),ks=p.merge(Pt),sr=h.extend({method:_("notifications/tasks/status"),params:ks}),Mr=u.extend({method:_("tasks/get"),params:c.extend({taskId:l()})}),Ur=f.merge(Pt),qr=u.extend({method:_("tasks/result"),params:c.extend({taskId:l()})}),aa=f.loose(),Te=oe.extend({method:_("tasks/list")}),ae=tt.extend({tasks:C(Pt)}),ir=u.extend({method:_("tasks/cancel"),params:c.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:d,RequestSchema:u,NotificationsParamsSchema:p,NotificationSchema:h,ResultSchema:f,RequestIdSchema:y,EmptyResultSchema:b,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:S,IconSchema:R,IconsSchema:v,BaseMetadataSchema:x,ImplementationSchema:N,ClientTasksCapabilitySchema:L,ServerTasksCapabilitySchema:Q,ClientCapabilitiesSchema:P,InitializeRequestParamsSchema:$,InitializeRequestSchema:j,ServerCapabilitiesSchema:B,InitializeResultSchema:ee,InitializedNotificationSchema:Ue,PingRequestSchema:De,ProgressSchema:Ge,ProgressNotificationParamsSchema:Y,ProgressNotificationSchema:le,PaginatedRequestParamsSchema:qe,PaginatedRequestSchema:oe,PaginatedResultSchema:tt,ResourceContentsSchema:_r,TextResourceContentsSchema:br,BlobResourceContentsSchema:vr,RoleSchema:dt,AnnotationsSchema:rt,ResourceSchema:Zt,ResourceTemplateSchema:Cn,ListResourcesRequestSchema:In,ListResourcesResultSchema:Tn,ListResourceTemplatesRequestSchema:Et,ListResourceTemplatesResultSchema:Cr,ResourceRequestParamsSchema:Yt,ReadResourceRequestParamsSchema:En,ReadResourceRequestSchema:kn,ReadResourceResultSchema:An,ResourceListChangedNotificationSchema:Pn,SubscribeRequestParamsSchema:xn,SubscribeRequestSchema:On,UnsubscribeRequestParamsSchema:Mn,UnsubscribeRequestSchema:Un,ResourceUpdatedNotificationParamsSchema:qn,ResourceUpdatedNotificationSchema:zn,PromptArgumentSchema:Nn,PromptSchema:jn,ListPromptsRequestSchema:Dn,ListPromptsResultSchema:Ln,GetPromptRequestParamsSchema:$n,GetPromptRequestSchema:Hn,TextContentSchema:Xt,ImageContentSchema:Qt,AudioContentSchema:er,ToolUseContentSchema:Bn,EmbeddedResourceSchema:kt,ResourceLinkSchema:Fn,ContentBlockSchema:Ke,PromptMessageSchema:Ir,GetPromptResultSchema:Tr,PromptListChangedNotificationSchema:tr,ToolAnnotationsSchema:Jn,ToolExecutionSchema:Er,ToolSchema:rr,ListToolsRequestSchema:kr,ListToolsResultSchema:Ar,CallToolResultSchema:Pr,CallToolRequestParamsSchema:ve,CallToolRequestSchema:Vn,ToolListChangedNotificationSchema:ms,LoggingLevelSchema:xr,SetLevelRequestParamsSchema:Gn,SetLevelRequestSchema:Kn,LoggingMessageNotificationParamsSchema:Wn,LoggingMessageNotificationSchema:Zn,ModelHintSchema:Yn,ModelPreferencesSchema:Xn,ToolChoiceSchema:Qn,ToolResultContentSchema:hs,SamplingContentSchema:eo,SamplingMessageContentBlockSchema:At,SamplingMessageSchema:to,CreateMessageRequestParamsSchema:ro,CreateMessageRequestSchema:no,CreateMessageResultSchema:oo,CreateMessageResultWithToolsSchema:so,BooleanSchemaSchema:io,StringSchemaSchema:ao,NumberSchemaSchema:co,UntitledSingleSelectEnumSchemaSchema:uo,TitledSingleSelectEnumSchemaSchema:lo,LegacyTitledEnumSchemaSchema:po,SingleSelectEnumSchemaSchema:mo,UntitledMultiSelectEnumSchemaSchema:nr,TitledMultiSelectEnumSchemaSchema:or,MultiSelectEnumSchemaSchema:fs,EnumSchemaSchema:gs,PrimitiveSchemaDefinitionSchema:Le,ElicitRequestFormParamsSchema:$e,ElicitRequestURLParamsSchema:ho,ElicitRequestParamsSchema:nt,ElicitRequestSchema:ys,ElicitationCompleteNotificationParamsSchema:Ss,ElicitationCompleteNotificationSchema:Rs,ElicitResultSchema:ws,ResourceTemplateReferenceSchema:_s,PromptReferenceSchema:bs,CompleteRequestParamsSchema:vs,CompleteRequestSchema:fo,CompleteResultSchema:Cs,RootSchema:Is,ListRootsRequestSchema:Or,ListRootsResultSchema:go,RootsListChangedNotificationSchema:Ts,TaskCreationParamsSchema:Es,TaskStatusSchema:yo,TaskSchema:Pt,CreateTaskResultSchema:ze,TaskStatusNotificationParamsSchema:ks,TaskStatusNotificationSchema:sr,GetTaskRequestSchema:Mr,GetTaskResultSchema:Ur,GetTaskPayloadRequestSchema:qr,GetTaskPayloadResultSchema:aa,ListTasksRequestSchema:Te,ListTasksResultSchema:ae,CancelTaskRequestSchema:ir,CancelTaskResultSchema:f.merge(Pt),ClientRequestSchema:q([De,j,fo,Kn,Hn,Dn,In,Et,kn,On,Un,Vn,kr,Mr,qr,Te,ir]),ClientNotificationSchema:q([S,le,Ue,Ts,sr]),ClientResultSchema:q([b,oo,so,ws,go,Ur,ae,ze]),ServerRequestSchema:q([De,no,ys,Or,Mr,qr,Te,ir]),ServerNotificationSchema:q([S,le,Zn,zn,Pn,ms,tr,sr,Rs]),ServerResultSchema:q([b,ee,Cs,Tr,Ln,Tn,Cr,An,Pr,Ar,Ur,ae,ze]),CallToolResultWireSchema:F().superRefine((Ce,q_)=>{if(!(typeof Ce!="object"||Ce===null||Array.isArray(Ce)||Ce.content!==void 0)){for(let Ru of Qh)if(Ru in Ce){q_.addIssue({code:"custom",message:`content is required when the body carries '${Ru}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(hb).pipe(Pr)}}o(fb,"build$1");var gb;function Ka(){return gb??=fb()}o(Ka,"buildSchemas2025");function ef(e){return e.type!=="object"}o(ef,"isNonObjectJsonSchemaRoot");var yb=new Set(["const","enum","default","examples"]),Sb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Dh(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}o(Dh,"establishesNewBase");function Rb(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Dh(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=jh(e.$schema)&&e.$recursiveAnchor!==!0,n=o((s,i)=>{if(Array.isArray(s))return s.map(d=>n(d,!1));if(s===null||typeof s!="object"||!i&&Dh(s.$id))return s;let a={},c=!1;for(let[d,u]of Object.entries(s))i?a[d]=n(u,!1):(d==="$ref"||d==="$dynamicRef")&&typeof u=="string"?a[d]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:d==="$recursiveRef"&&u==="#"&&r?c=!0:yb.has(d)?a[d]=u:Sb.has(d)?a[d]=n(u,!0):a[d]=n(u,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}o(Rb,"wrapOutputSchemaForLegacy");var tf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},rf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},wb={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},ri;function ai(){if(ri)return ri;let e=Ka();return ri={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},ri}o(ai,"registryMaps");function _b(){ai()}o(_b,"warmRegistryMaps2025");function nf(e){return Object.prototype.hasOwnProperty.call(tf,e)}o(nf,"hasRequestMethod2025");function of(e){return Object.prototype.hasOwnProperty.call(rf,e)}o(of,"hasNotificationMethod2025");function bb(e){return Object.prototype.hasOwnProperty.call(wb,e)}o(bb,"hasResultMethod");function vb(e){return bb(e)?ai().resultSchemas[e]:void 0}o(vb,"getResultSchema");function Cb(e){return nf(e)?ai().requestSchemas[e]:void 0}o(Cb,"getRequestSchema");function Ib(e){return of(e)?ai().notificationSchemas[e]:void 0}o(Ib,"getNotificationSchema");var dU=Object.keys(tf),uU=Object.keys(rf);function Ha(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ha,"isPlainObject$5");function ni(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(ni,"triState$1");var Lh={ok:!1,reason:"not-in-era"};function $h(e){return Ha(e)&&Ha(e.outputSchema)&&ef(e.outputSchema)}o($h,"toolNeedsLegacyWrap");var Wa={era:"2025-11-25",hasRequestMethod:nf,hasNotificationMethod:of,validateRequest:o((e,t)=>ni(Cb(e),t),"validateRequest"),validateResult:o((e,t)=>ni(vb(e),t),"validateResult"),validateNotification:o((e,t)=>ni(Ib(e),t),"validateNotification"),hasInputRequestMethod:o(()=>!1,"hasInputRequestMethod"),validateInputRequest:o(()=>Lh,"validateInputRequest"),validateInputResponse:o(()=>Lh,"validateInputResponse"),samplingResultVariant:o(((e,t)=>{let r=Ka();return ni(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:o(e=>{},"outboundEnvelope"),validateEnvelopeMeta:o(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Xh(e),n=r.structuredContent;if(n===void 0)return r;let s=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&ef(t);return!s&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Ha(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>$h(n))?t:{...t,tools:r.map(n=>$h(n)?{...n,outputSchema:Rb(n.outputSchema)}:n)}},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:o(e=>{},"checkInboundEnvelope")};function Tb(){let e=ua(()=>q([l(),A(),D(),As(),U(l(),e),C(e)])),t=U(l(),e),r=q([l(),A().int()]),n=l(),s=q([l(),A().int()]),i=K(["user","assistant"]),a=K(["debug","info","notice","warning","error","critical","alert","emergency"]),c=l().refine(ae=>{try{return atob(ae),!0}catch{return!1}},{message:"Invalid Base64 string"}),d=g({ttl:A().optional()}),u=g({taskId:l()}),p=V({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=g({_meta:p.optional()}),f=h.extend({task:d.optional()}),y=g({_meta:p.optional()}),b=g({method:l(),params:y.loose().optional()}),w=g({src:l(),mimeType:l().optional(),sizes:C(l()).optional(),theme:K(["light","dark"]).optional()}),S=g({icons:C(w).optional()}),R=g({name:l(),title:l().optional()}),v=R.extend({...R.shape,...S.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),x=So(g({applyDefaults:D().optional()}),t),N=Ps(ae=>ae&&typeof ae=="object"&&!Array.isArray(ae)&&Object.keys(ae).length===0?{form:{}}:ae,So(g({form:x.optional(),url:t.optional()}),t.optional())),T=V({list:t.optional(),cancel:t.optional(),requests:V({sampling:V({createMessage:t.optional()}).optional(),elicitation:V({create:t.optional()}).optional()}).optional()}),O=V({list:t.optional(),cancel:t.optional(),requests:V({tools:V({call:t.optional()}).optional()}).optional()}),L=g({experimental:U(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:N.optional(),roots:g({listChanged:D().optional()}).optional(),tasks:T.optional(),extensions:U(l(),t).optional()}),Q=g({experimental:U(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:D().optional()}).optional(),resources:g({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:g({listChanged:D().optional()}).optional(),tasks:O.optional(),extensions:U(l(),t).optional()}),P=g({progress:A(),total:J(A()),message:J(l())}),$=g({...y.shape,...P.shape,progressToken:r}),j=b.extend({method:_("notifications/progress"),params:$}),B=y.extend({level:a,logger:l().optional(),data:F()}),ee=b.extend({method:_("notifications/message"),params:B}),Ue=g({uri:l(),mimeType:J(l()),_meta:U(l(),F()).optional()}),De=Ue.extend({text:l()}),Ge=Ue.extend({blob:c}),Y=g({audience:C(i).optional(),priority:A().min(0).max(1).optional(),lastModified:Ro.datetime({offset:!0}).optional()}),le=g({...R.shape,...S.shape,uri:l(),description:J(l()),mimeType:J(l()),size:J(A()),annotations:Y.optional(),_meta:J(V({}))}),qe=g({...R.shape,...S.shape,uriTemplate:l(),description:J(l()),mimeType:J(l()),annotations:Y.optional(),_meta:J(V({}))}),oe=b.extend({method:_("notifications/resources/list_changed"),params:y.optional()}),tt=y.extend({uri:l()}),_r=b.extend({method:_("notifications/resources/updated"),params:tt}),br=g({name:l(),description:J(l()),required:J(D())}),Wt=g({...R.shape,...S.shape,description:J(l()),arguments:J(C(br)),_meta:J(V({}))}),vr=b.extend({method:_("notifications/prompts/list_changed"),params:y.optional()}),dt=g({type:_("text"),text:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),rt=g({type:_("image"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Zt=g({type:_("audio"),data:c,mimeType:l(),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Cn=g({type:_("tool_use"),name:l(),id:l(),input:U(l(),F()),_meta:U(l(),F()).optional()}),In=g({type:_("resource"),resource:q([De,Ge]),annotations:Y.optional(),_meta:U(l(),F()).optional()}),Tn=le.extend({type:_("resource_link")}),Et=q([dt,rt,Zt,Tn,In]),Cr=g({role:i,content:Et}),Yt=g({title:l().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),En=b.extend({method:_("notifications/tools/list_changed"),params:y.optional()}),kn=g({name:l().optional()}),An=g({hints:C(kn).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Pn=g({mode:K(["auto","required","none"]).optional()}),xn=g({type:_("boolean"),title:l().optional(),description:l().optional(),default:D().optional()}),On=g({type:_("string"),title:l().optional(),description:l().optional(),minLength:A().optional(),maxLength:A().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),Mn=g({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),Un=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),default:l().optional()}),qn=g({type:_("string"),title:l().optional(),description:l().optional(),oneOf:C(g({const:l(),title:l()})),default:l().optional()}),zn=g({type:_("string"),title:l().optional(),description:l().optional(),enum:C(l()),enumNames:C(l()).optional(),default:l().optional()}),Nn=q([Un,qn]),jn=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({type:_("string"),enum:C(l())}),default:C(l()).optional()}),Dn=g({type:_("array"),title:l().optional(),description:l().optional(),minItems:A().optional(),maxItems:A().optional(),items:g({anyOf:C(g({const:l(),title:l()}))}),default:C(l()).optional()}),Ln=q([jn,Dn]),$n=q([zn,Nn,Ln]),Hn=q([$n,xn,On,Mn]),Xt=f.extend({mode:_("form").optional(),message:l(),requestedSchema:g({type:_("object"),properties:U(l(),Hn),required:C(l()).optional()}).catchall(F())}),Qt=g({type:_("ref/resource"),uri:l()}),er=g({type:_("ref/prompt"),name:l()}),Bn=g({uri:l().startsWith("file://"),name:l().optional(),_meta:U(l(),F()).optional()}),kt=L.shape,Fn=g({experimental:kt.experimental,sampling:kt.sampling,elicitation:kt.elicitation,roots:kt.roots,extensions:kt.extensions}),Ke=Q.shape,Ir=g({experimental:Ke.experimental,logging:Ke.logging,completions:Ke.completions,prompts:Ke.prompts,resources:Ke.resources,tools:Ke.tools,extensions:Ke.extensions}),Tr=V({progressToken:r.optional(),[jr]:l(),[wo]:v.optional(),[Lr]:Fn,[_o]:a.optional()}),tr=g({...R.shape,...S.shape,description:l().optional(),inputSchema:V({$schema:l().optional(),type:_("object")}),outputSchema:V({$schema:l().optional()}).optional(),annotations:Yt.optional(),_meta:U(l(),F()).optional()}),Jn=g({type:_("tool_result"),toolUseId:l(),content:C(Et),structuredContent:F().optional(),isError:D().optional(),_meta:U(l(),F()).optional()}),Er=q([dt,rt,Zt,Cn,Jn]),rr=g({role:i,content:q([Er,C(Er)]),_meta:U(l(),F()).optional()}),kr=l(),Ar=V({[Dr]:v.optional().catch(void 0)}),Pr=Ar.optional();function ve(ae){return V({_meta:Pr,resultType:kr.default("complete"),...ae})}o(ve,"wireResult");let Vn=ve({}),ms=ve({nextCursor:n.optional()}),xr=ve({content:C(Et),structuredContent:F().optional(),isError:D().optional()}),Gn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:C(tr),nextCursor:n.optional()}),Kn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:C(Wt),nextCursor:n.optional()}),Wn=ve({description:l().optional(),messages:C(Cr)}),Zn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:C(le),nextCursor:n.optional()}),Yn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:C(qe),nextCursor:n.optional()}),Xn=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:C(q([De,Ge]))}),Qn=ve({completion:g({values:C(l()).max(100),total:A().int().optional(),hasMore:D().optional()}).loose()}),hs=ve({ttlMs:A().int().min(0),cacheScope:K(["public","private"])}),eo=ve({ttlMs:A().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:Ir,instructions:l().optional()}),At=g({messages:C(rr),modelPreferences:An.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:C(l()).optional(),metadata:t.optional(),tools:C(tr).optional(),toolChoice:Pn.optional()}),to=g({method:_("sampling/createMessage"),params:At}),ro=g({method:_("roots/list"),params:g({_meta:U(l(),F()).optional()}).optional()}),no=g({...rr.shape,model:l(),stopReason:l().optional()}),oo=g({roots:C(Bn)}),so=g({action:K(["accept","decline","cancel"]),content:U(l(),q([l(),A(),D(),C(l())])).optional()}),io=g({mode:_("url"),message:l(),url:l().url()}),ao=q([Xt,io]),co=g({method:_("elicitation/create"),params:ao}),uo=q([to,ro,co]),lo=q([no,oo,so]),po=U(l(),uo),mo=U(l(),lo),nr=ve({inputRequests:po.optional(),requestState:l().optional()}),or={inputResponses:mo.optional(),requestState:l().optional()},fs=g({_meta:Tr,...or}),gs=V({progressToken:r.optional()});function Le(ae,ir){return g({method:_(ae),params:g({_meta:Tr,...ir})})}o(Le,"wireRequest");function $e(ae,ir){return g({method:_(ae),params:g({_meta:gs.optional(),...ir}).optional()})}o($e,"dispatchRequest");let ho={name:l(),arguments:U(l(),F()).optional(),...or},nt={cursor:n.optional()},ys=Le("tools/call",ho),Ss=Le("tools/list",nt),Rs=Le("prompts/list",nt),ws=Le("prompts/get",{name:l(),arguments:U(l(),l()).optional(),...or}),_s=Le("resources/list",nt),bs=Le("resources/templates/list",nt),vs=Le("resources/read",{uri:l(),...or}),fo={ref:q([er,Qt]),argument:g({name:l(),value:l()}),context:g({arguments:U(l(),l()).optional()}).optional()},Cs=Le("completion/complete",fo),Is=Le("server/discover",{}),Or=g({toolsListChanged:D().optional(),promptsListChanged:D().optional(),resourcesListChanged:D().optional(),resourceSubscriptions:C(l()).optional()}),go={notifications:Or},Ts=Le("subscriptions/listen",go),Es=Ar.extend({"io.modelcontextprotocol/subscriptionId":s}),yo=V({_meta:Es,resultType:kr.default("complete")}),Pt={"tools/call":$e("tools/call",ho),"tools/list":$e("tools/list",nt),"prompts/get":$e("prompts/get",{name:l(),arguments:U(l(),l()).optional()}),"prompts/list":$e("prompts/list",nt),"resources/list":$e("resources/list",nt),"resources/templates/list":$e("resources/templates/list",nt),"resources/read":$e("resources/read",{uri:l()}),"completion/complete":$e("completion/complete",fo),"server/discover":$e("server/discover",{}),"subscriptions/listen":$e("subscriptions/listen",go)};function ze(ae){return V({_meta:Pr,...ae})}o(ze,"liftedResult");let ks={"tools/call":ze({content:C(Et),structuredContent:F().optional(),isError:D().optional()}),"tools/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),tools:C(tr),nextCursor:n.optional()}),"prompts/get":ze({description:l().optional(),messages:C(Cr)}),"prompts/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),prompts:C(Wt),nextCursor:n.optional()}),"resources/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resources:C(le),nextCursor:n.optional()}),"resources/templates/list":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:C(qe),nextCursor:n.optional()}),"resources/read":ze({ttlMs:A().int().min(0),cacheScope:K(["public","private"]),contents:C(q([De,Ge]))}),"completion/complete":ze({completion:g({values:C(l()).max(100),total:A().int().optional(),hasMore:D().optional()}).loose()}),"server/discover":ze({ttlMs:A().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:C(l()),capabilities:Ir,instructions:l().optional()}),"subscriptions/listen":ze({})},sr=V({"io.modelcontextprotocol/subscriptionId":s.optional()}),Mr=g({method:_("notifications/subscriptions/acknowledged"),params:g({_meta:sr.optional(),notifications:Or})}),Ur=g({_meta:sr.optional(),requestId:s,reason:l().optional()}),qr=g({method:_("notifications/cancelled"),params:Ur}),aa={"notifications/cancelled":qr,"notifications/progress":j,"notifications/message":ee,"notifications/resources/updated":_r,"notifications/resources/list_changed":oe,"notifications/tools/list_changed":En,"notifications/prompts/list_changed":vr,"notifications/subscriptions/acknowledged":Mr},Te=o(ae=>g({jsonrpc:_("2.0"),id:q([l(),A().int()]),result:ae}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:s,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:d,RelatedTaskMetadataSchema:u,RequestMetaSchema:p,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:y,NotificationSchema:b,IconSchema:w,IconsSchema:S,BaseMetadataSchema:R,ImplementationSchema:v,ClientTasksCapabilitySchema:T,ServerTasksCapabilitySchema:O,ClientCapabilitiesSchema:L,ServerCapabilitiesSchema:Q,ProgressSchema:P,ProgressNotificationParamsSchema:$,ProgressNotificationSchema:j,LoggingMessageNotificationParamsSchema:B,LoggingMessageNotificationSchema:ee,ResourceContentsSchema:Ue,TextResourceContentsSchema:De,BlobResourceContentsSchema:Ge,AnnotationsSchema:Y,ResourceSchema:le,ResourceTemplateSchema:qe,ResourceListChangedNotificationSchema:oe,ResourceUpdatedNotificationParamsSchema:tt,ResourceUpdatedNotificationSchema:_r,PromptArgumentSchema:br,PromptSchema:Wt,PromptListChangedNotificationSchema:vr,TextContentSchema:dt,ImageContentSchema:rt,AudioContentSchema:Zt,ToolUseContentSchema:Cn,EmbeddedResourceSchema:In,ResourceLinkSchema:Tn,ContentBlockSchema:Et,PromptMessageSchema:Cr,ToolAnnotationsSchema:Yt,ToolListChangedNotificationSchema:En,ModelHintSchema:kn,ModelPreferencesSchema:An,ToolChoiceSchema:Pn,BooleanSchemaSchema:xn,StringSchemaSchema:On,NumberSchemaSchema:Mn,UntitledSingleSelectEnumSchemaSchema:Un,TitledSingleSelectEnumSchemaSchema:qn,LegacyTitledEnumSchemaSchema:zn,SingleSelectEnumSchemaSchema:Nn,UntitledMultiSelectEnumSchemaSchema:jn,TitledMultiSelectEnumSchemaSchema:Dn,MultiSelectEnumSchemaSchema:Ln,EnumSchemaSchema:$n,PrimitiveSchemaDefinitionSchema:Hn,ElicitRequestFormParamsSchema:Xt,ResourceTemplateReferenceSchema:Qt,PromptReferenceSchema:er,RootSchema:Bn,ClientCapabilities2026Schema:Fn,ServerCapabilities2026Schema:Ir,RequestMetaEnvelopeSchema:Tr,ToolSchema:tr,ToolResultContentSchema:Jn,SamplingMessageContentBlockSchema:Er,SamplingMessageSchema:rr,ResultTypeSchema:kr,ResultMetaSchema:Ar,ResultSchema:Vn,PaginatedResultSchema:ms,CallToolResultSchema:xr,ListToolsResultSchema:Gn,ListPromptsResultSchema:Kn,GetPromptResultSchema:Wn,ListResourcesResultSchema:Zn,ListResourceTemplatesResultSchema:Yn,ReadResourceResultSchema:Xn,CompleteResultSchema:Qn,CacheableResultSchema:hs,DiscoverResultSchema:eo,CreateMessageRequestParamsSchema:At,CreateMessageRequestSchema:to,ListRootsRequestSchema:ro,CreateMessageResultSchema:no,ListRootsResultSchema:oo,ElicitResultSchema:so,ElicitRequestURLParamsSchema:io,ElicitRequestParamsSchema:ao,ElicitRequestSchema:co,InputRequestSchema:uo,InputResponseSchema:lo,InputRequestsSchema:po,InputResponsesSchema:mo,InputRequiredResultSchema:nr,InputResponseRequestParamsSchema:fs,CallToolRequestSchema:ys,ListToolsRequestSchema:Ss,ListPromptsRequestSchema:Rs,GetPromptRequestSchema:ws,ListResourcesRequestSchema:_s,ListResourceTemplatesRequestSchema:bs,ReadResourceRequestSchema:vs,CompleteRequestSchema:Cs,DiscoverRequestSchema:Is,SubscriptionFilterSchema:Or,SubscriptionsListenRequestSchema:Ts,SubscriptionsListenResultMetaSchema:Es,SubscriptionsListenResultSchema:yo,dispatchRequestSchemas:Pt,dispatchResultSchemas:ks,NotificationMetaSchema:sr,SubscriptionsAcknowledgedNotificationSchema:Mr,CancelledNotificationParamsSchema:Ur,CancelledNotificationSchema:qr,notificationSchemas2026:aa,JSONRPCResultResponseSchema:Te(Vn),CallToolResultResponseSchema:Te(q([xr,nr])),ListToolsResultResponseSchema:Te(Gn),ListPromptsResultResponseSchema:Te(Kn),GetPromptResultResponseSchema:Te(q([Wn,nr])),ListResourcesResultResponseSchema:Te(Zn),ListResourceTemplatesResultResponseSchema:Te(Yn),ReadResourceResultResponseSchema:Te(q([Xn,nr])),CompleteResultResponseSchema:Te(Qn),DiscoverResultResponseSchema:Te(eo),SubscriptionsListenResultResponseSchema:Te(yo)}}o(Tb,"build");var Eb;function Rt(){return Eb??=Tb()}o(Rt,"buildSchemas2026");var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Ab(e){return kb.includes(e)}o(Ab,"isCacheableResultMethod");var Za=Symbol("modelcontextprotocol.resultCacheHintFallback");function Pb(e){return e[Za]}o(Pb,"cacheHintFallbackOf");function sf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}o(sf,"isValidCacheTtlMs");function af(e){return e==="public"||e==="private"}o(af,"isValidCacheScope");var I=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),Re=class cf extends Error{static{o(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Fe(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",mr(this,new.target)}static fromError(t,r,n){if(t===I.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ci(s.elicitations,r)}if(t===I.UnsupportedProtocolVersion&&n){let s=n;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new uf({supported:s.supported,requested:s.requested},r)}if(t===I.InvalidParams||t===I.ResourceNotFound){let s=n;if(typeof s?.uri=="string"&&(t===I.ResourceNotFound||Object.keys(s).length===1))return new df(s.uri,r)}if(t===I.MissingRequiredClientCapability&&n){let s=n;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new lf({requiredCapabilities:s.requiredCapabilities},r)}return new cf(t,r,n)}},df=class extends Re{static{o(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(I.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},ci=class extends Re{static{o(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},uf=class extends Re{static{o(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(I.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},lf=class extends Re{static{o(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(I.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},xb=0,Ob="private",Mb=["tools/call","prompts/get","resources/read"];function Ub(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||Mb.includes(e))return t;throw new Re(I.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}o(Ub,"stampResultType");function qb(e,t){let r=Pb(t);if(t.resultType!=="complete"||!Ab(e))return r===void 0?t:Lb(t);let n=t,s=sf(n.ttlMs)?n.ttlMs:jb(r),i=af(n.cacheScope)?n.cacheScope:Db(r),a={...n,ttlMs:s,cacheScope:i};return delete a[Za],a}o(qb,"fillCacheFields");function zb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(zb,"isPlainObject$4");function Nb(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Dr]:t}}:!zb(r)||r[Dr]!==void 0?e:{...e,_meta:{...r,[Dr]:t}}}o(Nb,"stampServerInfoMeta");function jb(e){return e!==void 0&&sf(e.ttlMs)?e.ttlMs:xb}o(jb,"resolveTtlMs");function Db(e){return e!==void 0&&af(e.cacheScope)?e.cacheScope:Ob}o(Db,"resolveCacheScope");function Lb(e){let t={...e};return delete t[Za],t}o(Lb,"stripCacheHintFallback");var $b=["elicitation/create","sampling/createMessage","roots/list"],oi;function Ya(){if(oi)return oi;let e=Rt();return oi={request:{"elicitation/create":g({method:_("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:_("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:_("roots/list"),params:V({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},oi}o(Ya,"inputSchemaMaps");function Hb(){Ya()}o(Hb,"warmInputSchemaMaps2026");function pf(e){return $b.includes(e)}o(pf,"isInputRequestMethod2026");function za(e){return pf(e)?Ya().request[e]:void 0}o(za,"getInputRequestSchema2026");function Bb(e){return pf(e)?Ya().response[e]:void 0}o(Bb,"getInputResponseSchema2026");var Xa={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},mf={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function hf(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o(hf,"hasRequestMethod2026");function ff(e){return Object.prototype.hasOwnProperty.call(mf,e)}o(ff,"hasNotificationMethod2026");function Fb(e){return Object.prototype.hasOwnProperty.call(Xa,e)}o(Fb,"hasResultMethod2026");function Jb(e){return hf(e)?Rt().dispatchRequestSchemas[e]:void 0}o(Jb,"getRequestSchema2026");function Vb(e){return Fb(e)?Rt().dispatchResultSchemas[e]:void 0}o(Vb,"getResultSchema2026");function Gb(e){return ff(e)?Rt().notificationSchemas2026[e]:void 0}o(Gb,"getNotificationSchema2026");var lU=Object.keys(Xa),pU=Object.keys(mf);function qo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(qo,"isPlainObject$3");function Mo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}o(Mo,"triState");var Kb={ok:!1,reason:"not-in-era"},Wb=[jr,Lr];function Zb(e,t){let r=t,n=!1,s=o(()=>(n||(r={...r},n=!0),r),"copy"),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>qo(c)&&"execution"in c)&&(s().tools=i.map(c=>{if(!qo(c)||!("execution"in c))return c;let d={...c};return delete d.execution,d}));let a=t.capabilities;if(qo(a)&&"tasks"in a){let c={...a};delete c.tasks,s().capabilities=c}return r}o(Zb,"enforceDeletedFields");var Qa={era:"2026-07-28",hasRequestMethod:hf,hasNotificationMethod:ff,hasInputRequestMethod:o(e=>za(e)!==void 0,"hasInputRequestMethod"),validateRequest:o((e,t)=>Mo(Jb(e),t),"validateRequest"),validateResult:o((e,t)=>Mo(Vb(e),t),"validateResult"),validateNotification:o((e,t)=>Mo(Gb(e),t),"validateNotification"),validateInputRequest:o((e,t)=>Mo(za(e),t),"validateInputRequest"),validateInputResponse:o((e,t)=>Mo(Bb(e),t),"validateInputResponse"),samplingResultVariant:o(()=>Kb,"samplingResultVariant"),outboundEnvelope(e){return{[jr]:e.protocolVersion,[wo]:e.clientInfo,[Lr]:e.clientCapabilities,...e.logLevel!==void 0&&{[_o]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Wb)n in e||t.push({key:n,problem:"missing"});let r=Rt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let s=n.path.map(String),i=s.length>0?s.join("."):"_meta";s.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:o(e=>Xh(e),"projectCallToolResult"),inputRequestSchema:za,decodeResult(e,t){if(!qo(t))return{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,c=qo(a)?a:{},d=t.requestState,u=t._meta===void 0?void 0:Rt().ResultMetaSchema.safeParse(t._meta),p=u?.success?u.data:void 0;return Object.keys(c).length===0&&typeof d!="string"?{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof d=="string"&&{requestState:d},...p!==void 0&&{_meta:p}}}if(r!=="complete")return{kind:"invalid",error:new pe(Se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=gf(),s=Object.hasOwn(n,e)?n[e]:void 0;if(s!==void 0){let a=s.safeParse(t);if(!a.success)return{kind:"invalid",error:new pe(Se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return Nb(qb(e,Ub(e,Zb(e,t))),r)},encodeErrorCode:o(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Rt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},si;function gf(){if(si)return si;let e=Rt();return si={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},si}o(gf,"getWireResultSchemas");function Yb(){gf()}o(Yb,"warmWireResultSchemas2026");var ec="2026-07-28";function No(e){return e!==void 0&&Yh(e)?Qa:Wa}o(No,"codecForVersion");function Hh(e){return e.revision!==void 0?No(e.revision).era:e.era==="modern"?Qa.era:Wa.era}o(Hh,"classifiedWireEra");function Na(e){return yf.some(t=>t.hasRequestMethod(e))}o(Na,"isSpecRequestMethod");function ja(e){return yf.some(t=>t.hasNotificationMethod(e))}o(ja,"isSpecNotificationMethod");function Bh(e){return e==="tasks/get"||e==="tasks/cancel"}o(Bh,"isExtensionReusedRequestMethod");var yf=[Wa,Qa],Xb=zh({AnnotationsSchema:o(()=>Rl,"AnnotationsSchema"),AudioContentSchema:o(()=>Xl,"AudioContentSchema"),BaseMetadataSchema:o(()=>Yu,"BaseMetadataSchema"),BaseRequestParamsSchema:o(()=>Nu,"BaseRequestParamsSchema"),BlobResourceContentsSchema:o(()=>yl,"BlobResourceContentsSchema"),BooleanSchemaSchema:o(()=>ga,"BooleanSchemaSchema"),CallToolRequestParamsSchema:o(()=>mp,"CallToolRequestParamsSchema"),CallToolRequestSchema:o(()=>hp,"CallToolRequestSchema"),CallToolResultSchema:o(()=>lp,"CallToolResultSchema"),CancelTaskRequestSchema:o(()=>am,"CancelTaskRequestSchema"),CancelTaskResultSchema:o(()=>cm,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:o(()=>Gu,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:o(()=>Ku,"CancelledNotificationSchema"),ClientCapabilitiesSchema:o(()=>tl,"ClientCapabilitiesSchema"),ClientNotificationSchema:o(()=>um,"ClientNotificationSchema"),ClientRequestSchema:o(()=>dm,"ClientRequestSchema"),ClientResultSchema:o(()=>lm,"ClientResultSchema"),ClientTasksCapabilitySchema:o(()=>Qu,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:o(()=>pp,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:o(()=>Hp,"CompleteRequestParamsSchema"),CompleteRequestSchema:o(()=>Bp,"CompleteRequestSchema"),CompleteResultSchema:o(()=>Fp,"CompleteResultSchema"),ContentBlockSchema:o(()=>rp,"ContentBlockSchema"),CreateMessageRequestParamsSchema:o(()=>kp,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:o(()=>Ap,"CreateMessageRequestSchema"),CreateMessageResultSchema:o(()=>Pp,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:o(()=>xp,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:o(()=>Xp,"CreateTaskResultSchema"),CursorSchema:o(()=>Mu,"CursorSchema"),DiscoverRequestSchema:o(()=>al,"DiscoverRequestSchema"),DiscoverResultSchema:o(()=>ha,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:o(()=>Ns,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:o(()=>qp,"ElicitRequestParamsSchema"),ElicitRequestSchema:o(()=>zp,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:o(()=>js,"ElicitRequestURLParamsSchema"),ElicitResultSchema:o(()=>Dp,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:o(()=>Np,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:o(()=>jp,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:o(()=>ep,"EmbeddedResourceSchema"),EmptyResultSchema:o(()=>Vu,"EmptyResultSchema"),EnumSchemaSchema:o(()=>Up,"EnumSchemaSchema"),GetPromptRequestParamsSchema:o(()=>Kl,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:o(()=>Wl,"GetPromptRequestSchema"),GetPromptResultSchema:o(()=>op,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:o(()=>nm,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:o(()=>om,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:o(()=>tm,"GetTaskRequestSchema"),GetTaskResultSchema:o(()=>rm,"GetTaskResultSchema"),IconSchema:o(()=>Wu,"IconSchema"),IconsSchema:o(()=>Zu,"IconsSchema"),ImageContentSchema:o(()=>Yl,"ImageContentSchema"),ImplementationSchema:o(()=>Xu,"ImplementationSchema"),InitializeRequestParamsSchema:o(()=>rl,"InitializeRequestParamsSchema"),InitializeRequestSchema:o(()=>nl,"InitializeRequestSchema"),InitializeResultSchema:o(()=>sl,"InitializeResultSchema"),InitializedNotificationSchema:o(()=>il,"InitializedNotificationSchema"),JSONArraySchema:o(()=>xu,"JSONArraySchema"),JSONObjectSchema:o(()=>Pu,"JSONObjectSchema"),JSONRPCErrorResponseSchema:o(()=>bo,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:o(()=>ma,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:o(()=>la,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:o(()=>cr,"JSONRPCRequestSchema"),JSONRPCResponseSchema:o(()=>Ju,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:o(()=>pa,"JSONRPCResultResponseSchema"),JSONValueSchema:o(()=>Au,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:o(()=>Ra,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:o(()=>fa,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:o(()=>Vl,"ListPromptsRequestSchema"),ListPromptsResultSchema:o(()=>Gl,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:o(()=>Cl,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:o(()=>Il,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:o(()=>bl,"ListResourcesRequestSchema"),ListResourcesResultSchema:o(()=>vl,"ListResourcesResultSchema"),ListRootsRequestSchema:o(()=>Vp,"ListRootsRequestSchema"),ListRootsResultSchema:o(()=>Gp,"ListRootsResultSchema"),ListTasksRequestSchema:o(()=>sm,"ListTasksRequestSchema"),ListTasksResultSchema:o(()=>im,"ListTasksResultSchema"),ListToolsRequestSchema:o(()=>dp,"ListToolsRequestSchema"),ListToolsResultSchema:o(()=>up,"ListToolsResultSchema"),LoggingLevelSchema:o(()=>gp,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:o(()=>Rp,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:o(()=>wp,"LoggingMessageNotificationSchema"),ModelHintSchema:o(()=>_p,"ModelHintSchema"),ModelPreferencesSchema:o(()=>bp,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:o(()=>Mp,"MultiSelectEnumSchemaSchema"),NotificationSchema:o(()=>$u,"NotificationSchema"),NotificationsParamsSchema:o(()=>Lu,"NotificationsParamsSchema"),NumberSchemaSchema:o(()=>zs,"NumberSchemaSchema"),PaginatedRequestParamsSchema:o(()=>pl,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:o(()=>ml,"PaginatedRequestSchema"),PaginatedResultSchema:o(()=>hl,"PaginatedResultSchema"),PingRequestSchema:o(()=>cl,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:o(()=>ba,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:o(()=>ul,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:o(()=>ll,"ProgressNotificationSchema"),ProgressSchema:o(()=>dl,"ProgressSchema"),ProgressTokenSchema:o(()=>Ou,"ProgressTokenSchema"),PromptArgumentSchema:o(()=>Fl,"PromptArgumentSchema"),PromptListChangedNotificationSchema:o(()=>sp,"PromptListChangedNotificationSchema"),PromptMessageSchema:o(()=>np,"PromptMessageSchema"),PromptReferenceSchema:o(()=>$p,"PromptReferenceSchema"),PromptSchema:o(()=>Jl,"PromptSchema"),ReadResourceRequestParamsSchema:o(()=>El,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:o(()=>kl,"ReadResourceRequestSchema"),ReadResourceResultSchema:o(()=>Al,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:o(()=>qu,"RelatedTaskMetadataSchema"),RequestIdSchema:o(()=>Fu,"RequestIdSchema"),RequestMetaSchema:o(()=>zu,"RequestMetaSchema"),RequestSchema:o(()=>Du,"RequestSchema"),ResourceContentsSchema:o(()=>fl,"ResourceContentsSchema"),ResourceLinkSchema:o(()=>tp,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:o(()=>Pl,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:o(()=>Tl,"ResourceRequestParamsSchema"),ResourceSchema:o(()=>wl,"ResourceSchema"),ResourceTemplateReferenceSchema:o(()=>Lp,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:o(()=>_l,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:o(()=>Hl,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:o(()=>Bl,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:o(()=>Hu,"ResultMetaObjectSchema"),ResultSchema:o(()=>Bu,"ResultSchema"),RoleSchema:o(()=>Sl,"RoleSchema"),RootSchema:o(()=>Jp,"RootSchema"),RootsListChangedNotificationSchema:o(()=>Kp,"RootsListChangedNotificationSchema"),SamplingContentSchema:o(()=>Ip,"SamplingContentSchema"),SamplingMessageContentBlockSchema:o(()=>Tp,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:o(()=>Ep,"SamplingMessageSchema"),ServerCapabilitiesSchema:o(()=>ol,"ServerCapabilitiesSchema"),ServerNotificationSchema:o(()=>mm,"ServerNotificationSchema"),ServerRequestSchema:o(()=>pm,"ServerRequestSchema"),ServerResultSchema:o(()=>hm,"ServerResultSchema"),ServerTasksCapabilitySchema:o(()=>el,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:o(()=>yp,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:o(()=>Sp,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:o(()=>Op,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:o(()=>qs,"StringSchemaSchema"),SubscribeRequestParamsSchema:o(()=>xl,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:o(()=>Ol,"SubscribeRequestSchema"),SubscriptionFilterSchema:o(()=>ql,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:o(()=>jl,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:o(()=>Dl,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:o(()=>zl,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:o(()=>Nl,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:o(()=>Ll,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:o(()=>$l,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:o(()=>ju,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:o(()=>Wp,"TaskCreationParamsSchema"),TaskMetadataSchema:o(()=>Uu,"TaskMetadataSchema"),TaskSchema:o(()=>Yp,"TaskSchema"),TaskStatusNotificationParamsSchema:o(()=>Qp,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:o(()=>em,"TaskStatusNotificationSchema"),TaskStatusSchema:o(()=>Zp,"TaskStatusSchema"),TextContentSchema:o(()=>Zl,"TextContentSchema"),TextResourceContentsSchema:o(()=>gl,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:o(()=>_a,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:o(()=>Sa,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:o(()=>ip,"ToolAnnotationsSchema"),ToolChoiceSchema:o(()=>vp,"ToolChoiceSchema"),ToolExecutionSchema:o(()=>ap,"ToolExecutionSchema"),ToolListChangedNotificationSchema:o(()=>fp,"ToolListChangedNotificationSchema"),ToolResultContentSchema:o(()=>Cp,"ToolResultContentSchema"),ToolSchema:o(()=>cp,"ToolSchema"),ToolUseContentSchema:o(()=>Ql,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:o(()=>Ml,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:o(()=>Ul,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:o(()=>wa,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:o(()=>ya,"UntitledSingleSelectEnumSchemaSchema")});var Sf=o(e=>cr.safeParse(e).success,"isJSONRPCRequest"),Rf=o(e=>la.safeParse(e).success,"isJSONRPCNotification"),Ba=o(e=>pa.safeParse(e).success,"isJSONRPCResultResponse"),wf=o(e=>bo.safeParse(e).success,"isJSONRPCErrorResponse");var zo=-32020,mU=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[I.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[zo,I.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[I.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[I.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[I.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[zo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[I.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[zo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],hU={[I.ParseError]:400,[I.InvalidRequest]:400,[I.MethodNotFound]:404,[I.UnsupportedProtocolVersion]:400,[I.MissingRequiredClientCapability]:400,[zo]:400};function tc(e,t){return _u(e,t)}o(tc,"parseSchema");function Uo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}o(Uo,"shapeKeys");function Fa(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}o(Fa,"isStandardSchema");var Fh=!1,Ja="draft-2020-12";function Qb(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Ja});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Fh||(Fh=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=ca(e,{target:Ja,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:_f(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}o(Qb,"standardSchemaToJsonSchema");function _f(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||_f(n)))}return!1}o(_f,"isProvablyObjectShapedRoot");function ev(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}o(ev,"formatIssue");async function Da(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>ev(n)).join(", ")}:{success:!0,data:r.value}}o(Da,"validateStandardSchema");function tv(e){let t=ca(e,{target:Ja,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}o(tv,"zodEmittedPattern");var rv=/\\\.\\d\{(\d+)\}/;function nv(e){let t=rv.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(s=>r.map(i=>Ro.datetime({local:n,offset:s,precision:i}))))}o(nv,"datetimeReferenceSchemas");function ov(e,t){let r;switch(e){case"email":r=[bu()];break;case"uri":r=[vu()];break;case"date":r=[Ro.date()];break;case"date-time":r=nv(t);break}return new Set(r.map(n=>tv(n)).filter(n=>n!==void 0))}o(ov,"referencePatternsForFormat");function sv(e,t,r){return r!=="zod"?!0:ov(e,t).has(t)}o(sv,"isLibraryFormatPattern");function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(jo,"isJsonObject");function iv(e){try{return Qb(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new Re(I.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}o(iv,"convertStandardElicitationSchema");var av=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function rc(e){return av.has(e)||e.startsWith("x-")}o(rc,"isAnnotationOnlyJsonSchemaKeyword");var cv=new Set(["$schema",...Object.keys(Ns.shape.requestedSchema.shape)]),Jh={string:Uo([qs,ya,Sa,Ra]),number:Uo([zs]),integer:Uo([zs]),boolean:Uo([ga]),array:Uo([wa,_a])},dv=new Set(qs.shape.format.unwrap().options);function uv(e,t,r,n){if(!jo(e))return e;let s=typeof e.type=="string"&&Object.hasOwn(Jh,e.type)?Jh[e.type]:void 0;if(s===void 0)return e;let i={};for(let[a,c]of Object.entries(e))s.has(a)||rc(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?dv.has(e.format)?(typeof c!="string"||!sv(e.format,c,r))&&n.push(`${t}.${a}`):i[a]=c:n.push(`${t}.${a}`);return i}o(uv,"walkProperty");function lv(e,t){let r={},n=[];for(let[s,i]of Object.entries(e))s==="properties"&&jo(i)?r[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,uv(c,`properties.${a}`,t,n)])):cv.has(s)?r[s]=i:rc(s)||n.push(s);if(n.length>0)throw new Re(I.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}o(lv,"walkRequestedSchema");function pv(e,t){if(!jo(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!tc(ba,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}o(pv,"describeUnsupportedProperties");function Va(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,s)=>Va(n,t[s],`${r}[${s}]`)):!jo(e)||!jo(t)?[]:Object.entries(e).flatMap(([n,s])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Va(s,t[n],i):rc(n)?[]:[i]})}o(Va,"findDroppedConstraintPaths");function mv(e){if(!Fa(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=lv(iv(e.requestedSchema),t),n=tc(Ns.shape.requestedSchema,r);if(!n.success)throw new Re(I.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${pv(r,n.error.message)}`);let s=Va(r,n.data);if(s.length>0)throw new Re(I.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new Re(I.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}o(mv,"normalizeElicitInputParams");function hv(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}o(hv,"buildInputRequired");var fU=Object.assign(hv,{elicit(e){try{return{method:"elicitation/create",params:mv(e)}}catch(t){throw t instanceof Re?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var fv=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],gv={IdJagTokenExchangeResponseSchema:va,OAuthClientInformationFullSchema:dr,OAuthClientInformationSchema:vo,OAuthClientMetadataSchema:gm,OAuthClientRegistrationErrorSchema:ym,OAuthErrorResponseSchema:Ds,OAuthMetadataSchema:Hr,OAuthProtectedResourceMetadataSchema:$r,OAuthTokenRevocationRequestSchema:Sm,OAuthTokensSchema:Ot,OpenIdProviderDiscoveryMetadataSchema:Br,OpenIdProviderMetadataSchema:fm},bf={},vf={};function Cf(e,t){let r=e.slice(0,-6);bf[r]=t,vf[r]=n=>t.safeParse(n).success}o(Cf,"register");for(let e of fv)Cf(e,Xb[e]);for(let[e,t]of Object.entries(gv))Cf(e,t);var yv=Object.freeze(bf),Sv=Object.freeze(vf);function Rv(e){switch(e){case"initialize":case"notifications/initialized":return No(void 0);case"server/discover":return No(ec);default:return}}o(Rv,"bootstrapOutboundCodec");var If=6e4,wv=[jr,wo,Lr,_o],_v=["inputResponses","requestState"];function Vh(e,t){let r=e.params;if(!La(r))return{message:e,lifted:{}};let n=r._meta,s=La(n)?wv.filter(d=>d in n):[],i=t==="request"?_v.filter(d=>d in r):[];if(s.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...r};if(s.length>0&&La(n)){let d={},u={...n};for(let p of s)d[p]=n[p],delete u[p];a.envelope=d,Object.keys(u).length>0?c._meta=u:delete c._meta}for(let d of i)d==="inputResponses"&&(a.inputResponses=c[d]),d==="requestState"&&(a.requestState=c[d]),delete c[d];return{message:{...e,params:c},lifted:a}}o(Vh,"liftWireOnlyMaterial");function Gh(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let s=e.validateResult(t,n);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}o(Gh,"codecResultValidator");function Tf(e){return()=>e}o(Tf,"requestStateAccessor");var bv=Tf(void 0),vv,Cv=class{static{o(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{vv=o((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Nr,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new pe(Se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new pe(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Ba(s)||wf(s)?this._onresponse(s):Sf(s)?this._onrequest(s,i):Rf(s)?this._onnotification(s,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new pe(Se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Vh(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Hh(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(ja(r.method)&&!n.hasNotificationMethod(r.method))return;let s=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;s===void 0&&i===void 0||Promise.resolve().then(()=>s===void 0?i(r):s(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=Vh(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=o((w,S,R)=>{let v={jsonrpc:"2.0",id:r.id,error:{code:w,message:S,...R!==void 0&&{data:R}}};i?.send(v).catch(x=>this._onerror(new Error(`Failed to send an error response: ${x}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=Hh(t.classification);if(w!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${s.era}`));let S=t.classification.revision??w;a(I.UnsupportedProtocolVersion,`Unsupported protocol version: ${S}`,{supported:this._supportedProtocolVersions,requested:S});return}}if(Na(r.method)&&!s.hasRequestMethod(r.method)&&!(Bh(r.method)&&this._customSchemaRequestMethods.has(r.method))){a(I.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(c===void 0){a(I.MethodNotFound,"Method not found");return}let d=s.checkInboundEnvelope(n);if(d!==void 0){a(I.InvalidParams,d);return}let u=o((w,S)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...S,relatedRequestId:r.id}),"sendNotification"),p=o((w,S,R)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,S,{...R,relatedRequestId:r.id}),"sendRequest"),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let f=n.inputResponses===void 0?void 0:Iv(n.inputResponses),y={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:n.requestState===void 0?bv:Tf(n.requestState),signal:h.signal,send:o(((w,S,R)=>{let v=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(v,w.method),Fa(S))return p(w,S,R);let x=Gh(v,w.method);if(x===void 0)throw new TypeError(`'${w.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(w,x,S)}),"send"),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(y,t);Promise.resolve().then(()=>c(r,b)).then(async w=>{if(h.signal.aborted)return;let S;try{S=s.encodeResult(r.method,w,this._outboundServerInfo())}catch(v){this._onerror(new Error(`Failed to encode result for ${r.method}: ${v}`)),a(I.InternalError,"Internal error");return}let R={result:S,jsonrpc:"2.0",id:r.id};await i?.send(R)},async w=>{if(h.signal.aborted)return;let S=Number.isSafeInteger(w.code)?w.code:I.InternalError,R={jsonrpc:"2.0",id:r.id,error:{code:s.encodeErrorCode(S),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await i?.send(R)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Ba(e)?r(e):r(Re.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(Fa(t))return Bh(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let s=Gh(n,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,s,t)}_negotiatedWireCodec(){return No(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Rv(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Na(t)&&!e.hasRequestMethod(t))throw new pe(Se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c}=n??{},d=Date.now(),u,p;return new Promise((h,f)=>{let y=o(O=>{f(O)},"earlyReject");if(!this._transport){y(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(O){y(O);return}if(n?.signal?.aborted){let O=n.signal.reason;throw O instanceof pe?O:new pe(Se.RequestTimeout,String(O))}let b=e.era===ec&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;p=w;let S={...t,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),S.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let R=this._envelopeOutbound(S),v=!1,x=o(O=>{v||(this._progressHandlers.delete(w),b===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}}),{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(L=>this._onerror(new Error(`Failed to send cancellation: ${L}`))):b.abort(),f(O instanceof pe?O:new pe(Se.RequestTimeout,String(O))))},"cancel");this._responseHandlers.set(w,O=>{if(n?.signal?.aborted)return;if(v=!0,O instanceof Error)return f(O);let L;try{L=e.decodeResult(t.method,O.result)}catch(P){return f(P instanceof Error?P:new Error(String(P)))}if(L.kind==="invalid")return f(L.error);if(L.kind==="input_required"){if(n?.allowInputRequired===!0)return h(Tv(L));let P={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:d,retry:o(($,j)=>this._requestWithSchemaViaCodec(e,$===void 0?{method:t.method}:{method:t.method,params:$},r,j),"retry")};return h(this._resolveNonCompleteResult(L,P))}let Q=L.result;Da(r,Q).then(P=>{P.success?h(P.data):f(new pe(Se.InvalidResult,`Invalid result for ${t.method}: ${P.error}`))},f)}),u=o(()=>x(n?.signal?.reason),"onAbort"),n?.signal?.addEventListener("abort",u,{once:!0});let N=n?.timeout??If,T=o(()=>x(new pe(Se.RequestTimeout,"Request timed out",{timeout:N})),"timeoutHandler");this._setupTimeout(w,N,n?.maxTotalTimeout,T,n?.resetTimeoutOnProgress??!1),this._transport.send(R,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:b?.signal}).catch(O=>{this._progressHandlers.delete(w),f(O)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),p!==void 0&&(this._responseHandlers.delete(p),this._cleanupTimeout(p))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new pe(Se.NotConnected,"Not connected");if(ja(t.method)&&!e.hasNotificationMethod(t.method))throw new pe(Se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(s=>this._onerror(s))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Na(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=o((s,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,s);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,s)),!c.ok)throw c.reason==="not-in-era"?new Re(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))},"stored")}else if(r)n=o(async(s,i)=>{let a=await Da(t.params,{...s.params});if(!a.success)throw new Re(I.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)},"stored");else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!ja(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,s)=>{let i=s.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new Re(I.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let s=await Da(t.params,{...n.params});if(!s.success)throw new Re(I.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await r(s.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function La(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(La,"isPlainObject$1");function Kh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Kh,"isPlainObject");function Iv(e){let t={},r=[];if(!Kh(e))return{accepted:t,droppedKeys:r};for(let[n,s]of Object.entries(e)){if(!Kh(s)||"method"in s||"result"in s){r.push(n);continue}t[n]=s}return{accepted:t,droppedKeys:r}}o(Iv,"partitionInputResponses");function Tv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}o(Tv,"manualInputRequiredValue");var Ev=qh((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(c){if(!c)throw new TypeError("argument string is required");var d=typeof c=="object"?i(c):c;if(typeof d!="string")throw new TypeError("argument string is required to be a string");var u=d.indexOf(";"),p=u!==-1?d.slice(0,u).trim():d.trim();if(!n.test(p))throw new TypeError("invalid media type");var h=new a(p.toLowerCase());if(u!==-1){var f,y,b;for(t.lastIndex=u;y=t.exec(d);){if(y.index!==u)throw new TypeError("invalid parameter format");u+=y[0].length,f=y[1].toLowerCase(),b=y[2],b.charCodeAt(0)===34&&(b=b.slice(1,-1),b.indexOf("\\")!==-1&&(b=b.replace(r,"$1"))),h.parameters[f]=b}if(u!==d.length)throw new TypeError("invalid parameter format")}return h}o(s,"parse");function i(c){var d;if(typeof c.getHeader=="function"?d=c.getHeader("content-type"):typeof c.headers=="object"&&(d=c.headers&&c.headers["content-type"]),typeof d!="string")throw new TypeError("content-type header is missing from object");return d}o(i,"getcontenttype");function a(c){this.parameters=Object.create(null),this.type=c}o(a,"ContentType")})),gU=Nh(Ev(),1);var kv=10*1024*1024;var Av=new Set([301,302,303,307,308]),Pv=5;function xv(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}o(xv,"isWithinOrigin");function Ov(e,t){let r=Av.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}o(Ov,"redirectTarget");var Mv=new WeakSet;function di(e){return Mv.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let n=(r?.method??"GET").toUpperCase(),s=t;for(let i=0;;i++){let a=await e(s,{...r,redirect:"manual"}),c=Ov(s,a);if(!c||i===Pv)return a;let d=new URL(s),u=n==="GET"||a.status===307||a.status===308,p=!(c.username||c.password)||c.username===d.username&&c.password===d.password;if(!u||!p||!xv(d,c))return a;await a.text?.().catch(()=>{}),s=c}}}o(di,"fetchWithinOrigin");function nc(){Ka(),Rt(),_b(),Hb(),Yb()}o(nc,"preloadSchemas");var kU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var Uv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,qv=[0,31,28,31,30,31,30,31,31,30,31,30,31],zv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Nv=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,jv=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Dv=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Lv=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,$v=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Hv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Bv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Fv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Jv=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),Vv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Gv=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Kv=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function mt(e){return e.test.bind(e)}o(mt,"bind");var AU={date:Ef,time:kf.bind(void 0,!1),"date-time":Yv,duration:Kv,uri:eC,"uri-reference":mt(jv),"uri-template":mt(Dv),url:mt(Lv),email:Jv,hostname:mt(Nv),ipv4:mt(Vv),ipv6:mt(Gv),regex:rC,uuid:mt($v),"json-pointer":mt(Hv),"json-pointer-uri-fragment":mt(Bv),"relative-json-pointer":mt(Fv)};function Wv(e){return e%4===0&&(e%100!==0||e%400===0)}o(Wv,"isLeapYear");function Ef(e){let t=e.match(Uv);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&Wv(r)?29:qv[n])}o(Ef,"date");function kf(e,t){let r=t.match(zv);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!e||a)}o(kf,"time");var Zv=/t|\s/i;function Yv(e){let t=e.split(Zv);return t.length==2&&Ef(t[0])&&kf(!0,t[1])}o(Yv,"date_time");var Xv=/\/|:/,Qv=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function eC(e){return Xv.test(e)&&Qv.test(e)}o(eC,"uri");var tC=/[^\\]\\Z/;function rC(e){if(tC.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(rC,"regex");nc();var Af=!1;var oc;oc=globalThis.crypto;async function oC(e){return(await oc).getRandomValues(new Uint8Array(e))}o(oC,"getRandomValues");async function sC(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let s=await oC(e-n.length);for(let i of s)i<r&&(n+=t[i%t.length])}return n}o(sC,"random");async function iC(e){return await sC(e)}o(iC,"generateVerifier");async function aC(e){let t=await(await oc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(aC,"generateChallenge");async function sc(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await iC(e),r=await aC(t);return{code_verifier:t,code_challenge:r}}o(sc,"pkceChallenge");var Lo=class extends Error{static{o(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Fe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,e)}constructor(e){super(e),this.name=new.target.name,mr(this,new.target)}},Do=class extends Lo{static{o(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},uc=class extends Lo{static{o(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},pi=class extends Lo{static{o(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},li=class extends Lo{static{o(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Sq=class extends Lo{static{o(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function dc(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Mf(e.issuer,t)?e:void 0}o(dc,"discardIfIssuerMismatch");function Mf(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}o(Mf,"issuersMatch");var Rq=class extends Error{static{o(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Fe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",mr(this,new.target)}};function Uf(e){return e?.authorization_response_iss_parameter_supported===!0}o(Uf,"isIssParameterSupported");function qf({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Do("authorization_response",t,void 0);return}if(e!==t)throw new Do("authorization_response",t,e)}}o(qf,"validateAuthorizationResponseIssuer");function cC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(cC,"isClientAuthMethod");var ic="code",ac="S256";function dC(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&cC(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(dC,"selectClientAuthMethod");function uC(e,t,r,n){let{client_id:s,client_secret:i}=t;switch(e){case"client_secret_basic":lC(s,i,r);return;case"client_secret_post":pC(s,i,n);return;case"none":mC(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(uC,"applyClientAuthentication");function lC(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(lC,"applyBasicAuth");function pC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(pC,"applyPostAuth");function mC(e,t){t.set("client_id",e)}o(mC,"applyPublicAuth");function zf(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}o(zf,"isLoopbackHost");function hC(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!zf(t.hostname))throw new pi(t.href);return t}o(hC,"assertSecureTokenEndpoint");function fC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||zf(r.hostname))return"native"}return"web"}o(fC,"deriveApplicationType");function gC(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??fC(t.redirect_uris)}}o(gC,"resolveClientMetadata");async function Pf(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Ds.parse(JSON.parse(r));return Nt.fromResponse(n)}catch(n){let s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Nt(me.ServerError,s)}}o(Pf,"parseErrorResponse");function xf(e,t,r){let n=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`}o(xf,"warnCredentialInvalidation");async function lc(e,t){try{return await cc(e,t)}catch(r){if(r instanceof Nt){if(r.code===me.InvalidClient||r.code===me.UnauthorizedClient)return xf(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await cc(e,t);if(r.code===me.InvalidGrant||r.code===me.InvalidDpopProof)return xf(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await cc(e,t)}throw r}}o(lc,"auth");function yC(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:s}=e,i=t||r?.scopes_supported?.join(" ")||s.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&s.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}o(yC,"determineScope");async function cc(e,{serverUrl:t,authorizationCode:r,iss:n,scope:s,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:d}){let u=gC(e),p=await e.discoveryState?.(),h,f,y,b,w=i;if(!w&&p?.resourceMetadataUrl&&(w=new URL(p.resourceMetadataUrl)),p?.authorizationServerUrl){if(f=p.authorizationServerUrl,h=p.resourceMetadata,y=p.authorizationServerMetadata??await Lf(f,{fetchFn:a,skipIssuerValidation:c}),!h)try{h=await jf(t,{resourceMetadataUrl:w},a)}catch(B){if(B instanceof TypeError)throw B}(y!==p.authorizationServerMetadata||h!==p.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:w?.toString(),resourceMetadata:h,authorizationServerMetadata:y})}else{let B=await CC(t,{resourceMetadataUrl:w,fetchFn:a,skipIssuerMetadataValidation:c});f=B.authorizationServerUrl,y=B.authorizationServerMetadata,h=B.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:w?.toString(),resourceMetadata:h,authorizationServerMetadata:y}}let S=y?.issuer??String(f),R={issuer:S};if(await e.saveAuthorizationServerUrl?.(S),r!==void 0){let B=p?.authorizationServerMetadata?.issuer??p?.authorizationServerUrl;if(B===void 0){if(e.saveDiscoveryState!==void 0)throw new li("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",S);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Mf(B,S))throw new li(B,S)}b&&await e.saveDiscoveryState?.(b);let v=await SC(t,e,h),x=v&&h&&!e.validateResourceURL?h.resource:v;x&&await e.saveResourceUrl?.(mc(x));let N=yC({requestedScope:s,resourceMetadata:h,authServerMetadata:y,clientMetadata:e.clientMetadata}),T=await Promise.resolve(e.clientInformation(R)),O=dc(T,S,{canPersistStamp:e.saveClientInformation!==void 0});if(O===void 0&&T?.issuer&&e.saveClientInformation===void 0)throw new li(T.issuer,S);if(O&&O.issuer===void 0&&(O={...O,issuer:S},await e.saveClientInformation?.(O,R)),!O){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let B=y?.client_id_metadata_document_supported===!0,ee=e.clientMetadataUrl;if(ee&&!pc(ee))throw new Nt(me.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ee}`);if(B&&ee)O={client_id:ee,issuer:S},await e.saveClientInformation?.(O,R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");O={...await AC(f,{metadata:y,clientMetadata:u,scope:N,fetchFn:a}),issuer:S},await e.saveClientInformation(O,R)}}let L=!e.redirectUrl;if(r!==void 0||L){r!==void 0&&qf({iss:n,expectedIssuer:y?.issuer,issParameterSupported:Uf(y)});let B=await kC(e,f,{metadata:y,resource:x,authorizationCode:r,iss:n,scope:N,fetchFn:a});return await e.saveTokens({...B,issuer:S},R),"AUTHORIZED"}let Q=dc(await e.tokens(R),S);if(Q&&Q.issuer===void 0&&(Q={...Q,issuer:S},await e.saveTokens(Q,R)),Q?.refresh_token&&!d){let B;try{B=await EC(f,{metadata:y,clientInformation:O,refreshToken:Q.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(ee){if(ee instanceof pi||!(!(ee instanceof Nt)||ee.code===me.ServerError))throw ee}if(B)return await e.saveTokens({...B,issuer:S},R),"AUTHORIZED"}let P=e.state?await e.state():void 0,{authorizationUrl:$,codeVerifier:j}=await IC(f,{metadata:y,clientInformation:O,state:P,redirectUrl:e.redirectUrl,scope:N,resource:x});return await e.saveCodeVerifier(j),await e.redirectToAuthorization($),"REDIRECT"}o(cc,"authInternal");function pc(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(pc,"isHttpsUrl");async function SC(e,t,r){let n=Zh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ii({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(SC,"selectResourceURL");var RC=new Set(["bearer","dpop"]);function Nf(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(!r||!RC.has(r.toLowerCase())||!n)return{};let s=ui(e,"resource_metadata")||void 0,i;if(s)try{i=new URL(s)}catch{}let a=ui(e,"scope")||void 0,c=ui(e,"error")||void 0,d=ui(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:d}}o(Nf,"extractWWWAuthenticateParams");function ui(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),s=r.match(n);if(s){let i=s[1]||s[2];if(i)return i}return null}o(ui,"extractFieldFromWwwAuth");async function jf(e,t,r=fetch){let n=await bC(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return $r.parse(await n.json())}o(jf,"discoverOAuthProtectedResourceMetadata");async function Df(e,t,r=fetch){let n=di(r);try{return await n(e,{headers:t})}catch(s){if(!(s instanceof TypeError)||!Af)throw s;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}o(Df,"fetchWithCorsRetry");function wC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(wC,"buildWellKnownPath");async function Of(e,t,r=fetch){return await Df(e,{"MCP-Protocol-Version":t},r)}o(Of,"tryMetadataDiscovery");function _C(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}o(_C,"shouldAttemptFallback");async function bC(e,t,r,n){let s=new URL(e),i=n?.protocolVersion??Us,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let d=wC(t,s.pathname);a=new URL(d,n?.metadataServerUrl??s),a.search=s.search}let c=await Of(a,i,r);return!n?.metadataUrl&&_C(c,s.pathname)&&(c=await Of(new URL(`/.well-known/${t}`,s),i,r)),c}o(bC,"discoverMetadataWithFallback");function vC(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"},{url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(vC,"buildDiscoveryUrls");async function Lf(e,{fetchFn:t=fetch,protocolVersion:r=Us,skipIssuerValidation:n=!1}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},i=vC(e);for(let{url:a,type:c}of i){let d=await Df(a,s,t);if(!d)continue;if(!d.ok){if(await d.text?.().catch(()=>{}),d.status<500||d.status===502)continue;throw new Error(`HTTP ${d.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=c==="oauth"?Hr.parse(await d.json()):Br.parse(await d.json());if(!n){let p=typeof e=="string"?e:e.href;if(!(u.issuer===p||p.endsWith("/")&&u.issuer===p.slice(0,-1)))throw new Do("metadata",p,u.issuer)}return u}}o(Lf,"discoverAuthorizationServerMetadata");async function CC(e,t){let r,n;try{r=await jf(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let s=await Lf(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}o(CC,"discoverOAuthServerInfo");function mc(e){return typeof e=="string"?e:e.href}o(mc,"resourceIndicatorToString");async function IC(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ic))throw new Error(`Incompatible auth server: does not support response type ${ic}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ac))throw new Error(`Incompatible auth server: does not support code challenge method ${ac}`)}else c=new URL("/authorize",e);let d=await sc(),u=d.code_verifier,p=d.code_challenge;return c.searchParams.set("response_type",ic),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",ac),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),s&&c.searchParams.set("scope",s),s?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",mc(a)),{authorizationUrl:c,codeVerifier:u}}o(IC,"startAuthorization");function TC(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(TC,"prepareAuthorizationCodeRequest");async function $f(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,dpop:a,fetchFn:c}){let d=hC(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",mc(i)),!s&&n&&uC(dC(n,t?.token_endpoint_auth_methods_supported??[]),n,u,r);let p=o(async()=>{let y=new Headers(u);return s&&await s(y,r,d,t),a&&y.set("DPoP",await a.buildProof({htm:"POST",htu:d})),di(c??fetch)(d,{method:"POST",headers:y,body:r})},"requestOnce"),h=await p();if(a&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===me.UseDpopNonce&&(a.observeNonce(h,d),h=await p()),a?.observeNonce(h,d),!h.ok)throw await Pf(h);let f=await h.json();try{return Ot.parse(Ga(f))}catch(y){throw typeof f=="object"&&f!==null&&"error"in f?await Pf(JSON.stringify(f)):y}}o($f,"executeTokenRequest");async function EC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:n,...await $f(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:s,dpop:a,fetchFn:c})}}o(EC,"refreshAuthorization");async function kC(e,t,{metadata:r,resource:n,authorizationCode:s,iss:i,scope:a,fetchFn:c}={}){s!==void 0&&qf({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Uf(r)});let d=r?.issuer??String(t),u=o(async()=>{let y=await e.clientInformation({issuer:d}),b=dc(y,d,{canPersistStamp:!1});if(y&&b===void 0)throw new li(String(y.issuer),d);return b},"readClientInformation"),p=await u(),h=a??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(h)),!f){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");f=TC(s,await e.codeVerifier(),e.redirectUrl)}return p??=await u(),$f(t,{metadata:r,tokenRequestParams:f,clientInformation:p,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:c})}o(kC,"fetchToken");async function AC(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:s}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},c=await di(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new uc({status:c.status,body:await c.text(),submittedMetadata:a});return dr.parse(Ga(await c.json()))}o(AC,"registerClient");var wq=class extends Error{static{o(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Fe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Fe(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,mr(this,new.target)}};function we(e){let t=cr.safeParse(e);return t.success?t.data.id:void 0}o(we,"parseJsonRpcRequestId");function hc(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return we(t)}catch{return}}o(hc,"readJsonRpcRequestIdFromBody");function Pe(e){return bo.parse({jsonrpc:ar,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}o(Pe,"jsonRpcErrorResponse");function Hf(e){return new ci([js.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}o(Hf,"urlElicitationRequiredError");var fc=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],$o=[ur,...fc],PC=0,xC="private",OC="0.0.0";function MC(e){return{...e?.tools===!1?{}:{tools:{}},...e?.prompts===!1?{}:{prompts:{}},...e?.resources===!1?{}:{resources:{}}}}o(MC,"buildGatewayDiscoverCapabilities");function gc(e){let{connection:t}=e,r=t.serverInfo,n=r?.title??t.displayName,s=r?.icons!==void 0&&r.icons.length>0?r.icons:e.icons;return{name:r?.name??t.id,...n===void 0?{}:{title:n},version:r?.version??OC,...r?.description===void 0?{}:{description:r.description},...r?.websiteUrl===void 0?{}:{websiteUrl:r.websiteUrl},...s===void 0||s.length===0?{}:{icons:[...s]}}}o(gc,"buildGatewayDiscoverServerInfo");function Bf(e){let t=we(e.request.message);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",supportedVersions:[...e.supportedVersions??$o],capabilities:MC(e.capabilityFilter),_meta:{[Mt]:gc({connection:e.connection,icons:e.icons})},ttlMs:PC,cacheScope:xC}})}o(Bf,"gatewayDiscoverResponse");var UC=/^\d{4}-\d{2}-\d{2}$/;var hi="2026-07-28",Ho;function qC(){return Ho??=new Map,Ho}o(qC,"store");function mi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(mi,"isRecord");function Ff(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string"&&UC.test(r)))].slice(0,32);return t.length===0?void 0:t}o(Ff,"readVersionList");function fi(e,t){if(!mi(t))return;if(e==="server/discover"&&mi(t.result))return Ff(t.result.supportedVersions);let r=t.error;if(mi(r)&&r.code===-32022&&mi(r.data))return Ff(r.data.supported)}o(fi,"readUpstreamSupportedVersions");function gi(e,t,r={}){let n=qC(),s=n.get(e),i=t.some(d=>d<hi),a=r.modernOnly===!0||s?.modernOnly===!0&&!i,c=!i&&!a&&s?.complete===!0?s.versions.filter(d=>d<hi):[];if(n.delete(e),n.set(e,{versions:[...t,...c],complete:a||i||c.length>0,modernOnly:a}),n.size>512){let d=n.keys().next().value;d!==void 0&&n.delete(d)}}o(gi,"recordUpstreamSupportedVersions");function yi(e,t){let r=e===void 0?void 0:Ho?.get(e);if(r===void 0)return t;let n=t.filter(s=>r.versions.includes(s));return n.length===0?t:r.complete?n:t.filter(s=>s<hi||n.includes(s))}o(yi,"advertisedSupportedVersions");function Jf(e){let t=Ho?.get(e);t?.modernOnly===!0&&Ho?.set(e,{versions:t.versions,complete:t.versions.some(r=>r<hi),modernOnly:!1})}o(Jf,"recordUpstreamAcceptsInitialize");var zC=-32e3,NC="2025-11-25",jC=/^\d{4}-\d{2}-\d{2}$/,Sc=I.InternalError;function yc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yc,"isRecord");function DC(e,t){return typeof e=="string"&&jC.test(e)&&e>=t}o(DC,"isAtLeast");function LC(e){if(e.method!=="initialize")return!1;let t=yc(e.params)?e.params:void 0,n=(yc(t?.capabilities)?t.capabilities:void 0)?.elicitation,s=t?.protocolVersion;return DC(s,NC)&&!Co(s)&&yc(n)&&n.url!==void 0}o(LC,"acceptsUrlElicitation");function Rc(e){let{payload:t}=e,r=t.authUrl===void 0||!e.urlElicitation?void 0:Hf({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Pe({...e.id===void 0?{}:{id:e.id},error:{code:r?.code??e.fallbackCode,message:t.message,data:{...r?.data??{},connectRequired:t}}})}o(Rc,"legacyConnectRequiredError");function Vf(e,t){let r=Vr(e,t);if(r!==void 0)return{kind:"invalid",error:r};let n=e,s=we(e);return s===void 0?{kind:"accepted",response:typeof n.method!="string"}:{kind:"request",id:s,message:n}}o(Vf,"classifyMessage");function on(e,t){return Response.json(Pe({error:{code:e,message:t}}),{status:400})}o(on,"unidentifiedError");function Gf(){return new Response(null,{status:202})}o(Gf,"acceptedResponse");function $C(e,t){return te()?jm(e,t):void 0}o($C,"modernBatchVersion");function HC(e,t){let r=e.get("mcp-protocol-version"),n=$C(e,t)??(Hs(r)?r??void 0:void 0);return n===void 0?void 0:on(I.InvalidRequest,`Invalid Request: protocol version ${n} does not support JSON-RPC batches`)}o(HC,"batchRefusal");function Kf(e,t,r){let n=(Array.isArray(t)?t:[t]).filter(i=>Vr(i)===void 0);if(n.length===0)return;if(n.some(wm))return n.length>1?on(I.InvalidRequest,"Invalid Request: Only one initialization request is allowed"):void 0;let s=e.get("mcp-protocol-version");if(!(s===null||r.accepted(s)))return on(zC,`Bad Request: Unsupported protocol version: ${s} (supported versions: ${r.listed.join(", ")})`)}o(Kf,"transportVersionRefusal");function Wf(e,t){return Kf(e,t,{accepted:o(r=>Nr.includes(r),"accepted"),listed:Nr})}o(Wf,"handlerTransportVersionRefusal");function BC(e,t,r){let n=yi(r,te()?$o:fc);return Kf(e,t,{accepted:o(s=>n.includes(s)||te()&&s===ur,"accepted"),listed:n})}o(BC,"gatewayTransportVersionRefusal");function FC(e){return{jsonrpc:"2.0",id:e,result:{}}}o(FC,"pingResult");function Zf(e){if(e.parsed===void 0)return on(I.ParseError,"Parse error: Invalid JSON");let t=Array.isArray(e.parsed)?HC(e.headers,e.parsed):void 0;if(t!==void 0)return t;let r=BC(e.headers,e.parsed,e.payload.upstreamServerId);if(r!==void 0)return r;let n=o(i=>i.message.method==="ping"?FC(i.id):Rc({id:i.id,payload:e.payload,urlElicitation:LC(i.message),fallbackCode:Sc}),"answer");if(Array.isArray(e.parsed)){if(e.parsed.length===0)return on(I.InvalidRequest,"Invalid Request: empty batch");let i=e.parsed.map((c,d)=>Vf(c,d)),a=i.flatMap(c=>{switch(c.kind){case"request":return[n(c)];case"invalid":return[c.error];case"accepted":return[]}});return i.every(c=>c.kind==="invalid")?Response.json(a,{status:400}):a.length===0?Gf():Response.json(a)}let s=Vf(e.parsed);switch(s.kind){case"request":return Response.json(n(s));case"accepted":return s.response&&te()&&Co(e.headers.get("mcp-protocol-version"))?on(I.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):Gf();case"invalid":return Response.json(s.error,{status:400})}}o(Zf,"legacyConnectRequiredResponse");function xe(){return zr.instance.build.COMPATIBILITY_FLAGS.mcpGatewaySpecCompliance===!0}o(xe,"isMcpGatewaySpecComplianceEnabled");var JC={Allow:"POST"};function Si(e,t){return Ne.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},JC)}o(Si,"gatewayMethodNotAllowed");function We(e){return(e??"").split(";")[0].trim().toLowerCase()}o(We,"mediaTypeEssence");var VC=["content-encoding","content-length","content-md5","digest","content-digest","repr-digest"];function wt(e){for(let t of VC)e.delete(t);return e}o(wt,"deleteEncodedBodyHeaders");function Yf(){let e=zr.instance;return e.isDeno?"deno":e.isCloudflare?"workerd":"node"}o(Yf,"currentRuntime");var GC=new Set(["gzip","x-gzip","deflate","br","zstd"]);function ht(e,t=Yf()){let r=e.get("content-encoding")?.trim();if(!r||r.toLowerCase()==="identity")return!1;switch(t){case"deno":return!0;case"workerd":return r!=="gzip"&&r!=="br";default:return!r.toLowerCase().split(",").every(n=>GC.has(n.trim()))}}o(ht,"isBodyStillEncoded");function Xf(e){return ht(e)?e:wt(e)}o(Xf,"deleteEncodedBodyHeadersIfDecoded");function Qf(e,t=Yf()){let r=e.get("content-encoding")?.trim().toLowerCase();return(r!==void 0&&r!==""&&r!=="identity"?ht(e,t):e.has("content-length"))?e:wt(e)}o(Qf,"deleteEncodedBodyHeadersIfRuntimeDecoded");var tg=10*1024*1024,KC=1024,WC=32,ZC=64,hr=class extends Error{constructor(r,n=!1){super(`SSE event exceeds the ${r}-character limit`);this.maxEventChars=r;this.comment=n;this.name="SseEventTooLargeError"}maxEventChars;comment;static{o(this,"SseEventTooLargeError")}},YC=10;function XC(e,t){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e.then(void 0,t)}o(XC,"handleRejection");function rg(e){let t=e.indexOf(":");return t===-1?e:e.slice(0,t)}o(rg,"fieldName");var fr=class{static{o(this,"SseParser")}#e;#r;#t;#n=new TextDecoder("utf-8",{ignoreBOM:!0});#l=!1;#p=/\r\n|\r|\n/g;#m="";#d=[];#o=[];#i=0;#a=!1;#u=!1;#h=!1;#s=!1;#f=!1;#S=0;#C=0;#c=[];#g=0;#y=[];#R;#w;#_;#b=[];constructor(t={}){let r=t.maxEventChars??tg;if(!Number.isInteger(r)||r<=0)throw new RangeError(`maxEventChars must be a positive integer, got ${r}`);this.#e=r,this.#r=t.onOversize==="discard",this.#t=t.emitLoneComments===!0}get discardedEvents(){return this.#S}get discardedComments(){return this.#C}get discarding(){return this.#s||this.#f}get idle(){return this.#i===0&&!this.#a&&!this.#s&&this.#c.length===0}push(t){let r=[];return this.#T(this.#I(this.#n.decode(t,{stream:!0})),r),r}end(){let t=[];return this.#T(this.#I(this.#n.decode()),t),(this.#i>0||this.#a)&&this.#A(t,!1),this.#s||this.#P(t,!1),this.#s=!1,t}#I(t){return this.#l||t===""?t:(this.#l=!0,t.charCodeAt(0)===65279?t.slice(1):t)}#T(t,r){if(t==="")return;let n=0;this.#h&&(this.#h=!1,t.charCodeAt(0)===YC&&(n=1));let s=this.#p;s.lastIndex=n;let i=s.exec(t);for(;i!==null;)this.#E(t.slice(n,i.index)),this.#A(r),n=i.index+i[0].length,i[0]==="\r"&&n===t.length&&(this.#h=!0),i=s.exec(t);this.#E(t.slice(n))}#E(t){if(t!==""){if(this.#s||this.#f){this.#a=!0;return}if(this.#i===0?this.#m=t:(this.#o.push(t),this.#o.length>=ZC&&(this.#d.push(this.#o.join("")),this.#o=[])),this.#i+=t.length,this.#g+this.#i>this.#e){let r=this.#O();r&&this.#r?(this.#v(),this.#f=!0,this.#S++,this.#C++):this.#k(r),this.#a=!0}}}#O(){return this.#t&&this.#c.length===0&&this.#m.charCodeAt(0)===58}#k(t=!1){if(!this.#r)throw new hr(this.#e,t);this.#x(),this.#u=!1,this.#v(),this.#s=!0,this.#S++}#v(){this.#m="",this.#d.length>0&&(this.#d=[]),this.#o.length>0&&(this.#o=[]),this.#i=0}#A(t,r=!0){let n=this.#d.length===0&&this.#o.length===0?this.#m:this.#m+this.#d.join("")+this.#o.join(""),s=n===""&&!this.#a;if(this.#v(),this.#a=!1,this.#f){this.#f=!1,this.#u=!0;return}if(s){this.#s?this.#s=!1:this.#u&&this.#c.length===0?(this.#u=!1,t.push({lines:[],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[],terminated:!0})):(this.#u=!1,this.#P(t,!0));return}if(this.#s)return;if(this.#t&&r&&this.#c.length===0&&n.charCodeAt(0)===58){t.push({lines:[n],data:void 0,event:void 0,id:void 0,retry:void 0,comments:[n.slice(1)],terminated:!0,lone:!0}),this.#u=!0;return}if(this.#g+=n.length,this.#c.push(n),this.#c.length>KC&&(this.#g+=Math.max(0,WC-n.length),this.#g>this.#e)){this.#k();return}if(n.charCodeAt(0)===58){this.#b.push(n.slice(1));return}let i=n.indexOf(":"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);switch(c.charCodeAt(0)===32&&(c=c.slice(1)),a){case"data":this.#y.push(c);break;case"event":this.#R=c;break;case"id":c.includes("\0")||(this.#w=c);break;case"retry":/^[0-9]+$/.test(c)&&(this.#_=Number(c));break;default:break}}#P(t,r){this.#c.length>0&&t.push({lines:this.#c,data:this.#y.length>0?this.#y.join(`
|
|
26
|
-
`):void 0,event:this.#R,id:this.#w,retry:this.#_,comments:this.#b,terminated:r}),this.#x()}#x(){this.#c=[],this.#g=0,this.#y=[],this.#R=void 0,this.#w=void 0,this.#_=void 0,this.#b=[]}};function wc(e,t){if(/[\r\n]/.test(t))throw new TypeError(`SSE ${e} must not contain a line break`)}o(wc,"assertSingleLine");function _c(e){if("lines"in e){for(let n of e.lines){if(/[\r\n]/.test(n))throw new TypeError("SSE event line must not contain a line break");if(n==="")throw new TypeError("SSE event line must not be empty")}let r=e.lines.map(n=>`${n}
|
|
27
|
-
`).join("");return e.lines[0]?.charCodeAt(0)===65279&&(r=`
|
|
28
|
-
${r}`),e.terminated?`${r}
|
|
29
|
-
`:r}let t="";for(let r of e.comments??[])wc("comment",r),t+=`:${r}
|
|
30
|
-
`;if(e.event!==void 0&&(wc("event",e.event),t+=`event: ${e.event}
|
|
31
|
-
`),e.id!==void 0){if(wc("id",e.id),e.id.includes("\0"))throw new TypeError("SSE id must not contain NUL");t+=`id: ${e.id}
|
|
32
|
-
`}if(e.retry!==void 0){if(!Number.isSafeInteger(e.retry)||e.retry<0)throw new TypeError("SSE retry must be a non-negative integer");t+=`retry: ${e.retry}
|
|
33
|
-
`}if(e.data!==void 0)for(let r of e.data.split(/\r\n|\r|\n/))t+=`data: ${r}
|
|
34
|
-
`;return t===""?"":`${t}
|
|
35
|
-
`}o(_c,"serializeSseEvent");var QC=new Set(["data","event","id","retry"]);function ng(e){return e.lines.some(t=>t.charCodeAt(0)!==58&&!QC.has(rg(t)))}o(ng,"hasUnknownSseFields");function Fo(e,t){let r=t.split(/\r\n|\r|\n/);return{...e,lines:[...e.lines.filter(n=>rg(n)!=="data"),...r.map(n=>`data: ${n}`)],data:r.join(`
|
|
36
|
-
`)}}o(Fo,"replaceSseData");var og=Symbol("sse.terminate");function vc(...e){return{[og]:!0,events:e}}o(vc,"terminateSse");function eI(e){return typeof e=="object"&&e!==null&&og in e}o(eI,"isTerminate");var tI=64,eg=new Uint8Array(0),bc=class{static{o(this,"SseRawEventBytes")}#e=eg;#r=0;#t=[];#n=0;get length(){return this.#r+this.#n}get views(){return this.#t.length}push(t){t.length!==0&&(this.#t.push(t),this.#n+=t.length,this.#t.length>=tI&&this.#l())}take(){let t;return this.#r===0?t=sI(this.#t):(this.#l(),t=this.#e.subarray(0,this.#r)),this.clear(),t}clear(){this.#e=eg,this.#r=0,this.#t.length>0&&(this.#t=[]),this.#n=0}#l(){let t=this.#r+this.#n;if(t>this.#e.length){let r=new Uint8Array(Math.max(t,this.#e.length*2));r.set(this.#e.subarray(0,this.#r)),this.#e=r}for(let r of this.#t)this.#e.set(r,this.#r),this.#r+=r.length;this.#t=[],this.#n=0}},Bo=10,Ri=13,rI=[239,187,191];function nI(e){let t=[],r=0;for(let n=0;n<e.length;n++){let s=e[n];(s===Bo||s===Ri&&e[n+1]!==Bo)&&(t.push(e.subarray(r,n+1)),r=n+1)}return r<e.length&&t.push(e.subarray(r)),t}o(nI,"splitLines");function oI(e){let t=e[e.length-1];return t===Bo||t===Ri}o(oI,"endsLine");function Cc(e,t,r={}){let n=r.failureMode??"closed",s=n==="open"&&r.onOversize!=="discard",i=r.maxEventChars??tg,a=new fr(s?{maxEventChars:i,onOversize:"discard",emitLoneComments:!0}:{...r,emitLoneComments:!0}),c=new TextEncoder,d=new AbortController,u={signal:d.signal,get discardedEvents(){return s?0:a.discardedEvents}},p=e.getReader(),h=!1,f=!1,y=0,b=new bc,w=0,S=!1,R,v,x=o(P=>{h=!0,d.abort(P),p.cancel(P).catch(()=>{})},"stop"),N=o((P,$)=>{try{XC(r.onFailure?.(P,$),()=>{})}catch{}},"report"),T=o(P=>{N(P,{mode:n,kind:"oversize",...P.comment?{comment:!0}:{}})},"reportOversize"),O=o(P=>{if(!("lines"in P))return _c(P);if(P.terminated!==!0)throw new TypeError("SSE event returned by a rewriter must be terminated");return P.lone===!0&&P.lines.length>0&&P.lines.every($=>$.charCodeAt(0)===58)?_c({...P,terminated:!1}):_c(P)},"write"),L=o((P,$)=>eI(P)?{text:P.events.map(O).join(""),terminate:!0}:P===void 0?{text:$===void 0?"":O($),terminate:!1}:P===null?{text:"",terminate:!1}:{text:(Array.isArray(P)?P:[P]).map(O).join(""),terminate:!1},"render"),Q=o(P=>{if(!s)try{return a.push(P).map(j=>({event:j}))}catch(j){throw j instanceof hr&&T(j),j}let $=[];for(let j of nI(P)){if(S&&(S=!1,j[0]===Bo)){a.push(j),y+=j.length,$.push({raw:j,atStart:!1});continue}let B=a.discardedEvents,ee=a.discardedComments,Ue=a.discarding;!Ue&&b.length===0&&(w=y),y+=j.length;for(let De of a.push(j))$.push({event:De});Ue?($.push({raw:j,atStart:!1}),S=!a.discarding&&j[j.length-1]===Ri):a.discardedEvents>B?(T(new hr(i,a.discardedComments>ee)),b.push(j),$.push({raw:b.take(),atStart:w===0}),S=!a.discarding&&j[j.length-1]===Ri):oI(j)&&a.idle?b.clear():b.push(j)}return $},"parse");return new ReadableStream({async pull(P){if(v!==void 0){P.error(v.error);return}try{for(;;){let $=await p.read();if(h)return;let j,B=!1,ee=!1;if($.done){j=[],ee=s&&a.discarding;let Y=a.discardedEvents,le=a.discardedComments,qe;try{qe=a.end()}catch(oe){throw oe instanceof hr&&T(oe),oe}for(let oe of qe)oe.terminated?j.push({event:oe}):B=!0;a.discardedEvents>Y&&b.length>0&&(T(new hr(i,a.discardedComments>le)),j.push({raw:b.take(),atStart:w===0}),ee=!0),b.clear(),B||=ee}else j=Q($.value);let Ue=!1,De=o(Y=>{Y.length>0&&(P.enqueue(Y),Ue=!0,f=!0)},"enqueue"),Ge=o(Y=>{Y!==""&&De(c.encode(Y))},"emit");for(let Y of j){if("raw"in Y){!f&&!Y.atStart&&rI.every((oe,tt)=>Y.raw[tt]===oe)&&Ge(`
|
|
37
|
-
`),De(Y.raw.slice()),R=Y.raw[Y.raw.length-1];continue}let{event:le}=Y,qe;try{let oe=await t(le,u);if(h)return;qe=L(oe,le)}catch(oe){if(h)return;if(N(oe,{mode:n,kind:"transform",event:le}),n==="closed")throw oe;qe={text:O(le),terminate:!1}}if(Ge(qe.text),qe.terminate){x("SSE stream terminated by its rewriter"),P.close();return}}if($.done){if(r.end!==void 0){let Y;try{let le=await r.end({...u,unterminated:B});if(h)return;Y=L(le,void 0)}catch(le){if(h)return;if(N(le,{mode:n,kind:"end"}),n==="closed")throw le;Y={text:"",terminate:!1}}if(ee&&Y.text!==""&&Ge(R===Bo?`
|
|
38
|
-
`:`
|
|
39
|
-
|
|
40
|
-
`),Ge(Y.text),Y.terminate){x("SSE stream terminated by its rewriter"),P.close();return}}h=!0,P.close();return}if(Ue)return}}catch($){h||(x($),(P.desiredSize??0)<0?v={error:$}:P.error($))}},cancel(P){if(!h)return h=!0,d.abort(P),p.cancel(P)}},{highWaterMark:0})}o(Cc,"rewriteSseStream");function sI(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(sI,"concatBytes");function wi(e,t,r){if(e.body===null)return e;let n=wt(new Headers(e.headers));return n.set("content-type","text/event-stream"),new Response(Cc(e.body,t,r),{status:e.status,statusText:e.statusText,headers:n})}o(wi,"rewriteSseResponse");var ag=new Set(["jsonrpc","method","id","params"]),Ec=new Set(["name","uri","ref"]),cg=new Set(["type","name","uri"]),iI="subscriptions/listen",kc="notifications",dg="resourceSubscriptions",aI=new Set([...Ec,_t(kc)]),cI=new Set([_t(dg)]),dI=/[^\u0000-\u007f]/,uI=34,lI=92,sg=123,pI=125,mI=91,hI=93,fI=58,Ic=44;function Jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Jo,"isRecord");function _t(e){return e.toUpperCase().toLowerCase()}o(_t,"foldCase");function Tc(e,t){return Object.keys(e).some(r=>{let n=_t(r);return n!==r&&t.has(n)})}o(Tc,"hasCaseVariant");function ig(e,t){let r=_t(t);return Object.keys(e).some(n=>n!==t&&_t(n)===r)}o(ig,"hasCaseVariantOf");function gI(e,t){let r=o(a=>{switch(a.role){case"member":return ag;case"params":return t.has(a.member)?aI:Ec;case"ref":return cg;case"notifications":return cI;default:return}},"watchedFor"),n=[],s=0,i=o(a=>{let c=n.at(-1);if(c===void 0)return a?"member":"batch";if(a){if(c.role==="batch")return"member";if(c.role==="member"&&c.key==="params")return"params";if(c.role==="params"&&c.key==="ref")return"ref";if(c.role==="params"&&c.key===kc&&t.has(c.member))return"notifications"}},"childRole");for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(c===uI){let d=a;for(;;){if(d=e.indexOf('"',d+1),d===-1)return!0;let p=0;for(;e.charCodeAt(d-1-p)===lI;)p++;if(p%2===0)break}let u=s>0?void 0:n.at(-1);if(u?.isObject&&u.expectKey){let p=e.slice(a,d+1),h=p.includes("\\")?JSON.parse(p):p.slice(1,-1);if(dI.test(h))return!0;u.key=h;let f=_t(h);if(r(u)?.has(f)){if(u.seen.has(f))return!0;u.seen.add(f)}}a=d}else if(c===sg||c===mI){let d=c===sg,u=s>0?void 0:i(d);if(u===void 0)s++;else{let p=n.at(-1)?.member??0;n.push({role:u,isObject:d,seen:new Set,member:p,expectKey:d})}}else if(c===pI||c===hI)s>0?s--:n.pop();else if(s===0&&(c===fI||c===Ic)){let d=n.at(-1);d?.isObject?d.expectKey=c===Ic:d?.role==="batch"&&c===Ic&&d.member++}}return!1}o(gI,"hasUnsafeKeyInText");function ug(e){let t=new Set;for(let[r,n]of e.envelope.messages.entries()){let s=n.raw;if(Jo(s)){if(Tc(s,ag)||e.checksListen===!0&&s.method===iI&&(t.add(r),Jo(s.params)&&(ig(s.params,kc)||Jo(s.params.notifications)&&ig(s.params.notifications,dg))))return!0;if(!(typeof s.method!="string"||!e.isCapabilityMethod(s.method)||!Jo(s.params))&&(Tc(s.params,Ec)||Jo(s.params.ref)&&Tc(s.params.ref,cg)))return!0}}return gI(e.text,t)}o(ug,"hasAmbiguousIdentifyingKeys");var yI=o(e=>e===10||e===13||e===8232||e===8233,"isLineTerminator"),SI=47,lg=44,RI=38,Ac=o(e=>e!==SI&&e!==lg,"VALUE"),wI=o(e=>!yI(e),"ANY"),_I=o(e=>e!==RI,"QUERY_VALUE"),bI=["+","#",".","/","?","&"],Pc=class{static{o(this,"Builder")}edges=[[]];current=0;#e(){return this.edges.push([]),this.edges.length-1}literal(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r),s=this.#e();this.edges[this.current].push({test:o(i=>i===n,"test"),to:s}),this.current=s}}plus(t){let r=this.#e();this.edges[this.current].push({test:t,to:r}),this.edges[r].push({test:t,to:r}),this.current=r}value(t){if(this.plus(Ac),!t)return;let r=this.current,n=this.#e();this.edges[r].push({test:o(s=>s===lg,"test"),to:n}),this.edges[n].push({test:Ac,to:r})}};function pg(e){let t=new Pc,r="",n=0;for(;n<e.length;){if(e[n]!=="{"){r+=e[n],n++;continue}let s=e.indexOf("}",n);if(s===-1)return;t.literal(r),r="";let i=e.slice(n+1,s),a=bI.find(u=>i.startsWith(u))??"",c=i.includes("*"),d=i.slice(a.length).split(",").map(u=>u.replace("*","").trim()).filter(u=>u.length>0);switch(a){case"?":case"&":d.forEach((u,p)=>{t.literal(`${p===0?a:"&"}${u}=`),t.plus(_I)});break;case"+":case"#":t.plus(wI);break;case".":t.literal("."),t.plus(Ac);break;case"/":t.literal("/"),t.value(c);break;default:t.value(c)}n=s+1}return t.literal(r),{edges:t.edges,accept:t.current}}o(pg,"compileUriTemplate");function mg(e,t){if(t.length>1e6)return!1;let{edges:r,accept:n}=e,s=new Array(r.length).fill(-1),i=[0];for(let a=0;a<t.length;a++){let c=t.charCodeAt(a),d=[];for(let u of i)for(let p of r[u])s[p.to]!==a&&p.test(c)&&(s[p.to]=a,d.push(p.to));if(d.length===0)return!1;i=d}return i.includes(n)}o(mg,"matchesUriTemplate");var Ii=m.record(m.string(),m.unknown()),vI=m.record(m.string(),m.unknown()),jt=m.array(m.string().min(1)).min(1).optional(),CI=m.object({name:m.string().min(1),description:m.string().min(1).optional(),annotations:vI.optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),II=m.object({name:m.string().min(1),description:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),TI=m.object({uri:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),EI=m.object({uriTemplate:m.string().min(1),name:m.string().min(1).optional(),description:m.string().min(1).optional(),mimeType:m.string().min(1).optional(),_meta:Ii.optional(),roles:jt,groups:jt,public:m.boolean().optional()}).strict(),kI=m.array(m.union([m.string(),CI])),AI=m.array(m.union([m.string(),II])),PI=m.array(m.union([m.string(),TI])),xI=m.array(m.union([m.string(),EI])),OI=m.object({module:m.unknown(),export:m.string().min(1)}).strict(),MI=m.object({mode:m.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:m.string().min(1).optional(),groupClaim:m.string().min(1).optional(),identifier:OI.optional()}).strict(),UI=m.object({tools:kI.optional(),prompts:AI.optional(),resources:PI.optional(),resourceTemplates:xI.optional(),accessControl:MI.optional()}).strict(),bt=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read","resources/subscribe","resources/unsubscribe"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function qI(e,t){return Vm(UI,e,`MCP capability filter policy "${t}"`)}o(qI,"parseMcpCapabilityFilterOptions");function H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(H,"isRecord");function je(e){return typeof e.method=="string"?e.method:void 0}o(je,"messageMethod");function Go(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}o(Go,"correlationKey");function vg(e){let t=new Set,r=new Map;for(let n of e){let s=Go(n);if(s===void 0)continue;t.add(s);let i=String(n),a=r.get(i)??new Set;a.add(s),r.set(i,a)}return n=>{let s=Go(n);if(s===void 0)return;if(t.has(s))return s;let i=r.get(String(n));return i?.size===1?[...i][0]:void 0}}o(vg,"createReplyIdMatcher");function hg(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}o(hg,"asStringArray");function fg(e,t){if(!H(e))return[];let r=t in e?e[t]:t.split(".").reduce((n,s)=>H(n)?n[s]:void 0,e);return Array.isArray(r)?r.filter(n=>typeof n=="string"):typeof r=="string"?r.split(/\s+/).filter(n=>n.length>0):[]}o(fg,"readClaimValues");function jc(e,t){if(typeof e=="string")return{key:e,public:!1};if(!H(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:hg(e.roles),groups:hg(e.groups),public:e.public===!0}}o(jc,"normalizeEntry");function zI(e,t,r){if(e.public)return!0;let n=e.roles??[],s=e.groups??[];return n.length===0&&s.length===0?!1:n.some(i=>t.has(i))||s.some(i=>r.has(i))}o(zI,"isCallerAllowed");function _i(e,t,r,n){if(e===void 0)return;let s=[];for(let i of e){let a=jc(i,t);a!==void 0&&zI(a,r,n)&&s.push(a.key)}return s}o(_i,"allowedKeys");var Cg=o((e,t,r)=>{let n=r.accessControl?.roleClaim??"roles",s=r.accessControl?.groupClaim??"groups",i=new Set(fg(e.user?.data,n)),a=new Set(fg(e.user?.data,s));return{tools:_i(r.tools,"name",i,a),prompts:_i(r.prompts,"name",i,a),resources:_i(r.resources,"uri",i,a),resourceTemplates:_i(r.resourceTemplates,"uriTemplate",i,a)}},"claimsCapabilityResolver");function NI(e,t){let r=[];for(let n of bt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=jc(i,n.itemProperty);if(a===void 0)continue;let c=(a.roles?.length??0)>0||(a.groups?.length??0)>0;a.public&&c&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new re(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}o(NI,"assertNoConflictingMarkup");function jI(e,t){let r=[];for(let n of bt){let s=e[n.option];if(s!==void 0)for(let i of s){let a=jc(i,n.itemProperty);a!==void 0&&((a.roles?.length??0)>0||(a.groups?.length??0)>0||a.public)&&r.push(`${n.option} "${a.key}"`)}}if(r.length>0)throw new re(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}o(jI,"assertNoMarkup");function DI(e,t){let r=e.identifier;if(r===void 0)throw new re(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new re(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new re(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let n=r.module[r.export];if(typeof n!="function")throw new re(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let s=n;return async(i,a,c)=>{let d=await s(i,a,c);if(d==null)throw new k(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof d!="object"||Array.isArray(d))throw new k(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return d}}o(DI,"buildCustomResolver");function LI(e,t){let r=e.accessControl,n=r?.mode??"allPublic";if(n==="function"){if(r===void 0)throw new re(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return DI(r,t)}if(n==="rolesAndGroups")return NI(e,t),Cg;jI(e,t)}o(LI,"buildCapabilityResolver");function $I(e){let t={};for(let r of bt){let n=e[r.option];if(n===void 0)continue;let s=new Map;for(let i of n){let a=uT(i,r.itemProperty);a!==void 0&&s.set(a.key,a)}t[r.option]=s}return t}o($I,"buildProjectionMaps");function Ig(e){return e===void 0?void 0:bt.find(t=>t.listMethod===e)}o(Ig,"findListRule");function Dc(e){return e===void 0?void 0:bt.find(t=>t.directMethods.includes(e))}o(Dc,"findDirectRule");var Ti="completion/complete",Tg=["prompts","resources","resourceTemplates"];function Eg(e){return e===Ti||Dc(e)!==void 0}o(Eg,"isCapabilityMethod");var Ci="subscriptions/listen",HI=[...bt.flatMap(e=>[e.listMethod,...e.directMethods]),Ti,Ci];function BI(e){let t=_t(e.trim()),r=HI.find(n=>_t(n)===t);return r!==void 0&&r!==e?r:void 0}o(BI,"methodVariantOf");function gg(e,[t,r]){return{code:I.InvalidParams,message:`Invalid params for ${e}: ${t} must be ${r}`}}o(gg,"invalidParams");function Lc(e){return t=>({code:I.InvalidParams,message:`${e} "${$s(t)}" not found`})}o(Lc,"namedNotFound");function FI(e,t){return{code:Am(t),message:"Resource not found",data:{uri:Ls(e,Pm)}}}o(FI,"resourceNotFound");var JI={legacy:Lc("Tool"),modern:Io.tool},xc={legacy:Lc("Prompt"),modern:Io.prompt},VI={legacy:FI,modern:Io.resource},GI={legacy:Lc("Resource template"),modern:Io.resourceTemplate};function KI(e){let t=je(e);if(t===void 0||!Eg(t))return[];let r=H(e.raw)?e.raw.params:void 0,n=o((d,u)=>H(d)&&typeof d[u]=="string"?d[u]:void 0,"stringAt"),s=o(d=>H(r)?[d,"a string"]:["params","an object"],"stringIssue");if(t!==Ti){let d=Dc(t);return d.option==="resources"?[{options:["resources","resourceTemplates"],resource:!0,target:n(r,"uri"),issue:s("params.uri"),notFound:VI}]:[{options:[d.option],target:n(r,"name"),issue:s("params.name"),notFound:d.option==="tools"?JI:xc}]}let i=H(r)?r.ref:void 0,a=H(i)?i.type:void 0;if(a==="ref/prompt")return[{options:["prompts"],target:n(i,"name"),issue:["params.ref.name","a string"],notFound:xc}];if(a==="ref/resource"){let d=n(i,"uri");return[{options:["resources","resourceTemplates"],...d!==void 0&&WI(d)?{refusedBy:["resourceTemplates"]}:{},target:d,issue:["params.ref.uri","a string"],notFound:GI}]}let c=H(r)?H(i)?["params.ref.type",'"ref/prompt" or "ref/resource"']:["params.ref","an object"]:["params","an object"];return[{options:Tg,target:void 0,issue:c,notFound:xc}]}o(KI,"capabilityAccesses");function WI(e){let t=!1,r=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s===125){if(t&&r>0)return!0;t=!1,r=0}else ZI(s)?(t=!1,r=0):t?r++:s===123&&(t=!0)}return!1}o(WI,"hasTemplateExpression");function ZI(e){return e>32&&e<127?!1:YI.test(String.fromCharCode(e))}o(ZI,"isWhitespaceCode");var YI=/\s/;function XI(e){return e.type==="invalid"&&(!H(e.raw)||e.raw.jsonrpc!=="2.0")}o(XI,"isNonJsonRpcMember");function QI(e){return H(e.raw)&&Object.hasOwn(e.raw,"method")&&typeof e.raw.method!="string"}o(QI,"hasNonStringMethod");function kg(e){return e.type==="request"||e.type==="invalid"&&je(e)!==void 0}o(kg,"awaitsReply");function eT(e){return H(e.raw)&&H(e.raw.params)?e.raw.params:void 0}o(eT,"rawParams");function tT(e,t){let r=t.messages[0];return t.shape!=="single"||r===void 0?!1:te()&&Fr(e.headers,r.raw)}o(tT,"isModernRequest");var yg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Oc="=?base64?",Mc="?=",rT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function nT(e){if(!e.startsWith(Oc)||!e.endsWith(Mc)||e.length<Oc.length+Mc.length)return e;let t=e.slice(Oc.length,e.length-Mc.length);if(rT.test(t))try{let r=atob(t),n=Uint8Array.from(r,s=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}o(nT,"decodeMcpHeaderValue");var oT=-32020;function sT(e,t){let r=je(t);if(r===void 0)return;let n=H(t.raw)?t.raw.id:void 0,s=Ko(n)?n:void 0,i=e.headers.get("mcp-protocol-version"),a=Em(t.raw);if(i!==null&&a!==void 0&&i!==a)return bi(s,i,`the body envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let c=e.headers.get("mcp-method");if(c!==null&&c!==r)return bi(s,c,`the body names method ${r} but the Mcp-Method header names ${c}`);let d=e.headers.get("mcp-name"),u=Object.hasOwn(yg,r)?yg[r]:void 0;if(d===null||u===void 0||t.type==="notification")return;let p=nT(d);if(p===void 0)return bi(s,d,"the Mcp-Name header carries an invalid Base64 sentinel value");let h=eT(t)?.[u];if(typeof h=="string"&&p!==h)return bi(s,d,`the body carries params.${u}="${h}" but the Mcp-Name header names "${p}"`)}o(sT,"headerMismatchResponse");function bi(e,t,r){return st(400,{code:oT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}},e)}o(bi,"mismatchResponse");var iT={code:I.MethodNotFound,message:"Method not found"},Sg={code:I.InternalError,message:"The MCP capability filter could not resolve which capabilities the caller may use, so the request was not forwarded."},aT={code:I.InternalError,message:"The request was not forwarded, because another request in its batch was refused."},cT="2025-06-18";function Ko(e){return typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)}o(Ko,"isValidRequestId");function Ag(e){return H(e.raw)&&!Object.hasOwn(e.raw,"id")}o(Ag,"isSentAsNotification");function Vo(e,t){return{jsonrpc:"2.0",...t===void 0?{}:{id:t},error:e}}o(Vo,"jsonRpcError");function st(e,t,r){return Response.json(Vo(t,r),{status:e})}o(st,"jsonRpcErrorResponse");function vi(e){return st(400,{code:I.InvalidRequest,message:`Invalid Request: ${e}`})}o(vi,"invalidRequestResponse");function Uc(e,t,r=!1){if(Ag(e))return{status:400,body:Vo({code:I.InvalidRequest,message:`Invalid Request: a notification cannot use ${$s(je(e)??"this method")}; send it as a request with an id`})};let n=H(e.raw)?e.raw.id:void 0;return Ko(n)?{status:r&&t.code===I.MethodNotFound?404:200,body:Vo(t,n)}:{status:400,body:Vo({code:I.InvalidRequest,message:"Invalid Request: id must be a string or an integer"})}}o(Uc,"refusalOf");var Rg=-32e3;function dT(e,t){let r=e.headers.get("accept");if(r===null||!/application\/json/i.test(r))return st(406,{code:Rg,message:"Not Acceptable: Client must accept both application/json and text/event-stream"});if(!bm(e.headers.get("content-type")??void 0))return st(415,{code:Rg,message:"Unsupported Media Type: Content-Type must be application/json"});if(!(t.shape==="batch"&&Hs(e.headers.get("mcp-protocol-version")))){if(t.shape==="single"){let n=Vr(t.messages[0]?.raw);if(n!==void 0)return Response.json(n,{status:400})}return Wf(e.headers,t.shape==="batch"?t.messages.map(n=>n.raw):t.messages[0]?.raw)}}o(dT,"legacyTransportRefusal");function wg(e,t,r=!1,n=!1){let[s]=[...t];if(e.shape!=="batch"){let{status:d,body:u}=Uc(s[0],s[1],r);return Response.json(u,{status:d})}let i=e.protocolVersion;if(i!==void 0&&i>=cT)return vi(`protocol version ${$s(i)} does not support JSON-RPC batches`);let a=0,c=e.messages.flatMap((d,u)=>{let p=n?Vr(d.raw,u):void 0;if(p!==void 0)return a+=1,[p];if(d.type==="result"||d.type==="error"||Ag(d))return[];let h=H(d.raw)?d.raw.id:void 0;return n&&!t.has(d)&&je(d)==="ping"&&Ko(h)?[{jsonrpc:"2.0",id:h,result:{}}]:[Uc(d,t.get(d)??aT).body]});if(c.length===0){let{status:d,body:u}=Uc(s[0],s[1]);return Response.json(u,{status:d})}return Response.json(c,{status:a===e.messages.length?400:200})}o(wg,"refusalResponse");function uT(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!H(e))return;let r=e[t];if(typeof r!="string")return;let n={...e};return delete n.roles,delete n.groups,delete n.public,{key:r,overlay:n}}o(uT,"buildProjection");function _g(e){let t=e.base[e.property],r=e.overlay[e.property];return H(r)?H(t)?{...t,...r}:r:t}o(_g,"mergeRecordProperty");function lT(e,t){let r={...e,...t.overlay},n=_g({base:e,overlay:t.overlay,property:"annotations"});n!==void 0&&(r.annotations=n);let s=_g({base:e,overlay:t.overlay,property:"_meta"});return s!==void 0&&(r._meta=s),r}o(lT,"applyProjection");var Oe=Symbol("unreadable"),sn=Symbol("dropped");function pT(e,t,r,n,s){let i=e.result;if(!H(i))return Oe;let a=i[t.resultProperty];return!Array.isArray(a)||Object.hasOwn(i,"nextCursor")&&i.nextCursor!==null&&typeof i.nextCursor!="string"?Oe:{...e,result:{...i,...s?{cacheScope:"private"}:{},[t.resultProperty]:a.flatMap(d=>{if(!H(d))return[];let u=d[t.itemProperty];if(typeof u!="string")return[];if(n!==void 0&&!n.has(u))return[];let p=r.get(u);return p===void 0?[]:[lT(d,p)]})}}}o(pT,"filterAndProjectItems");var Pg="resources/read";function mT(e){let t=e.result;return!H(t)||t.cacheScope==="private"||t.resultType!==void 0&&t.resultType!=="complete"?e:{...e,result:{...t,cacheScope:"private"}}}o(mT,"withPrivateReadScope");function xg(e,t){let r=Ig(je(e)),n=r===void 0?void 0:t[r.option];return r===void 0||n===void 0?null:{rule:r,projections:n}}o(xg,"listTargetOf");function hT(e,t,r){return H(e)&&bt.some(n=>n!==t?.rule&&r[n.option]!==void 0&&Object.hasOwn(e,n.resultProperty))}o(hT,"carriesUnfilteredList");function fT(e){let{envelope:t,projectionMaps:r,allowedSets:n,privateScope:s,privateReadScope:i,isResourceVisible:a}=e,c=o(S=>xg(S,r),"listTarget"),d=t.messages.filter(kg),u=new Map;for(let S of d){let R=Go(S.id);R!==void 0&&!u.get(R)&&u.set(R,c(S))}let p=vg(d.map(S=>S.id)),h=t.messages[0],f=i&&t.shape==="single"&&h!==void 0&&je(h)===Pg,y=o(S=>{if(t.shape!=="batch")return h===void 0?void 0:c(h);let R=p(S);return R===void 0?void 0:u.get(R)},"targetForReply"),b=o(S=>{if(!H(S))return Oe;if(!("result"in S))return"method"in S&&!("error"in S)?w(S):"error"in S||"method"in S?S:Oe;let R=y(S.id);return R===void 0||hT(S.result,R,r)?Oe:R===null?f?mT(S):S:pT(S,R.rule,R.projections,n?.[R.rule.option],s)},"filterMessage"),w=o(S=>{if(a===void 0)return S;if(S.method==="notifications/resources/updated"){let R=H(S.params)?S.params.uri:void 0;return typeof R=="string"&&!a(R)?sn:S}if(S.method==="notifications/subscriptions/acknowledged"){let R=Ug(S.params,a);return R===void 0?S:{...S,params:R}}return S},"filterServerMessage");return S=>{if(!Array.isArray(S))return b(S);if(t.shape!=="batch")return Oe;let R=S.map(b);if(R.includes(Oe))return Oe;let v=R.filter(x=>x!==sn);return v.length===R.length?R:v.length===0?sn:v}}o(fT,"createReplyFilter");function gT(e){return We(e.headers.get("content-type")).includes("json")}o(gT,"isJsonResponse");function yT(e){return We(e.headers.get("content-type"))==="text/event-stream"}o(yT,"isEventStreamResponse");var ST=10*1024*1024,RT=/^[\w.~:/+=-]{0,256}$/;function wT(e){if(ng(e))return null;let t=!1;for(let n of e.lines){let s=n.indexOf(":"),i=s===-1?n:n.slice(0,s),a=s===-1?"":n.slice(s+1).replace(/^ /,""),c=i===""&&a.trim()===""||i==="data"||i==="event"&&(a===""||a==="message")||i==="id"&&RT.test(a)||i==="retry"&&/^[0-9]+$/.test(a);if(i===""&&!c)t=!0;else if(!c)return null}if(!t)return e;let r=o(n=>n.trim()===""?n:"","blank");return{...e,lines:e.lines.map(n=>n.startsWith(":")?`:${r(n.slice(1))}`:n),comments:e.comments.map(r)}}o(wT,"inspectSseLines");var Og="The MCP capability filter could not read the upstream's list response, so it was not forwarded.",_T="The MCP capability filter did not forward the upstream's reply to this request. The request may already have run.";function zc(e,t){let r=e.messages.filter(kg),n=new Map,s=new Set;for(let u of r){let p=u.id,h=Go(p);p==null||h===void 0||(n.set(h,p),xg(u,t)!==null&&s.add(h))}let i=vg(r.map(u=>u.id)),a=e.messages[0],c=e.shape==="batch"||a===void 0?void 0:Go(a.id),d=new Set;return{keyOf(u){if(!(!H(u)||!("result"in u||"error"in u)))return e.shape==="batch"?i(u.id):c},isPending:o(u=>u!==void 0&&n.has(u),"isPending"),hasFailed:o(u=>d.has(u),"hasFailed"),answer(u){u!==void 0&&n.delete(u)},fail(u){return[...u].flatMap(p=>{let h=n.get(p);return h===void 0?[]:(n.delete(p),d.add(p),[{jsonrpc:"2.0",id:h,error:{code:I.InternalError,message:s.has(p)?Og:_T}}])})},pendingKeys:o(()=>[...n.keys()],"pendingKeys")}}o(zc,"createReplyTracker");function Mg(e,t,r){let n=[],s=0;for(let i of e){let a=r.keyOf(i);if(a!==void 0&&r.hasFailed(a))continue;let c=Array.isArray(i)?Oe:t(i);c!==sn&&(c!==Oe?(n.push(c),r.answer(a)):r.isPending(a)?n.push(...r.fail([a])):s++)}return{replies:n,dropped:s}}o(Mg,"filterBatchMembers");function bT(e){let{response:t,envelope:r,projectionMaps:n,filterReply:s,warn:i}=e,a=zc(r,n),c=!1,d=o(h=>(c=!0,i(`dropped an upstream SSE event: ${h}`),null),"drop"),u=o(h=>h.map(f=>({data:JSON.stringify(f)})),"toEvents"),p=o(()=>a.pendingKeys().length===0,"isDone");return wi(t,h=>{let f=wT(h);if(f===null)return d("it has a line the filter does not forward");if(f.data===void 0||f.data==="")return f;let y;try{y=JSON.parse(f.data)}catch{return d("its data is not JSON")}let b=a.keyOf(y);if(b!==void 0&&a.hasFailed(b))return null;let w=s(y);if(w===sn)return null;if(w===Oe&&r.shape==="batch"&&Array.isArray(y)){let{replies:S,dropped:R}=Mg(y,s,a);if(R>0&&(c=!0),i("did not forward a batch reply member it could not read; sent the rest"),S.length===0)return null;let v=Fo(f,JSON.stringify(S));return p()?vc(v):v}if(w===Oe){if(!a.isPending(b))return d("the filter could not read the reply");i("did not forward an upstream reply it could not read; sent a JSON-RPC error");let S=u(a.fail([b]));return p()?vc(...S):S}for(let S of Array.isArray(w)?w:[w])a.answer(a.keyOf(S));return w===y?f:Fo(f,JSON.stringify(w))},{maxEventChars:ST,onOversize:"discard",end:o(({unterminated:h,discardedEvents:f})=>((h||f>0)&&i("dropped an oversize or unterminated upstream SSE event"),c||h||f>0?u(a.fail(a.pendingKeys())):null),"end"),onFailure:o((h,f)=>{i(`could not rewrite the upstream SSE stream (${f.kind})`)},"onFailure")})}o(bT,"filterEventStream");function $c(e){return je(e)===Ci}o($c,"isListenRequest");function vT(e){return te()&&e.messages.some($c)}o(vT,"filtersListen");function Ug(e,t){if(!H(e)||!H(e.notifications))return;let r=e.notifications.resourceSubscriptions;if(!Array.isArray(r))return;let n=r.filter(s=>typeof s=="string"&&t(s));if(n.length!==r.length)return{...e,notifications:{...e.notifications,resourceSubscriptions:n}}}o(Ug,"narrowSubscriptionParams");function CT(e,t,r){let n=!1,s=t.messages.map(a=>{if(!$c(a)||!H(a.raw))return a.raw;let c=Ug(a.raw.params,r);return c===void 0?a.raw:(n=!0,{...a.raw,params:c})});if(!n)return e;let i=new Headers(e.headers);return i.delete("content-length"),new xt(e,{headers:i,body:JSON.stringify(t.shape==="batch"?s:s[0])})}o(CT,"narrowListenSubscriptions");var qc=Symbol("access unresolved"),bg=10*1024*1024,qg="the request body could not be read";async function IT(e,t,r){let n=e.clone().body;if(n===null)return{blank:!0,overLimit:!1};let s=n.getReader(),i=new TextDecoder,a=0,c=!0;try{for(;;){let{done:d,value:u}=await s.read(),p=d?i.decode():i.decode(u,{stream:!0});if(a+=p.length,c&&=!/\S/.test(p),a>t)return{blank:c,overLimit:!0};if(d||r&&!c)return{blank:c,overLimit:!1}}}finally{s.cancel().catch(()=>{})}}o(IT,"scanBody");function Hc(e){return Array.isArray(e)?`batch member 0: ${Hc(e[0])}`:H(e)?'jsonrpc must be "2.0"':"expected a JSON-RPC message object"}o(Hc,"invalidMessageReason");async function TT(e,t){if(e.body===null)return;let r=o(()=>Ne.contentTooLarge(e,t,{detail:"The request body is larger than the MCP capability filter can inspect."}),"tooLarge");if(Number(e.headers.get("content-length")??Number.NaN)>bg)return r();let s=We(e.headers.get("content-type")).includes("json"),i=o(()=>Ne.unsupportedMediaType(e,t,{detail:"MCP requests must be sent as application/json."}),"notJson"),a=o(()=>st(400,{code:I.ParseError,message:`Parse error: ${qg}`}),"unreadable"),c;try{c=await IT(e,bg,!s)}catch{return s?a():i()}if(c.blank&&!c.overLimit)return;if(!s)return i();if(c.overLimit)return r();let d;try{d=JSON.parse(await e.clone().text())}catch(p){return p instanceof SyntaxError?st(400,{code:I.ParseError,message:"Parse error: Invalid JSON"}):a()}let u=H(d)?d.id:void 0;return st(400,{code:I.InvalidRequest,message:`Invalid Request: ${Hc(d)}`},Ko(u)?u:void 0)}o(TT,"refuseUninspectable");var Nc=class extends Os{static{o(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;#n;constructor(t,r){let n=qI(t,r);super(n,r),this.#r=r,this.#e=$I(n),this.#t=LI(n,r);let s=this.#e.resourceTemplates;this.#n=s===void 0?void 0:new Map([...s.keys()].map(i=>[i,pg(i)]))}async handler(t,r){let n=await zm(t);if(n===null)return await TT(t,r)??t;let s=tT(t,n);if(s){let T=n.messages[0],O=T===void 0?void 0:sT(t,T);if(O!==void 0)return O}let i=n.messages.findIndex(XI);if(i!==-1)return vi(`batch member ${i}: ${Hc(n.messages[i].raw)}`);let a=n.messages.findIndex(QI);if(a!==-1)return vi(n.shape==="batch"?`batch member ${a}: method must be a string`:"method must be a string");let c=qm(n);if(c===void 0)try{c=await t.clone().text()}catch{return st(400,{code:I.ParseError,message:`Parse error: ${qg}`})}if(ug({envelope:n,text:c,isCapabilityMethod:Eg,checksListen:this.#a()}))return vi("a key is not ASCII, repeated, or spelled in another case, so the MCP capability filter cannot inspect it safely");let d=new Map;for(let T of n.messages){let O=je(T),L=O===void 0?void 0:BI(O);L!==void 0&&this.#u(L)&&d.set(T,iT)}let u=vT(n),p=d.size===0&&this.#t!==void 0&&n.messages.some(T=>this.#i(T,u))?await this.#s(t,r):void 0,h=s&&Co(t.headers.get("mcp-protocol-version")),f=!s&&xe();if(d.size===0)for(let T of n.messages){let O=p===qc?this.#i(T,u)?Sg:void 0:this.#m(T,p,h,n.protocolVersion,f);O!==void 0&&d.set(T,O)}if(d.size>0){let T=n.messages[0],O=te()&&(n.shape==="batch"?Ia(t.headers,n.messages.map(B=>B.raw))!==void 0:T!==void 0&&Bs(t.headers,T.raw));if(O){let B=Om(t);if(B!==void 0)return B;if(n.shape==="batch"){let ee=Ia(t.headers,n.messages.map(Ue=>Ue.raw));if(ee!==void 0)return st(ee.status,ee.error)}}let L=H(T?.raw)?T.raw.id:void 0,Q=Ko(L)?L:void 0,P=O&&n.shape==="single"&&T!==void 0?Nm(t.headers,T.raw):void 0;if(P!==void 0)return st(P.status,P.error,Q);let $=O&&n.shape==="single"&&H(T?.raw)&&typeof T.raw.method=="string"?Um(T.raw,{modern:!0,protocolVersion:t.headers.get("mcp-protocol-version"),hasResource:o(()=>!0,"hasResource")}):void 0;return $!==void 0?st(200,$.error,Q):(!s&&!O&&xe()?dT(t,n):void 0)??wg(n,d,s,!s&&f)}if(p===qc)return wg(n,new Map(n.messages.map(T=>[T,Sg])),s);let y=u||s?this.#l(p):void 0,b=y===void 0?t:CT(t,n,y),w=s&&this.#t!==void 0,S=w&&this.#p();if(!this.#h(n,u,S))return b;let R=fT({envelope:n,projectionMaps:this.#e,allowedSets:p,privateScope:w,privateReadScope:S,isResourceVisible:y}),v=o(T=>r.log.warn(`MCP capability filter policy "${this.#r}" - ${T}`),"warn"),x=o((T,O)=>{v(`did not forward an upstream reply (${T}); answered -32603`);let L=zc(n,this.#e),Q=L.fail(L.pendingKeys()),P=wt(new Headers(O.headers));return P.set("content-type","application/json"),Q.length===0?new Response(JSON.stringify(Vo({code:I.InternalError,message:Og})),{status:502,headers:P}):new Response(JSON.stringify(n.shape==="batch"?Q:Q[0]),{status:200,headers:P})},"unreadable");r.addResponseSendingHook(async T=>{let O=!T.ok;if(T.body!==null&&ht(T.headers))return O?T:x("its body is still content-encoded",T);if(yT(T))return bT({response:T,envelope:n,projectionMaps:this.#e,filterReply:R,warn:v});if(!gT(T))return T.ok&&T.status!==202&&T.status!==204&&T.body!==null?x("no or an unknown media type",T):T;let L;try{L=await T.clone().json()}catch{return O?T:x("its body is not JSON",T)}if(O&&!Array.isArray(L)&&!(H(L)&&"result"in L))return T;let Q=R(L);if(Q===Oe&&n.shape==="batch"&&Array.isArray(L)){let $=zc(n,this.#e),{replies:j,dropped:B}=Mg(L,R,$);B>0&&j.push(...$.fail($.pendingKeys())),j.length>0&&(v("did not forward a batch reply member it could not read; sent the rest"),Q=j)}if(Q===Oe||Q===sn)return x("the filter could not read the reply",T);if(Q===L)return T;let P=wt(new Headers(T.headers));return new Response(JSON.stringify(Q),{status:T.status,statusText:T.statusText,headers:P})});let N=new xt(b);return N.headers.set("accept-encoding","gzip, br"),N}#l(t){if(!this.#p())return;let r=o((n,s)=>{let i=t?.[n];return this.#e[n]?.has(s)===!0&&(i===void 0||i.has(s))},"isAllowed");return n=>this.#d(n,r)}#p(){return this.#e.resources!==void 0||this.#e.resourceTemplates!==void 0}#m(t,r,n,s,i=!1){let a=o(d=>this.#e[d]!==void 0,"isConfigured"),c=o((d,u)=>{let p=r?.[d];return this.#e[d]?.has(u)===!0&&(p===void 0||p.has(u))},"isAllowed");for(let d of KI(t)){if(!(d.refusedBy??d.options).some(a))continue;let{target:u}=d;if(u===void 0)return gg(je(t)??"",d.issue);if(!(d.resource?this.#d(u,c):d.options.filter(a).some(h=>c(h,u)))){let h=je(t),f=H(t.raw)?t.raw.params:void 0,y=i&&h!==void 0?Mm(h,H(f)?f:void 0):void 0;return y!==void 0&&h!==void 0?gg(h,y):n?d.notFound.modern(u):d.notFound.legacy(u,s??null)}}}#d(t,r){let n=this.#e.resources!==void 0;if(n&&r("resources",t))return!0;let s=!1;for(let[i,a]of this.#n??[])if(!(a===void 0||!mg(a,t))){if(r("resourceTemplates",i))return!0;s=!0}return!n&&!s}#o(t){let r=o(n=>this.#e[n]!==void 0,"isConfigured");return t===Ti?Tg.some(r):Dc(t)?.option==="resources"&&r("resourceTemplates")?!0:bt.some(n=>r(n.option)&&(n.listMethod===t||n.directMethods.includes(t)))}#i(t,r){let n=je(t);return r&&n===Ci&&this.#p()?!0:n!==void 0&&this.#o(n)}#a(){return te()&&this.#p()}#u(t){return t===Ci?this.#a():this.#o(t)}#h(t,r,n){return t.messages.some(s=>{if(r&&$c(s))return this.#p();if(n&&t.shape==="single"&&je(s)===Pg)return!0;let i=Ig(je(s));return i!==void 0&&this.#e[i.option]!==void 0})}async#s(t,r){let n=this.#t;if(n===void 0)return{};let s;try{s=await n(t,r,this.options)}catch(a){return r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; refused the requests that needed it`,a),qc}let i={};for(let a of bt){let c=this.#e[a.option];if(c===void 0)continue;let d=s[a.option];if(d===void 0)continue;let u=new Set;if(Array.isArray(d))for(let p of d)typeof p=="string"&&c.has(p)&&u.add(p);i[a.option]=u}return i}};var Bc="zuplo.com",ET=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),kT=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function zg(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(zg,"s2FaviconHref");function AT(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}o(AT,"strictFaviconHref");var Ng=zg(Bc);function Fc(e){let t=e.toLowerCase();return t===Bc||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?zg(Bc):AT(e)}o(Fc,"resolveIconHref");function PT(e){try{return new URL(`http://${e}`).hostname}catch{return e}}o(PT,"hostnameFromHost");function xT(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}o(xT,"isLocalOrAddressHost");function OT(e){let t=PT(e).toLowerCase().replace(/\.$/,"");if(xT(t)||kT.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let n=r.slice(-2).join("."),s=ET.has(n)?3:2;return r.slice(-s).join(".")}o(OT,"inferFaviconDomain");function Jc(e){return{src:Fc(OT(e)),mimeType:"image/png",sizes:["128x128"]}}o(Jc,"resolveMcpFaviconIcon");function Ei(e){try{return Jc(new URL(e).host)}catch{return}}o(Ei,"resolveMcpFaviconIconFromUrl");var MT=-32020,Vc="(missing)",UT=new Set(["envelope-invalid","modern-header-without-claim","header-body-version-mismatch","method-header-mismatch","notification-envelope-invalid","notification-header-body-version-mismatch","notification-method-header-mismatch"]),jg={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"},Dg="=?base64?",Lg="?=",qT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function zT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(zT,"isRecord");function $g(e){return e===" "||e===" "}o($g,"isHttpOws");function NT(e){let t=0,r=e.length;for(;t<r&&$g(e[t]);)t++;for(;r>t&&$g(e[r-1]);)r--;return e.slice(t,r)}o(NT,"stripHttpOws");function an(e,t){return e.get(t)??void 0}o(an,"readHeader");function jT(e){if(!e.startsWith(Dg)||!e.endsWith(Lg))return e;let t=e.slice(Dg.length,e.length-Lg.length);if(qT.test(t))try{let r=Uint8Array.from(atob(t),n=>n.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}o(jT,"decodeMcpHeaderValue");function Kc(e,t,r){let n=we(e);return Response.json(Pe({...n===void 0?{}:{id:n},error:r}),{status:t})}o(Kc,"errorResponse");function Wo(e,t,r){return Kc(e,400,{code:MT,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}}})}o(Wo,"headerMismatchResponse");function DT(e,t,r){let n=t.method;if(an(e,"mcp-protocol-version")===void 0)return Wo(t,Vc,`the body envelope names protocol version ${r} but the required MCP-Protocol-Version header is absent`);if(an(e,"mcp-method")===void 0)return Wo(t,Vc,`the body names method ${String(n)} but the required Mcp-Method header is absent`);if(typeof n!="string"||!Object.hasOwn(jg,n))return;let s=jg[n],i=zT(t.params)?t.params[s]:void 0,a=typeof i=="string"?i:void 0,c=an(e,"mcp-name");if(c===void 0)return a===void 0?void 0:Wo(t,Vc,`the body carries params.${s}="${a}" but the required Mcp-Name header is absent`);let d=NT(c),u=jT(d);if(u===void 0)return Wo(t,d,"the Mcp-Name header carries an invalid Base64 sentinel value");if(a!==void 0&&u!==a)return Wo(t,d,`the body carries params.${s}="${a}" but the Mcp-Name header names "${u}"`)}o(DT,"standardHeadersResponse");function Hg(e){let{headers:t,message:r}=e,n=_m({httpMethod:"POST",...Gc("protocolVersionHeader",an(t,"mcp-protocol-version")),...Gc("mcpMethodHeader",an(t,"mcp-method")),...Gc("mcpNameHeader",an(t,"mcp-name")),body:r});if(n.kind==="reject")return UT.has(n.cell)||n.cell==="initialize-with-modern-header"&&xe()?Kc(r,n.httpStatus,{code:n.code,message:n.message,...n.data===void 0?{}:{data:n.data}}):void 0;if(n.kind!=="modern")return;let s=n.classification.revision;if(s===void 0||!e.supportedVersions.includes(s)){let i=new Rm({supported:[...e.supportedVersions],requested:s??"unknown"});return Kc(r,400,{code:i.code,message:i.message,data:i.data})}return n.messageKind==="request"?DT(t,r,s):void 0}o(Hg,"validateModernGatewayRequest");function Gc(e,t){return t===void 0?{}:{[e]:t}}o(Gc,"optionalHeader");import{context as LT,TraceFlags as $T,trace as HT}from"@opentelemetry/api";var Bg="mcp-session-id",BT=256*1024;function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(it,"isPlainObject");function Fg(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(Fg,"isJsonContentType");function Zc(e,t,r){if(t===void 0||r===void 0||r.byteLength>xh||!Fg(e))return;let n=t.value;if(!it(n)||typeof n.method!="string"||n.params!==void 0&&!it(n.params))return;let s=n.id;return{message:n,method:n.method,...typeof s=="string"||typeof s=="number"||s===null?{id:s}:{},...n.params===void 0?{}:{params:n.params},...typeof n.jsonrpc=="string"?{jsonrpc:n.jsonrpc}:{}}}o(Zc,"parseMcpRequestMessage");function Wc(e,t){let r=e?.[t];return typeof r=="string"?r:void 0}o(Wc,"readStringParam");function FT(e){switch(e.method){case"tools/call":return{capabilityType:"tool",capabilityName:Wc(e.params,"name")};case"prompts/get":return{capabilityType:"prompt",capabilityName:Wc(e.params,"name")};case"resources/read":case"resources/subscribe":case"resources/unsubscribe":return{resourceUri:Wc(e.params,"uri")};default:return{}}}o(FT,"readCapability");function Jg(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(Jg,"readHeader");function JT(e,t){try{let r=t.route.handler.options;if(typeof r?.__rewriteFunction!="function")return{};let n=new URL(r.__rewriteFunction(e,Tu(t))),s=n.port!==""?Number(n.port):n.protocol==="https:"?443:n.protocol==="http:"?80:void 0;return{serverAddress:n.hostname,...s===void 0?{}:{serverPort:s}}}catch{return{}}}o(JT,"readUpstreamServer");function Vg(e,t,r){let n=lr(e.headers,r.message),s=Jg(e.headers,Bg),i={methodName:r.method,...FT(r),...r.id===void 0?{}:{jsonRpcRequestId:r.id},...r.jsonrpc===void 0?{}:{jsonRpcProtocolVersion:r.jsonrpc},...s===void 0?{}:{mcpSessionId:s}};return{common:i,server:{...i,mcpProtocolVersion:n??Dm,clientAddress:t.incomingRequestProperties?.ip,params:r.params},requestedProtocolVersion:n}}o(Vg,"readServerSpanInput");function Gg(e){let{request:t,context:r,parsed:n}=e,{common:s,server:i,requestedProtocolVersion:a}=Vg(t,r,n),c=Ta(i),d;try{Ms(c.span);let u=c.span.isRecording()||$m()?JT(t,r):{};d=LT.with(c.ctx,()=>Hm({...s,...a===void 0?{}:{mcpProtocolVersion:a},...u})),Ms(d.span);let p={server:c,client:d,captureToolCallContent:e.captureToolCallContent===!0};return VT(p,n),Ca(r,c.span.spanContext()),p}catch(u){throw ki(d===void 0?[c]:[d,c]),u}}o(Gg,"startMcpProxySpans");function Kg(e,t,r){try{let n=e.filter(i=>i.span.isRecording());if(n.length===0)return;let s=Bm(r);if(s===void 0)return;Dt(n,i=>i.span.setAttribute(t,s))}catch{}}o(Kg,"setContentAttribute");function VT(e,t){e.captureToolCallContent!==!0||t.method!=="tools/call"||Kg([e.client,e.server],"gen_ai.tool.call.arguments",t.params?.arguments??{})}o(VT,"recordToolCallArguments");function GT(e,t){if(t.spans.captureToolCallContent!==!0||t.method!=="tools/call"||t.gatewayAnswered===!0)return;let r=t.tapResult.message?.result;!it(r)||r.isError===!0||Kg(e,"gen_ai.tool.call.result",r)}o(GT,"recordToolCallResult");var KT=["content-digest","repr-digest","digest","content-md5"];function WT(e){return KT.some(t=>e.has(t))}o(WT,"hasBodyIntegrityHeader");function Wg(e,t,r,n){let s=HT.getSpanContext(t.client.ctx);if(r.byteLength>BT||n!==void 0&&WT(n)||s===void 0||(s.traceFlags&$T.SAMPLED)===0)return r;let i=e.params?._meta;if(i!==void 0&&!it(i))return r;try{let a=Ea(void 0,t.client.ctx);if(Object.keys(a._meta).length===0||!Oh(r))return r;let c=Ea(e.params,t.client.ctx);return new TextEncoder().encode(JSON.stringify({...e.message,params:c}))}catch{return r}}o(Wg,"injectTraceContextIntoBody");function Zg(e,t){if(e){if(it(e.error)){let r=e.error.code,n=e.error.message;return{...typeof r=="number"?{code:r}:{},...typeof n=="string"?{message:Ls(n,Lm)}:{},httpStatusCode:t}}if(it(e.result)&&e.result.isError===!0)return{isError:!0}}}o(Zg,"readSpanResponse");function ZT(e,t,r){let n=Jg(t.headers,Bg),s=r?.result,i=xm(it(s)&&typeof s.protocolVersion=="string"?s.protocolVersion:void 0);Dt(e,a=>{n!==void 0&&a.span.setAttribute("mcp.session.id",n),i!==void 0&&a.span.setAttribute("mcp.protocol.version",i)})}o(ZT,"recordInitializeResult");function Yg(e){let{spans:t}=e,r=[t.client,t.server];try{YT(r,e)}catch{}finally{ki(r)}}o(Yg,"finishMcpProxySpans");function YT(e,t){let{spans:r,response:n,tapResult:s}=t;t.method==="initialize"&&(r.server.span.isRecording()||r.client.span.isRecording())&&ZT(e,n,s.message),GT(e,t);let i=Zg(s.message,n.status);i?Dt(e,a=>a.setResponse(i)):s.ended==="errored"?Dt(e,a=>a.fail(s.error)):n.status>=400&&s.message===void 0?Dt(e,a=>a.setErrorType(String(n.status))):s.ended==="cancelled"&&!s.message?Dt(e,a=>a.setErrorType("cancelled","The response stream was cancelled before the JSON-RPC response arrived.")):s.ended==="released"&&!s.message?Dt(e,a=>a.setErrorType("response_replaced","A different response was sent before the JSON-RPC response arrived.")):t.expectsResponse&&s.ended==="complete"&&!s.message&&!s.truncated&&!s.uninspected&&Dt(e,a=>a.setErrorType("no_response","The response stream ended without the JSON-RPC response."))}o(YT,"recordOutcome");function Dt(e,t){for(let r of e)try{t(r)}catch{}}o(Dt,"forEachHandle");function ki(e){for(let t of e)try{t.end()}catch{}}o(ki,"endEach");function Yc(e,t){for(let r of[e.client,e.server])try{r.fail(t),r.end()}catch{}}o(Yc,"failMcpProxySpans");function Xc(e){for(let t of[e.client,e.server])try{t.setErrorType("cancelled","The client cancelled the request before the upstream sent response headers.")}catch{}finally{ki([t])}}o(Xc,"cancelMcpProxySpans");function XT(e){switch(e){case"connect_required":return"The gateway asked the client to connect the upstream server; the request was not forwarded.";case"no_upstream_tokens":return"The upstream connection returned no OAuth tokens; the request was not forwarded.";case"upstream_token_refresh_unavailable":return"The upstream token endpoint could not refresh the connection; the request was not forwarded."}}o(XT,"gatewayAnswerMessage");var QT=64*1024;async function eE(e){if(e.body===null||!Fg(e))return;let t=await e.clone().text();if(t.length>QT)return;let r=JSON.parse(t);return it(r)?r:void 0}o(eE,"readGatewayAnswer");function tE(e){return it(e.error)?it(e.error.data)&&e.error.data.connectRequired!==void 0:it(e.result)&&e.result.resultType==="input_required"}o(tE,"isConnectRequiredAnswer");async function Xg(e){let t;try{let r=Zc(e.request,e.requestJson===void 0?void 0:{value:e.requestJson},e.requestBody);if(r===void 0)return;let{server:n}=Vg(e.request,e.context,r);t=Ta({...n,startTime:e.startTime}),Ms(t.span),Ca(e.context,t.span.spanContext());let s;try{s=await eE(e.response)}catch{}let i=Zg(s,e.response.status);i?t.setResponse(i):e.response.status>=400&&s===void 0&&t.setErrorType(String(e.response.status));let a=e.outcome??(s!==void 0&&tE(s)?"connect_required":void 0);a!==void 0&&t.setErrorType(a,XT(a))}catch{}finally{t&&ki([t])}}o(Xg,"recordGatewayAnsweredMcpSpan");function Lt(e){let t=Ie().connectionsById.get(e);if(!t)throw new re(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}o(Lt,"getUpstreamServerConfig");function Ai(e){let t=Ie().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new re(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}o(Ai,"getUpstreamAuthConfig");function cn(e,t){let r=Ai({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new re(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}o(cn,"requireUpstreamOAuthConfig");function Qg(e,t){let r=Ai({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new re(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}o(Qg,"requireUpstreamIdJagConfig");import{base64url as Pi}from"jose";var rE="__Host-",nE=16,oE=32,ty=".",sE=!1;function $t(){return sE}o($t,"isBrowserBindingEnforced");var Zo=m.object({id:m.string().regex(/^[A-Za-z0-9_-]{22}$/u),hash:m.string().regex(/^[A-Za-z0-9_-]{43}$/u)});function xi(e,t){return new URL(ce(e,t)).protocol==="https:"}o(xi,"isSecureGatewayOrigin");function Qc(e,t){return t?`${rE}${e}`:e}o(Qc,"gatewayCookieName");function Yo(e){let t=[`${e.name}=${e.value}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.maxAgeSeconds}`];return e.secure&&t.push("Secure"),t.join("; ")}o(Yo,"serializeGatewayCookie");function ed(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let s=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(s)try{t.set(s,decodeURIComponent(i))}catch{t.set(s,i)}}return t}o(ed,"parseCookieHeader");function ey(e){return Pi.encode(crypto.getRandomValues(new Uint8Array(e)))}o(ey,"randomBase64url");async function ry(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Pi.encode(new Uint8Array(t))}o(ry,"hashNonce");function iE(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}o(iE,"constantTimeEqual");function ny(e,t,r){return Qc(`zuplo_mcp_${e}_${t}`,r)}o(ny,"bindingCookieName");async function Xo(e){let t=ey(nE),r=ey(oE),n=xi(e.requestUrl,e.requestHeaders),s=e.payload===void 0?r:`${r}${ty}${Pi.encode(e.payload)}`;return{claim:{id:t,hash:await ry(r)},setCookie:Yo({name:ny(e.purpose,t,n),value:s,maxAgeSeconds:e.ttlSeconds,secure:n})}}o(Xo,"startBrowserBinding");async function Oi(e){let t=xi(e.request.url,e.request.headers),r=ny(e.purpose,e.claim.id,t),n=Yo({name:r,value:"",maxAgeSeconds:0,secure:t}),s=ed(e.request.headers.get("cookie")).get(r);if(s===void 0)return{matched:!1,clearCookie:n};let i=s.indexOf(ty),a=i<0?s:s.slice(0,i);if(!iE(await ry(a),e.claim.hash))return{matched:!1,clearCookie:n};if(i<0)return{matched:!0,clearCookie:n};try{return{matched:!0,payload:new TextDecoder().decode(Pi.decode(s.slice(i+1))),clearCookie:n}}catch{return{matched:!1,clearCookie:n}}}o(Oi,"verifyBrowserBinding");function oy(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(oy,"mergeAbortSignals");async function aE(e){try{await e.cancel()}catch{}}o(aE,"cancelReader");async function Mi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],s=0,i=await r.read();for(;!i.done;){let d=i.value;if(s+=d.byteLength,s>t.maxBytes)throw await aE(r),t.createLimitError();n.push(d),i=await r.read()}let a=new Uint8Array(s),c=0;for(let d of n)a.set(d,c),c+=d.byteLength;return a}o(Mi,"readBoundedByteStream");var cE=2,dE=1024*1024,uE=1e4,lE=new Set([301,302,303,307,308]),pE=["authorization","proxy-authorization","cookie","cookie2"];function td(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(td,"readRequestUrl");function dn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(dn,"readRequestMethod");function mE(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[M]:r}})}o(mE,"assertContentLengthWithinLimit");async function hE(e,t,r){return mE(e,t,r),Mi(e.body,{maxBytes:t,createLimitError:o(()=>new k({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[M]:r}}),"createLimitError")})}o(hE,"readBoundedResponseBody");function fE(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(fE,"responseFromBufferedBody");function gE(e,t){if(!lE.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(gE,"resolveRedirectUrl");function sy(e,t){try{return t.validateUrl(e)}catch(r){throw new k({message:"Outbound URL was not allowed.",extensionMembers:{[M]:t.problemCode}},{cause:r})}}o(sy,"validateOutboundUrl");var iy=new WeakSet;function ay(e){return e instanceof k&&iy.has(e)}o(ay,"isOutboundTransportFailure");function cy(e,t){if(e instanceof k&&Fs(e.extensionMembers?.[M]))throw e;let r=new k({message:"Outbound fetch failed.",extensionMembers:{[M]:t}},{cause:e});throw iy.add(r),r}o(cy,"normalizeFetchError");function Qo(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,s]of Object.entries(t.extra))s!==void 0&&(r[n]=s);t.error!==void 0&&Ae(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Qo,"logOutboundFailure");async function yE(e,t,r,n,s,i,a){let c=dn(r,n);try{return await t(r,n)}catch(d){let u=d instanceof DOMException&&d.name==="AbortError";Qo(e,{event:u?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:c,host:ie(i),error:d,extra:{abortReason:a()}}),cy(d,s)}}o(yE,"fetchWithNormalizedError");function SE(e){if(e.redirects>=e.maxRedirects)throw new k({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[M]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new k({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[M]:e.problemCode}})}o(SE,"assertRedirectAllowed");function RE(e,t){let r=new Headers(e);for(let n of pE)r.delete(n);for(let n of t)r.delete(n);return r}o(RE,"stripCrossOriginHeaders");function wE(e,t,r,n,s){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=RE(e.headers,s)),i}o(wE,"buildRedirectInit");function _E(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(_E,"buildInitialRequestInit");function bE(e){let t=dn(e.currentInput,e.currentInit);SE({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=sy(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),s=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:wE(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(bE,"followRedirect");async function rd(e,t,r){let n=r.problemCode??"invalid_request",s=r.maxRedirects??cE,i=r.maxResponseBytes??dE,a=r.timeoutMs??uE,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],u=r.context,p=new AbortController,h=oy(p,t.signal),f=!1,y=setTimeout(()=>{f=!0,p.abort()},a),b=e,w=_E(e,t,p.signal),S;try{S=sy(td(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(v){throw Qo(u,{event:"outbound_url_blocked",problemCode:n,method:dn(e,t),host:ie(td(e)),error:v}),clearTimeout(y),h?.(),v}let R=0;try{for(;;){let v=await yE(u,c,b,w,n,S,()=>f?`timeout_after_${a}ms`:void 0),x=gE(v,S);if(x!==void 0)try{let N=bE({currentInput:b,currentInit:w,currentUrl:S,redirectUrl:x,redirects:R,maxRedirects:s,problemCode:n,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});b=N.currentInput,w=N.currentInit,S=N.currentUrl,R=N.redirects;continue}catch(N){throw Qo(u,{event:"outbound_redirect_blocked",problemCode:n,method:dn(b,w),host:ie(S),error:N,extra:{redirects:R,maxRedirects:s,redirectTargetHost:ie(x)}}),N}try{return fE(v,await hE(v,i,n))}catch(N){let T=N instanceof k;Qo(u,{event:T?"outbound_response_size_exceeded":"outbound_response_body_failed",problemCode:n,method:dn(b,w),host:ie(S),error:N,extra:{maxResponseBytes:i,status:v.status}}),cy(N,n)}}}finally{clearTimeout(y),h?.()}}o(rd,"runSafeOutboundExchange");async function es(e,t,r){let n=await rd(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(s){throw Qo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:dn(e,t),host:ie(td(e)),error:s,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new k({message:"Outbound JSON response could not be parsed.",extensionMembers:{[M]:r.problemCode??"invalid_request"}},{cause:s})}}o(es,"runSafeOutboundJsonExchange");function dy(e,t={},r={}){return rd(e,t,{...r,validateUrl:xo})}o(dy,"fetchConfiguredOutbound");function uy(e,t={},r={}){return es(e,t,{...r,validateUrl:xo})}o(uy,"fetchConfiguredOutboundJson");function Ui(e,t={},r={}){return es(e,t,{...r,validateUrl:Rh})}o(Ui,"fetchIdentityProviderJson");function ly(e,t={},r={}){return es(e,t,{...r,validateUrl:Xs})}o(ly,"fetchCimdClientMetadataJson");function py(e,t={},r={}){return es(e,t,{...r,validateUrl:Oo})}o(py,"fetchCimdClientJwksJson");import{errors as Sy,jwtVerify as Ry,SignJWT as wy}from"jose";var fe="zuplo-mcp-gateway",_e=fe,be="HS256";import{base64url as vE}from"jose";var CE=new TextEncoder,IE="MCP gateway could not initialize secure key material.",TE=32,my=new Map,hy=new Map,EE;function kE(){return EE??zr.instance.authPrivateKey}o(kE,"readAuthPrivateKey");function fy(e){return new Ee(IE,e===void 0?void 0:{cause:e})}o(fy,"createGeneratedKeyMaterialError");function gy(e,t){let r=vE.decode(t);if(r.byteLength!==TE)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(gy,"decodeJwkKeyField");function AE(e){let t=kE();if(!t)throw fy();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=gy("d",r.d);gy("x",r.x);let s=CE.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(s.byteLength+n.byteLength);return i.set(s),i.set(n,s.byteLength),i}catch(r){throw fy(r)}}o(AE,"decodeGeneratedKeyMaterial");function PE(e){let t=my.get(e);return t||(t=AE(e),my.set(e,t)),t}o(PE,"getMasterKeyMaterial");async function Ze(e){let t=hy.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(PE(e.keyMaterialPurpose));return hy.set(e.purpose,r),r}o(Ze,"readCachedDerivedKey");var xE="SHA-256",OE=32,ME="zuplo-mcp-gateway:",UE=new TextEncoder,yy=new WeakMap;async function ft(e,t){let r=yy.get(e);r||(r=new Map,yy.set(e,r));let n=r.get(t);if(n)return n;let s=await qE(e,t);return r.set(t,s),s}o(ft,"deriveGatewaySigningKey");async function qE(e,t){let r=ye(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),s=UE.encode(`${ME}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:xE,salt:new Uint8Array,info:ye(s)},n,OE*8);return new Uint8Array(i)}o(qE,"hkdfExpand");var _y=900,zE=900,NE=rh.extend({id:Ch,browserBinding:Zo.optional()}),jE=NE.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),by=ka.extend({id:Ih,purpose:m.literal("browser_connect")}),DE=ka.extend({purpose:m.literal("browser_connect")}),LE=by.extend({exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),qi=_y*1e3;async function vy(){return Ze({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"oauth-state"),"derive")})}o(vy,"getOAuthStateKey");async function Cy(){return Ze({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-connect"),"derive")})}o(Cy,"getBrowserConnectKey");async function Iy(e){let t=Math.floor(Date.now()/1e3)+_y;return new wy(e).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await vy())}o(Iy,"signOAuthState");async function zi(e){try{let{payload:t}=await Ry(e,await vy(),{algorithms:[be],issuer:fe,audience:_e});return jE.parse(t)}catch(t){throw t instanceof Sy.JWTExpired?new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}},{cause:t}):new k({message:"OAuth state could not be verified",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:t})}}o(zi,"verifyOAuthState");async function Ty(e){let t=Math.floor(Date.now()/1e3)+zE,r=DE.parse(e),n=by.parse({...r,id:Ah()});return new wy(n).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(t).sign(await Cy())}o(Ty,"signBrowserConnectTicket");async function Ey(e){try{let{payload:t}=await Ry(e,await Cy(),{algorithms:[be],issuer:fe,audience:_e});return LE.parse(t)}catch(t){throw t instanceof Sy.JWTExpired?new k({message:"Browser connect ticket has expired",extensionMembers:{[M]:"oauth_state_expired"}},{cause:t}):new k({message:"Browser connect ticket could not be verified",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:t})}}o(Ey,"verifyBrowserConnectTicket");async function ky(e){if((await G().consumeBrowserConnectTicket({id:e.id,expiresAt:W(new Date(e.exp*1e3)),now:W(new Date)})).kind==="consumed")throw new k({message:"Browser connect ticket has already been used",extensionMembers:{[M]:"oauth_state_reused"}})}o(ky,"consumeBrowserConnectTicket");function $E(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o($E,"buildConnectRequiredMessage");async function HE(e){let t=ce(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Ty({...Ao(e),purpose:"browser_connect"})),r.toString()}o(HE,"buildGatewayBrowserTicketUrl");function BE(e){return ge().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}o(BE,"buildGatewayConnectPath");async function nd(e){return HE({...e,path:BE(e.upstreamServerId),redirect:!0})}o(nd,"buildGatewayConnectUrl");async function Ni(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await nd(t),message:$E(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Ni,"buildRedirectConnectRequiredResponse");function Ay(e){return Py({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(Ay,"buildAdminConnectRequiredResponse");function Py(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(Py,"buildAdminSetupRequiredResponse");function xy(e){return Ie().byOperationId.get(e)?.downstreamOAuth!==void 0}o(xy,"routeSupportsBrowserConnect");function Oy(e){return Py({...e,message:`An administrator must enable gateway sign-in on this MCP route before you can connect ${e.upstreamDisplayName}.`})}o(Oy,"buildBrowserConnectUnavailableResponse");var My=12;async function Uy(e){let t=await crypto.subtle.digest("SHA-256",ye(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}o(Uy,"sha256Hex");async function gr(e){if(e)return(await Uy(e)).slice(0,My)}o(gr,"fingerprintSecret");async function un(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Uy(t)).slice(0,My)}o(un,"fingerprintConnectionIdentity");var FE=6e4;function ln(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,n)=>t.scopes[n]!==r)}o(ln,"credentialGenerationChanged");function Me(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+FE)return"near_expiry"}return"usable"}o(Me,"describeAccessTokenState");var qy=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function JE(e,t){return e&&e.length>0?e.join(t):void 0}o(JE,"joinOAuthScopes");function VE(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of qy)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}o(VE,"sanitizeAuthorizationServerMetadata");function zy(e){let t=VE(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}o(zy,"sanitizeOAuthDiscoveryState");function Ny(e){let t=new URL(e);for(let r of qy){let n=t.searchParams.getAll(r);n.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,n.at(-1)??""))}return t}o(Ny,"dedupeSingletonAuthorizationRequestParams");function ji(e){let t=new URL(e);return He(t)&&Jm(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}o(ji,"normalizeLoopbackOAuthRedirectUri");function jy(e){return JE(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}o(jy,"readProtectedResourceMetadataScope");function GE(e){return`Zuplo MCP Gateway - ${e}`}o(GE,"buildGatewayOAuthClientName");function KE(e,t){return e&&e.length>0?e.join(t):void 0}o(KE,"joinOAuthScopeList");function WE(e){if(e.clientRegistration.mode!=="auto")return KE(e.scopes,e.scopeDelimiter)}o(WE,"readPublicClientMetadataScope");function od(e){return new URL(ge().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}o(od,"buildOAuthClientMetadataDocumentUrl");function sd(e){let t=Lt(e.upstreamServerId);return{client_name:GE(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}o(sd,"buildGatewayOAuthClientMetadata");function Dy(e,t,r){let n=cn(t,r),s=WE(n);return{client_id:od({origin:e,upstreamServerId:t}),...sd({origin:e,upstreamServerId:t,redirectUri:ji(new URL(n.redirectPath,e)).toString(),scope:s})}}o(Dy,"buildOAuthClientMetadataDocument");import{base64url as Ht}from"jose";var ZE="SHA-256",pn="AES-GCM",YE=12,ad="zuplo-secret",cd=1,Ly="generated:auth_private_key:token-encryption",XE=m.object({version:m.literal(cd),keyId:m.literal(Ly),algorithm:m.literal(pn),iv:m.string().min(1),ciphertext:m.string().min(1)}).strict();async function id(){return Ze({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(ZE,ye(e));return crypto.subtle.importKey("raw",t,{name:pn},!1,["encrypt","decrypt"])},"derive")})}o(id,"getEncryptionKey");function $y(e){return ye(new TextEncoder().encode(`${ad}:v${e.version}:${e.keyId}`))}o($y,"getAssociatedData");function QE(e){return`${ad}:v${e.version}:${Ht.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(QE,"encodeEnvelope");function ek(e){let t=`${ad}:v${cd}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Ht.decode(r));return XE.parse(JSON.parse(n))}o(ek,"decodeEnvelope");async function vt(e){let t=await id(),r=crypto.getRandomValues(new Uint8Array(YE)),n={version:cd,keyId:Ly},s=await crypto.subtle.encrypt({name:pn,iv:r,additionalData:$y(n)},t,new TextEncoder().encode(e));return QE({...n,algorithm:pn,iv:Ht.encode(r),ciphertext:Ht.encode(new Uint8Array(s))})}o(vt,"encryptSecret");async function Ct(e){let t=ek(e);if(t){let a=await id(),c=await crypto.subtle.decrypt({name:pn,iv:ye(Ht.decode(t.iv)),additionalData:$y(t)},a,ye(Ht.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new Ee("Encrypted payload is malformed");let s=await id(),i=await crypto.subtle.decrypt({name:pn,iv:ye(Ht.decode(r))},s,ye(Ht.decode(n)));return new TextDecoder().decode(i)}o(Ct,"decryptSecret");var Hy={issuer:m.string().min(1).optional()},tk=m.union([dr.extend(Hy),vo.extend(Hy)]),By=m.object({authorizationServerUrl:m.url(),resourceMetadataUrl:m.url().optional(),resourceMetadata:$r.optional(),authorizationServerMetadata:m.union([Hr,Br]).optional()}).passthrough(),rk="Bearer",nk="__zuplo_refresh_only_upstream_access_token__";function dd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(dd,"splitScopes");function ud(e,t){let r=new Set(e);return t.every(n=>r.has(n))}o(ud,"scopesCover");function ok(e){return Kr.parse(e)}o(ok,"parsePkceCodeVerifier");function sk(e){if(typeof e.expires_in=="number")return W(new Date(Date.now()+e.expires_in*1e3))}o(sk,"readTokenExpiry");async function ld(e){if(e!==void 0)return vt(JSON.stringify(e))}o(ld,"encryptJson");async function Fy(e,t){if(!e)return;let r=await Ct(e);try{return t.parse(JSON.parse(r))}catch(n){throw new k({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[M]:"oauth_state_invalid"}},{cause:n})}}o(Fy,"decryptJson");function ik(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(ik,"clientInformationAllowsRedirectUri");function ak(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}o(ak,"clientInformationMatchesCurrentClientMetadataUrl");function ck(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}o(ck,"isUrlBasedClientInformation");function dk(e,t){return t===void 0?e:{...e,scope:t}}o(dk,"applyOAuthClientMetadataScope");function uk(e,t){return jy({state:e,delimiter:t})}o(uk,"readResourceMetadataScope");function lk(e,t){return e&&e.length>0?e.join(t):void 0}o(lk,"joinOAuthScopeList");function pk(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new re(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return dr.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(pk,"buildManualOAuthClientInformation");function mk(e,t){let r=od({origin:new URL(t).origin,upstreamServerId:e});return pc(r)?r:void 0}o(mk,"buildClientMetadataUrl");function hk(e){for(let t of e)if(t!==void 0)return t}o(hk,"firstDefined");function fk(e){let t=cn(e.target.upstreamServerId,e.target.authProfileId),r=lk(t.scopes,t.scopeDelimiter),n=sd({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,configuredClientInformation:pk({clientMetadata:n,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let s=mk(e.target.upstreamServerId,e.redirectUri);return s===void 0?{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation}:{clientMetadata:n,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,skipIssuerMetadataValidation:t.skipIssuerMetadataValidation,skipResourceIndicatorValidation:t.skipResourceIndicatorValidation,clientMetadataUrl:s}}o(fk,"buildInitialOAuthClientSetup");function gk(e,t){if(t===void 0)return hk([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(gk,"readEncryptedClientInformation");function yk(e){return e.pendingState?.encryptedDiscoveryState}o(yk,"readEncryptedDiscoveryState");function Di(e,t){return t===void 0?e:{...e,issuer:t}}o(Di,"applyIssuerStamp");var Bt=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;browserBinding;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;skipIssuerMetadataValidationValue;skipResourceIndicatorValidationValue;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=fk({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.browserBinding=t.browserBinding,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.skipIssuerMetadataValidationValue=r.skipIssuerMetadataValidation,this.skipResourceIndicatorValidationValue=r.skipResourceIndicatorValidation,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=gk(t,this.configuredClientInformation),this.encryptedDiscoveryState=yk(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get skipIssuerMetadataValidation(){return this.skipIssuerMetadataValidationValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let n=dd(this.configuredScope??r??this.readEffectiveScope());return ud(t.scopes,n)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&Me(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let n=se();n&&n.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await un({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await gr(await Ct(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await G().conditionalUpsertUpstreamConnection(t,r)}catch(n){let s=se();if(s){let i=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:n}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});s.error(i,"Upstream OAuth conditional storage write failed")}throw n}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return dk(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Iy({id:t.id,...Ao({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId}),...this.browserBinding===void 0?{}:{browserBinding:this.browserBinding}})}async clientInformation(t){return this.configuredClientInformation?Di(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,se()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!ck({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await ld(t),await this.syncPendingState(!1)))}async validateResourceURL(t,r){if(r!==void 0){if(this.skipResourceIndicatorValidationValue!==!0&&!ii({requestedResource:t,configuredResource:r}))throw new Error(`Protected resource ${r} does not match expected ${t} (or origin)`);return new URL(r)}}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=zy(By.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await ld(r),await this.syncPendingState(!1),se()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:ie(r.authorizationServerUrl),resourceMetadataHost:ie(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=uk(r,this.scopeDelimiter);let n=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&n!==void 0){let s=dd(this.configuredScope).filter(i=>!n.includes(i));s.length>0&&se()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:s,scopesSupported:n},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return Di(r,t?.issuer)}async saveTokens(t){let r=Ot.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,s=this.credentialState.sourceConnection,i=!r.refresh_token&&!!s?.encryptedRefreshToken,a=r.refresh_token?await vt(r.refresh_token):s?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!s?.encryptedRefreshToken?r:Ot.parse({...r,refresh_token:await Ct(s.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:s?.id??Qs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await vt(r.access_token),encryptedRefreshToken:a,scopes:dd(r.scope??this.readEffectiveScope()),expiresAt:sk(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},d=s?{expectedUpdatedAt:s.updatedAt}:{expectAbsent:!0},u=await this.conditionalUpsertCredential(c,d),p=!1;if(u.kind==="precondition_failed"&&u.connection!==void 0&&(Me(u.connection)!=="usable"||!ud(u.connection.scopes,c.scopes)||!ln(s,u.connection))){p=!0;let f=u.connection,y={id:f.id,ownerMode:f.ownerMode,subjectId:f.subjectId,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId,status:"active",encryptedAccessToken:c.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?f.encryptedRefreshToken:c.encryptedRefreshToken,scopes:c.scopes,expiresAt:c.expiresAt,metadata:f.metadata};se()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f.id,sourceUpdatedAt:s?.updatedAt,winnerUpdatedAt:f.updatedAt,sourceScopeCount:s?.scopes.length,winnerScopeCount:f.scopes.length,resultingScopeCount:y.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),u=await this.conditionalUpsertCredential(y,{expectedUpdatedAt:f.updatedAt})}if(u.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=u.kind,u.kind==="persisted"?(this.credentialState.currentConnection=u.connection,this.credentialState.peerAdoption=void 0):u.kind==="precondition_failed"&&u.connection!==void 0?(this.credentialState.currentConnection=u.connection,ln(s,u.connection)&&Me(u.connection)==="usable"&&ud(u.connection.scopes,c.scopes)?this.adoptPeerConnection(u.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),p){let f=u.kind==="persisted"?"succeeded":u.kind==="precondition_failed"?"lost":"exhausted";se()?.info({event:`upstream_oauth_bounded_rebase_${f}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:s?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:s?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${f}`)}let h=u.kind==="persisted"?u.connection:void 0;se()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:h?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!a,sourceScopeCount:s?.scopes.length,priorStatus:s?.status,priorUpdatedAt:s?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await gr(r.refresh_token),reusedSnapshotRefreshToken:i,scopeCount:c.scopes.length,expiresAt:c.expiresAt,outcome:u.kind,rebaseAttempted:p,resultingUpdatedAt:h?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:h?.scopes.length??this.credentialState.currentConnection?.scopes.length},h?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=Ny(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:ok(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new k({message:"OAuth code verifier is missing",extensionMembers:{[M]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",s=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),s&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:kh(),...Ao({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:W(new Date(Date.now()+qi)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await G().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await Fy(this.encryptedClientInformation,tk)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!ik(r,this.redirectUriValue)||!ak({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r!==void 0&&r.issuer===void 0&&t?.issuer!==void 0&&(r=Di(r,t.issuer),this.encryptedClientInformation=await ld(r)),r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Di(vo.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await Fy(this.encryptedDiscoveryState,By)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){se()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await Ct(t.encryptedAccessToken):void 0,n=t.encryptedRefreshToken?await Ct(t.encryptedRefreshToken):void 0;if(!r&&!n)return;let s=se();this.usedRefreshTokenFingerprintValue=s?await gr(n):void 0,s?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!n,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Ot.parse({access_token:r??nk,token_type:rk,refresh_token:n,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=i,i}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let n=r.status,s=r.updatedAt,i={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let a=await this.conditionalUpsertCredential(i,{expectedUpdatedAt:r.updatedAt});a.kind==="persisted"?(this.credentialState.currentConnection=a.connection,this.credentialState.peerAdoption=void 0):a.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):a.connection!==void 0&&(this.credentialState.currentConnection=a.connection,ln(r,a.connection)&&Me(a.connection)==="usable"&&this.connectionSatisfiesRequestedScope(a.connection)?this.adoptPeerConnection(a.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let c=se();if(c){let d=a.kind==="missing"?void 0:a.connection,u={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:d?.id,clearedTokens:t,priorStatus:n,newStatus:d?.status,priorUpdatedAt:s,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:a.kind};a.kind==="precondition_failed"?c.warn({...u,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?c.warn(u,"Upstream OAuth credentials invalidated; connection now requires reconsent"):c.debug(u,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Sk=3e4,Rk=256*1024,wk=2,_k="does not support dynamic client registration",bk=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],vk=["trying to load OAuth metadata from","trying to load OpenID provider metadata from"],Ck=["Incompatible auth server: does not support response type","Incompatible auth server: does not support code challenge method"],Ik="Protected resource ",Tk=" does not match expected ",Ek=["HTTP 403 Forbidden","Access Denied","permission to access"],kk=new Set([me.AccessDenied,me.InvalidClient,me.InvalidGrant,me.InvalidRequest,me.InvalidScope,me.InvalidTarget,me.UnauthorizedClient,me.UnsupportedGrantType]);function Ak(e){return e instanceof Error&&e.message.includes(_k)}o(Ak,"isDynamicClientRegistrationUnsupported");function Pk(e){return e instanceof Error&&bk.some(t=>e.message.includes(t))}o(Pk,"isProtectedResourceMetadataUnavailable");function xk(e){return e instanceof Error&&vk.some(t=>e.message.includes(t))}o(xk,"isAuthorizationServerMetadataUnavailable");function Ok(e){return e instanceof Error&&Ck.some(t=>e.message.includes(t))}o(Ok,"isAuthorizationServerIncompatible");function Mk(e){return e instanceof Error&&e.message.includes(Ik)&&e.message.includes(Tk)}o(Mk,"isProtectedResourceMismatch");function Uk(e){return e instanceof Error&&Ek.some(t=>e.message.includes(t))}o(Uk,"isUpstreamProviderAccessDenied");function Jy(e){return e instanceof Nt&&kk.has(e.code)}o(Jy,"isStoredConnectionReconsentError");function It(e){let t=e.diagnostics??{};return new k({message:e.message,extensionMembers:{[M]:e.code,[To]:e.upstreamServerId,[Yr]:e.resourceMetadataUrl,...t.upstreamUrl===void 0?{}:{[pt]:t.upstreamUrl},...t.httpStatus===void 0?{}:{[lt]:t.httpStatus},...t.providerError===void 0?{}:{[Xr]:t.providerError},...t.providerErrorDescription===void 0?{}:{[Qr]:t.providerErrorDescription}}},{cause:e.cause})}o(It,"buildUpstreamSetupProblem");function qk(e,t){return`The authorization server for ${e} failed RFC 8414 \xA73.3 issuer validation: the gateway discovered it at "${t.expected}", but its metadata document declares issuer "${t.received}". Providers that publish a path-scoped authorization server whose metadata reports the root origin hit this; if that is the case here, set skipIssuerMetadataValidation on this upstream's OAuth config to accept it \u2014 that weakens the authorization-server mix-up defense, so scope it to this upstream. Otherwise correct the authorization server URL this upstream points at, or ask the provider to fix the published issuer.`}o(qk,"describeIssuerMetadataMismatch");var zk=128,Li=256;function ts(e,t){if(e!==void 0)return e.length<=t?e:`${e.slice(0,t)}\u2026`}o(ts,"truncateProviderDetail");function Nk(e){let{error:t,errorDescription:r}=$i(e.body),n=ts(t,zk),s=ts(r,Li);return{httpStatus:e.status,...n===void 0?{}:{providerError:n},...s===void 0?{}:{providerErrorDescription:s}}}o(Nk,"readRegistrationRejectionDiagnostics");function jk(e){return e.providerError===void 0?`HTTP ${e.httpStatus}`:e.providerErrorDescription===void 0?`HTTP ${e.httpStatus}, ${e.providerError}`:`HTTP ${e.httpStatus}, ${e.providerError}: ${e.providerErrorDescription}`}o(jk,"describeRegistrationRejection");function Dk(e){return/(https?:\/\/\S+)/.exec(e)?.[1]}o(Dk,"readDiscoveryEndpointUrl");function Lk(e){if(e.error instanceof k&&e.error.extensionMembers?.[M]!==void 0)return e.error;let t={upstreamServerId:e.upstreamServerId,resourceMetadataUrl:e.resourceMetadataUrl,cause:e.error};if(Ak(e.error))return It({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`});if(e.error instanceof uc){let r=Nk(e.error);return It({...t,code:"upstream_client_registration_required",message:`The authorization server for ${e.upstreamServerId} rejected the gateway's Dynamic Client Registration request (${jk(r)}). Register an OAuth client for the gateway manually and configure it on this upstream, or correct the registration metadata the provider objected to, before retrying.`,diagnostics:r})}if(e.error instanceof Do&&e.error.kind==="metadata")return It({...t,code:"upstream_oauth_issuer_mismatch",message:qk(e.upstreamServerId,e.error),diagnostics:{upstreamUrl:e.error.expected}});if(e.error instanceof pi)return It({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} publishes the non-HTTPS token endpoint "${e.error.tokenEndpoint}". The gateway will not send credentials to it. Ask the provider to serve the token endpoint over TLS before retrying.`,diagnostics:{upstreamUrl:e.error.tokenEndpoint}});if(Ok(e.error))return It({...t,code:"upstream_oauth_server_incompatible",message:`The authorization server for ${e.upstreamServerId} cannot run the OAuth flow the gateway requires: ${e.error.message}. Ask the provider to support the authorization code flow with PKCE (S256), or configure this upstream to use an authorization server that does.`});if(xk(e.error)){let r=Dk(e.error.message);return It({...t,code:"upstream_oauth_discovery_unavailable",message:`The gateway could not load OAuth authorization server metadata for the upstream MCP server "${e.upstreamServerId}": ${e.error.message}. Confirm the authorization server advertised by "${e.resourceMetadataUrl}" publishes RFC 8414 or OpenID Connect discovery metadata and is reachable from the gateway, then retry.`,diagnostics:r===void 0?{}:{upstreamUrl:r}})}if(Mk(e.error))return It({...t,code:"upstream_oauth_discovery_unavailable",message:`The protected resource metadata at "${e.resourceMetadataUrl}" names a resource that does not match the configured MCP URL for ${e.upstreamServerId}: ${e.error.message}. Point this upstream's MCP URL at the resource the provider publishes, or ask the provider to correct the advertised resource.`});if(Pk(e.error))return It({...t,code:"upstream_oauth_discovery_unavailable",message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`});if(Uk(e.error))return It({...t,code:"upstream_provider_access_denied",message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`})}o(Lk,"mapUpstreamOAuthSetupError");function $k(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o($k,"readOAuthFetchRequest");function Hk(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Hk,"readOAuthFetchMethod");function Bk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(Bk,"responseLooksJson");function Fk(e,t){let r=e.headers.get("content-type")??"",n=t.trimStart().toLowerCase();return r.includes("html")||n.startsWith("<!doctype html")||n.startsWith("<html")}o(Fk,"responseLooksHtml");var Jk=["/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server","/.well-known/openid-configuration"];function Vk(e){return Jk.some(t=>e.pathname.endsWith(t)||e.pathname.startsWith(`${t}/`))}o(Vk,"isMetadataDiscoveryRequest");function Gk(e,t,r){return e!=="GET"||!Vk(t)?!1:r>=400&&r<500||r===502}o(Gk,"sdkRetriesDiscoveryCandidate");function Kk(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new k({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[M]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[lt]:e.response.status,[Wr]:r,[pt]:e.request.url.toString(),[Zr]:e.body}})}o(Kk,"throwUpstreamHtmlError");var Wk=["message","error_message","detail","title"];function Vy(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}o(Vy,"readStringField");function Zk(e){for(let r of Wk){let n=Vy(e,r);if(n!==void 0)return n}let t=e.error;if(typeof t=="object"&&t!==null)return Vy(t,"message")}o(Zk,"readProviderMessage");function $i(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t,n=typeof r.error=="string"?r.error:void 0,s=typeof r.error_description=="string"?r.error_description:void 0;return{error:n,errorDescription:s,providerMessage:s===void 0?Zk(r):void 0}}catch{return{}}}o($i,"readUpstreamOAuthErrorBody");function Yk(e){let{error:t,errorDescription:r,providerMessage:n}=$i(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.method,host:ie(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:ts(r,Li),providerMessage:ts(n,Li)},"Upstream OAuth HTTP request returned an error response")}o(Yk,"logUpstreamOAuthHttpError");function Xk(e,t){if(e!=="POST")return!1;let r=t?.body;return r instanceof URLSearchParams?r.get("grant_type")==="refresh_token":typeof r=="string"?new URLSearchParams(r).get("grant_type")==="refresh_token":!1}o(Xk,"isRefreshTokenGrant");var Qk=new Set([void 0,me.ServerError,me.TemporarilyUnavailable]);function eA(e,t){return e.status<500&&e.status!==429?!1:Qk.has($i(t).error)}o(eA,"isTransientTokenEndpointResponse");var tA=[/\b(?:unknown|unrecognized|unrecognised)\s+client(?:[\s_-]?id)?(?=\s*(?:$|[.,:;!?'"`(]))/i,/\bclient(?:[\s_-]?id)?\s+(?:not\s+found|is\s+unknown|does\s+not\s+exist)\b/i];function rA(e,t){return e==="POST"&&t?.body instanceof URLSearchParams&&t.body.has("grant_type")}o(rA,"isTokenEndpointRequest");function nA(e,t){if(e<400||e>=500)return;let{error:r,providerMessage:n}=$i(t);if(!(r!==void 0||n===void 0))return tA.some(s=>s.test(n))?n:void 0}o(nA,"readUnknownClientRejection");function oA(e,t){let r=new Headers(e.headers);return r.set("content-type","application/json"),r.delete("content-length"),r.delete("content-encoding"),new Response(JSON.stringify({error:"invalid_client",error_description:t}),{status:e.status,statusText:e.statusText,headers:r})}o(oA,"rewriteUnknownClientRejection");function Gy(e,t){return async(r,n)=>{let s=$k(r),i=Hk(r,n),a=t!==void 0&&Xk(i,n),c=se(),d=Date.now(),u;try{u=await dy(r,n,{maxRedirects:wk,maxResponseBytes:Rk,problemCode:"upstream_token_exchange_failed",timeoutMs:Sk})}catch(h){throw a&&ay(h)&&(t.failure={url:s.url,cause:h}),h}let p=await u.clone().text();if(c?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:i,host:ie(s.url),path:s.url.pathname,status:u.status,durationMs:Date.now()-d,responseChars:p.length},"Upstream OAuth HTTP request completed"),u.ok||Yk({log:c,upstreamServerId:e,method:i,request:s,response:u,body:p}),a&&eA(u,p)&&(t.failure={url:s.url,status:u.status}),Gk(i,s.url,u.status))return u;if(rA(i,n)){let h=nA(u.status,p);if(h!==void 0)return c?.info({event:"upstream_oauth_unknown_client_rejected",upstreamServerId:e,host:ie(s.url),path:s.url.pathname,status:u.status,providerMessage:ts(h,Li)},"Upstream OAuth provider no longer recognizes the gateway's client; treating it as invalid_client"),oA(u,h)}if(!u.ok&&Fk(u,p)&&Kk({upstreamServerId:e,request:s,response:u,body:p}),!Bk(u,p))return u;try{JSON.parse(p)}catch(h){throw new k({message:`Upstream OAuth fetch ${s.url.origin}${s.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[M]:"upstream_token_exchange_failed"}},{cause:h})}return u}}o(Gy,"createUpstreamOAuthFetch");function Ky(e){se()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:ie(e.serverUrl),resourceMetadataHost:ie(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}o(Ky,"logUpstreamOAuthFlowStarted");function Wy(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=ie(e.serverUrl);r!==void 0&&(t.serverHost=r);let n=e.error instanceof k?e.error.extensionMembers?.[M]:void 0;typeof n=="string"&&(t.code=n),Ae(t,"error",e.error),se()?.warn(t,"Upstream OAuth flow failed before a connection was established")}o(Wy,"logUpstreamOAuthFlowFailed");function Zy(e,t){return e.configuredAuthorizationScope??t.requestedScope}o(Zy,"readAuthorizationRequestScope");async function Yy(e,t){e.applyChallengeScope(t.requestedScope),Ky({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Gy(t.upstreamServerId,t.refreshFailures)},n=Zy(e,t);return n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation),await lc(e,r)}catch(r){Wy({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let n=Lk({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw n!==void 0?n:r}}o(Yy,"runUpstreamOAuth");async function sA(e,t){e.applyChallengeScope(t.requestedScope),Ky({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Gy(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let n=Zy(e,t);n!==void 0&&(r.scope=n),e.skipIssuerMetadataValidation!==void 0&&(r.skipIssuerMetadataValidation=e.skipIssuerMetadataValidation);try{return await lc(e,r)}catch(s){throw Wy({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:s}),s}}o(sA,"exchangeUpstreamAuthorizationCode");async function pd(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await G().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||Me(r)!=="usable"||!ln(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}o(pd,"adoptPeerCredentialAtResolutionBoundary");async function Xy(e,t){let r=await Yy(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new k({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}}):new k({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}})}o(Xy,"requireUpstreamAuthorizationRedirect");function iA(e,t){let r=t.status===void 0?"did not respond":`answered HTTP ${t.status}`;return new k({message:`The token endpoint for ${e} ${r} while the gateway refreshed a stored connection. The connection was kept; retry the request.`,extensionMembers:{[M]:"upstream_token_refresh_unavailable",[To]:e,[pt]:`${t.url.origin}${t.url.pathname}`,...t.status===void 0?{}:{[lt]:t.status}}},t.cause===void 0?void 0:{cause:t.cause})}o(iA,"buildTransientRefreshProblem");function aA(e){e.log?.warn({event:"upstream_oauth_refresh_unavailable",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:e.connection?.id,host:ie(e.failure.url),path:e.failure.url.pathname,status:e.failure.status},"Upstream token endpoint could not refresh the connection; the connection was kept")}o(aA,"logTransientRefreshFailure");async function Qy(e){let t=Me(e.connection),r=!!e.forceRefresh,n=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),s=se(),i=s?await un({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(s?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:i,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!n,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},n?"Reusing stored upstream access token":"Refreshing upstream credential"),n)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let a={},c=o(u=>{throw aA({log:s,target:e.target,connection:e.connection,connectionFingerprint:i,failure:u}),iA(e.target.upstreamServerId,u)},"rejectTransientRefreshFailure"),d;try{d=await Yy(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,refreshFailures:a,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(u){if(a.failure!==void 0&&!Jy(u)){if(await pd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope}))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};c(a.failure)}if(e.connection===void 0||!Jy(u))throw u;return s?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:u.code,connectionFingerprint:i,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await pd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await md({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(d==="AUTHORIZED"){let u=e.provider.readUsablePeerAdoption(e.requestedScope);return u!==void 0&&await e.provider.adoptConnectionForDirectResolution(u,"cas_loss"),!e.provider.tokenWriteWasPersisted&&u===void 0?{kind:"connect_required",payload:await md({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(d!=="REDIRECT")throw new k({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${d}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new k({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});return await pd({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:(a.failure!==void 0&&c(a.failure),{kind:"connect_required",payload:await md({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})})}o(Qy,"authorizeUpstreamOAuthSession");async function cA(e){let t=await zi(e.stateToken),r=await G().consumeUpstreamOAuthState({id:t.id,now:W(new Date)}),n=dA(r);return uA({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),lA(n),n}o(cA,"consumeStoredCallbackState");function dA(e){switch(e.kind){case"consumed":throw new k({message:"OAuth state has already been used",extensionMembers:{[M]:"oauth_state_reused"}});case"missing":throw new k({message:"OAuth state is missing or expired",extensionMembers:{[M]:"oauth_state_expired"}});case"available":return e.record}}o(dA,"readConsumedCallbackState");function uA(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new k({message:"OAuth callback did not match the initiating request",extensionMembers:{[M]:"oauth_callback_mismatch"}})}o(uA,"assertStoredCallbackStateMatches");function lA(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new k({message:"OAuth state has expired",extensionMembers:{[M]:"oauth_state_expired"}})}o(lA,"assertStoredCallbackStateFresh");async function md(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Ay(r)}if($t()&&!xy(e.operationId))return se()?.warn({event:"upstream_connect_link_unavailable",upstreamServerId:e.upstreamServerId,operationId:e.operationId},"User-owned upstream needs a connection, but this MCP route has no gateway MCP OAuth sign-in to bind a connect link to; returning an administrator answer instead of a link"),Oy({upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,...e.connection===void 0?{}:{connectionId:e.connection.id},requiresReconsent:!!e.connection});let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Ni(t)}o(md,"buildOAuthConnectRequiredResponse");async function eS(e){let t=await cA({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Vs(t),[n]=await G().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),s={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(s.connection=n);let i=new Bt(s),a=await sA(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(a==="AUTHORIZED"){let c=i.readUsablePeerAdoption();if(c!==void 0&&await i.adoptConnectionForDirectResolution(c,"cas_loss"),!i.tokenWriteWasPersisted&&c===void 0)throw new k({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[M]:"upstream_token_exchange_failed"}});return t}throw a!=="REDIRECT"?new k({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${a}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}}):new k({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[M]:"upstream_token_exchange_failed"}})}o(eS,"finishUpstreamOAuthCallback");import{importPKCS8 as pA,SignJWT as mA}from"jose";var rS=1e4,nS=64*1024,oS=2,hA=300,at=m.string().min(1),fA=m.object({access_token:at,issued_token_type:m.literal(Pa),token_type:m.string().optional(),expires_in:m.number().int().positive().optional(),scope:at.optional()}).passthrough(),gA=m.object({id_token:at,token_type:at.optional(),expires_in:m.number().int().positive().optional(),refresh_token:at.optional(),scope:at.optional()}).passthrough(),yA=m.object({access_token:at,token_type:at,expires_in:m.number().int().positive().optional(),scope:at.optional(),resource:at.optional(),refresh_token:at.optional()}).passthrough();function tS(e){return encodeURIComponent(e).replace(/%20/g,"+")}o(tS,"formEncodeClientCredential");function SA(e){return e.replaceAll("\\n",`
|
|
41
|
-
`)}o(SA,"normalizePem");async function RA(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??hA,n=await pA(SA(e.clientAuth.privateKeyPem),t),s={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new mA({jti:crypto.randomUUID()}).setProtectedHeader(s).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(n)}o(RA,"createPrivateKeyJwtClientAssertion");async function wA(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=tS(e.clientAuth.clientId),r=tS(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Ks),e.form.set("client_assertion",await RA({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}o(wA,"appendClientAuthentication");async function hd(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await wA({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}o(hd,"buildFormRequest");function sS(e){return(t,r)=>Ui(t,r,{context:e,maxRedirects:oS,maxResponseBytes:nS,problemCode:"upstream_token_exchange_failed",timeoutMs:rS})}o(sS,"defaultIdpFetchJson");function _A(e){return(t,r)=>uy(t,r,{context:e,maxRedirects:oS,maxResponseBytes:nS,problemCode:"upstream_token_exchange_failed",timeoutMs:rS})}o(_A,"defaultResourceAsFetchJson");function Hi(e){let t={[M]:e.code,[pt]:e.tokenUrl};return e.response!==void 0&&(t[lt]=e.response.status),new k({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}o(Hi,"runtimeError");function fd(e){if(!e.response.ok)throw Hi({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}o(fd,"assertTokenEndpointSucceeded");function bA(e){let t=gA.safeParse(e.json);if(!t.success)throw Hi({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(bA,"parseIdpRefreshTokenResponse");function vA(e){let t=fA.safeParse(e.json);if(!t.success)throw Hi({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}o(vA,"parseIdJagTokenExchangeResponse");function CA(e){let t=yA.safeParse(e.json);if(!t.success)throw Hi({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}o(CA,"parseAccessTokenResponse");async function iS(e){let t=new URLSearchParams({grant_type:Gs,requested_token_type:Pa,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??sS(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return fd({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),vA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(iS,"requestIdJag");async function aS(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??sS(e.context),{response:n,json:s}=await r(e.idp.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return fd({response:n,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),bA({json:s,response:n,tokenUrl:e.idp.tokenUrl})}o(aS,"refreshIdpSubjectToken");async function cS(e){let t=new URLSearchParams({grant_type:zt,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??_A(e.context),{response:n,json:s}=await r(e.resourceAs.tokenUrl,await hd({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return fd({response:n,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),CA({json:s,response:n,tokenUrl:e.resourceAs.tokenUrl})}o(cS,"exchangeIdJagForAccessToken");function IA(e){return Me(e)==="usable"}o(IA,"hasUsableAccessToken");function TA(e){if(e.tokenType.toLowerCase()!=="bearer")throw new k({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[M]:"upstream_token_response_invalid"}})}o(TA,"assertBearerToken");function dS(e,t){if(t===nn)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}o(dS,"hasExpiredSubjectToken");async function EA(e){let t=await Ct(e.encryptedSubjectToken);if(e.subjectTokenType!==nn)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await aS({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:Po};let n=await G().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await vt(r.refreshToken),idpSubjectTokenType:nn,idpSubjectTokenExpiresAt:void 0}});return se()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:n.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await gr(t),newSubjectRefreshTokenFingerprint:await gr(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:n,subjectToken:r.idToken,subjectTokenType:Po}}o(EA,"resolveIdJagSubjectToken");async function uS(e){let t="preloadedConnection"in e?e.preloadedConnection:(await G().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Me(t),n=!!e.forceRefresh,s=!n&&r==="usable",i=se(),a=i?await un({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(i?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:a,connectionId:t?.id,accessTokenState:r,forceRefresh:n,willMint:!s,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},s?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&IA(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Ct(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,d=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||d===void 0||dS(t,d))return i?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:d,subjectTokenExpired:d!==void 0&&dS(t,d)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let u=Lt(e.upstreamServerId),p=Qg(e.upstreamServerId,e.authProfileId),h=p.resourceAs.resource??u.transport.baseUrl,f=e.requestedScope??(p.scopes.length===0?void 0:p.scopes.join(p.scopeDelimiter)),y=await EA({connection:t,connectionFingerprint:a,encryptedSubjectToken:c,subjectTokenType:d,idp:{tokenUrl:p.idp.tokenUrl},clientAuth:p.idp.clientAuth,context:e.context}),b=await iS({idp:{tokenUrl:p.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:p.resourceAs.audience,resource:h,scope:f,clientAuth:p.idp.clientAuth,context:e.context}),w=b.scope??f,S=await cS({resourceAs:{tokenUrl:p.resourceAs.tokenUrl},assertion:b.assertion,resource:h,scope:w,clientAuth:p.resourceAs.clientAuth,context:e.context});if(TA(S),t!==void 0){let v=(S.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],x=S.expiresIn===void 0?void 0:W(new Date(Date.now()+S.expiresIn*1e3)),N=await G().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await vt(S.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:v,expiresAt:x,metadata:y.connection.metadata});i?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:a,connectionId:N.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:v.length,expiresAt:x},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:S.accessToken}}}o(uS,"authorizeUpstreamIdJagRequest");var Bi=new Map;function kA(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}o(kA,"normalizeRefreshFlightScope");function AA(e){return ji(new URL(e.callbackPath,ce(e.requestUrl,e.requestHeaders))).toString()}o(AA,"buildGatewayOAuthRedirectUri");async function gd(e){let t=Lt(e.upstreamServerId),r=cn(e.upstreamServerId,e.authProfileId),n=AA({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),s="preloadedConnection"in e?e.preloadedConnection:(await G().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:s,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:n,returnOrigin:ce(e.request.url,e.request.headers)}}}o(gd,"prepareUpstreamOAuthRequest");async function lS(e){let t=await gd(e),r=new Bt({...t.providerInput,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding},...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Xy(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(lS,"startUpstreamConnect");async function pS(e){let t=await gd(e),r=new Bt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),n=o(()=>Qy({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&Me(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n();let s=Th({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),i=JSON.stringify([s,kA(r.configuredAuthorizationScope??e.requestedScope)]),a=Bi.get(i);if(a!==void 0){se()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let u=await a;if(u.kind==="usable"&&r.connectionSatisfiesRequestedScope(u.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(u.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:p,...h}=e;if(t=await gd(h),r=new Bt({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&Me(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return n()}let c=n(),d;return d=c.then(()=>{let u=r.currentConnection;return u!==void 0&&Me(u)==="usable"?{kind:"usable",connection:u}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{Bi.get(i)===d&&Bi.delete(i)}),Bi.set(i,d),c}o(pS,"authorizeUpstreamRequest");async function Fi(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return pS({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return uS({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Ee(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(Fi,"resolveUpstreamCredentialForRoute");async function mS(e){if(e.connectRequest.authMode==="id-jag")throw new Ee(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await lS({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo,...e.browserBinding===void 0?{}:{browserBinding:e.browserBinding}});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}o(mS,"startUpstreamConnectForRequest");async function PA(e,t){if(t===void 0)throw new k({message:"OAuth state was not started by the browser connect route, so it cannot be completed in a browser.",extensionMembers:{[M]:"oauth_callback_mismatch"}});let r=await Oi({purpose:"connect",claim:t,request:e.request});if(e.onBrowserBinding?.(r.clearCookie),!r.matched)throw new k({message:"The upstream connection was not started in this browser. Start the connection again from the browser you will finish it in.",extensionMembers:{[M]:"oauth_callback_mismatch"}})}o(PA,"requireCallbackBrowser");async function hS(e){let t=await zi(e.callbackRequest.state);$t()&&await PA(e,t.browserBinding);let r=t.authProfileId;if(Ai({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Ee(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return eS({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:Lt(e.callbackRequest.upstreamServerId)})}o(hS,"finishUpstreamCallbackForRequest");function xA(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(xA,"buildRouteAuthBaseFromConnection");function fS(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:nh(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}o(fS,"buildRouteAuthBaseFromPolicyOptions");function Ji(e,t){let n=Ie().byOperationId.get(t);if(!n)throw new re(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(n.connection===void 0)throw new re(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(n.connection.upstreamServerId!==e)throw new re(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return xA({connection:n.connection,operationId:t})}o(Ji,"resolveRouteAuthBase");function yd(e,t){switch(e){case"user":return tn(t);case"shared":return th()}}o(yd,"buildOwnerForSubject");function mn(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:yd("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:yd("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:yd("user",t),initiatedBySubjectId:t}}}o(mn,"resolveRouteAuthForSubject");import{base64url as OA,errors as gS,jwtVerify as MA,SignJWT as UA}from"jose";var Sd="zuplo-connect.",qA=600,yS="mcp_connect_request_state",zA=m.object({purpose:m.literal(yS),binding:m.string().min(1),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),NA=new TextEncoder;async function SS(){return Ze({purpose:"connect-request-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"connect-request-state"),"derive")})}o(SS,"getConnectRequestStateKey");async function RS(e){let t=JSON.stringify([e.subjectId,e.operationId,e.upstreamServerId,e.authProfileId,e.method,e.target]),r=await crypto.subtle.digest("SHA-256",NA.encode(t));return OA.encode(new Uint8Array(r))}o(RS,"digestBinding");function Rd(e){return typeof e=="string"&&e.startsWith(Sd)}o(Rd,"isConnectRequestState");async function wS(e,t=new Date){let r=Math.floor(t.getTime()/1e3),n=await new UA({purpose:yS,binding:await RS(e)}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt(r).setExpirationTime(r+qA).sign(await SS());return`${Sd}${n}`}o(wS,"signConnectRequestState");async function _S(e,t,r=new Date){if(!Rd(e))return"foreign";let n;try{let{payload:s}=await MA(e.slice(Sd.length),await SS(),{algorithms:[be],issuer:fe,audience:_e,currentDate:r,clockTolerance:0});n=zA.parse(s)}catch(s){return s instanceof gS.JWTExpired?"expired":s instanceof gS.JWTClaimValidationFailed||s instanceof m.ZodError?"invalid":"foreign"}return n.binding===await RS(t)?void 0:"mismatch"}o(_S,"verifyConnectRequestState");var jA=new Set(["initialize","ping","logging/setLevel","resources/subscribe","resources/unsubscribe","tasks/list","tasks/result"]);function bS(e){if(!xe()||!jA.has(e.method))return;let t=we(e.message);return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:I.MethodNotFound,message:"Method not found"}}),{status:404})}o(bS,"modernMethodNotFoundResponse");var DA=new Map([["tools/list","tools"],["prompts/list","prompts"],["resources/list","resources"],["resources/templates/list","resourceTemplates"]]),LA=0,$A="private",HA=new Set(["tools/call","prompts/get","resources/read"]);var BA=-32021,FA="Invalid or expired requestState";function yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(yr,"isRecord");function JA(e,t){if(!(!te()||!yr(t)||typeof t.method!="string"||!Fr(e,t)))return{message:t,method:t.method}}o(JA,"readModernMcpRequest");async function vS(e,t){return xe()?!te()||!yr(t)||typeof t.method!="string"||!Bs(e.headers,t)||await vm(e.clone(),t,{maxRequestBodySize:Number.MAX_SAFE_INTEGER})?void 0:{message:t,method:t.method}:JA(e.headers,t)}o(vS,"classifyModernMcpRequest");function wd(e){return!Object.hasOwn(e.message,"id")}o(wd,"isModernNotification");function _d(){return new Response(null,{status:202})}o(_d,"acceptedNotificationResponse");function bd(e){let t=e.message.params;return yr(t)?t:void 0}o(bd,"readParams");function CS(e){if(!HA.has(e.method))return;let t=bd(e),r=e.method==="resources/read"?t?.uri:t?.name;return typeof r=="string"?r:void 0}o(CS,"readInputRequiredTarget");function IS(e,t,r){return{...e,method:t.method,target:r}}o(IS,"buildBinding");function VA(e){let t=we(e.message);return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:I.InvalidParams,message:FA,data:{reason:"invalid_request_state"}}}))}o(VA,"invalidRequestStateResponse");function GA(e){if(!yr(e))return;let t=e[Jr],r=yr(t)?t.action:void 0;return r==="accept"||r==="decline"||r==="cancel"?r:void 0}o(GA,"readElicitationAction");function KA(e){let t={...bd(e)};if(delete t.requestState,yr(t.inputResponses)){let r={...t.inputResponses};delete r[Jr],Object.keys(r).length===0?delete t.inputResponses:t.inputResponses=r}return{...e.message,params:t}}o(KA,"stripConnectState");async function TS(e){let t=bd(e.request),r=t?.requestState;if(!Rd(r))return{kind:"none"};let n=CS(e.request),s=n===void 0?"mismatch":await _S(r,IS(e.binding,e.request,n),e.now);if(s==="foreign")return{kind:"none"};if(s!==void 0)return{kind:"rejected",reason:s,response:VA(e.request)};let i=KA(e.request),a=new TextEncoder().encode(JSON.stringify(i));return{kind:"accepted",body:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),request:{message:i,method:e.request.method},action:GA(t?.inputResponses)}}o(TS,"readModernConnectRetry");function WA(e){let t=km(e.message)?.elicitation;return yr(t)&&t.url!==void 0}o(WA,"declaresUrlElicitation");function ZA(e,t){return Response.json(Pe({...e===void 0?{}:{id:e},error:{code:Sc,message:t.message,data:{connectRequired:t}}}))}o(ZA,"connectRequiredErrorResponse");async function ES(e){if(wd(e.request))return _d();let t=we(e.request.message),r=DA.get(e.request.method);if(r!==void 0)return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"complete",[r]:[],ttlMs:LA,cacheScope:$A,_meta:{[Mt]:e.serverInfo}}});let n=CS(e.request),s=e.payload.authUrl;if(n===void 0||s===void 0||e.previousAction==="decline"||e.previousAction==="cancel")return ZA(t,e.payload);if(!WA(e.request))return Response.json(Pe({...t===void 0?{}:{id:t},error:{code:BA,message:`${e.payload.message} The client must declare URL elicitation (clientCapabilities.elicitation.url) to be sent the connect link.`,data:{requiredCapabilities:{elicitation:{url:{}}},connectRequired:e.payload}}}),{status:400});let i=await wS(IS(e.binding,e.request,n),e.now);return Response.json({jsonrpc:"2.0",...t===void 0?{}:{id:t},result:{resultType:"input_required",inputRequests:{[Jr]:{method:"elicitation/create",params:{mode:"url",message:e.payload.message,url:s}}},requestState:i,_meta:{[Mt]:e.serverInfo}}})}o(ES,"modernConnectRequiredResponse");var vd=new WeakMap;function kS(e,t){vd.set(e,t)}o(kS,"setUpstreamAuthRetry");function AS(e){let t=vd.get(e);return vd.delete(e),t}o(AS,"takeUpstreamAuthRetry");var PS=new WeakSet;function xS(e){PS.add(e)}o(xS,"markGatewayUpstreamCredential");function OS(e){return PS.has(e)}o(OS,"sentGatewayUpstreamCredential");async function MS(e){try{return await Fi(e)}catch(t){if(Be(t)==="upstream_token_refresh_unavailable")return{kind:"refresh_unavailable"};throw t}}o(MS,"resolveCredentialOrRefreshUnavailable");function US(e,t){return en(e,t,{code:"upstream_token_refresh_unavailable"})}o(US,"refreshUnavailableResponse");var YA="The upstream connection returned no OAuth tokens.";function qS(e){let t=hc(e);return Response.json(Pe({id:t,error:{code:I.InternalError,message:YA}}),{status:t===void 0?500:200})}o(qS,"noUpstreamTokensJsonRpcResponse");function XA(e,t){return{credentialType:e.type,forceRefresh:t}}o(XA,"buildCredentialResolvedAttributes");function QA(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}o(QA,"connectRequiredReasonCode");function zS(e){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,attributes:XA(e.credential,e.forceRefresh===!0)})}o(zS,"emitCredentialResolvedAnalyticsEvent");function NS(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,mcpProtocolVersion:e.mcpProtocolVersion,reasonCode:QA(e.payload.state),reasonClass:"auth",attributes:t})}o(NS,"emitCredentialMissingAnalyticsEvents");function eP(e){let t=e.route.raw();return Js.parse(t?.operationId)}o(eP,"readOperationId");async function tP(e,t,r,n,s){let i=await MS({request:e,context:n,routeAuth:t});if(i.kind==="refresh_unavailable")return i;if(i.kind==="connect_required")return NS({context:n,payload:i.payload,routeBinding:t,mcpProtocolVersion:s}),n.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(zS({context:n,credential:a,routeBinding:t,mcpProtocolVersion:s}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(n.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),{kind:"no_tokens"})}o(tP,"buildCredentialHeaders");var rP=new Set(["authorization","cookie","cookie2"]);function jS(e){if(e!==void 0)try{return JSON.parse(new TextDecoder().decode(e))}catch{return}}o(jS,"parseJsonRequestBody");function nP(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"method"in e&&typeof e.method=="string"?e.method:void 0}o(nP,"readJsonRequestMethod");function oP(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}o(oP,"isJsonResponse");function Ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ft,"isRecord");function DS(e){return Array.isArray(e)&&e.length>0}o(DS,"hasIconList");function LS(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Ei(Qm(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}o(LS,"readFallbackServerIcons");function sP(e){if(!Ft(e.body))return e.body;let t=e.body.result;if(!Ft(t))return e.body;let r=t.serverInfo;return!Ft(r)||DS(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}o(sP,"addMissingServerIcons");function iP(e){if(!Ft(e.body))return e.body;let t=e.body.result;if(!Ft(t))return e.body;let r=t._meta;if(!Ft(r))return e.body;let n=r[Mt];return!Ft(n)||DS(n.icons)?e.body:{...e.body,result:{...t,_meta:{...r,[Mt]:{...n,icons:e.icons}}}}}o(iP,"addMissingDiscoverServerIcons");function aP(e,t){let r=$S(e.headers);for(let n of rP)r.delete(n);for(let[n,s]of t)r.set(n,s);return new xt(e,{headers:r})}o(aP,"applyUpstreamHeaders");function $S(e){let t=new Headers(e);return ku(t),t}o($S,"buildProxyHeaders");async function cP(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}o(cP,"readRetryBody");function dP(e){return xe()&&e.httpMethod==="POST"?Zf({body:e.requestBody,parsed:jS(e.requestBody),headers:e.headers,payload:e.payload}):Response.json(Rc({id:hc(e.requestBody),payload:e.payload,urlElicitation:!0,fallbackCode:I.InvalidRequest}))}o(dP,"connectRequiredJsonRpcResponse");function uP(e){let t=e.modern;if(t===void 0)return{respond:o(async i=>xe()&&e.httpMethod!=="POST"?await Si(e.request,e.context):dP({requestBody:e.requestBody,httpMethod:e.httpMethod,headers:e.headers,payload:i}),"respond")};let r=o(()=>LS({connection:e.connection,context:e.context}),"readIcons"),n=yi(t.binding.upstreamServerId,$o),s=t.request.method==="server/discover"?async()=>Bf({request:t.request,supportedVersions:n,connection:e.connection,capabilityFilter:lP(e.context),icons:r()}):i=>ES({request:t.request,payload:i,binding:t.binding,previousAction:t.previousAction,serverInfo:gc({connection:e.connection,icons:r()})});return{respond:o(async i=>{let a=Hg({headers:e.headers,message:t.request.message,supportedVersions:n});return a!==void 0?a:wd(t.request)?_d():bS(t.request)??s(i)},"respond")}}o(uP,"createConnectRequiredResponder");function lP(e){return rn()?.byRoutePath.get(e.route.path)?.capabilityFilter}o(lP,"readRouteCapabilityFilter");async function pP(e){let{scope:t}=Nf(e.upstreamResponse),r=await MS({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="refresh_unavailable")return r;if(r.kind==="connect_required")return NS({context:e.context,payload:r.payload,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let n=new Headers(e.headers),s=r.credential;if(zS({context:e.context,credential:s,routeBinding:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,forceRefresh:!0}),s.type==="bearer_token")return n.set("authorization",`Bearer ${s.token}`),{kind:"headers",headers:n};let i=await s.provider.tokens();return i?(n.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:n}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"no_tokens"})}o(pP,"applyRefreshedCredentialHeaders");function mP(e){kS(e.context,{refresh:o(async(t,r)=>{let n=await pP({request:e.request,context:e.context,headers:$S(r),routeAuth:e.routeAuth,mcpProtocolVersion:e.mcpProtocolVersion,upstreamResponse:t});return n.kind==="connect_required"?{kind:"response",response:await e.connectRequired.respond(n.payload)}:n.kind==="no_tokens"?{kind:"response",response:qS(e.requestBody)}:n.kind==="refresh_unavailable"?{kind:"response",response:await US(e.request,e.context)}:n},"refresh")})}o(mP,"registerUpstreamAuthRetry");function hP(e){return e.body!==null&&e.status>=200&&e.status<=299&&We(e.headers.get("content-type"))==="text/event-stream"&&!ht(e.headers)}o(hP,"isRewritableEventStream");function fP(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(fP,"answersRequestId");function gP(e,t){if(e.data===void 0||e.data===""||e.event!==void 0&&e.event!=="message")return;let r;try{r=JSON.parse(e.data)}catch{return}if(!(!Ft(r)||"method"in r||!("result"in r||"error"in r)||!fP(r.id,t)))return r}o(gP,"readResponseInEvent");function yP(e){let t=!1;return wi(e.response,r=>{if(t)return;let n=gP(r,e.requestId);if(n===void 0)return;t=!0;let s=e.addMissingIcons({body:n,icons:e.icons});return s===n?void 0:Fo(r,JSON.stringify(s))},{failureMode:"open"})}o(yP,"addMissingIconsToEventStream");function SP(e){let t=nP(e.requestJson);if(t!=="initialize"&&!(e.modern&&t==="server/discover"))return;let r=t==="initialize"?sP:iP,n=LS({connection:e.connection,context:e.context});if(n===void 0||n.length===0)return;let s=te()?we(e.requestJson):void 0;e.context.addResponseSendingHook(async i=>{if(!oP(i))return s!==void 0&&hP(i)?yP({response:i,requestId:s,addMissingIcons:r,icons:n}):i;let a;try{a=await i.clone().json()}catch{return i}let c=r({body:a,icons:n});if(c===a)return i;let d=Xf(new Headers(i.headers));return d.delete("content-length"),new Response(JSON.stringify(c),{status:i.status,statusText:i.statusText,headers:d})})}o(SP,"installInitializeIconHook");function RP(e,t){let r=new Headers(e.headers);return r.delete("content-length"),new xt(e,{headers:r,body:t})}o(RP,"withRequestBody");async function Cd(e,t,r){let n=Date.now(),s=eP(t),i=e,a=await cP(i),c=jS(a),d=o(async(x,N)=>(await Xg({request:i,context:t,requestJson:c,requestBody:a,response:x,startTime:n,...N===void 0?{}:{outcome:N}}),x),"answer"),u=lr(i.headers,c),p=fS({connection:r,operationId:s}),h=pr(i.user,i.url,i.headers);Ph(t,h);let f=mn(p,h.subjectId),y=await vS(i,c),b={subjectId:h.subjectId,operationId:s,upstreamServerId:f.upstreamServerId,authProfileId:f.authProfileId},w;if(y!==void 0){let x=await TS({request:y,binding:b});if(x.kind==="rejected")return t.log.info({event:"mcp_connect_request_state_rejected",reason:x.reason,upstreamServerId:f.upstreamServerId},"MCP upstream proxy: connect requestState rejected"),d(x.response);x.kind==="accepted"&&(i=RP(i,x.body),a=x.body,c=x.request.message,y=x.request,w=x.action)}let S=uP({request:i,requestBody:a,httpMethod:i.method,headers:i.headers,modern:y===void 0?void 0:{request:y,binding:b,previousAction:w},context:t,connection:r}),R=await tP(i,f,r,t,u);if(R.kind==="connect_required")return d(await S.respond(R.payload));if(R.kind==="no_tokens")return d(qS(a),"no_upstream_tokens");if(R.kind==="refresh_unavailable")return d(await US(i,t),"upstream_token_refresh_unavailable");let v=aP(i,R.headers);return xS(t),mP({request:v,context:t,requestBody:a,connectRequired:S,routeAuth:f,mcpProtocolVersion:u}),SP({context:t,requestJson:c,connection:r,modern:y!==void 0}),v}o(Cd,"mcpTokenExchangePolicy");var Id=class extends Os{static{o(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let n=oh(t,r);super(n,r),this.#e=n}async handler(t,r){return Cd(t,r,this.#e)}};var HS=Symbol("Html");function wP(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}o(wP,"escapeHtml");function _P(e){return e===null||typeof e!="object"?!1:e[HS]===!0}o(_P,"isHtml");function Vi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Vi).join(""):_P(e)?e.value:wP(String(e))}o(Vi,"renderValue");function Ye(e){return{[HS]:!0,value:e}}o(Ye,"trustedHtml");var Xe=Ye("");function X(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Vi(t[n]),r+=e[n+1]??"";return Ye(r)}o(X,"html");function hn(e,t=Xe){let r=Vi(t),n="",s=!0;for(let i of e)s||(n+=r),n+=Vi(i),s=!1;return Ye(n)}o(hn,"joinHtml");function fn(e){return e.value}o(fn,"renderHtml");function BS(e){return X`<section class="page-section" aria-labelledby="error-next-steps"><h2 class="section-label" id="error-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol>${e.action}</section><section class="page-section" aria-labelledby="error-reference"><h2 class="section-label" id="error-reference">Reference</h2><dl class="kv kv--boxed">${e.reference}</dl></section><section class="page-section tech" aria-labelledby="error-technical"><h2 class="section-label" id="error-technical">Technical details <span class="section-label__count">for administrators</span></h2><dl class="kv">${e.diagnostics}</dl>${e.upstreamResponse}</section>`}o(BS,"renderBrowserErrorPage");var FS=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><path d="m8.25 12.25 2.5 2.5 5-5.25"/></svg>'),JS=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.25"/><line x1="12" y1="7.5" x2="12" y2="12.75"/><circle cx="12" cy="16.25" r=".9" fill="currentColor" stroke="none"/></svg>'),gn=Ye('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}.card__status{border:1px solid;border-radius:50%;justify-content:center;align-items:center;width:48px;height:48px;margin:0 auto 16px;display:flex}.card__status svg{width:24px;height:24px}.card__status--error{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger)}.card__status--success{background:var(--success-bg);border-color:var(--success-border);color:var(--success)}.card__status--neutral{background:var(--surface-2);border-color:var(--border);color:var(--text-3)}.page-section{flex-direction:column;gap:10px;display:flex}.steps{counter-reset:step;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.steps li{counter-increment:step;color:var(--text-2);align-items:flex-start;gap:10px;font-size:13.5px;line-height:1.5;display:flex}.steps li:before{content:counter(step);border:1px solid var(--border-strong);background:var(--surface);width:20px;height:20px;color:var(--text-2);border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;margin-top:1px;font-size:11.5px;font-weight:600;line-height:1;display:inline-flex}.kv{flex-direction:column;margin:0;display:flex}.kv__row{border-top:1px solid var(--border);grid-template-columns:124px minmax(0,1fr);gap:2px 12px;padding:7px 0;display:grid}.kv__row:first-child{border-top:0;padding-top:0}.kv__row:last-child{padding-bottom:0}.kv__row--block{grid-template-columns:minmax(0,1fr)}.kv__label{color:var(--text-3);margin:0;padding-top:1px;font-size:12px;font-weight:500}.kv__value{min-width:0;color:var(--text);overflow-wrap:anywhere;margin:0;font-size:13px;line-height:1.5}.kv__value code{font-family:var(--font-mono);color:var(--text);font-size:12px}.kv__row--fix .kv__value{color:var(--text);font-weight:500}.kv--boxed{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px}.kv--boxed .kv__row{grid-template-columns:92px minmax(0,1fr);padding:6px 0}.kv--boxed .kv__row:first-child{padding-top:0}.kv--boxed .kv__row:last-child{padding-bottom:0}.tech{border-top:1px solid var(--border);padding-top:18px}.provider-response{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2)}.provider-response__summary{cursor:pointer;user-select:none;color:var(--text-2);align-items:center;gap:8px;padding:9px 12px;font-size:12.5px;font-weight:500;list-style:none;display:flex}.provider-response__summary::-webkit-details-marker{display:none}.provider-response__summary:before{content:"";border-bottom:1.5px solid;border-right:1.5px solid;flex-shrink:0;width:6px;height:6px;margin-left:2px;transition:transform .15s;transform:rotate(-45deg)}.provider-response[open]>.provider-response__summary:before{transform:rotate(45deg)}.provider-response__summary:hover{color:var(--text)}.provider-response__summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--radius)}.provider-response__frame{border:0;border-top:1px solid var(--border);border-radius:0 0 var(--radius)var(--radius);background:#fff;width:100%;min-height:240px;display:block}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.kv__row{grid-template-columns:minmax(0,1fr)}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function yn(e){return X`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
|
|
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-OE2WMJXK.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",`
|
|
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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}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>
|
|
42
14
|
${e.styles}
|
|
43
|
-
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(yn,"renderShell");function Gi(e){return X`<div class="card__status card__status--${e}" aria-hidden="true">${e==="success"?FS:JS}</div>`}o(Gi,"renderStatusIcon");var bP="text/html; charset=utf-8";function Jt(e){try{return new URL(e).host}catch{return""}}o(Jt,"safeHostFromUrl");function Qe(e){let t=e.kind??"authorization_failed",r=CP(t),n=vP(e),s=e.title??r.title;return new Response(fn(yn({title:s,iconHref:"",styles:gn,headerIcon:Gi(t==="access_denied"?"neutral":"error"),heading:s,subhead:X`<p class="card__subtitle">${e.detail}</p>`,body:BS({steps:hn(r.steps.map(i=>X`<li>${i}</li>`)),action:EP(e.action),reference:kP(n),diagnostics:AP({diagnostic:n,detail:e.detail}),upstreamResponse:PP(e.upstreamHtml)}),footer:""})),{status:e.status??400,headers:{"content-type":bP,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Qe,"browserErrorPageResponse");function vP(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??IP(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??TP(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}o(vP,"buildBrowserErrorDiagnostic");function CP(e){switch(e){case"session_expired":return{title:"Authorization expired",steps:["Return to your MCP client and reconnect.","Expired authorization requests cannot be resumed, so start a new connection instead of reloading this page."]};case"access_denied":return{title:"Authorization canceled",steps:["Return to your MCP client.","If you want to grant access, start the connection again and approve the request."]};case"configuration_error":return{title:"Configuration needs attention",steps:["Contact your workspace admin and share the reference below.","The gateway or upstream configuration must be fixed before retrying."]};case"connection_failed":return{title:"Connection failed",steps:["Return to your MCP client and reconnect this upstream.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"invalid_request":return{title:"Authorization request invalid",steps:["Return to your MCP client and try connecting again.","If this keeps happening, the client request may need to be fixed."]};case"admin_required":return{title:"Admin setup required",steps:["Contact your workspace admin and share the reference below.","This connection cannot be completed until setup is finished."]};case"internal_error":return{title:"Gateway error",steps:["Try again later from your MCP client.","If this keeps happening, contact your gateway administrator and share the reference below."]};case"authorization_failed":return{title:"Authorization failed",steps:["Return to your MCP client and start authorization again.","If this keeps happening, contact your gateway administrator and share the reference below."]}}}o(CP,"readBrowserErrorPagePresentation");function IP(e){switch(e){case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_refresh_unavailable":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}o(IP,"readBrowserErrorStage");function TP(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_oauth_issuer_mismatch":return"Point the upstream at the authorization server URL that matches the `issuer` its metadata document publishes, or ask the provider to correct that issuer value. If the provider publishes a path-scoped authorization server that reports its root origin, set skipIssuerMetadataValidation on this upstream \u2014 that weakens the mix-up defense, so scope it to this one upstream.";case"upstream_oauth_server_incompatible":return"Ask the provider to support the OAuth 2.1 authorization code flow with PKCE (S256) over HTTPS, or configure the upstream to use an authorization server that does.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}o(TP,"readBrowserErrorSuggestedFix");function EP(e){return e===void 0?Xe:X`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(EP,"renderAction");function Ki(e){if(e.value===void 0||e.value==="")return Xe;let t=["kv__row",e.block?"kv__row--block":void 0,e.modifier].filter(r=>r!==void 0).join(" ");return X`<div class="${t}"><dt class="kv__label">${e.label}</dt><dd class="kv__value">${e.value}</dd></div>`}o(Ki,"renderRow");function Je(e){return Ki({label:e.label,value:e.value===void 0?void 0:X`<code>${e.value}</code>`})}o(Je,"renderCodeRow");function kP(e){return hn([Ki({label:"Error code",value:X`<code data-gateway-error-code="${e.code}">${e.code}</code>`}),Je({label:"Request ID",value:e.requestId}),Je({label:"Time",value:e.timestamp})])}o(kP,"renderReference");function AP(e){let{diagnostic:t}=e,r=t.underlyingError===e.detail?void 0:t.underlyingError;return hn([Ki({label:"Suggested fix",value:t.suggestedFix,block:!0,modifier:"kv__row--fix"}),Ki({label:"Reason",value:r,block:!0}),Je({label:"Stage",value:t.stage}),Je({label:"Gateway route",value:t.routePath}),Je({label:"Operation ID",value:t.operationId}),Je({label:"Upstream",value:t.upstreamServerId}),Je({label:"Auth profile",value:t.authProfileId}),Je({label:"Upstream URL",value:t.upstreamUrl}),Je({label:"Metadata URL",value:t.metadataUrl}),Je({label:"HTTP status",value:t.httpStatus}),Je({label:"Content type",value:t.contentType}),Je({label:"Provider error",value:t.providerError}),Je({label:"Provider error description",value:t.providerErrorDescription})])}o(AP,"renderDiagnostics");function PP(e){return e===void 0?Xe:X`<details class="provider-response"><summary class="provider-response__summary">Show the provider's response</summary><iframe title="Upstream HTML error response" sandbox class="provider-response__frame" srcdoc="${e}"></iframe></details>`}o(PP,"renderUpstreamHtml");var VS="application/json",xP="application/x-www-form-urlencoded";function Wi(e,t){return new k({message:e,extensionMembers:{[M]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Wi,"invalidRequestError");function OP(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(OP,"normalizeContentType");function MP(e,t){return e===t?!0:t===VS&&e.endsWith("+json")}o(MP,"contentTypeMatches");function UP(e,t){if(!t||t.length===0)return;let r=OP(e.headers.get("content-type"));if(!t.some(n=>MP(r,n)))throw Wi(`Request body must be ${t.join(" or ")}.`)}o(UP,"assertExpectedContentType");function qP(e,t,r){let n=e.headers.get("content-length");if(!n)return;let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s>t)throw Wi(`${r} exceeded the maximum allowed size.`)}o(qP,"assertContentLengthWithinLimit");async function GS(e,t){let r=t.label??"Request body";UP(e,t.expectedContentTypes),qP(e,t.maxBytes,r);let n=await Mi(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Wi(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(GS,"readBoundedTextBody");async function KS(e,t){let r=await GS(e,{...t,expectedContentTypes:[VS]});try{return JSON.parse(r)}catch(n){throw Wi("Request body must be valid JSON.",n)}}o(KS,"readBoundedJsonBody");async function WS(e,t){let r=await GS(e,{...t,expectedContentTypes:[xP]});return new URLSearchParams(r)}o(WS,"readBoundedFormUrlEncodedBody");import{errors as YS,jwtVerify as XS,SignJWT as Ed}from"jose";import{base64url as zP}from"jose";var NP="mcp-browser-login-pkce:",jP=new TextEncoder;async function DP(e){return crypto.subtle.importKey("raw",ye(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}o(DP,"importHmacKey");async function Td(e){let t=await DP(e.signingKey),r=jP.encode(`${NP}${e.stateId}`),n=await crypto.subtle.sign("HMAC",t,ye(r));return Kr.parse(zP.encode(new Uint8Array(n)))}o(Td,"deriveBrowserLoginPkceVerifier");async function ZS(e){let t=await Td(e),r=await ei(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:Gr}}o(ZS,"deriveBrowserLoginPkceParams");var LP={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},E=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=LP[t],s){super(r,s),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var $P=300,QS=m.string().min(1).optional(),HP=m.object({purpose:m.literal("gateway_browser_login"),transactionId:xa,stateId:Ws,binding:Zo,authorizationServerIssuer:QS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),BP=m.object({purpose:m.literal("gateway_browser_login_return"),stateId:Ws,binding:Zo,exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),FP=m.discriminatedUnion("purpose",[HP,BP]),JP=m.object({purpose:m.literal("gateway_authorization_setup"),transactionId:xa,stateId:Ws,authorizationServerIssuer:QS,exp:m.number().int().positive(),iat:m.number().int().positive().optional()});async function Sn(){return Ze({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-login"),"derive")})}o(Sn,"getBrowserLoginKey");async function eR(){return Ze({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"authorization-csrf"),"derive")})}o(eR,"getCsrfKey");function tR(e){return{now:e.now??new Date,ttlSeconds:kd()}}o(tR,"readPendingTransactionDependencies");function kd(){return ke().browserLogin.stateTtlSeconds}o(kd,"readBrowserLoginStateTtlSeconds");function VP(e){let t=ge();return He(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}o(VP,"isLoopbackDevLoginUrl");async function rR(e){let t=ke().browserLogin,r=ge(),n=new URL(Ut("url")),s=new URL(r.actionPath("/oauth/callback"),qt(e.requestUrl,e.requestHeaders));if(VP(n))return n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("state",e.state),n;if(n.searchParams.set("response_type","code"),n.searchParams.set("client_id",Ut("clientId")),n.searchParams.set("redirect_uri",s.toString()),n.searchParams.set("scope",t.scope),n.searchParams.set("state",e.state),n.searchParams.set("nonce",e.nonce),t.audience&&n.searchParams.set("audience",t.audience),t.pkce===Gr){let i=await ZS({stateId:e.stateId,signingKey:await Sn()});n.searchParams.set("code_challenge",i.codeChallenge),n.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return n}o(rR,"buildBrowserLoginUrl");function GP(e,t){return e.subjectId===t.subjectId}o(GP,"principalsMatch");function nR(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(nR,"toPendingPrincipal");function oR(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:W(e.now),expiresAt:W(gt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw z("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:nR(e.principal)}}o(oR,"createTransactionRecord");async function sR(e){let{id:t,...r}=e.record,n=await G().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw z("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new E("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new E("invalid_request","redirect_uri is not registered for the client.")}}o(sR,"startPendingTransaction");async function KP(e){return new Ed({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId,binding:e.binding,...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Sn())}o(KP,"signBrowserLoginState");async function iR(e){return new Ed({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ys(),...e.authorizationServerIssuer===void 0?{}:{authorizationServerIssuer:e.authorizationServerIssuer}}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await eR())}o(iR,"signCsrfToken");async function Ad(e){try{let{payload:t}=await XS(e,await Sn(),{algorithms:[be],issuer:fe,audience:_e}),r=FP.parse(t);return r.purpose==="gateway_browser_login"?{kind:"authorization",transactionId:r.transactionId,stateId:r.stateId,binding:r.binding,authorizationServerIssuer:r.authorizationServerIssuer}:{kind:"return_to",stateId:r.stateId,binding:r.binding}}catch(t){throw t instanceof YS.JWTExpired?z("oauth_state_expired","Browser login state has expired.",t):z("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Ad,"verifyAnyBrowserLoginStateToken");async function WP(e){let t=await Ad(e);if(t.kind!=="authorization")throw z("oauth_state_invalid","Browser login state does not belong to an authorization request.");return{transactionId:t.transactionId,stateId:t.stateId,binding:t.binding,authorizationServerIssuer:t.authorizationServerIssuer}}o(WP,"verifyBrowserLoginStateToken");async function Zi(e){try{let{payload:t}=await XS(e,await eR(),{algorithms:[be],issuer:fe,audience:_e}),r=JP.parse(t);return{transactionId:r.transactionId,authorizationServerIssuer:r.authorizationServerIssuer}}catch(t){throw t instanceof YS.JWTExpired?z("oauth_state_expired","Authorization setup state has expired.",t):z("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Zi,"verifyCsrfToken");function Pd(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Pd,"pendingStateErrorCode");function ZP(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(ZP,"toPendingAuthorizationGetResult");function YP(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(YP,"toPendingAuthorizationAdvanceResult");function xd(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Pd(e==="consumed_already"?"consumed_already":e)}o(xd,"setupDecisionErrorCode");async function aR(e){let t=e.now??new Date,r=await Zi(e.csrfToken),n=await G().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:W(t)});if(n.kind!=="marked")throw z(xd(n.kind),"Authorization setup state is invalid, expired, or already used.");return cR({kind:"available",record:n.transaction})}o(aR,"markSetupApproved");function cR(e){if(e.kind!=="available")throw z(Pd(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(cR,"requireAwaitingSetup");function XP(e){if(!GP(e.currentBrowserPrincipal,e.transaction.principal))throw z("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(XP,"requireCurrentPrincipalMatches");async function dR(e){let t=e.now??new Date,r=kd(),n=Oa(),s=Ys(),i=await Xo({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:r}),a=await KP({transactionId:n,stateId:s,binding:i.claim,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),c=oR({id:n,transaction:e.transaction,currentStateHash:await de(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await sR({record:c,client:e.transaction.client});if(d.phase!=="awaiting_login")throw z("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await rR({state:a,nonce:s,stateId:s,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:d,browserLoginStateToken:a,browserLoginUrl:u,browserBindingCookie:i.setCookie}}o(dR,"startAwaitingLogin");async function uR(e){let t=kd(),r=Ys(),n=await Xo({purpose:"login",requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t,payload:e.returnTo}),s=await new Ed({purpose:"gateway_browser_login_return",stateId:r,binding:n.claim}).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Sn());return{browserLoginUrl:await rR({state:s,nonce:r,stateId:r,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}}),browserBindingCookie:n.setCookie}}o(uR,"startReturnToBrowserLogin");async function lR(e){let{now:t,ttlSeconds:r}=tR(e),n=Oa(),s=await iR({transactionId:n,ttlSeconds:r,authorizationServerIssuer:e.transaction.authorizationServerIssuer}),i=oR({id:n,transaction:e.transaction,currentStateHash:await de(s),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");let a=await sR({record:i,client:e.transaction.client});if(a.phase!=="awaiting_setup")throw z("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:a,csrfToken:s}}o(lR,"startAwaitingSetup");async function pR(e){let{now:t,ttlSeconds:r}=tR(e),n=await WP(e.browserLoginStateToken),s=await iR({transactionId:n.transactionId,ttlSeconds:r,authorizationServerIssuer:n.authorizationServerIssuer}),i=YP(await G().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await de(e.browserLoginStateToken),nextStateHash:await de(s),nextPhase:"awaiting_setup",principal:nR(e.principal),now:W(t)}));if(i.kind!=="advanced")throw z(Pd(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw z("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:s}}o(pR,"completeLogin");async function mR(e){let t=await Od(e);return XP({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(mR,"getSetup");async function Od(e){let t=e.now??new Date,r=await Zi(e.csrfToken);return cR(ZP(await G().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await de(e.csrfToken),now:W(t)})))}o(Od,"getSetupTransaction");async function QP(e){let t=await Zi(e.csrfToken),r=St(),n=W(gt(e.now,$P)),s=await G().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await de(r),authorizationCodeExpiresAt:n,grantId:lh(),now:W(e.now)});if(s.kind!=="approved")throw z(s.kind==="cancelled"?"oauth_state_invalid":xd(s.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(s.transaction.redirectUri);return i.searchParams.set("code",r),s.transaction.clientState&&i.searchParams.set("state",s.transaction.clientState),Yi(i,t.authorizationServerIssuer),i}o(QP,"createAuthorizationCodeRedirectWithDecision");async function ex(e){let t=await Zi(e.csrfToken),r=await G().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await de(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:W(e.now)});if(r.kind!=="cancelled")throw z(r.kind==="approved"?"oauth_state_invalid":xd(r.kind),"Authorization setup state is invalid, expired, or already used.");return tx({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState,authorizationServerIssuer:t.authorizationServerIssuer})}o(ex,"createCancelRedirectWithDecision");function Yi(e,t){t!==void 0&&te()&&e.searchParams.set("iss",t)}o(Yi,"setAuthorizationResponseIssuer");function tx(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),Yi(t,e.authorizationServerIssuer),t}o(tx,"buildClientCancelRedirect");async function hR(e){let t=e.now??new Date;return QP({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(hR,"approve");async function fR(e){let t=e.now??new Date;return ex({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(fR,"cancel");import{createRemoteJWKSet as rx,errors as Rn,jwtVerify as gR,SignJWT as nx}from"jose";var ox="zuplo_mcp_session",sx=m.object({purpose:m.literal("gateway_browser_session"),sub:Eo,browserLoginOrigin:m.string().min(1),roles:m.array(m.string().min(1)).optional(),exp:m.number().int().positive(),iat:m.number().int().positive().optional()}),ix=m.object({id_token:m.string().min(1),token_type:m.string().min(1).optional(),expires_in:m.number().optional(),access_token:m.string().min(1).optional(),refresh_token:m.string().min(1).optional(),scope:m.string().min(1).optional()}),ax=m.object({error:m.string().min(1).optional(),error_description:m.string().min(1).optional(),error_uri:m.string().min(1).optional()}),cx=m.object({sub:Eo,nonce:m.string().min(1)}).catchall(m.unknown()),Md;async function yR(){return Ze({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>ft(e,"browser-session"),"derive")})}o(yR,"getBrowserSessionKey");function qd(e,t){let r=xi(e,t);return{name:Qc(ox,r),secure:r}}o(qd,"browserSessionCookieName");function Ud(e,t){let{name:r,secure:n}=qd(e,t);return Yo({name:r,value:"",maxAgeSeconds:0,secure:n})}o(Ud,"buildBrowserSessionEvictionCookie");function dx(e){let{name:t,secure:r}=qd(e.requestUrl,e.requestHeaders);return Yo({name:t,value:encodeURIComponent(e.value),maxAgeSeconds:e.ttlSeconds,secure:r})}o(dx,"serializeSessionCookie");function SR(){return new URL(Ut("url")).origin}o(SR,"readBrowserLoginOrigin");function ux(e){let t=ax.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(ux,"readIdpErrorFields");function lx(e){return e instanceof Rn.JWTExpired?"expired":e instanceof Rn.JWTClaimValidationFailed?"claim":e instanceof Rn.JWSSignatureVerificationFailed?"signature":e instanceof Rn.JWKSNoMatchingKey?"jwks_no_match":e instanceof Rn.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(lx,"readJwtFailureKind");function px(e){return e instanceof Error&&"cause"in e?e.cause:e}o(px,"readErrorCause");function mx(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(mx,"readRuntimeGatewayCode");function hx(){if(!Md){let e=ke();Md=rx(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Md}o(hx,"readFederatedJwks");function RR(e){if(!e.user)throw z("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return pr(e.user,e.url)}o(RR,"resolveCurrentRequestPrincipal");async function wn(e,t={}){let r=ed(e.headers.get("cookie")).get(qd(e.url,e.headers).name);if(!r)return{};try{let{payload:n}=await gR(r,await yR(),{algorithms:[be],issuer:fe,audience:_e}),s=sx.parse(n);if(s.browserLoginOrigin!==SR())return{evictCookie:Ud(e.url,e.headers)};let i={subjectId:s.sub};return s.roles&&s.roles.length>0&&(i.roles=s.roles),{principal:i}}catch(n){return n instanceof Rn.JWTExpired?{evictCookie:Ud(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:Ud(e.url,e.headers)})}}o(wn,"readBrowserSession");async function rs(e){let t=ke().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:SR()};e.principal.roles&&(r.roles=e.principal.roles);let n=await new nx(r).setProtectedHeader({alg:be,typ:"JWT"}).setIssuer(fe).setAudience(_e).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await yR());return dx({value:n,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}o(rs,"createBrowserSessionCookie");async function fx(e){let t=ke(),r=Ut("tokenUrl"),n=Ut("clientId"),s=Ut("clientSecret"),i=new URL(ge().actionPath("/oauth/callback"),qt(e.requestUrl,e.requestHeaders)).toString(),a=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:s});if(t.browserLogin.pkce===Gr){let c=await Td({stateId:e.stateId,signingKey:await Sn()});a.set("code_verifier",c)}try{let{response:c,json:d}=await Ui(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:a},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!c.ok){let y=ux(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ie(r),idpStatus:c.status,...y},"Federated browser login token exchange returned non-2xx from the identity provider"),z({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${y.idpError?` idp_error=${y.idpError}`:""}${y.idpErrorDescription?` idp_error_description=${y.idpErrorDescription}`:""})`)})}let u=ix.parse(d),p;try{({payload:p}=await gR(u.id_token,hx(),{issuer:t.oidc.issuer,audience:n}))}catch(y){let b={};throw Ae(b,"error",y),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:lx(y),idpHost:ie(r),expectedIssuer:t.oidc.issuer,...b},"Federated id_token failed jose verification"),y}if(p.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ie(r),nonceMissingFromIdToken:p.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),z("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let h=cx.parse(p);return{principal:pr({sub:h.sub,data:h},e.requestUrl),subjectToken:{token:u.id_token,tokenType:Po,expiresAt:typeof p.exp=="number"?W(new Date(p.exp*1e3)):void 0}}}catch(c){let d=Be(c)??mx(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:z("browser_login_verification_failed","Federated browser login callback could not be verified.",px(c))}}o(fx,"exchangeFederatedAuthorizationCode");async function zd(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return fx({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await wn(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw z("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}o(zd,"resolveBrowserLoginCallbackIdentity");var gx=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function yx(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(yx,"readScheme");function Sx(e){return e.protocol==="https:"}o(Sx,"isSpecCompliantRedirectUri");function Rx(e){let t=yx(e);return t.length>0&&t!=="http"&&t!=="https"&&!gx.has(t)}o(Rx,"isNativeAppCustomSchemeRedirectUri");var _R=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>Sx(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>He(e),"accepts"),matches:o((e,t)=>He(e)&&He(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>Rx(e),"accepts")}];function bR(e){let t=_R.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(bR,"evaluateBuiltInRedirectUriCompatibility");function wR(e){try{return new URL(e)}catch{return}}o(wR,"parseUrl");function vR(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=wR(e.registeredRedirectUri),r=wR(e.requestedRedirectUri);return t===void 0||r===void 0?!1:_R.some(n=>n.matches?.(t,r))}o(vR,"redirectUriMatchesBuiltInCompatibility");var wx=1e4,_x=5*1024,bx=0,vx=2160*60*60,CR=["authorization_code","refresh_token",Gs,zt],Cx=["authorization_code","refresh_token"],IR=[ch],Ix=["code"],Tx=m.object({client_name:m.string().min(1).optional(),redirect_uris:m.array(m.string().min(1)).min(1),grant_types:m.array(m.enum(CR)).min(1).max(CR.length).optional(),authorization_grant_profiles_supported:m.array(m.enum(IR)).min(1).max(IR.length).optional(),response_types:m.array(m.enum(Ix)).min(1).max(1).optional(),scope:m.literal(he).optional(),token_endpoint_auth_method:uh.optional(),jwks_uri:m.string().min(1).optional()});function Ex(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&He(t))&&t.pathname!=="/"}catch{return!1}}o(Ex,"isCimdClientIdCandidate");function TR(e,t){throw new E("invalid_client",wh({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}o(TR,"invalidCimdClientError");function _n(e,t="invalid_request"){if(kx(e))throw new E(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new E(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new E(t,"redirect_uris must not include credentials or fragments.");if(bR({url:r}).kind==="rejected")throw new E(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(_n,"assertValidRedirectUri");function kx(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(kx,"hasForbiddenRawRedirectUriCharacter");async function Ax(e){let{response:t,json:r}=await ly(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:bx,maxResponseBytes:_x,timeoutMs:wx});if(!t.ok)throw z("invalid_request","CIMD metadata could not be fetched.");let n=Zs(r);for(let s of n.redirect_uris)_n(s,"invalid_request");if(n.jwks_uri!==void 0&&Oo(n.jwks_uri),n.client_id!==e.clientId)throw z("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(Ax,"fetchCimdMetadata");async function Px(e){let t=Xs(e),r=await Ax({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(Px,"resolveCimdClient");async function Xi(e,t){let r=yt.parse(e);if(Ex(r)){ke().gateway.downstreamCimdEnabled||TR(r);try{return await Px(r)}catch(s){TR(r,s)}}let n=await G().readClient({clientId:r});if(n.kind==="found"){let s=n.client,i=bh(s.clientId),a=i===void 0?s.tokenEndpointAuthMethod:"private_key_jwt",c=s.jwksUri??i;if(a==="private_key_jwt"&&c===void 0)throw new E("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let d=Zs({client_id:s.clientId,client_name:s.clientName,redirect_uris:s.redirectUris,token_endpoint_auth_method:a,...c===void 0?{}:{jwks_uri:c}}),u={kind:"dcr",clientId:r,metadata:d};return s.hashedClientSecret&&(u.hashedClientSecret=s.hashedClientSecret),u}throw new E("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(Xi,"resolveClient");function ER(e,t){if(!e.metadata.redirect_uris.some(r=>vR({registeredRedirectUri:r,requestedRedirectUri:t})))throw z("invalid_request","redirect_uri is not registered for the client.")}o(ER,"assertRedirectRegistered");function xx(e){return e===void 0?[...Cx]:Array.from(new Set(e))}o(xx,"normalizeGrantTypes");function Ox(e){try{Oo(e)}catch(t){throw new E("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}o(Ox,"assertValidDcrJwksUri");function Mx(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?yt.parse(_h({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):yt.parse(`dcr:${crypto.randomUUID()}`)}o(Mx,"createDcrClientId");function bn(e){if(e===void 0||e===he)return he;throw new E("invalid_request",`Only the ${he} scope is supported.`)}o(bn,"assertSupportedOAuthScope");function Sr(e,t,r){let n;try{n=new URL(t)}catch{throw new E("invalid_target","resource must be an absolute URI.")}if(n.hash)throw new E("invalid_target","resource must not include a fragment.");if(n.protocol!=="https:"&&!He(n))throw new E("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let s=ce(e,r),i=rn(),a=i?[...i.byOperationId.values()].find(c=>new URL(c.routePath,s).toString()===t):void 0;if(!a)throw new E("invalid_target","resource must match a published MCP route.");return a}o(Sr,"resolveResource");async function kR(e){let t;try{t=Tx.parse(e)}catch(y){if(y instanceof m.ZodError){let b=y.issues.some(w=>w.path[0]==="redirect_uris");throw new E(b?"invalid_redirect_uri":"invalid_client_metadata",y.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:y})}throw y}for(let y of t.redirect_uris)_n(y,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new E("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&Ox(t.jwks_uri);let r=new Date,n=t.token_endpoint_auth_method??"none",s=n==="private_key_jwt"?"none":n,i=Mx({tokenEndpointAuthMethod:n,jwksUri:t.jwks_uri}),a=Zs({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:n,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),c=gt(r,vx),d=Math.floor(r.getTime()/1e3),u=Math.floor(c.getTime()/1e3),p={client_id:a.client_id,client_name:a.client_name,redirect_uris:a.redirect_uris,grant_types:xx(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:he,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d,jwks_uri:a.jwks_uri},h={clientId:a.client_id,clientName:a.client_name,redirectUris:a.redirect_uris,tokenEndpointAuthMethod:s,createdAt:W(r),clientExpiresAt:W(c)};if(n==="client_secret_basic"||n==="client_secret_post"){let y=St();h.hashedClientSecret=await de(y),h.clientSecretExpiresAt=W(c),p.client_secret=y,p.client_secret_expires_at=u,p.client_secret_issued_at=d}if((await G().registerClient(h)).kind==="already_exists")throw z("invalid_request","OAuth client is already registered.");return p}o(kR,"registerDownstreamClient");function Ux(e){return e?.metadata?.idpSubjectTokenType!==nn&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}o(Ux,"hasStoredIdJagSubjectTokenBinding");async function AR(e){let t=tn(e.principal.subjectId);return(await G().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}o(AR,"readIdJagSubjectConnection");async function Nd(e){let t=Ie().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await AR({connection:t.connection,principal:e.principal});return!Ux(r)}o(Nd,"requiresIdJagSubjectTokenBinding");async function PR(e){if(e.subjectToken===void 0)return;let t=Ie().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await AR({connection:t.connection,principal:e.principal});return G().upsertUpstreamConnection({id:r?.id??Qs(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await vt(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}o(PR,"bindIdJagSubjectTokenForAuthorizationTransaction");function xR(e){return X`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(xR,"renderShellIcon");function OR(e){return X`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(OR,"renderActions");var MR=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function UR(e){return X`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(UR,"renderBannerWarning");var N1=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),j1=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var D1=Ye('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var qx="data:,",qR=X`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,zR=X`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function zx(e,t,r){if(e)try{let n=new URL(t).origin,s=new URL(e,n);return s.origin!==n||!s.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:s.toString()}catch{return}}o(zx,"safeGatewayConnectHref");function Nx(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Nx,"deriveMode");function jx(e){return OR({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:qR,authorizeAttrs:Xe})}o(jx,"renderActions");function jd(e,t,r,n){for(let s of e){if(s.ownerMode!=="user"||s.status!==r)continue;let i=zx(s.connectUrl,t,n);if(i)return i}}o(jd,"firstUserConnectHref");function Dx(e){let t=e.connectHref===void 0?Xe:X`<a class="button button--primary" href="${e.connectHref}" ${zR}>Connect</a>`;return X`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${qR}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}o(Dx,"renderSetupActions");function Lx(e){return e?X`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${zR}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Xe}o(Lx,"renderReconnectAction");function $x(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}o($x,"isRenderableIconHref");function NR(e){return e?.find(t=>$x(t.src))?.src}o(NR,"readIconHref");function Hx(e){return NR(e.serverIcons)??(e.transportHost===void 0?void 0:Jc(e.transportHost).src)}o(Hx,"readUpstreamIconHref");function Bx(e){let t=NR(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let n=Hx(r);if(n!==void 0)return n}}o(Bx,"readHeaderIconHref");function Fx(e){let t=e.setupMessage===void 0?Xe:UR({icon:MR,message:e.setupMessage});return X`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}o(Fx,"renderBody");function Dd(e){let t=Nx(e.upstreams),r=jd(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),n=jd(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),s=jd(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??n:void 0,a=t==="setup"?e.upstreams.find(u=>u.ownerMode==="user"&&u.status!=="active"&&u.connectUrl===void 0&&u.setupMessage!==void 0)?.setupMessage:void 0,c=Bx({routeIcons:e.routeIcons,upstreams:e.upstreams}),d=t==="setup"?X`<footer class="card__footer">${Dx({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:X`<footer class="card__footer">${Lx(s)}${jx({state:e.state,gateway:e.gateway})}</footer>`;return fn(yn({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:c??qx,styles:gn,headerIcon:c===void 0?Xe:xR({iconHref:c,fallbackIconHref:Ng}),heading:"Authorize access",subhead:Xe,body:Fx({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:a}),footer:d}))}o(Dd,"renderConsentPage");var Jx=1e4,Vx=2e3,Gx=64*1024,jR=1024*1024,VR={name:"zuplo-mcp-gateway-readiness",version:"0.0.0"},Ld="mcp-session-id",GR=1,Kx=/^\d{4}-\d{2}-\d{2}$/,Wx;function $d(){return{tools:[],prompts:[],resources:[]}}o($d,"emptyCapabilities");function DR(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ma})}o(DR,"buildReadinessHeaders");async function LR(e){if(e.type==="bearer_token"){let n=DR();return n.set("authorization",`Bearer ${e.token}`),n}let t=await e.provider.tokens();if(!t)return;let r=DR();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}o(LR,"buildAsyncCredentialHeaders");function Zx(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(cr.parse({jsonrpc:ar,id:GR,method:"initialize",params:{protocolVersion:Ma,capabilities:{},clientInfo:VR}}))})}o(Zx,"buildInitializePreflight");function Yx(e){let t=new Headers(e.headers);return t.set("mcp-protocol-version",ur),t.set("mcp-method","server/discover"),new Request(e.upstreamUrl,{method:"POST",headers:t,body:JSON.stringify({jsonrpc:ar,id:1,method:"server/discover",params:{_meta:{[Cm]:ur,[Im]:{},[Tm]:VR}}})})}o(Yx,"buildDiscoverPreflight");async function Xx(e){if(e.status!==400&&e.status!==404)return!1;let t=await KR(e);if(t===void 0)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&"error"in r&&typeof r.error=="object"&&r.error!==null&&"code"in r.error&&typeof r.error.code=="number"}catch{return!1}}o(Xx,"isModernRejectionOfInitialize");async function KR(e,t=Gx){let r=new TextDecoder,n="";return WR(e,t,s=>{if(s===void 0)return n+r.decode();n+=r.decode(s,{stream:!0})})}o(KR,"readBoundedBody");async function WR(e,t,r){let n=e.body?.getReader();if(n===void 0)return;let s,i=new Promise(c=>{s=setTimeout(()=>c("timeout"),Vx)}),a=(async()=>{let c=0;for(;;){let{done:d,value:u}=await n.read();if(d)return r(void 0);if(c+=u.byteLength,c>t)return;let p=r(u);if(p!==void 0)return p}})();try{let c=await Promise.race([a,i]);return c==="timeout"?void 0:c}catch{return}finally{clearTimeout(s),n.cancel().catch(()=>{})}}o(WR,"readBoundedChunks");async function Hd(e){xo(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Jx);try{let n=new Request(e,{redirect:"manual",signal:t.signal});return await wu.fetch(n)}finally{clearTimeout(r)}}o(Hd,"runPreflight");function ns(e){e.body?.cancel().catch(()=>{})}o(ns,"releasePreflightBody");async function ZR(e){if(We(e.headers.get("content-type"))!=="text/event-stream"){let n=await KR(e,jR);return n===void 0?void 0:$R(HR(n))?.result}let t=new fr;return(await WR(e,jR,n=>{let s=n===void 0?t.end():t.push(n);for(let i of s){let a=i.data===void 0?void 0:$R(HR(i.data));if(a!==void 0)return a}}))?.result}o(ZR,"readProbeResult");async function Qx(e){let t=(await ZR(e))?.protocolVersion;return typeof t=="string"&&Kx.test(t)?t:void 0}o(Qx,"readNegotiatedProtocolVersion");function $R(e){if(!(!BR(e)||e.id!==GR))return{result:BR(e.result)?e.result:void 0}}o($R,"probeAnswer");function HR(e){try{return JSON.parse(e)}catch{return}}o(HR,"parseJson");function BR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(BR,"isRecord");async function eO(e){let t=e.response.headers.get(Ld);if(!t)return;let r=new Headers(e.headers);r.set(Ld,t),r.delete("content-type"),e.protocolVersion!==void 0&&r.set("mcp-protocol-version",e.protocolVersion);try{let n=await Hd(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));ns(n)}catch{}}o(eO,"terminatePreflightSession");async function YR(e){let{response:t}=e;if(e.discover===!0){let s=await ZR(t),i=fi("server/discover",{result:s});return i!==void 0&&e.upstreamServerId!==void 0&&gi(e.upstreamServerId,i,{modernOnly:!0}),{kind:"ready",upstreamStatus:t.status,capabilities:$d()}}let r=xe()&&t.status>=200&&t.status<300&&t.headers.has(Ld),n=r?await Qx(t):void 0;return r||ns(t),t.status>=200&&t.status<300?(te()&&e.upstreamServerId!==void 0&&Jf(e.upstreamServerId),await eO({...e,protocolVersion:n}),{kind:"ready",upstreamStatus:t.status,capabilities:$d()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}o(YR,"classifyResponse");function FR(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}o(FR,"connectRequiredResult");async function XR(e){let t=await Hd(Zx(e));if(!te()||!await Xx(t))return{response:t,discover:!1};try{let r=await Hd(Yx(e));if(r.status>=200&&r.status<300)return ns(t),{response:r,discover:!0};ns(r)}catch{}return{response:t,discover:!1}}o(XR,"probeUpstream");async function tO(e){try{let t=await XR(e);return YR({response:t.response,discover:t.discover,upstreamUrl:e.upstreamUrl,headers:e.headers,upstreamServerId:e.upstreamServerId})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}o(tO,"classifyPreflight");async function JR(e){try{return await Fi(e)}catch(t){if(Be(t)!=="upstream_token_refresh_unavailable")throw t;return{kind:"upstream_unavailable",message:"The upstream token endpoint could not refresh the connection. Retry later."}}}o(JR,"resolveReadinessCredential");async function rO(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:$d()};let r=Ji(t.upstreamServerId,e.route.operationId),n=mn(r,e.subjectId),s=e.returnTo===void 0?n:{...n,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),a=await JR({request:i,routeAuth:s,preloadedConnection:e.preloadedConnection});if(a.kind==="upstream_unavailable")return a;if(a.kind==="connect_required")return FR(a.payload);let c=await LR(a.credential);if(c===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let d;try{d=await XR({upstreamUrl:t.mcpUrl,headers:c})}catch(f){return{kind:"upstream_unavailable",message:f instanceof Error?f.message:"Upstream MCP server readiness preflight failed."}}let{response:u}=d;if(u.status!==401)return YR({response:u,discover:d.discover,upstreamUrl:t.mcpUrl,headers:c,upstreamServerId:t.upstreamServerId});ns(u);let p=await JR({request:i,routeAuth:s,forceRefresh:!0});if(p.kind==="upstream_unavailable")return p;if(p.kind==="connect_required")return FR(p.payload);let h=await LR(p.credential);return h===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:tO({upstreamUrl:t.mcpUrl,headers:h,upstreamServerId:t.upstreamServerId})}o(rO,"checkUpstreamRouteReadinessImpl");function QR(e){return(Wx??rO)(e)}o(QR,"checkUpstreamRouteReadiness");function nO(e){try{return new URL(e).host}catch{return}}o(nO,"safeUrlHost");function ew(e){return e!==void 0&&e.length>0}o(ew,"hasItems");function oO(e){let t=e.serverInfo?.icons;if(ew(t))return t;let r=Ei(e.mcpUrl);return r===void 0?void 0:[r]}o(oO,"readServerIcons");async function sO(e){let{authConfig:t,authMode:r,description:n,displayName:s,mcpUrl:i,ownerMode:a,upstreamServerId:c,authProfileId:d}=e.registeredConnection,u=a==="user",p=u&&r!=="id-jag",h=e.readiness??(u?Eh(e.connection):{connected:!0,status:"active"}),f=p?e.readiness?.connectUrl??(e.returnTo!==void 0?await nd({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:c,authProfileId:d,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,y=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:c,authProfileId:d,authMode:r,ownerMode:a,upstreamDisplayName:s,description:n,transportHost:nO(i),scopesRequested:ew(y)?y:void 0,serverIcons:oO(e.registeredConnection),status:h.status,connected:h.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:f,setupMessage:e.setupMessage,updatedAt:u&&"updatedAt"in h&&h.updatedAt!==void 0?h.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}o(sO,"buildSetupRequirement");function tw(e){let t=Ie().byOperationId.get(e);if(!t)throw z("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}o(tw,"requireRoute");async function Bd(e){let t=tw(e.transaction.operationId),r=tn(e.transaction.principal.subjectId),n=t.connection;if(n===void 0)return[];let i=n.ownerMode==="user"?(await G().batchGetUpstreamConnections([{owner:r,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId}]))[0]:void 0,a=await QR({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),c="connectionStatus"in a?a.connectionStatus:void 0,d=(a.kind==="connect_required"||a.kind==="admin_setup_required")&&a.payload.authUrl!==void 0?a.payload.authUrl:void 0,u=a.kind==="admin_setup_required"?a.payload.message:void 0;return[await sO({connection:i,registeredConnection:n,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:u,readiness:c===void 0?void 0:{...c,connectUrl:d}})]}o(Bd,"requirementsForSetup");async function Fd(e){let t=tw(e.transaction.operationId),r=await G().readClient({clientId:e.transaction.clientId}),n=r.kind==="found"?r.client:void 0,s={gatewayOrigin:ce(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:n?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(s.routeDescription=i),s}o(Fd,"consentContext");function Jd(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Jd,"hasUnresolvedUserUpstream");var iO=["mcp_user"],aO="dev-browser-user",cO=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),dO=m.object({response_type:m.literal("code"),client_id:m.string().min(1),redirect_uri:m.string().min(1),resource:m.url(),code_challenge:m.string().min(43),code_challenge_method:Zm,state:m.string().min(1).optional(),scope:m.literal(he).default(he)}),uO=m.enum(["continue","approve","cancel"]).default("continue"),lO=m.object({state:m.string().min(1),decision:uO}),Vt=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;authorizationServerIssuer;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription,this.authorizationServerIssuer=t.authorizationServerIssuer}};function rw(e){return typeof e=="string"&&e.length>0?e:void 0}o(rw,"readQueryString");function pO(e,t){let r=rw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new E("invalid_target",cO)}let n=gh(t,e.url,e.headers);if(r===void 0||r===n)return n;throw new E("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(pO,"requireAuthorizeResource");async function mO(e,t){let r={};t!==void 0&&(r.context=t);let n=await wn(e,r);if(n.principal)return{principal:n.principal};if(!e.user)return n.evictCookie===void 0?{}:{setCookie:n.evictCookie};let s=RR(e);return{principal:s,setCookie:await rs({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}o(mO,"resolveBrowserPrincipal");async function hO(e,t){let r={};t!==void 0&&(r.context=t);let n=await wn(e,r);if(!n.principal)throw z("authentication_required","Authorization setup requires a current browser session.");return n.principal}o(hO,"requireSetupPrincipal");function nw(e){return`${ge().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}o(nw,"buildSetupReturnTo");async function ow(e){let t=await Bd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:nw(e.csrfToken)}),r=await Fd({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),n={kind:"setup_page",html:Dd({state:e.csrfToken,operationId:e.transaction.operationId,gateway:ge(),upstreams:t,...r})};return e.setCookies!==void 0&&e.setCookies.length>0&&(n.setCookies=e.setCookies),n}o(ow,"renderSetup");function fO(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(fO,"toAuthorizationTransactionClient");async function Vd(e,t={}){let r=dO.parse({...e.query,resource:pO(e,t.operationId),state:rw(e.query.state)}),n=bn(r.scope);_n(r.redirect_uri,"invalid_request");let s=te()?t.operationId===void 0?qt(e.url,e.headers):ph({operationId:t.operationId,requestUrl:e.url,requestHeaders:e.headers}):void 0,i=new Date,a=yt.parse(r.client_id),c=await Xi(r.client_id,i);ER(c,r.redirect_uri);try{let d=Sr(e.url,r.resource,e.headers),u=fO(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:d.operationId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&ne(t.context,{eventType:Z.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type}});let p={clientId:c?.clientId??a,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state},authorizationServerIssuer:s},{principal:h,setCookie:f}=await mO(e,t.context),y=h===void 0?!1:await Nd({operationId:d.operationId,principal:h});if(!h||y){let w=await dR({transaction:p,requestUrl:e.url,requestHeaders:e.headers,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:d.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login"),{kind:"redirect",location:w.browserLoginUrl,setCookies:[...f===void 0?[]:[f],w.browserBindingCookie]}}let b=await lR({transaction:p,principal:h,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:d.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&ne(t.context,{eventType:Z.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:a,scope:n,responseType:r.response_type,subjectId:h.subjectId}}),ow({transaction:b.transaction,csrfToken:b.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:f===void 0?void 0:[f]})}catch(d){throw gO({redirectUri:r.redirect_uri,clientState:r.state,authorizationServerIssuer:s,cause:d})}}o(Vd,"authorizeDownstreamClient");function gO(e){if(e.cause instanceof Vt)return e.cause;let t=yO(e.cause);return t?new Vt({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,authorizationServerIssuer:e.authorizationServerIssuer,cause:e.cause}):e.cause}o(gO,"toDownstreamAuthorizeRedirectError");function yO(e){if(e instanceof E)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof m.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(yO,"mapToOAuthRedirectError");async function sw(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let u=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,p=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...u===void 0?{}:{idpErrorDescription:u},...p===void 0?{}:{idpErrorUri:p}},"Identity provider redirected browser-login callback with an error"),z("provider_access_denied",u??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),z("oauth_state_invalid","Browser login callback is missing state.");let s=await Ad(n),i=await Oi({purpose:"login",claim:s.binding,request:e});if(!i.matched&&$t())throw t.context?.log.warn({event:"browser_login_callback_binding_mismatch",code:"oauth_callback_mismatch",stateKind:s.kind},"Browser login callback arrived in a browser that did not start the login"),z("oauth_callback_mismatch","Browser login was not started in this browser.");let a={request:e,stateId:s.stateId};if(t.context!==void 0&&(a.context=t.context),s.kind==="return_to"){let u=SO(i.payload),p=await zd(a);return{kind:"redirect",location:new URL(u,ce(e.url,e.headers)),setCookies:[await rs({principal:p.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]}}let c=await zd(a),d=await pR({browserLoginStateToken:n,principal:c.principal});if(await PR({transaction:d.transaction,principal:c.principal,subjectToken:c.subjectToken}),await Nd({operationId:d.transaction.operationId,principal:c.principal}))throw z("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");return ow({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookies:[await rs({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),i.clearCookie]})}o(sw,"completeBrowserLoginCallback");function SO(e){let t=ko(e),r=ge().actionPath("/auth/connections/"),n=t===void 0?void 0:new URL(t,"https://gateway.local").pathname;if(t===void 0||n===void 0||!n.startsWith(r)||!/^[^/]+\/connect$/u.test(n.slice(r.length)))throw z("oauth_state_invalid","Browser login return path must be the gateway's upstream connect route.");return t}o(SO,"readConnectReturnTo");async function iw(e){let t=await uR(e);return{location:t.browserLoginUrl,setCookie:t.browserBindingCookie}}o(iw,"startConnectBrowserLogin");async function aw(e){let t=ke(),r=new URL(e.url);if(!He(r))throw z("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw z("oauth_state_invalid","Local browser login is missing state.");let s=ge().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:s,ce(e.url)),a=new URL(ce(e.url)).origin;if(i.origin!==a||i.pathname!==s)throw z("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${s} route.`);i.searchParams.set("state",n);let c={subjectId:Eo.parse(aO),roles:iO};return{kind:"redirect",location:i,setCookies:[await rs({principal:c,requestUrl:e.url,requestHeaders:e.headers})]}}o(aw,"completeLocalDevBrowserLogin");function RO(e){let t=e.method==="POST"?e.body:e.query;return lO.parse(t)}o(RO,"readSetupContinueRequest");async function cw(e){let{state:t,decision:r}=RO({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,s=await Od({csrfToken:t,now:n}),i=await hO(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await fR({csrfToken:t,currentBrowserPrincipal:i,now:n})};let a=await mR({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Bd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:nw(t)});if(r==="approve"&&Jd(c)&&await aR({csrfToken:t,currentBrowserPrincipal:i,now:n}),Jd(c)){let d=await Fd({transaction:a,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:Dd({state:t,operationId:a.operationId,gateway:ge(),upstreams:c,...d})}}return{kind:"redirect",location:await hR({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(cw,"continueDownstreamAuthorizeSetup");import{createLocalJWKSet as OO,decodeJwt as MO,errors as ss,jwtVerify as UO}from"jose";import{createRemoteJWKSet as wO,decodeJwt as _O,decodeProtectedHeader as bO,errors as os,jwtVerify as vO}from"jose";var mw=30,ue=m.string().min(1),CO=m.union([ue,m.array(ue).min(1)]),IO=m.union([ue,m.array(ue).min(1)]),TO=m.object({type:ue,locations:m.array(ue).optional(),actions:m.array(ue).optional(),datatypes:m.array(ue).optional(),identifier:ue.optional(),privileges:m.array(ue).optional()}).passthrough(),EO=m.object({iss:m.url(),sub:ue,aud:CO,client_id:ue,resource:IO.optional(),scope:ue.optional(),authorization_details:m.array(TO).optional(),jti:ue,iat:m.number().int(),nbf:m.number().int().optional(),exp:m.number().int(),tenant:ue.optional(),aud_tenant:ue.optional(),aud_sub:ue.optional(),sub_id:ue.optional(),act:m.unknown().optional(),email:ue.optional(),auth_time:m.number().int().optional(),acr:ue.optional(),amr:m.array(ue).optional(),cnf:m.unknown().optional()}).passthrough();function Ve(e){throw new E("invalid_grant",e)}o(Ve,"throwInvalidGrant");function kO(e){return e instanceof os.JWTExpired?"expired":e instanceof os.JWTClaimValidationFailed?"claim":e instanceof os.JWSSignatureVerificationFailed?"signature":e instanceof os.JWKSNoMatchingKey?"jwks_no_match":e instanceof os.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(kO,"readJwtFailureKind");function AO(e){return Array.isArray(e.aud)?(e.aud.length!==1&&Ve("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}o(AO,"readSingleAudience");function dw(e){try{let t=EO.parse(e);return AO(t),t}catch(t){if(t instanceof E)throw t;Ve("ID-JAG claims are invalid.")}}o(dw,"parseIdJagClaims");function PO(e,t){e.idJag.enabled||Ve("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(n=>n.issuer===t);return r===void 0&&Ve("ID-JAG issuer is not trusted."),r}o(PO,"readTrustedIssuer");function xO(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(n=>r.has(n.type))}o(xO,"readGrantedAuthorizationDetails");function uw(e){if(e.clientAuth.method==="none")throw new E("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&Ve("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&Ve("ID-JAG client_id is not allowed for this issuer.")}o(uw,"assertClientBinding");function lw(e){e.cnf!==void 0&&Ve("ID-JAG cnf-bound assertions require DPoP support.")}o(lw,"assertProofOfPossessionNotDeferred");function pw(e){let t=Math.floor(e.now.getTime()/1e3)+mw;e.claims.iat>t&&Ve("ID-JAG iat must not be in the future.")}o(pw,"assertIssuedAtNotInFuture");async function hw(e){let t;try{t=bO(e.assertion)}catch{Ve("ID-JAG assertion is malformed.")}t.typ!==Aa&&Ve('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=dw(_O(e.assertion))}catch(c){if(c instanceof E)throw c;Ve("ID-JAG assertion is malformed.")}let n=qt(e.requestUrl,e.requestHeaders),s=[n];e.requestedResource!==void 0&&e.requestedResource!==n&&s.push(e.requestedResource);let i=PO(e.config,r.iss);s.includes(r.iss)&&Ve("ID-JAG issuer must be different from the gateway."),uw({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),lw(r),pw({claims:r,now:e.now});let a;try{let c=wO(new URL(i.jwksUrl)),{payload:d}=await vO(e.assertion,c,{issuer:i.issuer,audience:s,currentDate:e.now,clockTolerance:mw,typ:Aa});a=dw(d)}catch(c){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:kO(c)},"OAuth ID-JAG assertion verification failed"),Ve("ID-JAG assertion verification failed.")}return uw({claims:a,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),lw(a),pw({claims:a,now:e.now}),{claims:a,trustedIssuer:i,subjectId:yh({issuer:a.iss,subject:a.sub,gatewayIssuer:n,subjectMapping:i.subjectMapping,tenant:a.tenant}),grantedAuthorizationDetails:xO({authorizationDetails:a.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}o(hw,"verifyIdJagAssertion");var qO=new Set(["authorization_code","refresh_token",zt]),zO=1e4,NO=32*1024,jO=2,DO=3600,Gd=m.object({client_id:m.string().min(1).optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),LO=m.discriminatedUnion("grant_type",[Gd.extend({grant_type:m.literal("authorization_code"),code:m.string().min(1),redirect_uri:m.string().min(1),code_verifier:Kr,resource:m.url().optional(),scope:m.literal(he).optional()}),Gd.extend({grant_type:m.literal("refresh_token"),refresh_token:m.string().min(1),resource:m.url().optional(),scope:m.literal(he).optional()}),Gd.extend({grant_type:m.literal(zt),assertion:m.string().min(1),resource:m.url().optional(),scope:m.literal(he).optional(),authorization_details:m.string().min(1).optional()})]);function $O(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!qO.has(t)))throw new E("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o($O,"assertSupportedGrantType");var HO=m.object({token:m.string().min(1),client_id:m.string().min(1).optional(),token_type_hint:m.string().optional(),client_secret:m.string().min(1).optional(),client_assertion_type:m.string().min(1).optional(),client_assertion:m.string().min(1).optional()}),BO=m.object({keys:m.array(m.record(m.string(),m.unknown())).min(1)}).passthrough();function gw(){return ke().gateway.accessTokenTtlSeconds}o(gw,"readAccessTokenTtlSeconds");function FO(){return ke().gateway.refreshTokenTtlSeconds}o(FO,"readRefreshTokenTtlSeconds");function fw(e,t){let r=gw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),s=Math.min(r,n);return{expiresAt:W(gt(e,s)),expiresIn:s}}o(fw,"calculateAccessTokenExpiresAt");function JO(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new E("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new E("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new E("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}o(JO,"readIdJagResource");function VO(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new E("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}o(VO,"readIdJagGrantedAuthorizationDetails");function GO(e){if(e.claimScope?.split(/\s+/).includes(he)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return he;if(e.claimScope===void 0)throw new E("invalid_grant",`ID-JAG must include ${he} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(he))throw new E("invalid_grant",`ID-JAG scope must include ${he}.`);return he}o(GO,"readIdJagGrantedScope");function KO(e){if(e!==void 0&&e.get("dpop")!==null)throw new E("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}o(KO,"assertNoDpopProofForIdJag");function yw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new E("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new E("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new E("invalid_client","Malformed HTTP Basic client authentication.")}}o(yw,"readBasicClientSecret");function Sw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new E("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=MO(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new E("invalid_client","Malformed private_key_jwt client assertion.")}throw new E("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new E("invalid_client","Client authentication or client_id is required.")}o(Sw,"resolveAuthenticatedClientId");function WO(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new E("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(WO,"resolveClientSecretInput");function ZO(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(ZO,"hasClientAssertion");function YO(e){if(e.requestUrl===void 0)throw new E("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(ge().actionPath(e.pathname),ce(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}o(YO,"buildEndpointAudience");function XO(e){return e instanceof ss.JWTExpired?"expired":e instanceof ss.JWTClaimValidationFailed?"claim":e instanceof ss.JWSSignatureVerificationFailed?"signature":e instanceof ss.JWKSNoMatchingKey?"jwks_no_match":e instanceof ss.JWTInvalid?"invalid":e instanceof m.ZodError?"schema":"other"}o(XO,"readJwtFailureKind");async function QO(e){let{response:t,json:r}=await py(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:jO,maxResponseBytes:NO,timeoutMs:zO});if(!t.ok)throw new E("invalid_client","Client JWKS could not be fetched.");return BO.parse(r)}o(QO,"fetchClientJwks");async function eM(e){if(e.clientAssertionType!==Ks||e.clientAssertion===void 0)throw new E("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=yt.parse(e.clientId),r=await Xi(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new E("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new E("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let s=YO({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await QO({jwksUri:n,context:e.context}),{payload:a}=await UO(e.clientAssertion,OO(i),{issuer:t,subject:t,audience:s,currentDate:e.now}),c=Math.floor(e.now.getTime()/1e3)+DO;if(typeof a.exp!="number"||a.exp>c)throw new E("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:XO(i)},"OAuth private_key_jwt client authentication failed"),new E("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(eM,"verifyPrivateKeyJwtClientAssertion");async function tM(e){let t=yt.parse(e.clientId);if(vh(t))throw new E("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await de(e.clientSecret)}}o(tM,"buildRuntimeHttpClientAuth");async function Rw(e){if(ZO({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new E("invalid_request","Use only one client authentication method per request.");return eM(e)}let t=WO({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return tM({clientId:e.clientId,...t})}o(Rw,"resolveRuntimeHttpClientAuth");async function ww(e){$O(e.body);let t=LO.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date,i=await Rw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:s,context:e.context});return rM({parsed:t,clientId:n,clientAuth:i,now:s,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}o(ww,"exchangeDownstreamToken");async function rM(e){if(e.parsed.grant_type==="authorization_code"){_n(e.parsed.redirect_uri,"invalid_request"),bn(e.parsed.scope),e.parsed.resource!==void 0&&Sr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let c=St(),d=St(),u=W(gt(e.now,FO())),p=fw(e.now,u),h=await G().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await de(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await ei(e.parsed.code_verifier),currentRefreshTokenHash:await de(c),accessTokenHash:await de(d),grantExpiresAt:u,accessTokenExpiresAt:p.expiresAt,now:W(e.now)});if(h.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(h.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the authorization code resource.");if(h.kind!=="exchanged")throw new E("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:p.expiresIn,refresh_token:c,scope:h.grant.scope,resource:h.grant.resource}}if(e.parsed.grant_type===zt){bn(e.parsed.scope),KO(e.requestHeaders);let c=await hw({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:ke()}),d=JO({claimedResource:c.claims.resource,requestedResource:e.parsed.resource}),u=Sr(e.requestUrl??d,d,e.requestHeaders),p=VO({claimAuthorizationDetails:c.claims.authorization_details,grantedAuthorizationDetails:c.grantedAuthorizationDetails,resource:d}),h=GO({claimScope:c.claims.scope,grantedAuthorizationDetails:p}),f=St(),y=W(new Date(c.claims.exp*1e3)),b=fw(e.now,y),w=await G().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await de(f),subjectId:c.subjectId,resource:d,operationId:u.operationId,scope:h,authorizationDetails:p,accessTokenExpiresAt:b.expiresAt,now:W(e.now),idJag:{issuer:c.claims.iss,jti:c.claims.jti,tenant:c.claims.tenant,expiresAt:y}});if(w.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(w.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:f,token_type:"Bearer",expires_in:b.expiresIn,scope:w.grant.scope,resource:w.grant.resource,...p===void 0?{}:{authorization_details:p}}}bn(e.parsed.scope),e.parsed.resource!==void 0&&Sr(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await de(e.parsed.refresh_token),r=e.parsed.refresh_token,n=St(),s=W(gt(e.now,gw())),i=await G().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await de(n),resource:e.parsed.resource,accessTokenExpiresAt:s,now:W(e.now)});if(i.kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new E("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new E("invalid_grant","Refresh token is invalid, expired, or revoked.");Sr(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let a=i.accessToken.expiresAt;return e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(rM,"exchangeDownstreamTokenWithRuntimeHttp");async function _w(e){let t=HO.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),s=new Date;if((await G().revokeOAuthToken({clientAuth:await Rw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:s,context:e.context}),tokenHash:await de(t.token),now:W(s)})).kind==="invalid_client")throw new E("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&ne(e.context,{eventType:Z.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(_w,"revokeDownstreamToken");var nM=64*1024,oM=16*1024,sM="text/html; charset=utf-8";function iM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(iM,"formDataToObject");async function aM(e){return KS(e,{maxBytes:nM,label:"Request body"})}o(aM,"readJsonBody");async function Wd(e){return iM(await WS(e,{maxBytes:oM,label:"Request body"}))}o(Wd,"readFormBody");async function bw(e,t,r){let n=Be(r),s=r instanceof m.ZodError?Gt(r):void 0,i={code:n??(r instanceof m.ZodError?"invalid_request":"internal_server_error")};return s!==void 0&&(i.detail=s),en(e,t,i)}o(bw,"handleProblem");function vw(e){return e?.requestId}o(vw,"readBrowserRequestId");function Cw(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(Cw,"readUpstreamHtmlError");function vn(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(vn,"readRuntimeErrorExtensionString");function cM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(cM,"readRuntimeErrorExtensionNumber");function dM(e){try{return new URL(e.url).pathname}catch{return}}o(dM,"readBrowserRequestPath");function Rr(e){let t={code:e.code,requestId:e.requestId,routePath:dM(e.request),underlyingError:e.underlyingError};return e.error instanceof k&&(t.httpStatus=cM(e.error,lt),t.contentType=vn(e.error,Wr),t.upstreamUrl=vn(e.error,pt),t.upstreamServerId=vn(e.error,To),t.metadataUrl=vn(e.error,Yr),t.providerError=vn(e.error,Xr),t.providerErrorDescription=vn(e.error,Qr)),t}o(Rr,"buildBrowserErrorDiagnostic");function is(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(is,"oauthErrorResponse");function uM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(uM,"readOAuthProtocolHeaders");function lM(e,t){let r=ot("internal_server_error");return is({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:uM(e,t)})}o(lM,"oauthProtocolErrorResponse");function Kd(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(Kd,"readZodOAuthErrorCode");function pM(e){let t={error:Kd(e)},r=Gt(e);return r!==void 0&&(t.errorDescription=r),is(t)}o(pM,"oauthZodErrorResponse");function mM(e){let t=Be(e);if(t===void 0)return;let r=ot(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:fM(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,is(n)}o(mM,"oauthGatewayProblemResponse");function hM(){let t={error:"server_error",status:500,errorDescription:ot("internal_server_error").publicDetail};return is(t)}o(hM,"oauthFallbackErrorResponse");function fM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(fM,"readOAuthStatus");function Zd(e,t={}){return e instanceof Vt?Ew(e):e instanceof E?lM(e,t):e instanceof m.ZodError?pM(e):mM(e)??hM()}o(Zd,"oauthProblemResponse");function Yd(e,t,r){let n=Jt(e.url),s=vw(t);if(r instanceof Vt)return Ew(r);if(r instanceof E){let c=ot("internal_server_error");return Qe({host:n,kind:gM(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?c.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?c.publicDetail:r.message,code:r.errorCode,diagnostic:Rr({request:e,requestId:s,code:r.errorCode,underlyingError:r.errorCode==="server_error"?c.publicDetail:r.message,error:r}),requestId:s,status:r.status})}if(r instanceof m.ZodError)return Qe({host:n,kind:"invalid_request",detail:Gt(r)??"The authorization request was invalid.",developerDetail:Gt(r)??"The authorization request was invalid.",code:Kd(r),diagnostic:Rr({request:e,requestId:s,code:Kd(r),underlyingError:Gt(r)??"The authorization request was invalid.",error:r}),requestId:s});let i=Be(r);if(i!==void 0){let c=ot(i);return Qe({host:n,kind:Tw(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:Rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Cw(r),status:c.status})}let a=ot("internal_server_error");return Qe({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"server_error",diagnostic:Rr({request:e,requestId:s,code:"server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(Yd,"browserOAuthProblemResponse");function Iw(e,t,r){let n=Jt(e.url),s=vw(t),i=Be(r);if(i!==void 0){let c=ot(i);return Qe({host:n,kind:Tw(i),detail:c.publicDetail,developerDetail:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,code:i,diagnostic:Rr({request:e,requestId:s,code:i,underlyingError:c.status>=500||!(r instanceof Error)?c.publicDetail:r.message,error:r}),requestId:s,upstreamHtml:Cw(r),status:c.status})}if(r instanceof m.ZodError)return Qe({host:n,kind:"invalid_request",detail:Gt(r)??"The authorization request was invalid.",developerDetail:Gt(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:Rr({request:e,requestId:s,code:"invalid_request",underlyingError:Gt(r)??"The authorization request was invalid.",error:r}),requestId:s});let a=ot("internal_server_error");return Qe({host:n,kind:"internal_error",detail:a.publicDetail,developerDetail:a.publicDetail,code:"internal_server_error",diagnostic:Rr({request:e,requestId:s,code:"internal_server_error",underlyingError:a.publicDetail,error:r}),requestId:s,status:a.status})}o(Iw,"browserGatewayProblemResponse");function gM(e){return e==="server_error"?"internal_error":"invalid_request"}o(gM,"readOAuthBrowserErrorKind");function Tw(e){if(ot(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":case"upstream_token_refresh_unavailable":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(Tw,"readGatewayBrowserErrorKind");function Tt(e,t,r){let n={event:t},s=!1;if(r instanceof E)n.oauthError=r.errorCode,n.status=r.status,Ae(n,"error",r);else if(r instanceof Vt)n.oauthError=r.errorCode,Ae(n,"error",r);else if(r instanceof m.ZodError){n.code="invalid_request",Ae(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=Be(r);if(i!==void 0){let a=ot(i);n.code=i,n.status=a.status,a.oauthError!==void 0&&(n.oauthError=a.oauthError),s=a.status>=500||a.oauthError==="server_error",Ae(n,"error",r)}else s=!0,Ae(n,"error",r)}if(s){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Tt,"logUnexpectedOAuthHandlerError");function Ew(e){let t;try{t=new URL(e.redirectUri)}catch{return is({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),Yi(t,e.authorizationServerIssuer);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(Ew,"downstreamAuthorizeRedirectErrorResponse");function Gt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Gt,"formatZodErrorDetail");function yM(e,t){let r={event:"browser_login_callback_failed",code:Be(t)??"invalid_request"};Ae(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(yM,"logBrowserLoginCallbackFailure");function kw(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(null,{status:302,headers:t})}o(kw,"redirectResultResponse");function Qi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":sM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});for(let r of e.setCookies??[])t.append("set-cookie",r);return new Response(e.html,{status:200,headers:t})}return kw(e)}o(Qi,"authorizeResultResponse");async function Aw(e,t){try{return Response.json(mh(e.url,e.headers))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),bw(e,t,r)}}o(Aw,"authorizationServerMetadataHandler");async function Pw(e,t){try{let r=Ua(e.params.routePath);return Response.json(hh({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return Tt(t,"oauth_authorization_server_metadata_failed",r),bw(e,t,r)}}o(Pw,"scopedAuthorizationServerMetadataHandler");async function xw(e,t){try{let r=await kR(await aM(e)),n=r.client_id,s=r.client_name,i=r.redirect_uris.length,a=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:n,clientName:s,redirectUriCount:i,tokenEndpointAuthMethod:a},"OAuth Dynamic Client Registration completed"),ne(t,{eventType:Z.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:n,redirectUriCount:i,tokenEndpointAuthMethod:a}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Tt(t,"oauth_register_failed",r),Zd(r)}}o(xw,"registerHandler");async function Ow(e,t){try{return Qi(await Vd(e,{context:t}))}catch(r){return Tt(t,"oauth_authorize_failed",r),Yd(e,t,r)}}o(Ow,"authorizeHandler");async function Mw(e,t){try{let r=Ua(e.params.routePath);return Qi(await Vd(e,{operationId:r.operationId,context:t}))}catch(r){return Tt(t,"oauth_authorize_scoped_failed",r),Yd(e,t,r)}}o(Mw,"scopedAuthorizeHandler");async function Uw(e,t){try{let r=await sw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Qi(r)}catch(r){return yM(t,r),Iw(e,t,r)}}o(Uw,"callbackHandler");async function qw(e,t){try{return kw(await aw(e))}catch(r){return Tt(t,"oauth_dev_login_failed",r),Yd(e,t,r)}}o(qw,"devLoginHandler");async function zw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await cw({request:e,body:e.method==="POST"?await Wd(e):void 0,context:t});return Qi(r)}catch(r){return Tt(t,"oauth_setup_failed",r),Iw(e,t,r)}}o(zw,"setupHandler");async function Nw(e,t){try{return Response.json(await ww({body:await Wd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Tt(t,"oauth_token_failed",r),Zd(r)}}o(Nw,"tokenHandler");async function jw(e,t){try{return await _w({body:await Wd(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Tt(t,"oauth_revoke_failed",r),Zd(r)}}o(jw,"revokeHandler");var Dw="0.0.0",SM=new Set(["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"]);function as(...e){for(let t of e)if(t!==void 0&&t.trim().length>0)return t}o(as,"firstNonBlank");function cs(e,t){let r=[...e];return r.length<=t?e:`${r.slice(0,t-3).join("")}...`}o(cs,"clampToCodePoints");function RM(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}o(RM,"shortHash");function Lw(e,t){let r=[...e];if(r.length<=t)return e;let n=`-${RM(e)}`;return t<=n.length?r.slice(0,t).join(""):`${r.slice(0,t-n.length).join("")}${n}`}o(Lw,"clampNameSegment");function wM(e){let t=e.replace(/[^A-Za-z0-9._-]+/gu,"-").replace(/^[-.]+|[-.]+$/gu,"");return t.length>0?t:"server"}o(wM,"sanitizeRegistryNameSegment");var _M=/^\d{1,3}(\.\d{1,3}){3}$/u;function bM(e){let t=new URL(e).hostname.toLowerCase();if(_M.test(t)||t.startsWith("["))return"local";let r=t.split(".").reverse().map(n=>n.replace(/[^a-z0-9-]+/gu,"-").replace(/^-+|-+$/gu,"")).filter(n=>n.length>0);return r.length>0?r.join("."):"local"}o(bM,"buildRegistryNamespaceFromOrigin");function vM(e){if(e!==void 0)try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?void 0:t.toString()}catch{return}}o(vM,"sanitizeWebsiteUrl");function CM(e){if(e===void 0)return;let t=[];for(let r of e){if(typeof r.src!="string"||r.src.length===0)continue;let n;try{let i=new URL(r.src);if(i.protocol!=="https:")continue;n=i.toString()}catch{continue}if(n.length>255||r.mimeType!==void 0&&!SM.has(r.mimeType))continue;let s=r.sizes?.filter(i=>/^(\d+x\d+|any)$/u.test(i));t.push({src:n,...r.mimeType===void 0?{}:{mimeType:r.mimeType},...s===void 0||s.length===0?{}:{sizes:s},...r.theme===void 0?{}:{theme:r.theme}})}return t.length>0?t:void 0}o(CM,"sanitizeIcons");function IM(e){return e.replace(/^\/+|\/+$/gu,"").split("/").join("-")}o(IM,"localNameFromRoutePath");function $w(e){return e.includes("{")||e.includes(":")}o($w,"isParameterizedRoutePath");var TM=/^\s*[~^<>=]|\s|\|\||(?:^|[.\s])[x*](?:$|[.\s])/u;function Hw(e){let t=as(e)??Dw;return TM.test(t)?Dw:cs(t,255)}o(Hw,"sanitizeRegistryVersion");function Bw(e){let t=Lw(bM(e.origin),150),r=200-t.length-1,n=new Set,s=[];function i(c){let d=Lw(wM(c),r),u=d;for(let p=2;n.has(u);p++){let h=`-${p}`;u=`${[...d].slice(0,r-h.length).join("")}${h}`}return n.add(u),u}o(i,"claimLocalName");function a(c,d){let u=`${t}/${i(c)}`;s.push({name:u,response:{server:{...d,name:u},_meta:{"io.modelcontextprotocol.registry/official":{status:"active",isLatest:!0}}}})}o(a,"pushEntry");for(let c of e.registry.byRoutePath.values()){if($w(c.routePath))continue;let d=c.connection,u=d?.serverInfo,p=cs(as(d?.description,u?.description,d?.displayName,c.operationId)??c.operationId,100),h=as(u?.title,d?.displayName),f=vM(u?.websiteUrl),y=CM(u?.icons);a(c.operationId,{description:p,...h===void 0?{}:{title:cs(h,100)},version:Hw(u?.version),...f===void 0?{}:{websiteUrl:f},...y===void 0?{}:{icons:y},remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}for(let c of e.registry.standaloneMcpRoutes){if($w(c.routePath))continue;let d=c.operationId??IM(c.routePath),u=cs(as(c.summary,c.description,c.serverName,c.operationId,d)??d,100),p=as(c.serverName);a(d,{description:u,...p===void 0?{}:{title:cs(p,100)},version:Hw(c.serverVersion),remotes:[{type:"streamable-http",url:new URL(c.routePath,e.origin).toString()}]})}return s}o(Bw,"buildMcpRegistryDirectory");var EM=30,Fw=100;function ct(e,t){return Promise.resolve(Response.json({error:t},{status:e}))}o(ct,"registryErrorResponse");function Qd(e){return Bw({registry:Ie(),origin:ce(e.url,e.headers)})}o(Qd,"readEntries");function Xd(e){if(typeof e!="string")return{ok:!1};try{return{ok:!0,value:decodeURIComponent(e)}}catch{return{ok:!1}}}o(Xd,"decodePathParam");function Jw(e,t){return e.find(r=>r.name===t)}o(Jw,"findEntryByName");function kM(e){let t=e.get("limit");return t===null?{ok:!0,value:EM}:!/^\d+$/u.test(t)||Number.parseInt(t,10)<1?{ok:!1}:{ok:!0,value:Math.min(Number.parseInt(t,10),Fw)}}o(kM,"parseLimit");function AM(e){let t=e.get("cursor");return t===null?{ok:!0,value:0}:/^\d+$/u.test(t)?{ok:!0,value:Number.parseInt(t,10)}:{ok:!1}}o(AM,"parseCursor");var PM=/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(\.\d+)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;function xM(e){let t=PM.exec(e);if(!t)return!1;let[,r,n,s,i,a,c]=t,d=new Date(Date.UTC(Number(r),Number(n)-1,Number(s),Number(i),Number(a),Number(c)));return d.getUTCFullYear()===Number(r)&&d.getUTCMonth()===Number(n)-1&&d.getUTCDate()===Number(s)&&d.getUTCHours()===Number(i)&&d.getUTCMinutes()===Number(a)&&d.getUTCSeconds()===Number(c)}o(xM,"isValidRfc3339Timestamp");async function Vw(e,t){let r=new URL(e.url).searchParams,n=kM(r);if(!n.ok)return ct(400,`Invalid 'limit' parameter: expected a positive integer (max ${Fw}).`);let s=AM(r);if(!s.ok)return ct(400,"Invalid 'cursor' parameter: pass the exact 'metadata.nextCursor' value returned by a previous list response.");let i=r.get("updated_since");if(i!==null&&!xM(i))return ct(400,"Invalid 'updated_since' parameter: expected an RFC3339 timestamp like 2025-08-07T13:15:04Z.");let a=r.get("search")?.toLowerCase(),c=r.get("version"),d=Qd(e).sort((h,f)=>h.name<f.name?-1:h.name>f.name?1:0);a!==void 0&&a!==""&&(d=d.filter(h=>h.name.toLowerCase().includes(a))),c!==null&&c!=="latest"&&(d=d.filter(h=>h.response.server.version===c));let u=d.slice(s.value,s.value+n.value),p=s.value+n.value;return Response.json({servers:u.map(h=>h.response),metadata:{count:u.length,...p<d.length?{nextCursor:String(p)}:{}}})}o(Vw,"listMcpRegistryServersHandler");async function Gw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return ct(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Jw(Qd(e),r.value);return n===void 0?ct(404,"Server not found"):Response.json({servers:[n.response],metadata:{count:1}})}o(Gw,"listMcpRegistryServerVersionsHandler");async function Kw(e,t){let r=Xd(e.params.serverName);if(!r.ok)return ct(400,"Invalid server name: the name must be URL-encoded (e.g. 'com.example%2Fmy-server').");let n=Xd(e.params.version);if(!n.ok)return ct(400,"Invalid version: malformed encoding.");let s=Jw(Qd(e),r.value);return s===void 0?ct(404,"Server not found"):n.value!=="latest"&&n.value!==s.response.server.version?ct(404,"Server or version not found"):Response.json(s.response)}o(Kw,"getMcpRegistryServerVersionHandler");function ea(e,t){return(r,n)=>ct(e,t)}o(ea,"createWriteNotSupportedHandler");async function Ww(e,t){return ct(404,"Not found")}o(Ww,"mcpRegistryNotFoundHandler");var Zw=ea(501,"Publishing is not supported by this registry"),Yw=ea(501,"Updates are not supported by this registry"),Xw=ea(501,"Deletion is not supported by this registry"),eu=ea(403,"You do not have publish or edit permissions for this server");function Qw(e){return X`<section class="page-section" aria-labelledby="result-next-steps"><h2 class="section-label" id="result-next-steps">What to do next</h2><ol class="steps" role="list">${e.steps}</ol></section>`}o(Qw,"renderBrowserResult");var OM="text/html; charset=utf-8";function MM(e){return yn({title:e.title,iconHref:Fc(e.host),styles:gn,headerIcon:Gi("success"),heading:e.title,subhead:X`<p class="card__subtitle">${e.detail}</p>`,body:Qw({steps:hn(e.steps.map(t=>X`<li>${t}</li>`))}),footer:""})}o(MM,"browserResultHtml");function UM(e,t=200){return new Response(fn(e),{status:t,headers:{"content-type":OM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(UM,"browserResultResponse");function e_(e){return UM(MM(e))}o(e_,"browserConnectionSuccessResponse");function ta(e,t,r={}){let n=Xm(t);return Qe({host:e,kind:qM(t),detail:n.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}o(ta,"browserConnectionFailureResponse");function qM(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_oauth_issuer_mismatch":case"upstream_oauth_server_incompatible":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}o(qM,"readCallbackFailureBrowserErrorKind");var zM={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},t_=Symbol("upstream-request");function ds(e,t){Object.defineProperty(e,t_,{configurable:!0,value:t})}o(ds,"setUpstreamRequestContext");function NM(e){let t=e[t_];if(!t)throw new Ee("Upstream request context has not been set");return t}o(NM,"readUpstreamRequestContext");function jM(e,t){return t.some(r=>r===e)}o(jM,"requestContextMatchesKind");function DM(e){return typeof e=="string"?[e]:e}o(DM,"toExpectedKinds");function us(e,t){let r=NM(e),n=DM(t);if(!jM(r.kind,n)){let s=zM[n[0]];throw new Ee(`${s} request context has not been set`)}return r}o(us,"requireUpstreamRequestContext");function Kt(e){if(typeof e=="string"&&e.length!==0)return e}o(Kt,"readOptionalQueryString");function LM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Ee(`Validated path parameter ${t} is missing`);return $M(r,t)}o(LM,"requirePathString");function $M(e,t){try{return decodeURIComponent(e)}catch(r){throw new k({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[M]:"invalid_request"}},{cause:r})}}o($M,"decodePathString");function HM(e){let t=Kt(e);return t?Js.parse(t):void 0}o(HM,"readOptionalOperationId");function BM(e){let t=Ie().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new k({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[M]:"unknown_upstream_server"}})}o(BM,"readRegisteredAuthProfileId");function FM(e){let t=HM(e);if(!t)throw new k({message:"operationId query parameter is required.",extensionMembers:{[M]:"invalid_request"}});return t}o(FM,"readRequiredOperationId");async function tu(e){return e.redirect?Qe({host:Jt(e.request.url),kind:"authorization_failed",title:e.title,detail:e.detail,code:e.status===401?"authentication_required":"forbidden",requestId:e.context.requestId,status:e.status}):e.status===401?Ne.unauthorized(e.request,e.context,{code:"authentication_required",detail:e.detail}):Ne.forbidden(e.request,e.context,{code:"forbidden",detail:e.detail})}o(tu,"browserConnectRefusal");function JM(e,t){if(t.length===0)return e;let r=new Headers(e.headers);for(let n of t)r.append("set-cookie",n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(JM,"withSetCookies");async function VM(e){let{request:t,context:r,ticket:n,redirect:s}=e;if(Km(r)===void 0)return r.log.warn({event:"upstream_connect_browser_login_unavailable",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link refused: this gateway has no MCP OAuth browser sign-in to confirm who opened it"),await tu({request:t,context:r,redirect:s,status:403,title:"Ask an administrator",detail:"This gateway cannot confirm who opened this link, so it cannot connect an account from it. Ask an administrator to connect this service."});let i=await wn(t,{context:r}),a=i.evictCookie===void 0?[]:[i.evictCookie];if(i.principal===void 0){if(!s)return JM(await tu({request:t,context:r,redirect:s,status:401,title:"Sign in required",detail:"Open this connect link in a browser. The gateway asks you to sign in before it connects an account."}),a);let d=new URL(t.url),u=ko(`${d.pathname}${d.search}`);if(u===void 0)throw new Ee("Connect request path is empty");let p=await iw({returnTo:u,requestUrl:t.url,requestHeaders:t.headers});r.log.info({event:"upstream_connect_browser_login_required",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened without a gateway browser session; redirecting to browser login");let h=new Headers({location:p.location.toString(),"cache-control":"no-store"});for(let f of[...a,p.setCookie])h.append("set-cookie",f);return new Response(null,{status:302,headers:h})}let c=n.ownerMode==="user"?n.ownerSubjectId:n.initiatedBySubjectId;if(i.principal.subjectId!==c)return r.log.warn({event:"upstream_connect_browser_user_mismatch",upstreamServerId:n.upstreamServerId,operationId:n.operationId},"Upstream connect link opened by a different gateway user; connection refused"),await tu({request:t,context:r,redirect:s,status:403,title:"This link is for another account",detail:"This connect link was created for a different gateway user, so it cannot connect an account in this browser. Ask your MCP client for its own connect link, or sign in to the gateway as the user who received this one."})}o(VM,"requireTicketOwnerBrowser");async function GM(e,t,r){let n=Ji(r,FM(e.query.operationId));if(n.authMode==="id-jag")throw new k({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[M]:"invalid_request"}});let s=e.query.redirect==="true",i=Kt(e.query.browserTicket);if(e.user){if(i)throw new k({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[M]:"invalid_request"}});let d=pr(e.user,e.url),u={kind:"connect",...mn(n,d.subjectId),redirect:s},p=ko(Kt(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!i)throw new k({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[M]:"authentication_required"}});let a=await Ey(i);if(a.ownerMode!==n.ownerMode||a.upstreamServerId!==n.upstreamServerId||a.authProfileId!==n.authProfileId||a.operationId!==n.operationId)throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});if($t()){let d=await VM({request:e,context:t,ticket:a,redirect:s});if(d!==void 0)return d}await ky(a);let c=Vs(a);switch(n.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}case"user-oauth":{if(c.mode!=="user")throw new k({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[M]:"oauth_callback_mismatch"}});let d={kind:"connect",...n,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:a.initiatedBySubjectId,redirect:s};return a.returnTo!==void 0&&(d.returnTo=a.returnTo),d}}}o(GM,"resolveConnectContext");async function KM(e,t,r){let n=eh.parse(LM(e,"connection"));switch(r){case"connect":{let s=await GM(e,t,n);if(s instanceof Response)return s;ds(e,s);return}case"callback":{let s=Kt(e.query.error);if(s){let c={kind:"callback_provider_error",upstreamServerId:n,error:s},d=Kt(e.query.error_description);d!==void 0&&(c.errorDescription=d),ds(e,c);return}let i=Kt(e.query.code),a=Kt(e.query.state);if(i&&a){let c=Kt(e.query.iss);ds(e,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:a,...c===void 0?{}:{iss:c}});return}ds(e,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":ds(e,{kind:"client_metadata",upstreamServerId:n,authProfileId:BM(n)});return}}o(KM,"resolveUpstreamRequestInbound");async function WM(e,t,r){try{return await KM(e,t,r)}catch(n){let s=n instanceof k?n.extensionMembers?.[M]:void 0,i=n instanceof Error?n.message:void 0;switch(s){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return Ne.badRequest(e,t,{code:s,detail:i});case"authentication_required":return Ne.unauthorized(e,t,{code:s,detail:i});default:throw n}}}o(WM,"applyUpstreamRequestContext");function ra(e,t){return o(async(n,s)=>{let i=await WM(n,s,e);return i||t(n,s)},"wrapped")}o(ra,"withUpstreamRequestContext");var ZM=["callback_authorization_code","callback_provider_error","callback_invalid"];function ru(e){try{return new URL(e.url).pathname}catch{return}}o(ru,"readBrowserRequestPath");function YM(e){return"cause"in e?e.cause:void 0}o(YM,"readErrorCause");function XM(e){return e.stack?.split(`
|
|
44
|
-
`).slice(1,4).map(t=>t.trim()).join(" | ")}o(XM,"readFirstStackFrame");function r_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=XM(r))}o(r_,"addErrorAttributes");function nu(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[M];return Fs(t)?t:void 0}o(nu,"readRuntimeGatewayCode");function ls(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}o(ls,"readRuntimeErrorExtensionString");function QM(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}o(QM,"readRuntimeErrorExtensionNumber");function e0(e,t,r,n){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),ne(t,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),ta(n,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:ru(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),ta(n,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:ru(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}o(e0,"requireAuthorizationCallbackRequest");function t0(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(t0,"emitCallbackReceivedAnalyticsEvent");function r0(e,t){ne(e,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}o(r0,"emitTokenExchangeSucceededAnalyticsEvent");function n0(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return e_({host:Jt(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}o(n0,"buildSuccessfulCallbackResponse");function o0(e){let t={detail:e instanceof Error?e.message:void 0};return r_(t,"error",e),e instanceof Error&&r_(t,"cause",YM(e)),t}o(o0,"buildTokenExchangeFailureAttributes");function s0(e){ne(e.context,{eventType:Z.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:nu(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:o0(e.error)})}o(s0,"emitTokenExchangeFailedAnalyticsEvent");function i0(e){let t=e.error,r=nu(t),n=Ym(r)?r:"upstream_token_exchange_failed",s={code:n,requestId:e.context.requestId,routePath:ru(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof k?{httpStatus:QM(t,lt),contentType:ls(t,Wr),upstreamUrl:ls(t,pt),metadataUrl:ls(t,Yr),providerError:ls(t,Xr),providerErrorDescription:ls(t,Qr)}:{}};return ta(e.host,n,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:a0(t)})}o(i0,"tokenExchangeFailureResponse");function n_(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}o(n_,"withSetCookie");function a0(e){if(!(e instanceof k))return;let t=e.extensionMembers?.[Zr];return typeof t=="string"?t:void 0}o(a0,"readUpstreamHtmlError");async function ou(e,t){let r=us(e,ZM),n=Jt(e.url),s=e0(e,t,r,n);if(s instanceof Response)return s;t0(t,s);let i;try{let a=await hS({request:e,callbackRequest:s,onBrowserBinding:o(c=>{i=c},"onBrowserBinding")});return r0(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),n_(n0(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:nu(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return Ae(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),s0({context:t,callbackRequest:s,error:a}),n_(i0({request:e,context:t,host:n,callbackRequest:s,error:a}),i)}}o(ou,"callbackHandler");function c0(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(c0,"clientMetadataProblemDetail");async function o_(e,t){let r=us(e,"connect"),n=r.redirect?await Xo({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:qi/1e3}):void 0,s=await mS({request:e,connectRequest:r,...n===void 0?{}:{browserBinding:n.claim}});if(ne(t,{eventType:Z.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),n!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":n.setCookie,"cache-control":"no-store"}});let i=await Ni({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}o(o_,"connectHandler");async function s_(e,t){let r=us(e,"client_metadata");try{let n=ce(e.url,e.headers),s=Dy(n,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(n){if(!(n instanceof re))throw n;let s=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),Ne.notFound(e,t,{code:"not_found",detail:c0(n)})}}o(s_,"oauthClientMetadataHandler");function d0(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}o(d0,"resolveInternalRoutePath");var u0={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function l0(){return new Response(null,{status:204,headers:u0})}o(l0,"buildWellKnownPreflightResponse");function p0(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(p0,"withWellKnownCorsHeaders");function wr(e){return async(t,r)=>t.method==="OPTIONS"?l0():p0(await e(t,r))}o(wr,"wrapWellKnownHandler");var i_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:wr(Aw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:wr(Pw),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:wr(fh),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:xw},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Ow},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Mw},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Uw},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:qw},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:zw},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Nw},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:jw},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ra("client_metadata",s_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ra("connect",o_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ra("callback",ou)}],m0=i_.filter(e=>!e.routeName.startsWith("upstream_")),h0=i_.filter(e=>e.routeName.startsWith("upstream_"));function f0(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:wr(Vw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:wr(Gw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:wr(Kw),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:Zw},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:Yw},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:Xw},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:eu},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:eu},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:wr(Ww),corsPolicy:"anything-goes"}]}o(f0,"buildMcpRegistryInternalRoutes");function g0(e){let t=sh({routes:e.routes,policies:e.policies,gateway:e.gateway});return ih(t),t}o(g0,"initializeMcpGatewayConnectionRegistry");function y0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}o(y0,"hasDownstreamOAuthRoutes");function S0(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}o(S0,"hasIdJagDownstreamOAuth");function R0(e){let t=new Map;for(let n of e.byOperationId.values())n.downstreamOAuth&&t.set(n.downstreamOAuth.policyName,n.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new Ee("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(n=>`"${n}"`).join(", ");throw new re(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}o(R0,"readSingletonDownstreamOAuthConfig");function w0(e,t,r){let n=String(t.params.routePath??""),s=e.byRoutePath.get(dh(n));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?en(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}o(w0,"readScopedDownstreamOAuthConfig");function _0(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}o(_0,"routeUsesScopedOAuthConfig");function su(e,t,r){return async(n,s)=>{if(r){let d=await r(n,s);if(d instanceof Response)return d;d&&Gm(s,d)}let i=n.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:n.method},`MCP gateway: ${e} received`);let c=await t(n,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}o(su,"wrapInternalHandler");function iu(e,t,r,n){e.addPluginRoute({path:d0(t,r),methods:t.methods,handler:n,processors:[Iu],corsPolicy:t.corsPolicy??"none"})}o(iu,"addInternalRoute");function a_(e,t){let r=g0(t);if(r.gateway.registry.enabled){ut("plugin.mcp-gateway.registry");for(let c of f0(r.gateway.registry))iu(e,c,r.gateway,su(c.routeName,c.handler))}let n=y0(r),s=r.connectionsById.size>0,i,a=o(()=>(i===void 0&&(i=R0(r)),i),"readSingletonOAuthConfig");if(n){ut("plugin.mcp-gateway.downstream-oauth"),S0(r)&&ut("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of m0){let d=_0(c)?(u,p)=>w0(r,u,p):a;iu(e,c,r.gateway,su(c.routeName,c.handler,d))}}if(s){ut("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())ut(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of h0)iu(e,c,r.gateway,su(c.routeName,c.handler,n?a:void 0))}}o(a_,"registerMcpGatewayInternalRoutes");var au=class extends Cu{static{o(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),ut("plugin.mcp-gateway"),this.#e=Wm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&a_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as U_}from"@opentelemetry/api";var b0="zuplo_mcp_",v0=["__host-","__secure-"];function C0(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let n of v0)r.startsWith(n)&&(r=r.slice(n.length));return r.startsWith(b0)}o(C0,"setsGatewayCookie");function c_(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!C0(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let n=new Headers(e.headers);n.delete("clear-site-data"),n.delete("set-cookie");for(let s of r)n.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}o(c_,"stripUpstreamOriginStateHeaders");function et(e){return e&&typeof e=="object"?e:void 0}o(et,"readRecord");function ps(e,t){let r=et(e)?.[t];return typeof r=="string"?r:void 0}o(ps,"readStringProperty");function u_(e,t){let r=et(e)?.[t];return typeof r=="number"?r:void 0}o(u_,"readNumberProperty");function d_(e,t){return u_(e,"code")??(t>=400?t:void 0)}o(d_,"readErrorCode");function l_(e){return Array.isArray(e)?e.map(l_).find(t=>t?.method):et(e)}o(l_,"readJsonRpcMessage");function cu(e){let t=l_(e),r=typeof t?.method=="string"?t.method:"",n=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:ps(n,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:ps(n,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=ps(n,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}o(cu,"buildBaseCapabilityInput");function na(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}o(na,"isCapabilityListMethod");function I0(e,t,r){let i=et(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}o(I0,"readItemCount");function p_(e){let t=cu(e);return!t||na(t.mcpMethod)?null:{eventType:Z.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}o(p_,"buildCapabilityInvokedAnalyticsInput");function T0(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}o(T0,"readMissingResponseFailure");function m_(e,t,r={}){let n=cu(e);if(!n)return null;let s=et(t.message),i=et(s?.error),a=et(i?.data),c=s?.result,d=n.mcpMethod==="tools/call"&&et(c)?.isError===!0,u=et(c),p=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&et(et(u.inputRequests)?.[Jr])!==void 0;if(et(a?.connectRequired)||p)return{eventType:Z.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...n,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:u_(i,"code"),mcpErrorType:ps(i,"message")};let h=t.status<400?T0(t):void 0;if(h&&!i)return{eventType:na(n.mcpMethod)?Z.MCP_CAPABILITY_LISTED:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,...h};if(na(n.mcpMethod)){let f=t.status>=400?void 0:I0(n.mcpMethod,n.capabilityType,c),y=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:Z.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...n,httpStatusCode:t.status,...y?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:d_(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...n,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:d_(i,t.status),mcpErrorType:ps(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:Z.MCP_CAPABILITY_COMPLETED,outcome:"success",...n,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:Z.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...n,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}o(m_,"buildCapabilityFinalAnalyticsInput");function h_(e,t){let r=cu(e);return r?{eventType:na(r.mcpMethod)?Z.MCP_CAPABILITY_LISTED:Z.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}o(h_,"buildCapabilityThrownAnalyticsInput");var du={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},f_={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},g_={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var mu=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),uu=64*1024,hu=1024*1024,E0=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function y_(e,t={}){return e===void 0?uu:E0.has(e)||t.modern===!0&&e==="server/discover"||t.captureToolCallContent===!0&&e==="tools/call"?hu:uu}o(y_,"tapMaxBytesForMethod");function k0(e){let t=We(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}o(k0,"readTapMode");function A0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(A0,"isPlainObject");function P0(e){return A0(e)&&!("method"in e)&&("result"in e||"error"in e)}o(P0,"isResponseShaped");function x0(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}o(x0,"isSameJsonRpcIdValue");function S_(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(P0);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>x0(a.id,t));if(i||r)return i}return s[0]}o(S_,"selectResponse");function R_(e){try{return JSON.parse(e)}catch{return}}o(R_,"tryParseJson");var lu=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{o(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let n of this.#e)t.set(n,r),r+=n.byteLength;this.#e=[],this.#n=S_(R_(new TextDecoder().decode(t)),this.requestId,!1)}},pu=class{constructor(t,r){this.requestId=t;this.#e=new fr({maxEventChars:r,onOversize:"discard"})}requestId;static{o(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let n=t(r);this.#r||=r.discardedEvents>0;for(let s of n){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=S_(R_(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},O0={push(){},end(){},message:void 0,truncated:!1};function M0(e,t,r){switch(e){case"json":return new lu(t,r);case"sse":return new pu(t,r);case"passthrough":return O0}}o(M0,"createObserver");function w_(e,t={}){let r=e.body;if(r===null){let v=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:v,outcome:v}}let n=ht(e.headers)?"passthrough":k0(e),s=M0(n,t.requestId,t.maxBytes??uu),i,a=new Promise(v=>{i=v}),c,d=new Promise(v=>{c=v}),u=!1,p=o(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,y=o((v,x)=>{if(f)return;if(f=!0,v==="complete")try{s.end()}catch{}let N={ended:v,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...n==="passthrough"&&h>0?{uninspected:!0}:{},...x===void 0?{}:{error:x}};i(N),u||(u=!0,c(N))},"settle"),b=r.getReader(),w=new ReadableStream({async pull(v){let x;try{x=await b.read()}catch(N){y("errored",N),v.error(N);return}if(x.done){y("complete"),v.close();return}if(h+=x.value.byteLength,!f)try{s.push(x.value)}catch{}v.enqueue(x.value),p()},async cancel(v){y(v===mu?"released":"cancelled"),await b.cancel(v)}},{highWaterMark:0}),S=Qf(new Headers(e.headers)),R;try{R=new Response(w,{status:e.status,statusText:e.statusText,headers:S})}catch(v){throw b.cancel(v).catch(()=>{}),v}return{response:R,done:a,outcome:d}}o(w_,"tapJsonRpcResponse");function __(e){try{let r=e.route?.handler?.options?.telemetry;return r!==null&&typeof r=="object"&&r.captureToolCallContent===!0}catch{return!1}}o(__,"readCaptureToolCallContent");var U0=-32603,q0="The upstream MCP server ended the response stream without a response to this request.",z0="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function b_(e){return`${typeof e}:${String(e)}`}o(b_,"idKey");function N0(e,t){if(e.delete(b_(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}o(N0,"clearAnsweredRequest");function oa(e){let t=Array.isArray(e)?e:[e],r=[];for(let n of t){if(!v_(n)||typeof n.method!="string"||typeof n.id!="string"&&typeof n.id!="number")continue;let s=we(n);s!==void 0&&r.push(s)}return r}o(oa,"readJsonRpcRequestIds");function v_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(v_,"isRecord");function j0(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],n=[];for(let s of r)v_(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&n.push(s.id);return n}o(j0,"readResponseIds");function D0(e){let t=e.getReader();return new ReadableStream({async pull(r){let n;try{n=await t.read()}catch{r.close();return}if(n.done){r.close();return}r.enqueue(n.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}o(D0,"endOnError");function C_(e,t,r=hu,n){let s=new Map;for(let a of t)s.set(b_(a),a);let i=!1;return Cc(D0(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of j0(a.data))N0(s,c)},{failureMode:"open",maxEventChars:r,onFailure:o((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:o(()=>{if(s.size===0||i)return[];let a=n?.aborted?z0:q0;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:U0,message:a}})}))},"end")})}o(C_,"answerUnansweredRequests");var L0="The upstream MCP server rejected the gateway's credential.";function I_(e){return e.status===401||e.status===403&&e.headers.has("www-authenticate")}o(I_,"isUpstreamCredentialRejection");function T_(e,t){let r={code:I.InternalError,message:L0,data:{upstreamStatus:t}},n=oa(e);if(n.length===0)return Response.json(Pe({error:r}),{status:502});let s=n.map(i=>Pe({id:i,error:r}));return Response.json(Array.isArray(e)?s:s[0])}o(T_,"upstreamCredentialRejectedResponse");var E_="mcp-session-id";async function $0(e){try{return await e.clone().arrayBuffer()}catch{return}}o($0,"readRequestBody");function gu(e){try{let t=ah(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}o(gu,"readRouteAnalyticsFields");function H0(e,t,r){if(!te())return;let n=fi(t,r.message);if(n===void 0)return;let s=rn()?.byRoutePath.get(e.route.path)?.connection?.upstreamServerId;s!==void 0&&gi(s,n)}o(H0,"learnUpstreamSupportedVersions");function yu(e){return Sh(e.user,e.url,e.headers)?.subjectId}o(yu,"readRequestSubjectId");function fu(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}o(fu,"readRequestMethod");function k_(e,t){let r=e.get(t);return r===null||r===""?void 0:r}o(k_,"readHeader");function Su(e){let t=k_(e.request.headers,E_)??(e.response?k_(e.response.headers,E_):void 0),r=e.tapResult?.message?.result,n=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=lr(e.request.headers,e.requestJson?.value)??n;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}o(Su,"readMcpProtocolFields");function B0(e){let t=p_(e.requestJson?.value);t&&ne(e.context,{...t,...gu(e.context),...Su({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http"})}o(B0,"emitCapabilityInvokedAnalytics");function F0(e){let t=m_(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended},{modern:e.modern,gatewayAnswered:e.gatewayAnswered});t&&qa(e.context,{...t,...gu(e.context),...Su(e),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(F0,"emitCapabilityFinalAnalytics");function sa(e){let t=h_(e.requestJson?.value,e.details);t&&(e.late?qa:ne)(e.context,{...t,...gu(e.context),...Su({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:yu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}o(sa,"emitCapabilityThrownAnalytics");async function A_(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let n=new xt(e.request,{headers:t,...r===void 0?{}:{body:r}}),s=o(i=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=i)},"onTimeoutSignal");return Fm(n,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}o(A_,"callUpstream");function J0(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}o(J0,"readClientSignal");function P_(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}o(P_,"throwIfClientCancelled");function V0(e){let{clientSignal:t,context:r,onCancel:n}=e,s=!1,i=o(()=>(t.removeEventListener("abort",a),s?!1:(s=!0,!0)),"claim"),a=o(()=>{i()&&r.waitUntil(Promise.resolve().then(n).catch(c=>{try{xs.getLogger(r).error(c,"Error recording an MCP request whose client cancelled before headers")}catch{}}))},"onAbort");return t.addEventListener("abort",a,{once:!0}),{claim:i}}o(V0,"watchClientCancelBeforeHeaders");async function ia(e){try{await e.body?.cancel()}catch{}}o(ia,"discardBody");function G0(e,t){return e===t.reason?!0:e instanceof Error||e instanceof DOMException?e.name==="AbortError"||e instanceof Error&&e.cause===t.reason:!1}o(G0,"isClientAbortError");function K0(e,t){try{xs.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}o(K0,"logErrorAfterClientLeft");async function x_(e){P_(e.clientSignal);let t=await A_(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=AS(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await ia(t);let n=o(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await U_.with(e.refreshContext,n):await n();return P_(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await A_({...e,headers:s.headers}),gatewayAnswered:!1}}o(x_,"forwardToUpstream");function W0(e){let{request:t,context:r,requestBody:n,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?x_({request:t,context:r,bodyBytes:n,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):U_.with(i.client.ctx,()=>x_({request:t,context:r,bodyBytes:n===void 0?void 0:Wg(s,i,n,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}o(W0,"callUpstreamOperation");function Z0(e,t,r){if(e.body===null||e.status<200||e.status>299||We(e.headers.get("content-type"))!=="text/event-stream"||ht(e.headers))return e;let n=oa(t?.value);if(n.length===0)return e;let s=wt(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(C_(e.body,n,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}o(Z0,"withUnansweredRequestErrors");function Y0(e,t){if(e.body===null||!t.rewritten&&!t.clientSignal)return e;let r=new Headers(e.headers);return t.rewritten&&r.set("x-accel-buffering","no"),new Response(X0(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}o(Y0,"finishModernResponse");function X0(e,t){if(!t)return e;let r=e.getReader(),n=!1,s=o(()=>{},"onAbort"),i=o(()=>{n=!0,t.removeEventListener("abort",s)},"finish");return new ReadableStream({start(a){s=o(()=>{if(!n){i(),r.cancel(t.reason).catch(()=>{});try{a.close()}catch{}}},"onAbort"),t.aborted?s():t.addEventListener("abort",s,{once:!0})},async pull(a){let c;try{c=await r.read()}catch(d){n||(i(),a.error(d));return}if(!n){if(c.done){i(),a.close();return}a.enqueue(c.value)}},async cancel(a){i(),await r.cancel(a)}},{highWaterMark:0})}o(X0,"cancelOnClientAbort");function Q0(e,t){Eu.findContextExtensions(e)?.addPipelineExitHook(r=>{let n=t.body;r===t||n===null||r?.body===n||n.locked||n.cancel(mu).catch(()=>{})})}o(Q0,"releaseBodyIfNotSent");function O_(e,t){return Ne.format({type:"https://httpproblems.com/http-status/499",title:"Client Closed Request",status:499,detail:"The client cancelled the request before the upstream MCP server responded."},e,t)}o(O_,"clientClosedResponse");function M_(e){return e instanceof re?g_:f_}o(M_,"thrownDetails");async function eU(e,t){if(ut("handler.mcp-gateway-proxy"),e.method==="GET")return Si(e,t);let r=Date.now(),n=await $0(e),s=Mh(n,{readMetaProtocolVersion:te()});Uh(t,lr(e.headers,s?.value));let i=Zc(e,s,n),a=__(t),c;if(i!==void 0)try{c=Gg({request:e,context:t,parsed:i,captureToolCallContent:a})}catch{c=void 0}B0({context:t,request:e,requestJson:s});let d=te()&&Fr(e.headers,s?.value),u=d&&fu(s)==="subscriptions/listen",p=d?J0(e):void 0,h=p?V0({clientSignal:p,context:t,onCancel:o(()=>{c&&Xc(c),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:d,late:!0})},"onCancel")}):void 0,f={},y,b;try{let R=await W0({request:e,context:t,requestBody:n,parsed:i,spans:c,modern:d,listen:u,clientSignal:p,upstreamTimeout:f});b=R.gatewayAnswered;let v=R.response;!b&&xe()&&OS(t)&&I_(v)&&(t.log.warn({event:"mcp_upstream_credential_rejected",upstreamStatus:v.status},"MCP upstream proxy: upstream rejected the gateway credential"),await ia(v),v=T_(s?.value,v.status),b=!0),y=c_(v)}catch(R){let v=h?.claim()??!0;if(p?.aborted)return G0(R,p)||K0(t,R),v&&(c&&Xc(c),sa({context:t,request:e,requestJson:s,startedAt:r,details:du,modern:d})),O_(e,t);throw c&&Yc(c,R),sa({context:t,request:e,requestJson:s,startedAt:r,details:M_(R),modern:d}),R}if(h&&!h.claim())return await ia(y),O_(e,t);let w,S;try{w=w_(y,{requestId:we(s?.value),maxBytes:y_(fu(s),{modern:d,captureToolCallContent:a})});let R=Z0(w.response,s,f.signal);S=d?Y0(R,{rewritten:R!==w.response,clientSignal:p}):R,Q0(t,S)}catch(R){throw await ia(w?.response??y),c&&Yc(c,R),sa({context:t,request:e,requestJson:s,startedAt:r,details:M_(R),modern:d}),R}return t.waitUntil(w.outcome.then(R=>{b||H0(t,fu(s),R);try{F0({context:t,request:e,requestJson:s,response:y,tapResult:R,startedAt:r,modern:d,gatewayAnswered:b})}finally{c&&i&&Yg({spans:c,method:i.method,response:y,tapResult:R,expectsResponse:i.id!==void 0,gatewayAnswered:b})}}).catch(R=>{try{xs.getLogger(t).error(R,"Error emitting MCP gateway capability analytics")}catch{}})),S}o(eU,"McpProxyHandler");export{V_ as McpAuth0OAuthInboundPolicy,Nc as McpCapabilityFilterInboundPolicy,z_ as McpClerkOAuthInboundPolicy,N_ as McpCognitoOAuthInboundPolicy,j_ as McpEntraOAuthInboundPolicy,au as McpGatewayPlugin,D_ as McpGoogleOAuthInboundPolicy,L_ as McpKeycloakOAuthInboundPolicy,$_ as McpLogtoOAuthInboundPolicy,G_ as McpOAuthInboundPolicy,H_ as McpOktaOAuthInboundPolicy,B_ as McpOneLoginOAuthInboundPolicy,F_ as McpPingOAuthInboundPolicy,eU as McpProxyHandler,Id as McpTokenExchangeInboundPolicy,J_ as McpWorkosOAuthInboundPolicy,Cg as claimsCapabilityResolver};
|
|
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(`
|
|
16
|
+
`).slice(1,4).map(t=>t.trim()).join(" | ")}n(EO,"readFirstStackFrame");function J_(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=EO(r))}n(J_,"addErrorAttributes");function Zd(e){if(!(e instanceof E))return;let t=e.extensionMembers?.[x];return Bs(t)?t:void 0}n(Zd,"readRuntimeGatewayCode");function as(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(as,"readRuntimeErrorExtensionString");function kO(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(kO,"readRuntimeErrorExtensionNumber");function AO(e,t,r,o){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),Q(t,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),Xi(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:Wd(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Xi(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:Wd(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n(AO,"requireAuthorizationCallbackRequest");function PO(e,t){Q(e,{eventType:V.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(PO,"emitCallbackReceivedAnalyticsEvent");function xO(e,t){Q(e,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(xO,"emitTokenExchangeSucceededAnalyticsEvent");function MO(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return B_({host:Ht(e.url),title:"Connection complete",detail:"Your account is connected and the gateway saved the authorization.",steps:["Close this window.","Return to your MCP client to continue."]})}n(MO,"buildSuccessfulCallbackResponse");function OO(e){let t={detail:e instanceof Error?e.message:void 0};return J_(t,"error",e),e instanceof Error&&J_(t,"cause",TO(e)),t}n(OO,"buildTokenExchangeFailureAttributes");function UO(e){Q(e.context,{eventType:V.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Zd(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:OO(e.error)})}n(UO,"emitTokenExchangeFailedAnalyticsEvent");function qO(e){let t=e.error,r=Zd(t),o=Km(r)?r:"upstream_token_exchange_failed",s={code:o,requestId:e.context.requestId,routePath:Wd(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof E?{httpStatus:kO(t,ot),contentType:as(t,Jr),upstreamUrl:as(t,st),metadataUrl:as(t,Gr),providerError:as(t,Kr),providerErrorDescription:as(t,Wr)}:{}};return Xi(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:s,upstreamHtml:zO(t)})}n(qO,"tokenExchangeFailureResponse");function V_(e,t){if(t===void 0)return e;let r=new Headers(e.headers);return r.append("set-cookie",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}n(V_,"withSetCookie");function zO(e){if(!(e instanceof E))return;let t=e.extensionMembers?.[Vr];return typeof t=="string"?t:void 0}n(zO,"readUpstreamHtmlError");async function Yd(e,t){let r=is(e,IO),o=Ht(e.url),s=AO(e,t,r,o);if(s instanceof Response)return s;PO(t,s);let i;try{let a=await nS({request:e,callbackRequest:s,onBrowserBinding:n(c=>{i=c},"onBrowserBinding")});return xO(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),V_(MO(e,a),i)}catch(a){let c={event:"upstream_oauth_token_exchange_failed",code:Zd(a)??"upstream_token_exchange_failed",upstreamServerId:s.upstreamServerId};return Ie(c,"error",a),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),UO({context:t,callbackRequest:s,error:a}),V_(qO({request:e,context:t,host:o,callbackRequest:s,error:a}),i)}}n(Yd,"callbackHandler");function NO(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(NO,"clientMetadataProblemDetail");async function G_(e,t){let r=is(e,"connect"),o=r.redirect?await Ko({purpose:"connect",requestUrl:e.url,requestHeaders:e.headers,ttlSeconds:Mi/1e3}):void 0,s=await rS({request:e,connectRequest:r,...o===void 0?{}:{browserBinding:o.claim}});if(Q(t,{eventType:V.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:s.operationId,upstreamServerTitle:s.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,operationId:s.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),o!==void 0)return new Response(null,{status:302,headers:{location:s.authUrl,"set-cookie":o.setCookie,"cache-control":"no-store"}});let i=await Ui({requestUrl:e.url,requestHeaders:e.headers,owner:s.owner,initiatedBySubjectId:s.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:s.authProfileId,upstreamDisplayName:s.upstreamDisplayName,operationId:s.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(G_,"connectHandler");async function K_(e,t){let r=is(e,"client_metadata");try{let o=oe(e.url,e.headers),s=ky(o,r.upstreamServerId,r.authProfileId);return Response.json(s)}catch(o){if(!(o instanceof X))throw o;let s=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:s},"Failed to serve OAuth client metadata document for upstream connection"),Me.notFound(e,t,{code:"not_found",detail:NO(o)})}}n(K_,"oauthClientMetadataHandler");function jO(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(jO,"resolveInternalRoutePath");var DO={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function $O(){return new Response(null,{status:204,headers:DO})}n($O,"buildWellKnownPreflightResponse");function LO(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(LO,"withWellKnownCorsHeaders");function gr(e){return async(t,r)=>t.method==="OPTIONS"?$O():LO(await e(t,r))}n(gr,"wrapWellKnownHandler");var W_=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:gr(S_),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:gr(R_),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:gr(ph),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:__},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:w_},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:b_},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:v_},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:C_},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:I_},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:T_},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:E_},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Qi("client_metadata",K_)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Qi("connect",G_)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Qi("callback",Yd)}],HO=W_.filter(e=>!e.routeName.startsWith("upstream_")),BO=W_.filter(e=>e.routeName.startsWith("upstream_"));function FO(e){return[{routeName:"mcp_registry_list_servers",mount:"root",path:e.registryPath("/v0.1/servers"),methods:["GET","OPTIONS"],handler:gr(q_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_list_server_versions",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions"),methods:["GET","OPTIONS"],handler:gr(z_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_get_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["GET","OPTIONS"],handler:gr(N_),corsPolicy:"anything-goes"},{routeName:"mcp_registry_publish",mount:"root",path:e.registryPath("/v0.1/publish"),methods:["POST"],handler:D_},{routeName:"mcp_registry_update_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["PUT"],handler:$_},{routeName:"mcp_registry_delete_server_version",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version"),methods:["DELETE"],handler:L_},{routeName:"mcp_registry_update_server_version_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/versions/:version/status"),methods:["PATCH"],handler:Gd},{routeName:"mcp_registry_update_server_status",mount:"root",path:e.registryPath("/v0.1/servers/:serverName/status"),methods:["PATCH"],handler:Gd},{routeName:"mcp_registry_not_found",mount:"root",path:e.registryPath("/v0.1/:rest*"),methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],handler:gr(j_),corsPolicy:"anything-goes"}]}n(FO,"buildMcpRegistryInternalRoutes");function JO(e){let t=rh({routes:e.routes,policies:e.policies,gateway:e.gateway});return nh(t),t}n(JO,"initializeMcpGatewayConnectionRegistry");function VO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(VO,"hasDownstreamOAuthRoutes");function GO(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(GO,"hasIdJagDownstreamOAuth");function KO(e){let t=new Map;for(let o of e.byOperationId.values())o.downstreamOAuth&&t.set(o.downstreamOAuth.policyName,o.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];if(t.size===0)throw new ve("MCP gateway is registering downstream OAuth routes but the connection registry yielded no attached MCP OAuth policy.");let r=[...t.keys()].map(o=>`"${o}"`).join(", ");throw new X(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}n(KO,"readSingletonDownstreamOAuthConfig");function WO(e,t,r){let o=String(t.params.routePath??""),s=e.byRoutePath.get(ih(o));if(s===void 0)return;let i=s?.downstreamOAuth?.config;return i===void 0?Zr(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(WO,"readScopedDownstreamOAuthConfig");function ZO(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(ZO,"routeUsesScopedOAuthConfig");function Xd(e,t,r){return async(o,s)=>{if(r){let d=await r(o,s);if(d instanceof Response)return d;d&&Fm(s,d)}let i=o.method==="OPTIONS",a=Date.now();i||s.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,s);return i||s.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-a},`MCP gateway: ${e} responded`),c}}n(Xd,"wrapInternalHandler");function Qd(e,t,r,o){e.addPluginRoute({path:jO(t,r),methods:t.methods,handler:o,processors:[bu],corsPolicy:t.corsPolicy??"none"})}n(Qd,"addInternalRoute");function Z_(e,t){let r=JO(t);if(r.gateway.registry.enabled){nt("plugin.mcp-gateway.registry");for(let c of FO(r.gateway.registry))Qd(e,c,r.gateway,Xd(c.routeName,c.handler))}let o=VO(r),s=r.connectionsById.size>0,i,a=n(()=>(i===void 0&&(i=KO(r)),i),"readSingletonOAuthConfig");if(o){nt("plugin.mcp-gateway.downstream-oauth"),GO(r)&&nt("plugin.mcp-gateway.downstream-oauth.id-jag");for(let c of HO){let d=ZO(c)?(u,p)=>WO(r,u,p):a;Qd(e,c,r.gateway,Xd(c.routeName,c.handler,d))}}if(s){nt("plugin.mcp-gateway.upstream-auth");for(let c of r.connectionsById.values())nt(`plugin.mcp-gateway.upstream-auth.${c.authMode}`);for(let c of BO)Qd(e,c,r.gateway,Xd(c.routeName,c.handler,o?a:void 0))}}n(Z_,"registerMcpGatewayInternalRoutes");var eu=class extends wu{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),nt("plugin.mcp-gateway"),this.#e=Vm(t)}registerRoutes(t){let r=t.parsedRouteData;r&&Z_(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};import{context as vw}from"@opentelemetry/api";var YO="zuplo_mcp_",XO=["__host-","__secure-"];function QO(e){let r=e.split(";",1)[0].trim().replace(/^=\s*/,"").split("=",1)[0].trim().toLowerCase();for(let o of XO)r.startsWith(o)&&(r=r.slice(o.length));return r.startsWith(YO)}n(QO,"setsGatewayCookie");function Y_(e){let t=e.headers.getSetCookie(),r=t.filter(s=>!QO(s));if(r.length===t.length&&!e.headers.has("clear-site-data"))return e;let o=new Headers(e.headers);o.delete("clear-site-data"),o.delete("set-cookie");for(let s of r)o.append("set-cookie",s);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:o})}n(Y_,"stripUpstreamOriginStateHeaders");function Ge(e){return e&&typeof e=="object"?e:void 0}n(Ge,"readRecord");function cs(e,t){let r=Ge(e)?.[t];return typeof r=="string"?r:void 0}n(cs,"readStringProperty");function Q_(e,t){let r=Ge(e)?.[t];return typeof r=="number"?r:void 0}n(Q_,"readNumberProperty");function X_(e,t){return Q_(e,"code")??(t>=400?t:void 0)}n(X_,"readErrorCode");function ew(e){return Array.isArray(e)?e.map(ew).find(t=>t?.method):Ge(e)}n(ew,"readJsonRpcMessage");function tu(e){let t=ew(e),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:cs(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:cs(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let s=cs(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:s,resourceUri:s}}default:return null}}n(tu,"buildBaseCapabilityInput");function ea(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(ea,"isCapabilityListMethod");function eU(e,t,r){let i=Ge(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(eU,"readItemCount");function tw(e){let t=tu(e);return!t||ea(t.mcpMethod)?null:{eventType:V.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(tw,"buildCapabilityInvokedAnalyticsInput");function tU(e){if(e.message===void 0)switch(e.ended){case"errored":return{reasonCode:"upstream_stream_error",reasonClass:"upstream",failureOrigin:"upstream",errorType:"stream_error"};case"cancelled":return{reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",failureStage:"egress",errorType:"client_cancelled"};case"released":return{reasonCode:"response_replaced",reasonClass:"policy",failureOrigin:"policy",failureStage:"egress",errorType:"response_replaced"};case"complete":return e.truncated===!0||e.uninspected===!0?void 0:{reasonCode:"upstream_no_response",reasonClass:"upstream",failureOrigin:"upstream",errorType:"no_response"};default:return}}n(tU,"readMissingResponseFailure");function rw(e,t,r={}){let o=tu(e);if(!o)return null;let s=Ge(t.message),i=Ge(s?.error),a=Ge(i?.data),c=s?.result,d=o.mcpMethod==="tools/call"&&Ge(c)?.isError===!0,u=Ge(c),p=r.modern===!0&&r.gatewayAnswered===!0&&u?.resultType==="input_required"&&Ge(Ge(u.inputRequests)?.[Lr])!==void 0;if(Ge(a?.connectRequired)||p)return{eventType:V.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...o,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:Q_(i,"code"),mcpErrorType:cs(i,"message")};let h=t.status<400?tU(t):void 0;if(h&&!i)return{eventType:ea(o.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...o,httpStatusCode:t.status,...h};if(ea(o.mcpMethod)){let f=t.status>=400?void 0:eU(o.mcpMethod,o.capabilityType,c),y=t.status<400&&!i&&t.message===void 0&&(t.truncated===!0||t.uninspected===!0);return{eventType:V.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...o,httpStatusCode:t.status,...y?{mcpStatus:"not_parsed"}:{},...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",failureOrigin:"upstream",errorType:"capability_list_error",errorCode:X_(i,t.status)}:{},...f===void 0?{}:{attributes:{itemCount:f}}}}return t.status>=400||i?{eventType:V.MCP_CAPABILITY_FAILED,outcome:"failure",...o,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:X_(i,t.status),mcpErrorType:cs(i,"message")}:t.message===void 0&&(t.truncated===!0||t.uninspected===!0)?{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:"success",...o,httpStatusCode:t.status,mcpStatus:"not_parsed"}:{eventType:V.MCP_CAPABILITY_COMPLETED,outcome:d?"application_error":"success",...o,httpStatusCode:t.status,toolResultIsError:d,applicationError:d}}n(rw,"buildCapabilityFinalAnalyticsInput");function nw(e,t){let r=tu(e);return r?{eventType:ea(r.mcpMethod)?V.MCP_CAPABILITY_LISTED:V.MCP_CAPABILITY_FAILED,outcome:"failure",...r,...t}:null}n(nw,"buildCapabilityThrownAnalyticsInput");var ru={httpStatusCode:499,reasonCode:"client_cancelled",reasonClass:"client",failureOrigin:"client",errorType:"client_cancelled"},ow={httpStatusCode:502,reasonCode:"upstream_unreachable",reasonClass:"upstream",failureOrigin:"upstream",errorType:"fetch_error"},sw={httpStatusCode:500,reasonCode:"route_configuration_error",reasonClass:"config",failureOrigin:"config",errorType:"configuration_error"};var iu=Object.freeze({name:"GatewayRelease",message:"The MCP Gateway response was replaced"}),nu=64*1024,au=1024*1024,rU=new Set(["initialize","tools/list","prompts/list","resources/list","resources/templates/list"]);function iw(e,t={}){return e===void 0?nu:rU.has(e)||t.modern===!0&&e==="server/discover"||t.captureToolCallContent===!0&&e==="tools/call"?au:nu}n(iw,"tapMaxBytesForMethod");function nU(e){let t=He(e.headers.get("content-type"));return t==="text/event-stream"?"sse":/^application\/(?:[\w.+-]+\+)?json$/.test(t)?"json":"passthrough"}n(nU,"readTapMode");function oU(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(oU,"isPlainObject");function sU(e){return oU(e)&&!("method"in e)&&("result"in e||"error"in e)}n(sU,"isResponseShaped");function iU(e,t){return(typeof e=="string"||typeof e=="number")&&String(e)===String(t)}n(iU,"isSameJsonRpcIdValue");function aw(e,t,r){let s=(Array.isArray(e)?e:[e]).filter(sU);if(t!==void 0){let i=s.find(a=>a.id===t)??s.find(a=>iU(a.id,t));if(i||r)return i}return s[0]}n(aw,"selectResponse");function cw(e){try{return JSON.parse(e)}catch{return}}n(cw,"tryParseJson");var ou=class{constructor(t,r){this.requestId=t;this.maxBytes=r}requestId;maxBytes;static{n(this,"JsonBodyObserver")}#e=[];#r=0;#t=!1;#n;get message(){return this.#n}get truncated(){return this.#t}push(t){if(!this.#t){if(this.#r+=t.byteLength,this.#r>this.maxBytes){this.#t=!0,this.#e=[];return}this.#e.push(t.slice())}}end(){if(this.#t)return;let t=new Uint8Array(this.#r),r=0;for(let o of this.#e)t.set(o,r),r+=o.byteLength;this.#e=[],this.#n=aw(cw(new TextDecoder().decode(t)),this.requestId,!1)}},su=class{constructor(t,r){this.requestId=t;this.#e=new As({maxEventChars:r,onOversize:"discard"})}requestId;static{n(this,"SseBodyObserver")}#e;#r=!1;#t;get message(){return this.#t}get truncated(){return this.#r}push(t){this.#n(r=>r.push(t))}end(){this.#n(t=>t.end()),this.#e=void 0}#n(t){let r=this.#e;if(r===void 0)return;let o=t(r);this.#r||=r.discardedEvents>0;for(let s of o){if(!s.terminated||s.data===void 0||!s.data.includes('"id"'))continue;let i=aw(cw(s.data),this.requestId,!0);if(i!==void 0){this.#t=i,this.#e=void 0;return}}}},aU={push(){},end(){},message:void 0,truncated:!1};function cU(e,t,r){switch(e){case"json":return new ou(t,r);case"sse":return new su(t,r);case"passthrough":return aU}}n(cU,"createObserver");function dw(e,t={}){let r=e.body;if(r===null){let v=Promise.resolve({ended:"complete",truncated:!1});return{response:e,done:v,outcome:v}}let o=Et(e.headers)?"passthrough":nU(e),s=cU(o,t.requestId,t.maxBytes??nu),i,a=new Promise(v=>{i=v}),c,d=new Promise(v=>{c=v}),u=!1,p=n(()=>{u||s.message===void 0||(u=!0,c({ended:"matched",message:s.message,truncated:s.truncated}))},"reportMatch"),h=0,f=!1,y=n((v,P)=>{if(f)return;if(f=!0,v==="complete")try{s.end()}catch{}let N={ended:v,...s.message===void 0?{}:{message:s.message},truncated:s.truncated,...o==="passthrough"&&h>0?{uninspected:!0}:{},...P===void 0?{}:{error:P}};i(N),u||(u=!0,c(N))},"settle"),b=r.getReader(),_=new ReadableStream({async pull(v){let P;try{P=await b.read()}catch(N){y("errored",N),v.error(N);return}if(P.done){y("complete"),v.close();return}if(h+=P.value.byteLength,!f)try{s.push(P.value)}catch{}v.enqueue(P.value),p()},async cancel(v){y(v===iu?"released":"cancelled"),await b.cancel(v)}},{highWaterMark:0}),S=Su(new Headers(e.headers)),R;try{R=new Response(_,{status:e.status,statusText:e.statusText,headers:S})}catch(v){throw b.cancel(v).catch(()=>{}),v}return{response:R,done:a,outcome:d}}n(dw,"tapJsonRpcResponse");function uw(e){try{let r=e.route?.handler?.options?.telemetry;return r!==null&&typeof r=="object"&&r.captureToolCallContent===!0}catch{return!1}}n(uw,"readCaptureToolCallContent");var dU=-32603,uU="The upstream MCP server ended the response stream without a response to this request.",lU="The gateway's request timeout ended the upstream response stream before a response to this request arrived.";function lw(e){return`${typeof e}:${String(e)}`}n(lw,"idKey");function pU(e,t){if(e.delete(lw(t)))return;let r=typeof t=="number"?"string":"number";e.delete(`${r}:${String(t)}`)}n(pU,"clearAnsweredRequest");function ta(e){let t=Array.isArray(e)?e:[e],r=[];for(let o of t){if(!pw(o)||typeof o.method!="string"||typeof o.id!="string"&&typeof o.id!="number")continue;let s=ge(o);s!==void 0&&r.push(s)}return r}n(ta,"readJsonRpcRequestIds");function pw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(pw,"isRecord");function mU(e){let t;try{t=JSON.parse(e)}catch{return[]}let r=Array.isArray(t)?t:[t],o=[];for(let s of r)pw(s)&&!("method"in s)&&("result"in s||"error"in s)&&(typeof s.id=="string"||typeof s.id=="number")&&o.push(s.id);return o}n(mU,"readResponseIds");function hU(e){let t=e.getReader();return new ReadableStream({async pull(r){let o;try{o=await t.read()}catch{r.close();return}if(o.done){r.close();return}r.enqueue(o.value)},async cancel(r){await t.cancel(r)}},{highWaterMark:0})}n(hU,"endOnError");function mw(e,t,r=au,o){let s=new Map;for(let a of t)s.set(lw(a),a);let i=!1;return _u(hU(e),a=>{if(a.data!==void 0&&s.size>0)for(let c of mU(a.data))pU(s,c)},{failureMode:"open",maxEventChars:r,onFailure:n((a,c)=>{c.kind==="oversize"&&c.comment!==!0&&(i=!0)},"onFailure"),end:n(()=>{if(s.size===0||i)return[];let a=o?.aborted?lU:uU;return[...s.values()].map(c=>({event:"message",data:JSON.stringify({jsonrpc:"2.0",id:c,error:{code:dU,message:a}})}))},"end")})}n(mw,"answerUnansweredRequests");var fU="The upstream MCP server rejected the gateway's credential.";function hw(e){return e.status===401||e.status===403&&e.headers.has("www-authenticate")}n(hw,"isUpstreamCredentialRejection");function fw(e,t){let r={code:I.InternalError,message:fU,data:{upstreamStatus:t}},o=ta(e);if(o.length===0)return Response.json(Te({error:r}),{status:502});let s=o.map(i=>Te({id:i,error:r}));return Response.json(Array.isArray(e)?s:s[0])}n(fw,"upstreamCredentialRejectedResponse");var gw="mcp-session-id";async function gU(e){try{return await e.clone().arrayBuffer()}catch{return}}n(gU,"readRequestBody");function du(e){try{let t=oh(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}n(du,"readRouteAnalyticsFields");function yU(e,t,r){if(!Y())return;let o=hi(t,r.message);if(o===void 0)return;let s=Xr()?.byRoutePath.get(e.route.path)?.connection?.upstreamServerId;s!==void 0&&fi(s,o)}n(yU,"learnUpstreamSupportedVersions");function uu(e){return fh(e.user,e.url,e.headers)?.subjectId}n(uu,"readRequestSubjectId");function cu(e){let t=e?.value;return t!==null&&typeof t=="object"&&"method"in t&&typeof t.method=="string"?t.method:void 0}n(cu,"readRequestMethod");function yw(e,t){let r=e.get(t);return r===null||r===""?void 0:r}n(yw,"readHeader");function lu(e){let t=yw(e.request.headers,gw)??(e.response?yw(e.response.headers,gw):void 0),r=e.tapResult?.message?.result,o=r!==null&&typeof r=="object"&&"protocolVersion"in r&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0,s=dr(e.request.headers,e.requestJson?.value)??o;return{...t===void 0?{}:{mcpSessionId:t,sessionId:t},...s===void 0?{}:{mcpProtocolVersion:s}}}n(lu,"readMcpProtocolFields");function SU(e){let t=tw(e.requestJson?.value);t&&Q(e.context,{...t,...du(e.context),...lu({request:e.request,requestJson:e.requestJson}),httpMethod:e.request.method,subjectId:uu(e.request),transport:"http"})}n(SU,"emitCapabilityInvokedAnalytics");function RU(e){let t=rw(e.requestJson?.value,{status:e.response.status,message:e.tapResult.message,truncated:e.tapResult.truncated,uninspected:e.tapResult.uninspected,ended:e.tapResult.ended},{modern:e.modern,gatewayAnswered:e.gatewayAnswered});t&&Oa(e.context,{...t,...du(e.context),...lu(e),httpMethod:e.request.method,subjectId:uu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(RU,"emitCapabilityFinalAnalytics");function ra(e){let t=nw(e.requestJson?.value,e.details);t&&(e.late?Oa:Q)(e.context,{...t,...du(e.context),...lu({request:e.request,...e.modern?{requestJson:e.requestJson}:{}}),httpMethod:e.request.method,subjectId:uu(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(ra,"emitCapabilityThrownAnalytics");async function Sw(e){let t=new Headers(e.headers??e.request.headers),r=e.request.body===null?void 0:e.bodyBytes;r!==void 0?t.set("content-length",String(r.byteLength)):t.delete("content-length"),t.set("accept-encoding","gzip, br");let o=new kt(e.request,{headers:t,...r===void 0?{}:{body:r}}),s=n(i=>{e.upstreamTimeout&&(e.upstreamTimeout.signal=i)},"onTimeoutSignal");return Lm(o,e.context,e.modern?{onTimeoutSignal:s,...e.listen?{timeoutUntilHeaders:!0}:{},...e.clientSignal?{cancelSignal:e.clientSignal}:{}}:{onTimeoutSignal:s})}n(Sw,"callUpstream");function _U(e){let t=e.originalRequest?.signal??e.signal;return t instanceof AbortSignal?t:void 0}n(_U,"readClientSignal");function Rw(e){if(e?.aborted)throw e.reason??new DOMException("The client aborted","AbortError")}n(Rw,"throwIfClientCancelled");function wU(e){let{clientSignal:t,context:r,onCancel:o}=e,s=!1,i=n(()=>(t.removeEventListener("abort",a),s?!1:(s=!0,!0)),"claim"),a=n(()=>{i()&&r.waitUntil(Promise.resolve().then(o).catch(c=>{try{ks.getLogger(r).error(c,"Error recording an MCP request whose client cancelled before headers")}catch{}}))},"onAbort");return t.addEventListener("abort",a,{once:!0}),{claim:i}}n(wU,"watchClientCancelBeforeHeaders");async function na(e){try{await e.body?.cancel()}catch{}}n(na,"discardBody");function bU(e,t){return e===t.reason?!0:e instanceof Error||e instanceof DOMException?e.name==="AbortError"||e instanceof Error&&e.cause===t.reason:!1}n(bU,"isClientAbortError");function vU(e,t){try{ks.getLogger(e).error(t,"MCP upstream request failed after the client cancelled the request")}catch{}}n(vU,"logErrorAfterClientLeft");async function _w(e){Rw(e.clientSignal);let t=await Sw(e);if(t.status!==401)return{response:t,gatewayAnswered:!1};let r=SS(e.context);if(!r||e.bodyBytes===void 0&&e.request.body!==null)return{response:t,gatewayAnswered:!1};await na(t);let o=n(()=>r.refresh(t,new Headers(e.request.headers)),"refresh"),s=e.refreshContext?await vw.with(e.refreshContext,o):await o();return Rw(e.clientSignal),s.kind==="response"?{response:s.response,gatewayAnswered:!0}:{response:await Sw({...e,headers:s.headers}),gatewayAnswered:!1}}n(_w,"forwardToUpstream");function CU(e){let{request:t,context:r,requestBody:o,parsed:s,spans:i,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}=e;return!i||!s?_w({request:t,context:r,bodyBytes:o,modern:a,listen:c,clientSignal:d,upstreamTimeout:u}):vw.with(i.client.ctx,()=>_w({request:t,context:r,bodyBytes:o===void 0?void 0:jg(s,i,o,t.headers),modern:a,listen:c,clientSignal:d,upstreamTimeout:u,refreshContext:i.server.ctx}))}n(CU,"callUpstreamOperation");function IU(e,t,r){if(e.body===null||e.status<200||e.status>299||He(e.headers.get("content-type"))!=="text/event-stream"||Et(e.headers))return e;let o=ta(t?.value);if(o.length===0)return e;let s=go(new Headers(e.headers));return s.set("content-type","text/event-stream"),new Response(mw(e.body,o,void 0,r),{status:e.status,statusText:e.statusText,headers:s})}n(IU,"withUnansweredRequestErrors");function TU(e,t){if(e.body===null||!t.rewritten&&!t.clientSignal)return e;let r=new Headers(e.headers);return t.rewritten&&r.set("x-accel-buffering","no"),new Response(EU(e.body,t.clientSignal),{status:e.status,statusText:e.statusText,headers:r})}n(TU,"finishModernResponse");function EU(e,t){if(!t)return e;let r=e.getReader(),o=!1,s=n(()=>{},"onAbort"),i=n(()=>{o=!0,t.removeEventListener("abort",s)},"finish");return new ReadableStream({start(a){s=n(()=>{if(!o){i(),r.cancel(t.reason).catch(()=>{});try{a.close()}catch{}}},"onAbort"),t.aborted?s():t.addEventListener("abort",s,{once:!0})},async pull(a){let c;try{c=await r.read()}catch(d){o||(i(),a.error(d));return}if(!o){if(c.done){i(),a.close();return}a.enqueue(c.value)}},async cancel(a){i(),await r.cancel(a)}},{highWaterMark:0})}n(EU,"cancelOnClientAbort");function kU(e,t){Cu.findContextExtensions(e)?.addPipelineExitHook(r=>{let o=t.body;r===t||o===null||r?.body===o||o.locked||o.cancel(iu).catch(()=>{})})}n(kU,"releaseBodyIfNotSent");function ww(e,t){return Me.format({type:"https://httpproblems.com/http-status/499",title:"Client Closed Request",status:499,detail:"The client cancelled the request before the upstream MCP server responded."},e,t)}n(ww,"clientClosedResponse");function bw(e){return e instanceof X?sw:ow}n(bw,"thrownDetails");async function AU(e,t){if(nt("handler.mcp-gateway-proxy"),e.method==="GET")return yi(e,t);let r=Date.now(),o=await gU(e),s=Ph(o,{readMetaProtocolVersion:Y()});xh(t,dr(e.headers,s?.value));let i=Bc(e,s,o),a=uw(t),c;if(i!==void 0)try{c=zg({request:e,context:t,parsed:i,captureToolCallContent:a})}catch{c=void 0}SU({context:t,request:e,requestJson:s});let d=Y()&&$r(e.headers,s?.value),u=d&&cu(s)==="subscriptions/listen",p=d?_U(e):void 0,h=p?wU({clientSignal:p,context:t,onCancel:n(()=>{c&&Jc(c),ra({context:t,request:e,requestJson:s,startedAt:r,details:ru,modern:d,late:!0})},"onCancel")}):void 0,f={},y,b;try{let R=await CU({request:e,context:t,requestBody:o,parsed:i,spans:c,modern:d,listen:u,clientSignal:p,upstreamTimeout:f});b=R.gatewayAnswered;let v=R.response;!b&&Ee()&&wS(t)&&hw(v)&&(t.log.warn({event:"mcp_upstream_credential_rejected",upstreamStatus:v.status},"MCP upstream proxy: upstream rejected the gateway credential"),await na(v),v=fw(s?.value,v.status),b=!0),y=Y_(v)}catch(R){let v=h?.claim()??!0;if(p?.aborted)return bU(R,p)||vU(t,R),v&&(c&&Jc(c),ra({context:t,request:e,requestJson:s,startedAt:r,details:ru,modern:d})),ww(e,t);throw c&&Fc(c,R),ra({context:t,request:e,requestJson:s,startedAt:r,details:bw(R),modern:d}),R}if(h&&!h.claim())return await na(y),ww(e,t);let _,S;try{_=dw(y,{requestId:ge(s?.value),maxBytes:iw(cu(s),{modern:d,captureToolCallContent:a})});let R=IU(_.response,s,f.signal);S=d?TU(R,{rewritten:R!==_.response,clientSignal:p}):R,kU(t,S)}catch(R){throw await na(_?.response??y),c&&Fc(c,R),ra({context:t,request:e,requestJson:s,startedAt:r,details:bw(R),modern:d}),R}return t.waitUntil(_.outcome.then(R=>{b||yU(t,cu(s),R);try{RU({context:t,request:e,requestJson:s,response:y,tapResult:R,startedAt:r,modern:d,gatewayAnswered:b})}finally{c&&i&&$g({spans:c,method:i.method,response:y,tapResult:R,expectsResponse:i.id!==void 0,gatewayAnswered:b})}}).catch(R=>{try{ks.getLogger(t).error(R,"Error emitting MCP gateway capability analytics")}catch{}})),S}n(AU,"McpProxyHandler");export{qw as McpAuth0OAuthInboundPolicy,Pc as McpCapabilityFilterInboundPolicy,Iw as McpClerkOAuthInboundPolicy,Tw as McpCognitoOAuthInboundPolicy,Ew as McpEntraOAuthInboundPolicy,eu as McpGatewayPlugin,kw as McpGoogleOAuthInboundPolicy,Aw as McpKeycloakOAuthInboundPolicy,Pw as McpLogtoOAuthInboundPolicy,zw as McpOAuthInboundPolicy,xw as McpOktaOAuthInboundPolicy,Mw as McpOneLoginOAuthInboundPolicy,Ow as McpPingOAuthInboundPolicy,AU as McpProxyHandler,Sd as McpTokenExchangeInboundPolicy,Uw as McpWorkosOAuthInboundPolicy,mg as claimsCapabilityResolver};
|
|
45
17
|
/*! For license information please see index.js.LEGAL.txt */
|
|
46
18
|
//# sourceMappingURL=index.js.map
|